From 177b4b1fcfb78b7fe312f9ec357d29bfa4ecc1d7 Mon Sep 17 00:00:00 2001 From: Libby Date: Tue, 10 Nov 2026 17:42:29 +0000 Subject: [PATCH 001/223] Blender add-on tests: the guard test no longer pins the store's spelling of an empty put CultLib's store now refuses it as message_invalid, not malformed, so the test failed on main against current CultLib. It now asserts what it means: past the guard, a coded store refusal that is not the guard's own (codeless, names the token field). Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/tests/test_server_guard.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/tests/test_server_guard.py b/surfaces/blender/tests/test_server_guard.py index 10f964b..439cfe0 100644 --- a/surfaces/blender/tests/test_server_guard.py +++ b/surfaces/blender/tests/test_server_guard.py @@ -259,7 +259,11 @@ class RealServerTests(unittest.TestCase): self.assertEqual(server._handle_connection_message(message, {})[0]["schemaVersion"], "cultnet.error.v0") message[sg.TOKEN_FIELD] = self.target.session_token response = server._handle_connection_message(message, {}) - self.assertIn("malformed", response[0].get("code", "")) # past the guard, refused by the store as an empty put + # Past the guard: the store refuses the empty put and says so with a code. The guard's own + # refusal is codeless and names the token field, so either is told apart from the other + # without pinning the store's spelling of "an empty put is invalid". + self.assertTrue(response[0].get("code")) + self.assertNotIn(sg.TOKEN_FIELD, str(response[0])) def test_a_peer_put_is_accepted_over_tcp_because_the_target_grants_peer_writes(self): status = self.start() From 6f0e70042d6b053043e24410d4c981ed6715599f Mon Sep 17 00:00:00 2001 From: Libby Date: Tue, 10 Nov 2026 17:42:46 +0000 Subject: [PATCH 002/223] Blender add-on tests: token-guard test no longer pins the store spelling (#9) --- surfaces/blender/tests/test_server_guard.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/tests/test_server_guard.py b/surfaces/blender/tests/test_server_guard.py index 10f964b..439cfe0 100644 --- a/surfaces/blender/tests/test_server_guard.py +++ b/surfaces/blender/tests/test_server_guard.py @@ -259,7 +259,11 @@ class RealServerTests(unittest.TestCase): self.assertEqual(server._handle_connection_message(message, {})[0]["schemaVersion"], "cultnet.error.v0") message[sg.TOKEN_FIELD] = self.target.session_token response = server._handle_connection_message(message, {}) - self.assertIn("malformed", response[0].get("code", "")) # past the guard, refused by the store as an empty put + # Past the guard: the store refuses the empty put and says so with a code. The guard's own + # refusal is codeless and names the token field, so either is told apart from the other + # without pinning the store's spelling of "an empty put is invalid". + self.assertTrue(response[0].get("code")) + self.assertNotIn(sg.TOKEN_FIELD, str(response[0])) def test_a_peer_put_is_accepted_over_tcp_because_the_target_grants_peer_writes(self): status = self.start() From 6995eabf51acd98b7d9a2586dd08f0774e38490b Mon Sep 17 00:00:00 2001 From: Libby Date: Tue, 10 Nov 2026 17:54:18 +0000 Subject: [PATCH 003/223] Blender add-on: geometry node graph actions, modifier inputs, evaluated snapshot (#5) --- brokkr-daemon/src/main.rs | 18 + docs/provider-contract.md | 3 + .../blender/brokkr_bridge/blender_target.py | 86 +- .../blender/brokkr_bridge/node_actions.py | 375 ++++++ surfaces/blender/docs/node-actions.md | 39 + surfaces/blender/tests/live/gn_actions.py | 269 ++++ .../blender/tests/live/gn_actions.result.json | 1097 +++++++++++++++++ surfaces/blender/tests/live/gn_recreation.py | 178 +++ .../tests/live/gn_recreation.result.json | 141 +++ surfaces/blender/tests/test_node_actions.py | 722 +++++++++++ 10 files changed, 2926 insertions(+), 2 deletions(-) create mode 100644 surfaces/blender/brokkr_bridge/node_actions.py create mode 100644 surfaces/blender/docs/node-actions.md create mode 100644 surfaces/blender/tests/live/gn_actions.py create mode 100644 surfaces/blender/tests/live/gn_actions.result.json create mode 100644 surfaces/blender/tests/live/gn_recreation.py create mode 100644 surfaces/blender/tests/live/gn_recreation.result.json create mode 100644 surfaces/blender/tests/test_node_actions.py diff --git a/brokkr-daemon/src/main.rs b/brokkr-daemon/src/main.rs index e34d56a..3b05166 100644 --- a/brokkr-daemon/src/main.rs +++ b/brokkr-daemon/src/main.rs @@ -244,6 +244,13 @@ fn build_provider_advertisement() -> ProviderAdvertisement { "material.assign", "selection.read", "selection.write", + "asset.import.gltf", + "camera.write", + "light.write", + "world.write", + "render.still", + "nodegraph.geometry.write", + "geometry.evaluated.read", "sync.session.publish", "sync.object.bind", "sync.var.publish", @@ -1985,6 +1992,17 @@ mod tests { assert!(blender.capabilities.contains(&"object.graph.read")); assert!(blender.capabilities.contains(&"object.transform.write")); assert!(blender.capabilities.contains(&"material.assign")); + for scene_and_graph in [ + "asset.import.gltf", + "camera.write", + "light.write", + "world.write", + "render.still", + "nodegraph.geometry.write", + "geometry.evaluated.read", + ] { + assert!(blender.capabilities.contains(&scene_and_graph), "{scene_and_graph}"); + } let route_sources: Vec<_> = provider .realtime_routes diff --git a/docs/provider-contract.md b/docs/provider-contract.md index bc30905..8c1132f 100644 --- a/docs/provider-contract.md +++ b/docs/provider-contract.md @@ -220,6 +220,9 @@ All Blender writes use `brokkr.blender.command_intent.v0` and receive - `setLight` - `setWorld` - `renderStill` +- `createNodeGroup`, `addNode`, `removeNode`, `linkSockets`, `unlinkSockets`, `addModifier`, + `removeModifier`, `setModifierInput` (Geometry Nodes graphs; fields in + `surfaces/blender/docs/node-actions.md`) Blender owns the mutation. Brokkr advertises the command surface; Verse clients write typed command intents; Blender executes recognized intents and publishes diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index f482de9..628c199 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -5,10 +5,12 @@ import math import os import sys import uuid +from array import array from datetime import datetime, timezone from pathlib import Path from typing import Any, Iterable +from . import node_actions as na from . import scene_actions as sa from .server_guard import BindRefused, SessionGuard, check_bind, guarded_server_class, is_loopback_host, purge_command_intents @@ -32,6 +34,10 @@ SYNC_VAR_SCHEMA = "brokkr.sync.var.v0" SYNC_TIMELINE_BINDING_SCHEMA = "brokkr.sync.timeline_binding.v0" SYNC_RECEIPT_SCHEMA = "brokkr.sync.receipt.v0" +EVALUATED_POSITION_CAP = 256 +EVALUATED_VERTEX_LIMIT = 1_000_000 +EVALUATED_INSTANCE_SCAN_LIMIT = 100_000 # depsgraph items visited per capture; iterating one in Python costs ~5 us + CAPABILITIES = ( "cultcache.mirror.publish", "cultcache.intent.watch", @@ -50,6 +56,8 @@ CAPABILITIES = ( "light.write", "world.write", "render.still", + "nodegraph.geometry.write", + "geometry.evaluated.read", "command.receipt.publish", ) @@ -73,6 +81,7 @@ class BrokkrBlenderTarget: self._debug_mirror_root: str = "" self.import_dir: str = "" self.output_dir: str = "" + self.nodes = na.NodeActions(bpy_module) def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: """The directories importGltf and renderStill may touch; empty leaves that action disabled.""" @@ -441,6 +450,7 @@ class BrokkrBlenderTarget: def capture_snapshot(self, context: Any) -> dict[str, Any]: bpy = self.bpy + scan = self._instance_scan() if any(o.type == "MESH" and len(o.modifiers) for o in bpy.data.objects) else None selected = [item.name for item in context.selected_objects if item is not None] active_object = context.active_object.name if context.active_object else "" active_scene = context.scene.name if context.scene else "" @@ -463,7 +473,7 @@ class BrokkrBlenderTarget: "imageCount": len(bpy.data.images), "capabilities": list(CAPABILITIES), "scenes": [self._scene_snapshot(scene) for scene in bpy.data.scenes], - "objects": [self._object_snapshot(obj) for obj in bpy.data.objects], + "objects": [self._object_snapshot(obj, scan) for obj in bpy.data.objects], "materials": [self._material_snapshot(material) for material in bpy.data.materials], "collections": [self._collection_snapshot(collection) for collection in bpy.data.collections], } @@ -497,6 +507,9 @@ class BrokkrBlenderTarget: return self._set_world(context, command) if action == "renderStill": return self._render_still(context, command) + if action in na.NodeActions.ACTIONS: + message, name = self.nodes.execute(action, command) + return self._receipt(command, "accepted", message, name) return self._receipt(command, "failed", f"Unsupported Blender command action: {action}", "") except sa.ActionRefused as error: return self._receipt(command, "failed", str(error), "") @@ -573,6 +586,10 @@ class BrokkrBlenderTarget: property_name = command.get("propertyName") or "brokkrValue" if property_name.startswith("customProperties."): property_name = property_name[len("customProperties."):] + modifier_name = na.drives_modifier_input(obj, property_name) + if modifier_name: + return self._receipt(command, "failed", f"{property_name!r} is an input of Geometry Nodes modifier {modifier_name!r}; " + "a custom property does not drive it, use setModifierInput.", obj.name) obj[property_name] = command.get("value") return self._receipt(command, "accepted", "Blender custom property updated.", obj.name) @@ -761,7 +778,7 @@ class BrokkrBlenderTarget: "collectionName": scene.collection.name if scene.collection else "", } - def _object_snapshot(self, obj: Any) -> dict[str, Any]: + def _object_snapshot(self, obj: Any, scan: Any = None) -> dict[str, Any]: data = obj.data if hasattr(obj, "data") else None return { "name": obj.name, @@ -780,6 +797,7 @@ class BrokkrBlenderTarget: "constraints": [constraint.name for constraint in obj.constraints], "camera": self._camera_snapshot(data) if obj.type == "CAMERA" and data else None, "mesh": self._mesh_snapshot(data) if obj.type == "MESH" and data else None, + "evaluated": self._evaluated_snapshot(obj, scan), "customProperties": self._custom_properties(obj.items()), } @@ -801,6 +819,70 @@ class BrokkrBlenderTarget: "shapeKeyCount": len(mesh.shape_keys.key_blocks) if mesh.shape_keys else 0, } + def _instance_scan(self) -> Any: + """One pass over the depsgraph's instances: per original parent object, the count, the first locations + and the running bounds (world space). Nothing is kept per instance beyond the cap.""" + depsgraph = self.bpy.context.evaluated_depsgraph_get() + depsgraph.update() + found: dict[str, dict[str, Any]] = {} + visited = 0 + complete = True + for item in depsgraph.object_instances: + visited += 1 + if visited > EVALUATED_INSTANCE_SCAN_LIMIT: + complete = False + break + if not item.is_instance or item.parent is None: + continue + entry = found.setdefault(item.parent.original.name, {"count": 0, "first": [], "min": None, "max": None}) + point = tuple(float(c) for c in item.matrix_world.translation) + entry["count"] += 1 + if len(entry["first"]) < EVALUATED_POSITION_CAP: + entry["first"].append([round(c, 5) for c in point]) + entry["min"] = list(point) if entry["min"] is None else [min(a, b) for a, b in zip(entry["min"], point)] + entry["max"] = list(point) if entry["max"] is None else [max(a, b) for a, b in zip(entry["max"], point)] + return depsgraph, found, complete + + def _evaluated_snapshot(self, obj: Any, scan: Any) -> dict[str, Any] | None: + """What the modifier stack produced, for mesh objects that have one. Vertex positions and their bounds + are in the object's local space; instance locations and their bounds are world space. A Geometry Nodes + object's own mesh is empty, so the base mesh counts say nothing about it. Above EVALUATED_VERTEX_LIMIT + vertices only the counts are read, and any non-finite coordinate drops the positions and sets nonFinite.""" + if obj.type != "MESH" or not len(obj.modifiers) or scan is None: + return None + depsgraph, found, complete = scan + evaluated = obj.evaluated_get(depsgraph) + mesh = evaluated.to_mesh() + try: + count = len(mesh.vertices) + result = {"vertexCount": count, "edgeCount": len(mesh.edges), "polygonCount": len(mesh.polygons)} + coords = array("f", bytes(12 * count)) if 0 < count <= EVALUATED_VERTEX_LIMIT else None + if coords is not None: + mesh.vertices.foreach_get("co", coords) + finally: + evaluated.to_mesh_clear() + entry = found.get(obj.name) + reached = entry is not None + entry = entry or {"count": 0, "first": [], "min": [], "max": []} + finite = all(math.isfinite(c) for c in coords) if coords is not None else True + finite = finite and all(math.isfinite(c) for c in (entry["min"] or []) + (entry["max"] or []) + [c for p in entry["first"] for c in p]) + points = [coords[i:i + 3] for i in range(0, 3 * count, 3)] if coords is not None else [] + result.update({ + # An object the stopped scan never reached has an unknown count, not zero. + "instanceCount": entry["count"] if complete or reached else None, + "instancesComplete": complete, + "positionsSkipped": count > EVALUATED_VERTEX_LIMIT, + "nonFinite": not finite, + "vertexBoundsMin": [min(p[a] for p in points) for a in range(3)] if points and finite else [], + "vertexBoundsMax": [max(p[a] for p in points) for a in range(3)] if points and finite else [], + "vertexLocations": [[round(c, 5) for c in p] for p in points[:EVALUATED_POSITION_CAP]] if finite else [], + "instanceBoundsMin": entry["min"] if finite and entry["min"] else [], + "instanceBoundsMax": entry["max"] if finite and entry["max"] else [], + "instanceLocations": entry["first"] if finite else [], + "truncated": count > EVALUATED_POSITION_CAP or entry["count"] > EVALUATED_POSITION_CAP, + }) + return result + def _modifier_snapshot(self, modifier: Any) -> dict[str, Any]: return { "name": modifier.name, diff --git a/surfaces/blender/brokkr_bridge/node_actions.py b/surfaces/blender/brokkr_bridge/node_actions.py new file mode 100644 index 0000000..5210b86 --- /dev/null +++ b/surfaces/blender/brokkr_bridge/node_actions.py @@ -0,0 +1,375 @@ +"""Geometry node graph command actions: createNodeGroup, addNode, linkSockets, addModifier, setModifierInput. + +Owner of how an intent becomes a node group, a node, a link or a modifier input on Blender 5.2. +Validation is plain Python and runs before bpy is touched; apply steps that can still fail after +Blender has been asked (an unknown node type, an enum that is not offered) undo what they made, so a +refused intent leaves the tree as it was. Docs: docs/node-actions.md. The design is PR #3 (branch libby/blender-node-graphs-design). +""" +from __future__ import annotations + +import math +import re +from typing import Any + +from .scene_actions import ActionRefused + +ID_PATTERN = re.compile(r"[A-Za-z0-9._-]{1,63}") +KEY_PATTERN = re.compile(r"[A-Za-z0-9 ._-]{1,63}") +# A geometry tree may hold geometry, function and shader math nodes. Nodes that read or write files, +# run code, write caches, nest groups or sample images are not part of this cut. +NODE_IDNAME = re.compile(r"(GeometryNode|FunctionNode|ShaderNode)[A-Za-z0-9]+") +NODE_DENIED = ("Import", "Export", "Script", "Bake", "Group", "Simulation", "Repeat", "Foreach", "Viewer", "TexImage", "TexEnvironment", + "ImageTexture", "InputImage", "TexIES") +MAX_NODES = 500 +MAX_INTERFACE = 64 +MAX_MODIFIERS = 8 +MAX_VALUE = 1.0e9 +MAX_INT = 4096 # counts, levels and sizes multiply: a 4096 x 4096 grid is the ceiling +SOCKET_TYPES = {"Geometry": "NodeSocketGeometry", "Float": "NodeSocketFloat", "Int": "NodeSocketInt", + "Bool": "NodeSocketBool", "Vector": "NodeSocketVector"} +IN_OUT = {"INPUT", "OUTPUT"} +# Node properties that are not node settings, or that make a node reach outside the tree. +NODE_PROPERTY_DENIED = frozenset({"name", "label", "location", "width", "height", "parent", "node_tree", "select", + "mute", "hide", "show_options", "show_preview", "show_texture", "use_custom_color", + "color", "bl_idname", "bl_label", "bl_description", "bl_icon", "bl_static_type", + "bl_width_default", "bl_width_min", "bl_width_max", "bl_height_default", + "bl_height_min", "bl_height_max", "rna_type", "type", "internal_links"}) +SETTABLE_PROPERTY_TYPES = ("ENUM", "BOOLEAN", "INT", "FLOAT") + + +def text(command: dict[str, Any], key: str, pattern: re.Pattern, label: str, *, required: bool = True) -> str: + value = command.get(key) + if value is None or value == "": + if required: + raise ActionRefused(f"{label} is required.") + return "" + if not isinstance(value, str) or not pattern.fullmatch(value): + raise ActionRefused(f"{label} must be 1..63 characters of letters, digits, space, '.', '_' or '-'.") + return value + + +def tree_key(command: dict[str, Any]) -> str: + kind = command.get("treeKind", "geometry") + if kind != "geometry": + raise ActionRefused(f"treeKind {kind!r} is not supported; only 'geometry'.") + return text(command, "treeKey", KEY_PATTERN, "treeKey") + + +def finite(value: Any, label: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or abs(value) > MAX_VALUE: + raise ActionRefused(f"{label} must be a finite number within +-{MAX_VALUE:g}.") + return float(value) + + +def typed_value(value: Any, kind: str, label: str) -> Any: + """A value for a socket of `kind` (Blender's socket.type, or the interface type's tail), or ActionRefused.""" + if kind in ("VALUE", "FLOAT", "Float"): + return finite(value, label) + if kind in ("INT", "Int"): + number = finite(value, label) + if number != int(number) or abs(number) > MAX_INT: + raise ActionRefused(f"{label} must be a whole number within +-{MAX_INT}.") + return int(number) + if kind in ("BOOLEAN", "Bool"): + if not isinstance(value, bool): + raise ActionRefused(f"{label} must be true or false.") + return value + if kind in ("VECTOR", "Vector", "RGBA"): + size = 4 if kind == "RGBA" else 3 + if not isinstance(value, (list, tuple)) or len(value) != size: + raise ActionRefused(f"{label} must be exactly {size} numbers.") + return tuple(finite(part, f"{label}[{i}]") for i, part in enumerate(value)) + raise ActionRefused(f"{label}: socket type {kind} cannot be set by an intent.") + + +def check_idname(idname: Any) -> str: + if not isinstance(idname, str) or not NODE_IDNAME.fullmatch(idname): + raise ActionRefused("blIdname must be a GeometryNode*, FunctionNode* or ShaderNode* type.") + for denied in NODE_DENIED: + if denied in idname: + raise ActionRefused(f"node type {idname} is not allowed in this cut ({denied}).") + return idname + + +def check_interface(items: Any) -> list[dict[str, str]]: + if not isinstance(items, list) or not items or len(items) > MAX_INTERFACE: + raise ActionRefused(f"interface must be a list of 1..{MAX_INTERFACE} sockets.") + seen: set[tuple[str, str]] = set() + result = [] + for i, item in enumerate(items): + if not isinstance(item, dict): + raise ActionRefused(f"interface[{i}] must be an object.") + in_out = str(item.get("inOut", "")).upper() + name = item.get("name") + socket_type = item.get("type") + if in_out not in IN_OUT or not isinstance(name, str) or not name or len(name) > 63 or socket_type not in SOCKET_TYPES: + raise ActionRefused(f"interface[{i}] needs inOut INPUT|OUTPUT, a name and a type of {sorted(SOCKET_TYPES)}.") + if (in_out, name) in seen: + raise ActionRefused(f"interface[{i}] repeats {in_out} socket {name!r}.") + seen.add((in_out, name)) + entry = {"inOut": in_out, "name": name, "type": socket_type} + if "default" in item: + entry["default"] = typed_value(item["default"], socket_type, f"interface[{i}].default") + result.append(entry) + return result + + +class NodeActions: + """Applies the node-graph actions to a bpy module. Stateless: every lookup goes to bpy.data.""" + + ACTIONS = ("createNodeGroup", "addNode", "removeNode", "linkSockets", "unlinkSockets", "addModifier", "removeModifier", "setModifierInput") + + def __init__(self, bpy_module: Any): + self.bpy = bpy_module + + def execute(self, action: str, command: dict[str, Any]) -> tuple[str, str]: + return getattr(self, "_" + action)(command) + + # tree and node lookup + def _tree(self, key: str) -> Any: + tree = self.bpy.data.node_groups.get(key) + if tree is None: + raise ActionRefused(f"Node group {key!r} does not exist; createNodeGroup first.") + if tree.bl_idname != "GeometryNodeTree": + raise ActionRefused(f"Node group {key!r} is not a geometry node group.") + if getattr(tree, "library", None): + raise ActionRefused(f"Node group {key!r} is linked from a library and read-only.") + return tree + + @staticmethod + def _node(tree: Any, node_id: str) -> Any: + for node in tree.nodes: + if node.get("brokkr_id") == node_id: + return node + raise ActionRefused(f"Node {node_id!r} does not exist in {tree.name!r}.") + + @staticmethod + def _socket(sockets: Any, key: str, label: str) -> Any: + """A socket of a node by identifier, else by display name when exactly one available socket has it.""" + usable = [s for s in sockets if s.identifier and getattr(s, "enabled", True)] + for socket in usable: + if socket.identifier == key: + return socket + named = [s for s in usable if s.name == key] + if len(named) == 1: + return named[0] + raise ActionRefused(f"{label}: socket {key!r} " + ("is ambiguous by name; use its identifier." if named else "was not found.")) + + # actions + def _createNodeGroup(self, command: dict[str, Any]) -> tuple[str, str]: + key = tree_key(command) + interface = check_interface(command.get("interface")) + existing = self.bpy.data.node_groups.get(key) + if existing is not None: + raise ActionRefused(f"Node group {key!r} already exists.") + tree = self.bpy.data.node_groups.new(key, "GeometryNodeTree") + try: + made = [] + for entry in interface: + socket = tree.interface.new_socket(entry["name"], in_out=entry["inOut"], socket_type=SOCKET_TYPES[entry["type"]]) + if "default" in entry: + socket.default_value = entry["default"] + made.append(f"{entry['inOut'].lower()} {entry['name']}={socket.identifier}") + for node_id, idname in (("gin", "NodeGroupInput"), ("gout", "NodeGroupOutput")): + node = tree.nodes.new(idname) + node["brokkr_id"] = node_id + except Exception: + self.bpy.data.node_groups.remove(tree) + raise + return "Created node group; interface identifiers: " + ", ".join(made), tree.name + + def _addNode(self, command: dict[str, Any]) -> tuple[str, str]: + tree = self._tree(tree_key(command)) + node_id = text(command, "id", ID_PATTERN, "id") + idname = check_idname(command.get("blIdname")) + location = command.get("location", [0, 0]) + if not isinstance(location, (list, tuple)) or len(location) != 2: + raise ActionRefused("location must be two numbers.") + location = [finite(part, "location") for part in location] + properties = command.get("properties") or {} + inputs = command.get("inputs") or {} + if not isinstance(properties, dict) or not isinstance(inputs, dict): + raise ActionRefused("properties and inputs must be objects.") + if any(n.get("brokkr_id") == node_id for n in tree.nodes): + raise ActionRefused(f"Node id {node_id!r} already exists in {tree.name!r}.") + if len(tree.nodes) >= MAX_NODES: + raise ActionRefused(f"Node group {tree.name!r} already has {MAX_NODES} nodes.") + try: + node = tree.nodes.new(idname) + except RuntimeError as error: + raise ActionRefused(f"Blender does not offer node type {idname}: {error}") from None + try: + node["brokkr_id"] = node_id + node.location = location + if command.get("label"): + node.label = str(command["label"])[:63] + for name, value in properties.items(): # node settings first: they decide which sockets exist + self._set_property(node, name, value) + for name, value in inputs.items(): + socket = self._socket(node.inputs, name, f"input {name!r}") + if socket.is_linked or not hasattr(socket, "default_value"): + raise ActionRefused(f"input {name!r} has no settable default.") + socket.default_value = typed_value(value, socket.type, f"input {name!r}") + except Exception: + tree.nodes.remove(node) + raise + return "Node added.", node_id + + def _set_property(self, node: Any, name: str, value: Any) -> None: + prop = node.bl_rna.properties.get(name) if isinstance(name, str) else None + if prop is None or prop.is_readonly or name in NODE_PROPERTY_DENIED or prop.type not in SETTABLE_PROPERTY_TYPES: + raise ActionRefused(f"{node.bl_idname} has no settable property {name!r}.") + if prop.type == "ENUM": + if not isinstance(value, str): + raise ActionRefused(f"property {name!r} needs an enum identifier.") + else: + value = typed_value(value, {"BOOLEAN": "BOOLEAN", "INT": "INT", "FLOAT": "FLOAT"}[prop.type], f"property {name!r}") + try: + setattr(node, name, value) + except (TypeError, ValueError) as error: + raise ActionRefused(f"property {name!r} cannot be {value!r}: {error}") from None + + def _removeNode(self, command: dict[str, Any]) -> tuple[str, str]: + tree = self._tree(tree_key(command)) + node_id = text(command, "id", ID_PATTERN, "id") + if node_id in ("gin", "gout"): + raise ActionRefused(f"{node_id!r} is the group's own input/output node and stays.") + node = next((n for n in tree.nodes if n.get("brokkr_id") == node_id), None) + if node is None: + return f"Node {node_id!r} was already absent.", node_id + tree.nodes.remove(node) # Blender drops the node's links with it + return "Node removed.", node_id + + def _unlinkSockets(self, command: dict[str, Any]) -> tuple[str, str]: + tree = self._tree(tree_key(command)) + target = self._node(tree, text(command, "toNode", ID_PATTERN, "toNode")) + into = self._socket(target.inputs, str(command.get("toSocket", "")), "toSocket") + source = out = None + if command.get("fromNode") or command.get("fromSocket"): + source = self._node(tree, text(command, "fromNode", ID_PATTERN, "fromNode")) + out = self._socket(source.outputs, str(command.get("fromSocket", "")), "fromSocket") + doomed = [l for l in tree.links if l.to_socket == into and (out is None or l.from_socket == out)] + for link in doomed: + tree.links.remove(link) + return f"Removed {len(doomed)} link(s).", tree.name + + def _linkSockets(self, command: dict[str, Any]) -> tuple[str, str]: + tree = self._tree(tree_key(command)) + source = self._node(tree, text(command, "fromNode", ID_PATTERN, "fromNode")) + target = self._node(tree, text(command, "toNode", ID_PATTERN, "toNode")) + out = self._socket(source.outputs, str(command.get("fromSocket", "")), "fromSocket") + into = self._socket(target.inputs, str(command.get("toSocket", "")), "toSocket") + if reaches(tree, target, source): # includes a self link + raise ActionRefused(f"Link {source.get('brokkr_id')} -> {target.get('brokkr_id')} would make a cycle.") + displaced = [(l.from_socket, l.is_muted) for l in tree.links if l.to_socket == into] if not getattr(into, "is_multi_input", False) else [] + link = tree.links.new(out, into) # replaces whatever single link the input had + if not link.is_valid: + tree.links.remove(link) + for old, muted in displaced: + tree.links.new(old, into).is_muted = muted + raise ActionRefused(f"Link {out.name} -> {into.name} is not valid (type or field/single-value mismatch).") + return f"Linked {source.get('brokkr_id')}.{out.identifier} -> {target.get('brokkr_id')}.{into.identifier}.", tree.name + + def _object(self, command: dict[str, Any]) -> Any: + name = command.get("objectName") or command.get("targetObjectName") + obj = self.bpy.data.objects.get(name) if name else None + if obj is None: + raise ActionRefused(f"Object {name!r} was not found.") + return obj + + def _addModifier(self, command: dict[str, Any]) -> tuple[str, str]: + obj = self._object(command) + kind = command.get("modifierType", "NODES") + if kind != "NODES": + raise ActionRefused("modifierType must be NODES; other modifiers are not part of this cut.") + tree = self._tree(tree_key(command)) + name = text(command, "modifierName", KEY_PATTERN, "modifierName", required=False) or "Brokkr GeoNodes" + modifier = obj.modifiers.get(name) + if modifier is not None and modifier.type != "NODES": + raise ActionRefused(f"{obj.name!r} already has a non-Geometry-Nodes modifier named {name!r}.") + if modifier is None: + if len(obj.modifiers) >= MAX_MODIFIERS: + raise ActionRefused(f"{obj.name!r} already has {MAX_MODIFIERS} modifiers.") + modifier = obj.modifiers.new(name, "NODES") + if modifier is None: + raise ActionRefused(f"{obj.name!r} is a {obj.type} object; it cannot take a Geometry Nodes modifier.") + modifier.node_group = tree + obj.update_tag() + return "Geometry Nodes modifier set.", obj.name + + def _removeModifier(self, command: dict[str, Any]) -> tuple[str, str]: + obj = self._object(command) + # A lookup, not a creation: a modifier made by hand may have any name Blender allows. + name = command.get("modifierName") or "Brokkr GeoNodes" + if not isinstance(name, str) or len(name) > 255 or "\0" in name: + raise ActionRefused("modifierName must be a string of at most 255 characters.") + modifier = obj.modifiers.get(name) + if modifier is None: + return f"Modifier {name!r} was already absent.", obj.name + if modifier.type != "NODES": + raise ActionRefused(f"{name!r} is not a Geometry Nodes modifier; only those are removed here.") + obj.modifiers.remove(modifier) + obj.update_tag() + return "Modifier removed.", obj.name + + def _setModifierInput(self, command: dict[str, Any]) -> tuple[str, str]: + obj = self._object(command) + modifier = obj.modifiers.get(str(command.get("modifierName") or "Brokkr GeoNodes")) + if modifier is None or modifier.type != "NODES" or modifier.node_group is None: + raise ActionRefused(f"{obj.name!r} has no Geometry Nodes modifier with a node group of that name.") + item = modifier_input(modifier.node_group, str(command.get("socket", ""))) + value = typed_value(command.get("value"), item.socket_type.replace("NodeSocket", ""), f"input {item.name!r}") + # modifier.properties.inputs[id] is a raw IDPropertyGroup on 5.2.3; attribute access reaches the struct. + getattr(modifier.properties.inputs, item.identifier).value = value + obj.update_tag() # without it a headless re-evaluation returned the previous result + return f"Modifier input {item.name} set.", obj.name + + +def node_key(node: Any) -> Any: + """A stable identity for a node: bpy hands out a fresh wrapper per access, so id() of one is reused by the next.""" + return node.as_pointer() if hasattr(node, "as_pointer") else id(node) + + +def reaches(tree: Any, start: Any, goal: Any) -> bool: + """True if following links forward from `start` arrives at `goal` (so a link goal -> start closes a cycle). + The adjacency is built once per call, so a call costs O(links).""" + forward: dict[Any, list[Any]] = {} + for link in tree.links: + forward.setdefault(node_key(link.from_node), []).append(link.to_node) + target = node_key(goal) + seen: set[Any] = set() + stack = [start] + while stack: + node = stack.pop() + key = node_key(node) + if key == target: + return True + if key in seen: + continue + seen.add(key) + stack.extend(forward.get(key, ())) + return False + + +def modifier_input(tree: Any, key: str) -> Any: + """An INPUT socket of a group's interface, by identifier or by its unique name.""" + items = [i for i in tree.interface.items_tree if i.item_type == "SOCKET" and i.in_out == "INPUT"] + for item in items: + if item.identifier == key: + return item + named = [i for i in items if i.name == key] + if len(named) == 1: + return named[0] + raise ActionRefused(f"Interface input {key!r} " + ("is ambiguous by name; use its identifier." if named else "was not found.")) + + +def drives_modifier_input(obj: Any, property_name: str) -> str: + """The modifier whose group has an interface input with identifier property_name (Socket_N), else ''. + An object custom property never drives a modifier input, so only the modifier's own identifiers are + refused; a property that merely shares an input's display name is an ordinary custom property.""" + for modifier in obj.modifiers: + if modifier.type == "NODES" and modifier.node_group is not None: + for item in modifier.node_group.interface.items_tree: + if item.item_type == "SOCKET" and item.in_out == "INPUT" and property_name == item.identifier: + return modifier.name + return "" diff --git a/surfaces/blender/docs/node-actions.md b/surfaces/blender/docs/node-actions.md new file mode 100644 index 0000000..3458b95 --- /dev/null +++ b/surfaces/blender/docs/node-actions.md @@ -0,0 +1,39 @@ +# Geometry node graph actions + +Command intents (`brokkr.blender.command_intent.v0`) that build and drive a Geometry Nodes graph. +Owner: `brokkr_bridge/node_actions.py`; the target only dispatches. Every field is validated before +`bpy` is touched; a refused intent is a `failed` receipt naming the rule and leaves the tree as it was. +Design and the parts not built yet: the design document lives in PR #3 (branch `libby/blender-node-graphs-design`), not in this tree. + +| action | fields | rule | +|---|---|---| +| `createNodeGroup` | `treeKey`, `interface` `[{inOut, name, type, default?}]` | New geometry node group with `gin` and `gout` nodes. Types: Geometry, Float, Int, Bool, Vector. Refuses an existing group. The receipt lists the interface identifiers (`Socket_N`). | +| `addNode` | `treeKey`, `id`, `blIdname`, `location?`, `label?`, `properties?`, `inputs?` | `id` is Brokkr's key (stored as the node's `brokkr_id`). Type must be a `GeometryNode*`, `FunctionNode*` or `ShaderNode*` name that is not an importer, exporter, script, bake, group, zone, viewer or image-texture node. Properties are enum/bool/int/float node settings (set first, they decide which sockets exist); inputs are unlinked defaults (float, int, bool, vector, colour). At most 500 nodes per group. | +| `removeNode` | `treeKey`, `id` | Removes the node and its links. Absent id: accepted. `gin` and `gout` stay. | +| `linkSockets` | `treeKey`, `fromNode`, `fromSocket`, `toNode`, `toSocket` | Sockets by identifier, or by display name when exactly one available socket has it (Group Input/Output sockets are addressed by interface name). A link Blender calls invalid (field into a single value, type mismatch) is removed and refused, and the single link it displaced is put back. A valid link into a single-link input replaces the old one (Blender's behaviour); a link that would close a cycle, or link a node to itself, is refused before Blender is asked. | +| `unlinkSockets` | `treeKey`, `toNode`, `toSocket`, `fromNode?`, `fromSocket?` | Removes the links into an input, or only the one from the given source. None to remove: accepted. | +| `addModifier` | `objectName`, `treeKey`, `modifierName?` (default `Brokkr GeoNodes`) | `NODES` only. Reuses a modifier of that name; at most 8 per object. | +| `removeModifier` | `objectName`, `modifierName?` | Geometry Nodes modifiers only (a Subdivision or other modifier is refused). Absent: accepted. | +| `setModifierInput` | `objectName`, `modifierName?`, `socket` (identifier or unique interface name), `value` | Float, Int, Bool, Vector inputs. Written as `getattr(modifier.properties.inputs, id).value = v` (indexing `inputs[id]` yields a raw ID property group without `.value` on 5.2.3), then `object.update_tag()`. | + +`setObjectCustomProperty` refuses a property whose name is the identifier (`Socket_N`) of an input of a Geometry +Nodes modifier on that object; a custom property never drives a modifier input. A name that only equals an +input's display name is an ordinary custom property. + +The host snapshot's object entries carry `evaluated` for mesh objects with modifiers: vertex, edge and +polygon counts, `instanceCount`, and up to 256 vertex and instance locations (`truncated` when cut). Vertex +positions and `vertexBounds*` are in the object's local space; instance locations and `instanceBounds*` are +world space. Above 1,000,000 vertices only counts are read (`positionsSkipped`); a non-finite coordinate sets +`nonFinite` and drops the positions and bounds. The instances come from one depsgraph scan per capture. +`instancesComplete` is false when the depsgraph scan stopped at 100,000 items (`instanceCount` and the instance bounds are then lower bounds); the scan is what costs time (about 5 microseconds per instance in Python), so a 2000 x 2000 grid instanced on points captures in 1.4 s on the test machine where an unbounded scan took 22 s. `instanceCount` is `null` for an object the stopped scan never reached (unknown, not zero); the 100,000 budget is shared across all objects in depsgraph order, so a host after a heavy one can be starved. Otherwise `instanceCount` counts evaluated instances whose parent is the object, so a curve, point or volume result +also reads as one instance. `mesh` stays the base mesh. + +Known edges: a node duplicated by hand copies its `brokkr_id`, so id lookups act on the first match; `gin`/`gout` are protected by id, and a group whose output node was deleted by hand cannot get a new one through `addNode`; removing a group's last modifier does not delete the group (it may stay in the file until it is saved and reloaded; `addModifier` can reuse it); `removeModifier` takes any modifier name Blender allows because it only looks the modifier up. + +Not built: zones, item sockets, multi-input ordering, library groups, group-in-group nodes, batches/rollback across +intents, an expectedRevision check, per-node cost estimates. Int values are capped at +-4096 and floats at +-1e9, +which bounds a request but not the cost of a graph: Blender evaluates what it is given, and the snapshot evaluates +every mesh with modifiers on each capture (mesh grids measured: 16.7M vertices evaluate and read in 0.4 s). +`addModifier` refuses object types that take no modifiers. + +Live proof: `tests/live/gn_actions.py` (Blender 5.2.3, headless). Unit tests: `tests/test_node_actions.py`. diff --git a/surfaces/blender/tests/live/gn_actions.py b/surfaces/blender/tests/live/gn_actions.py new file mode 100644 index 0000000..1d9e329 --- /dev/null +++ b/surfaces/blender/tests/live/gn_actions.py @@ -0,0 +1,269 @@ +"""Live proof of the node-graph actions: rebuild three geometry-node setups through Brokkr actions only. + + BROKKR_ADDON= \ + blender -b --factory-startup --python gn_actions.py -- result.json + +Each native tree is built with bpy as the reference and evaluated with the depsgraph. The Brokkr side +uses BrokkrBlenderTarget.execute_command for every build step and capture_snapshot().objects[].evaluated +for every read: no bpy call touches the Brokkr-built scene except the harness's own reference trees. +Exit status is non-zero if any check fails. +""" +import bpy, sys, os, json, types, math +from pathlib import Path + +ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() +pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)] +sys.modules["brokkr_bridge"] = pkg +from brokkr_bridge import blender_target as bt + +out = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else "gn_actions_result.json" +R = {"blender": bpy.app.version_string, "checks": []} + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}); print("CHECK", "ok " if ok else "FAIL", name, detail if not ok else "", flush=True) + +def fresh(): + bpy.ops.wm.read_factory_settings(use_empty=True) + return bt.BrokkrBlenderTarget(bpy) + +N = [0] +def act(t, **cmd): + N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]) + r = t.execute_command(bpy.context, cmd) + if r["status"] != "accepted": print("REFUSED", cmd["action"], r["message"], flush=True) + return r + +def ok(t, **cmd): + r = act(t, **cmd); check("%s %s" % (cmd["action"], cmd.get("id") or cmd.get("treeKey") or cmd.get("objectName") or ""), r["status"] == "accepted", r["message"]); return r + +def evaluated(t, name): + snap = t.capture_snapshot(bpy.context) + return [o for o in snap["objects"] if o["name"] == name][0]["evaluated"] + +def native_tree(build): + g = bpy.data.node_groups.new("native", "GeometryNodeTree") + g.interface.new_socket("Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry") + gout = g.nodes.new("NodeGroupOutput"); build(g, gout) + me = bpy.data.meshes.new("nm"); ob = bpy.data.objects.new("native_host", me); bpy.context.scene.collection.objects.link(ob) + ob.modifiers.new("GN", "NODES").node_group = g + dg = bpy.context.evaluated_depsgraph_get(); dg.update() + ev = ob.evaluated_get(dg); m = ev.to_mesh() + verts = sorted(tuple(round(c, 5) for c in v.co) for v in m.vertices); ev.to_mesh_clear() + inst = sorted(tuple(round(c, 5) for c in i.matrix_world.translation) for i in dg.object_instances if i.is_instance) + bpy.data.objects.remove(ob); bpy.data.node_groups.remove(g); bpy.data.meshes.remove(me) + return verts, inst + +def srt(rows): return sorted(tuple(r) for r in rows) + +def host(t, name, tree, mod="GN"): + ok(t, action="createObject", objectType="MESH", name=name) + ok(t, action="addModifier", objectName=name, modifierName=mod, treeKey=tree) + +def graph(t, tree, interface, nodes, links): + ok(t, action="createNodeGroup", treeKey=tree, interface=interface) + for n in nodes: ok(t, action="addNode", treeKey=tree, **n) + for a, b, c, d in links: ok(t, action="linkSockets", treeKey=tree, fromNode=a, fromSocket=b, toNode=c, toSocket=d) + +GEO_OUT = [{"inOut": "OUTPUT", "name": "Geometry", "type": "Geometry"}] + +# ---- 1. ring of instances +def ring(g, gout): + c = g.nodes.new("GeometryNodeMeshCircle"); c.inputs["Vertices"].default_value = 8; c.inputs["Radius"].default_value = 2.0 + cu = g.nodes.new("GeometryNodeMeshCube"); cu.inputs["Size"].default_value = (0.3, 0.3, 0.3) + i = g.nodes.new("GeometryNodeInstanceOnPoints") + g.links.new(c.outputs["Mesh"], i.inputs["Points"]); g.links.new(cu.outputs["Mesh"], i.inputs["Instance"]); g.links.new(i.outputs["Instances"], gout.inputs["Geometry"]) +nv, ni = native_tree(ring) +t = fresh(); N[0] = 0 +graph(t, "Ring", GEO_OUT, + [dict(id="circle", blIdname="GeometryNodeMeshCircle", inputs={"Vertices": 8, "Radius": 2.0}), + dict(id="cube", blIdname="GeometryNodeMeshCube", inputs={"Size": [0.3, 0.3, 0.3]}), + dict(id="iop", blIdname="GeometryNodeInstanceOnPoints")], + [("circle", "Mesh", "iop", "Points"), ("cube", "Mesh", "iop", "Instance"), ("iop", "Instances", "gout", "Geometry")]) +host(t, "RingHost", "Ring") +ev = evaluated(t, "RingHost") +check("ring instances equal native", srt(ev["instanceLocations"]) == ni and ev["instanceCount"] == 8, {"brokkr": ev["instanceLocations"], "native": ni}) +# parameter change by setModifierInput on an exposed input: rebuild with an exposed Count +t = fresh() +graph(t, "RingN", GEO_OUT + [{"inOut": "INPUT", "name": "Count", "type": "Int", "default": 8}], + [dict(id="circle", blIdname="GeometryNodeMeshCircle", inputs={"Radius": 2.0}), + dict(id="cube", blIdname="GeometryNodeMeshCube"), dict(id="iop", blIdname="GeometryNodeInstanceOnPoints")], + [("gin", "Count", "circle", "Vertices"), ("circle", "Mesh", "iop", "Points"), ("cube", "Mesh", "iop", "Instance"), ("iop", "Instances", "gout", "Geometry")]) +host(t, "RingHost", "RingN") +before = evaluated(t, "RingHost")["instanceCount"] +ok(t, action="setModifierInput", objectName="RingHost", modifierName="GN", socket="Count", value=12) +after = evaluated(t, "RingHost")["instanceCount"] +check("setModifierInput changes evaluated instances", (before, after) == (8, 12), (before, after)) +r = act(t, action="setObjectCustomProperty", targetObjectName="RingHost", propertyName="Socket_1", value=3) +check("custom property naming a modifier input identifier is refused", r["status"] == "failed" and "setModifierInput" in r["message"], r["message"]) +check("refused custom property changed nothing", evaluated(t, "RingHost")["instanceCount"] == 12) +r = act(t, action="setObjectCustomProperty", targetObjectName="RingHost", propertyName="Count", value=3) +check("a custom property sharing only a display name is ordinary", r["status"] == "accepted", r["message"]) + +# ---- 2. boundary step +B = 0.5 +def boundary(g, gout): + ln = g.nodes.new("GeometryNodeMeshLine"); ln.inputs["Count"].default_value = 3; ln.inputs["Offset"].default_value = (2, 0, 0) + pos = g.nodes.new("GeometryNodeInputPosition") + d = g.nodes.new("ShaderNodeVectorMath"); d.operation = "LENGTH" + c = g.nodes.new("FunctionNodeCompare"); c.data_type = "FLOAT"; c.operation = "GREATER_THAN"; c.inputs["B"].default_value = B + nm = g.nodes.new("ShaderNodeVectorMath"); nm.operation = "NORMALIZE" + sc = g.nodes.new("ShaderNodeVectorMath"); sc.operation = "SCALE"; sc.inputs["Scale"].default_value = B + sp = g.nodes.new("GeometryNodeSetPosition") + g.links.new(pos.outputs[0], d.inputs[0]); g.links.new(d.outputs["Value"], c.inputs["A"]); g.links.new(pos.outputs[0], nm.inputs[0]); g.links.new(nm.outputs[0], sc.inputs[0]) + g.links.new(ln.outputs["Mesh"], sp.inputs["Geometry"]); g.links.new(c.outputs["Result"], sp.inputs["Selection"]); g.links.new(sc.outputs[0], sp.inputs["Position"]); g.links.new(sp.outputs["Geometry"], gout.inputs["Geometry"]) +nv, ni = native_tree(boundary) +t = fresh() +graph(t, "Boundary", GEO_OUT, + [dict(id="line", blIdname="GeometryNodeMeshLine", inputs={"Count": 3, "Offset": [2, 0, 0]}), + dict(id="pos", blIdname="GeometryNodeInputPosition"), + dict(id="len", blIdname="ShaderNodeVectorMath", properties={"operation": "LENGTH"}), + dict(id="gt", blIdname="FunctionNodeCompare", properties={"data_type": "FLOAT", "operation": "GREATER_THAN"}, inputs={"B": B}), + dict(id="nrm", blIdname="ShaderNodeVectorMath", properties={"operation": "NORMALIZE"}), + dict(id="edge", blIdname="ShaderNodeVectorMath", properties={"operation": "SCALE"}, inputs={"Scale": B}), + dict(id="set", blIdname="GeometryNodeSetPosition")], + [("pos", "Position", "len", "Vector"), ("len", "Value", "gt", "A"), ("pos", "Position", "nrm", "Vector"), ("nrm", "Vector", "edge", "Vector"), + ("line", "Mesh", "set", "Geometry"), ("gt", "Result", "set", "Selection"), ("edge", "Vector", "set", "Position"), ("set", "Geometry", "gout", "Geometry")]) +host(t, "BoundaryHost", "Boundary") +ev = evaluated(t, "BoundaryHost") +check("boundary_step vertices equal native", srt(ev["vertexLocations"]) == nv, {"brokkr": ev["vertexLocations"], "native": nv}) + +# ---- 3. seeded scatter +def scatter(g, gout): + gr = g.nodes.new("GeometryNodeMeshGrid"); gr.inputs["Size X"].default_value = 3; gr.inputs["Size Y"].default_value = 3 + di = g.nodes.new("GeometryNodeDistributePointsOnFaces"); di.distribute_method = "RANDOM"; di.inputs["Density"].default_value = 4; di.inputs["Seed"].default_value = 7 + co = g.nodes.new("GeometryNodeMeshCone"); co.inputs["Radius Bottom"].default_value = 0.05; co.inputs["Depth"].default_value = 0.4 + i = g.nodes.new("GeometryNodeInstanceOnPoints") + g.links.new(gr.outputs["Mesh"], di.inputs["Mesh"]); g.links.new(di.outputs["Points"], i.inputs["Points"]); g.links.new(co.outputs["Mesh"], i.inputs["Instance"]); g.links.new(i.outputs["Instances"], gout.inputs["Geometry"]) +nv, ni = native_tree(scatter) +t = fresh() +graph(t, "Scatter", GEO_OUT + [{"inOut": "INPUT", "name": "Seed", "type": "Int", "default": 7}], + [dict(id="grid", blIdname="GeometryNodeMeshGrid", inputs={"Size X": 3, "Size Y": 3}), + dict(id="dist", blIdname="GeometryNodeDistributePointsOnFaces", properties={"distribute_method": "RANDOM"}, inputs={"Density": 4, "Seed": 7}), + dict(id="cone", blIdname="GeometryNodeMeshCone", inputs={"Radius Bottom": 0.05, "Depth": 0.4}), + dict(id="iop", blIdname="GeometryNodeInstanceOnPoints")], + [("grid", "Mesh", "dist", "Mesh"), ("dist", "Points", "iop", "Points"), ("cone", "Mesh", "iop", "Instance"), ("iop", "Instances", "gout", "Geometry")]) +host(t, "ScatterHost", "Scatter") +ev = evaluated(t, "ScatterHost") +check("scatter instances equal native", srt(ev["instanceLocations"]) == ni and ev["instanceCount"] == len(ni), {"brokkr": ev["instanceCount"], "native": len(ni)}) +ok(t, action="setModifierInput", objectName="ScatterHost", modifierName="GN", socket="Seed", value=7) # exposed but unwired: no effect +check("unwired exposed input leaves result", srt(evaluated(t, "ScatterHost")["instanceLocations"]) == ni) + +# ---- refusals on the real API +r = act(t, action="addNode", treeKey="Scatter", id="bad", blIdname="GeometryNodeMeshCube", inputs={"Nope": 1}); check("unknown input refused", r["status"] == "failed", r["message"]) +check("refused addNode left no node", not any(n.get("brokkr_id") == "bad" for n in bpy.data.node_groups["Scatter"].nodes)) +r = act(t, action="addNode", treeKey="Scatter", id="bad2", blIdname="GeometryNodeMeshCube", properties={"nope": 1}); check("unknown property refused", r["status"] == "failed", r["message"]) +r = act(t, action="addNode", treeKey="Scatter", id="bad3", blIdname="GeometryNodeImportOBJ"); check("file-reading node refused", r["status"] == "failed", r["message"]) +r = act(t, action="addNode", treeKey="Scatter", id="bad4", blIdname="GeometryNodeNoSuchThing"); check("unknown node type refused", r["status"] == "failed", r["message"]) +r = act(t, action="linkSockets", treeKey="Scatter", fromNode="cone", fromSocket="Mesh", toNode="dist", toSocket="Density"); check("invalid link refused and removed", r["status"] == "failed" and not any(l.to_socket.name == "Density" for l in bpy.data.node_groups["Scatter"].links), r["message"]) +r = act(t, action="setModifierInput", objectName="ScatterHost", modifierName="GN", socket="Seed", value="x"); check("wrong value type refused", r["status"] == "failed", r["message"]) +r = act(t, action="addNode", treeKey="Scatter", id="grid", blIdname="GeometryNodeMeshCube"); check("duplicate id refused", r["status"] == "failed", r["message"]) + +t2 = fresh() +graph(t2, "L", GEO_OUT, [dict(id="cube", blIdname="GeometryNodeMeshCube"), dict(id="m", blIdname="ShaderNodeMath"), dict(id="iop", blIdname="GeometryNodeInstanceOnPoints")], + [("cube", "Mesh", "iop", "Points")]) +before = [(l.from_node.get("brokkr_id"), l.to_socket.identifier) for l in bpy.data.node_groups["L"].links if l.to_node.get("brokkr_id") == "iop"] +r = act(t2, action="linkSockets", treeKey="L", fromNode="m", fromSocket="Value", toNode="iop", toSocket="Points") +after = [(l.from_node.get("brokkr_id"), l.to_socket.identifier) for l in bpy.data.node_groups["L"].links if l.to_node.get("brokkr_id") == "iop"] +check("refused link keeps the link it would have replaced", r["status"] == "failed" and before == after == [("cube", "Points")], (r["message"], before, after)) +ok(t2, action="createObject", objectType="CAMERA", name="Cam") +r = act(t2, action="addModifier", objectName="Cam", treeKey="L"); check("modifier on a camera refused clearly", r["status"] == "failed" and "CAMERA" in r["message"], r["message"]) +r = act(t2, action="addNode", treeKey="L", id="n\n", blIdname="ShaderNodeMath"); check("trailing newline in an id refused", r["status"] == "failed", r["message"]) +# off-origin host: vertices are local, instances world, bounds kept apart +t3 = fresh() +graph(t3, "Off", GEO_OUT, [dict(id="circle", blIdname="GeometryNodeMeshCircle", inputs={"Vertices": 4, "Radius": 1.0}), dict(id="cube", blIdname="GeometryNodeMeshCube"), dict(id="iop", blIdname="GeometryNodeInstanceOnPoints"), dict(id="join", blIdname="GeometryNodeJoinGeometry")], + [("circle", "Mesh", "iop", "Points"), ("cube", "Mesh", "iop", "Instance"), ("iop", "Instances", "join", "Geometry"), ("circle", "Mesh", "join", "Geometry"), ("join", "Geometry", "gout", "Geometry")]) +ok(t3, action="createObject", objectType="MESH", name="OffHost", location=[100, 0, 0]); ok(t3, action="addModifier", objectName="OffHost", modifierName="GN", treeKey="Off") +ev = evaluated(t3, "OffHost") +check("local vertex bounds and world instance bounds are separate", max(ev["vertexBoundsMax"]) <= 1.01 and ev["instanceBoundsMin"][0] >= 98.9 and ev["instanceCount"] == 4, ev) +# non-finite positions are flagged +ok(t3, action="createNodeGroup", treeKey="Inf", interface=GEO_OUT) +for i in range(6): ok(t3, action="addNode", treeKey="Inf", id="s%d" % i, blIdname="ShaderNodeVectorMath", properties={"operation": "SCALE"}, inputs={"Scale": 1e9, "Vector": [1, 1, 1]}) if i == 0 else ok(t3, action="addNode", treeKey="Inf", id="s%d" % i, blIdname="ShaderNodeVectorMath", properties={"operation": "SCALE"}, inputs={"Scale": 1e9}) +ok(t3, action="addNode", treeKey="Inf", id="cube", blIdname="GeometryNodeMeshCube"); ok(t3, action="addNode", treeKey="Inf", id="set", blIdname="GeometryNodeSetPosition") +for i in range(1, 6): ok(t3, action="linkSockets", treeKey="Inf", fromNode="s%d" % (i - 1), fromSocket="Vector", toNode="s%d" % i, toSocket="Vector") +ok(t3, action="linkSockets", treeKey="Inf", fromNode="cube", fromSocket="Mesh", toNode="set", toSocket="Geometry"); ok(t3, action="linkSockets", treeKey="Inf", fromNode="s5", fromSocket="Vector", toNode="set", toSocket="Position"); ok(t3, action="linkSockets", treeKey="Inf", fromNode="set", fromSocket="Geometry", toNode="gout", toSocket="Geometry") +ok(t3, action="createObject", objectType="MESH", name="InfHost"); ok(t3, action="addModifier", objectName="InfHost", treeKey="Inf") +ev = evaluated(t3, "InfHost") +check("non-finite evaluated positions are flagged and not published", ev["nonFinite"] and ev["vertexLocations"] == [] and json.dumps(ev, allow_nan=False), ev) + + +# ---- removal, unlinking, cycles (cut 2) +import time +t4 = fresh() +graph(t4, "R", GEO_OUT + [{"inOut": "INPUT", "name": "Count", "type": "Int", "default": 4}], + [dict(id="circle", blIdname="GeometryNodeMeshCircle", inputs={"Radius": 1.0}), dict(id="cube", blIdname="GeometryNodeMeshCube"), dict(id="iop", blIdname="GeometryNodeInstanceOnPoints"), + dict(id="m1", blIdname="ShaderNodeMath"), dict(id="m2", blIdname="ShaderNodeMath")], + [("gin", "Count", "circle", "Vertices"), ("circle", "Mesh", "iop", "Points"), ("cube", "Mesh", "iop", "Instance"), ("iop", "Instances", "gout", "Geometry"), ("m1", "Value", "m2", "Value")]) +host(t4, "RHost", "R") +check("graph evaluates before removal", evaluated(t4, "RHost")["instanceCount"] == 4) +for src, dst in (("m2", "m1"), ("m1", "m1")): + r = act(t4, action="linkSockets", treeKey="R", fromNode=src, fromSocket="Value", toNode=dst, toSocket="Value_001"); check("cycle %s->%s refused" % (src, dst), r["status"] == "failed" and "cycle" in r["message"], r["message"]) +check("refused cycle left the link set alone", len(bpy.data.node_groups["R"].links) == 5) +r = ok(t4, action="unlinkSockets", treeKey="R", fromNode="m1", fromSocket="Value", toNode="m2", toSocket="Value") +check("unlinked exactly one link", len(bpy.data.node_groups["R"].links) == 4, r["message"]) +r = ok(t4, action="unlinkSockets", treeKey="R", toNode="m2", toSocket="Value"); check("unlink of nothing is accepted", "Removed 0" in r["message"], r["message"]) +ok(t4, action="unlinkSockets", treeKey="R", toNode="iop", toSocket="Instance") +check("unlinking the instance changes the result", evaluated(t4, "RHost")["instanceCount"] == 0, evaluated(t4, "RHost")) +ok(t4, action="linkSockets", treeKey="R", fromNode="cube", fromSocket="Mesh", toNode="iop", toSocket="Instance") +check("relinked", evaluated(t4, "RHost")["instanceCount"] == 4) +links_before = len(bpy.data.node_groups["R"].links) +ok(t4, action="removeNode", treeKey="R", id="cube") +check("removeNode drops the node and its links", not any(n.get("brokkr_id") == "cube" for n in bpy.data.node_groups["R"].nodes) and len(bpy.data.node_groups["R"].links) == links_before - 1) +r = act(t4, action="removeNode", treeKey="R", id="gout"); check("group output node stays", r["status"] == "failed", r["message"]) +check("removeNode of an absent id is accepted", act(t4, action="removeNode", treeKey="R", id="cube")["status"] == "accepted") +ok(t4, action="removeModifier", objectName="RHost", modifierName="GN") +check("removeModifier removes it; evaluated block gone", len(bpy.data.objects["RHost"].modifiers) == 0 and evaluated(t4, "RHost") is None) +bpy.data.objects["RHost"].modifiers.new("Sub", "SUBSURF") +r = act(t4, action="removeModifier", objectName="RHost", modifierName="Sub"); check("non-Geometry-Nodes modifier is not removed", r["status"] == "failed" and len(bpy.data.objects["RHost"].modifiers) == 1, r["message"]) + + +# ---- cycle detection on a long chain (bpy hands out a fresh wrapper per access; id() would be reused) +t5 = fresh() +ok(t5, action="createNodeGroup", treeKey="C", interface=GEO_OUT) +ids = ["c%d" % i for i in range(60)] +for i in ids: act(t5, action="addNode", treeKey="C", id=i, blIdname="ShaderNodeMath") +for a_, b_ in zip(ids, ids[1:]): act(t5, action="linkSockets", treeKey="C", fromNode=a_, fromSocket="Value", toNode=b_, toSocket="Value") +for a_, b_ in zip(ids[:-2], ids[2:]): act(t5, action="linkSockets", treeKey="C", fromNode=a_, fromSocket="Value", toNode=b_, toSocket="Value_001") +before = len(bpy.data.node_groups["C"].links) +t0 = time.time() +refused = [act(t5, action="linkSockets", treeKey="C", fromNode=ids[-1], fromSocket="Value", toNode=h, toSocket="Value_002")["status"] == "failed" for h in ids[:-1]] +R["cycle_probe_seconds"] = round(time.time() - t0, 3) +check("every closing link on a 60-node chain with skip links is refused", all(refused) and len(bpy.data.node_groups["C"].links) == before, (sum(refused), len(refused), R["cycle_probe_seconds"])) + + +# ---- fix-pass checks: muted state survives a refused link; hand-made Unicode modifier names are removable +t6 = fresh() +graph(t6, "Mu", GEO_OUT, [dict(id="cube", blIdname="GeometryNodeMeshCube"), dict(id="m", blIdname="ShaderNodeMath"), dict(id="iop", blIdname="GeometryNodeInstanceOnPoints")], [("cube", "Mesh", "iop", "Points")]) +for l in bpy.data.node_groups["Mu"].links: + if l.to_node.get("brokkr_id") == "iop": l.is_muted = True +r = act(t6, action="linkSockets", treeKey="Mu", fromNode="m", fromSocket="Value", toNode="iop", toSocket="Points") +muted = [l.is_muted for l in bpy.data.node_groups["Mu"].links if l.to_node.get("brokkr_id") == "iop"] +check("refused link restores the displaced link's muted state", r["status"] == "failed" and muted == [True], (r["message"], muted)) +ok(t6, action="createObject", objectType="MESH", name="U") +bpy.data.objects["U"].modifiers.new("G\u00e9 x", "NODES") +r = act(t6, action="removeModifier", objectName="U", modifierName="G\u00e9 x") +check("hand-made Unicode modifier name is removable", r["status"] == "accepted" and len(bpy.data.objects["U"].modifiers) == 0, r["message"]) + +# ---- cost: a heavy graph must not stall capture +def heavy(n, instanced): + tt = fresh() + nodes = [dict(id="grid", blIdname="GeometryNodeMeshGrid", inputs={"Vertices X": n, "Vertices Y": n})] + links = [] + if instanced: + nodes += [dict(id="cube", blIdname="GeometryNodeMeshCube"), dict(id="iop", blIdname="GeometryNodeInstanceOnPoints")] + links = [("grid", "Mesh", "iop", "Points"), ("cube", "Mesh", "iop", "Instance"), ("iop", "Instances", "gout", "Geometry")] + else: + links = [("grid", "Mesh", "gout", "Geometry")] + graph(tt, "Heavy", GEO_OUT, nodes, links); host(tt, "HeavyHost", "Heavy") + t0 = time.time(); snap = tt.capture_snapshot(bpy.context); dt = time.time() - t0 + return dt, [o for o in snap["objects"] if o["name"] == "HeavyHost"][0]["evaluated"] +dt, ev = heavy(2000, True) +R["capture_2000_grid_instanced_seconds"] = round(dt, 3) +check("2000x2000 instanced grid: capture is bounded", dt < 3.0 and ev["instancesComplete"] is False and ev["instanceCount"] <= 100000, (round(dt, 2), ev["instanceCount"], ev["instancesComplete"])) +dt, ev = heavy(2000, False) +R["capture_2000_grid_mesh_seconds"] = round(dt, 3) +check("2000x2000 mesh grid: counts only, bounded", dt < 3.0 and ev["vertexCount"] == 4000000 and ev["positionsSkipped"], (round(dt, 2), ev["vertexCount"])) + +json.dump(R, open(out, "w"), indent=1, default=str) +bad = [c for c in R["checks"] if not c["ok"]] +print("DONE", len(R["checks"]), "checks,", len(bad), "failed") +sys.exit(1 if bad else 0) diff --git a/surfaces/blender/tests/live/gn_actions.result.json b/surfaces/blender/tests/live/gn_actions.result.json new file mode 100644 index 0000000..cdcc1f5 --- /dev/null +++ b/surfaces/blender/tests/live/gn_actions.result.json @@ -0,0 +1,1097 @@ +{ + "blender": "5.2.3 LTS", + "checks": [ + { + "name": "createNodeGroup Ring", + "ok": true, + "detail": "Created node group; interface identifiers: output Geometry=Socket_0" + }, + { + "name": "addNode circle", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode cube", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode iop", + "ok": true, + "detail": "Node added." + }, + { + "name": "linkSockets Ring", + "ok": true, + "detail": "Linked circle.Mesh -> iop.Points." + }, + { + "name": "linkSockets Ring", + "ok": true, + "detail": "Linked cube.Mesh -> iop.Instance." + }, + { + "name": "linkSockets Ring", + "ok": true, + "detail": "Linked iop.Instances -> gout.Socket_0." + }, + { + "name": "createObject ", + "ok": true, + "detail": "Blender object created." + }, + { + "name": "addModifier Ring", + "ok": true, + "detail": "Geometry Nodes modifier set." + }, + { + "name": "ring instances equal native", + "ok": true, + "detail": { + "brokkr": [ + [ + 2.0, + 0.0, + 0.0 + ], + [ + 1.41421, + 1.41421, + 0.0 + ], + [ + -0.0, + 2.0, + 0.0 + ], + [ + -1.41421, + 1.41421, + 0.0 + ], + [ + -2.0, + -0.0, + 0.0 + ], + [ + -1.41421, + -1.41421, + 0.0 + ], + [ + 0.0, + -2.0, + 0.0 + ], + [ + 1.41421, + -1.41421, + 0.0 + ] + ], + "native": [ + [ + -2.0, + -0.0, + 0.0 + ], + [ + -1.41421, + -1.41421, + 0.0 + ], + [ + -1.41421, + 1.41421, + 0.0 + ], + [ + 0.0, + -2.0, + 0.0 + ], + [ + -0.0, + 2.0, + 0.0 + ], + [ + 1.41421, + -1.41421, + 0.0 + ], + [ + 1.41421, + 1.41421, + 0.0 + ], + [ + 2.0, + 0.0, + 0.0 + ] + ] + } + }, + { + "name": "createNodeGroup RingN", + "ok": true, + "detail": "Created node group; interface identifiers: output Geometry=Socket_0, input Count=Socket_1" + }, + { + "name": "addNode circle", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode cube", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode iop", + "ok": true, + "detail": "Node added." + }, + { + "name": "linkSockets RingN", + "ok": true, + "detail": "Linked gin.Socket_1 -> circle.Vertices." + }, + { + "name": "linkSockets RingN", + "ok": true, + "detail": "Linked circle.Mesh -> iop.Points." + }, + { + "name": "linkSockets RingN", + "ok": true, + "detail": "Linked cube.Mesh -> iop.Instance." + }, + { + "name": "linkSockets RingN", + "ok": true, + "detail": "Linked iop.Instances -> gout.Socket_0." + }, + { + "name": "createObject ", + "ok": true, + "detail": "Blender object created." + }, + { + "name": "addModifier RingN", + "ok": true, + "detail": "Geometry Nodes modifier set." + }, + { + "name": "setModifierInput RingHost", + "ok": true, + "detail": "Modifier input Count set." + }, + { + "name": "setModifierInput changes evaluated instances", + "ok": true, + "detail": [ + 8, + 12 + ] + }, + { + "name": "custom property naming a modifier input identifier is refused", + "ok": true, + "detail": "'Socket_1' is an input of Geometry Nodes modifier 'GN'; a custom property does not drive it, use setModifierInput." + }, + { + "name": "refused custom property changed nothing", + "ok": true, + "detail": null + }, + { + "name": "a custom property sharing only a display name is ordinary", + "ok": true, + "detail": "Blender custom property updated." + }, + { + "name": "createNodeGroup Boundary", + "ok": true, + "detail": "Created node group; interface identifiers: output Geometry=Socket_0" + }, + { + "name": "addNode line", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode pos", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode len", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode gt", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode nrm", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode edge", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode set", + "ok": true, + "detail": "Node added." + }, + { + "name": "linkSockets Boundary", + "ok": true, + "detail": "Linked pos.Position -> len.Vector." + }, + { + "name": "linkSockets Boundary", + "ok": true, + "detail": "Linked len.Value -> gt.A." + }, + { + "name": "linkSockets Boundary", + "ok": true, + "detail": "Linked pos.Position -> nrm.Vector." + }, + { + "name": "linkSockets Boundary", + "ok": true, + "detail": "Linked nrm.Vector -> edge.Vector." + }, + { + "name": "linkSockets Boundary", + "ok": true, + "detail": "Linked line.Mesh -> set.Geometry." + }, + { + "name": "linkSockets Boundary", + "ok": true, + "detail": "Linked gt.Result -> set.Selection." + }, + { + "name": "linkSockets Boundary", + "ok": true, + "detail": "Linked edge.Vector -> set.Position." + }, + { + "name": "linkSockets Boundary", + "ok": true, + "detail": "Linked set.Geometry -> gout.Socket_0." + }, + { + "name": "createObject ", + "ok": true, + "detail": "Blender object created." + }, + { + "name": "addModifier Boundary", + "ok": true, + "detail": "Geometry Nodes modifier set." + }, + { + "name": "boundary_step vertices equal native", + "ok": true, + "detail": { + "brokkr": [ + [ + 0.0, + 0.0, + 0.0 + ], + [ + 0.5, + 0.0, + 0.0 + ], + [ + 0.5, + 0.0, + 0.0 + ] + ], + "native": [ + [ + 0.0, + 0.0, + 0.0 + ], + [ + 0.5, + 0.0, + 0.0 + ], + [ + 0.5, + 0.0, + 0.0 + ] + ] + } + }, + { + "name": "createNodeGroup Scatter", + "ok": true, + "detail": "Created node group; interface identifiers: output Geometry=Socket_0, input Seed=Socket_1" + }, + { + "name": "addNode grid", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode dist", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode cone", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode iop", + "ok": true, + "detail": "Node added." + }, + { + "name": "linkSockets Scatter", + "ok": true, + "detail": "Linked grid.Mesh -> dist.Mesh." + }, + { + "name": "linkSockets Scatter", + "ok": true, + "detail": "Linked dist.Points -> iop.Points." + }, + { + "name": "linkSockets Scatter", + "ok": true, + "detail": "Linked cone.Mesh -> iop.Instance." + }, + { + "name": "linkSockets Scatter", + "ok": true, + "detail": "Linked iop.Instances -> gout.Socket_0." + }, + { + "name": "createObject ", + "ok": true, + "detail": "Blender object created." + }, + { + "name": "addModifier Scatter", + "ok": true, + "detail": "Geometry Nodes modifier set." + }, + { + "name": "scatter instances equal native", + "ok": true, + "detail": { + "brokkr": 38, + "native": 38 + } + }, + { + "name": "setModifierInput ScatterHost", + "ok": true, + "detail": "Modifier input Seed set." + }, + { + "name": "unwired exposed input leaves result", + "ok": true, + "detail": null + }, + { + "name": "unknown input refused", + "ok": true, + "detail": "input 'Nope': socket 'Nope' was not found." + }, + { + "name": "refused addNode left no node", + "ok": true, + "detail": null + }, + { + "name": "unknown property refused", + "ok": true, + "detail": "GeometryNodeMeshCube has no settable property 'nope'." + }, + { + "name": "file-reading node refused", + "ok": true, + "detail": "node type GeometryNodeImportOBJ is not allowed in this cut (Import)." + }, + { + "name": "unknown node type refused", + "ok": true, + "detail": "Blender does not offer node type GeometryNodeNoSuchThing: Error: Node type GeometryNodeNoSuchThing undefined\n" + }, + { + "name": "invalid link refused and removed", + "ok": true, + "detail": "Link Mesh -> Density is not valid (type or field/single-value mismatch)." + }, + { + "name": "wrong value type refused", + "ok": true, + "detail": "input 'Seed' must be a finite number within +-1e+09." + }, + { + "name": "duplicate id refused", + "ok": true, + "detail": "Node id 'grid' already exists in 'Scatter'." + }, + { + "name": "createNodeGroup L", + "ok": true, + "detail": "Created node group; interface identifiers: output Geometry=Socket_0" + }, + { + "name": "addNode cube", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode m", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode iop", + "ok": true, + "detail": "Node added." + }, + { + "name": "linkSockets L", + "ok": true, + "detail": "Linked cube.Mesh -> iop.Points." + }, + { + "name": "refused link keeps the link it would have replaced", + "ok": true, + "detail": [ + "Link Value -> Points is not valid (type or field/single-value mismatch).", + [ + [ + "cube", + "Points" + ] + ], + [ + [ + "cube", + "Points" + ] + ] + ] + }, + { + "name": "createObject ", + "ok": true, + "detail": "Blender object created." + }, + { + "name": "modifier on a camera refused clearly", + "ok": true, + "detail": "'Cam' is a CAMERA object; it cannot take a Geometry Nodes modifier." + }, + { + "name": "trailing newline in an id refused", + "ok": true, + "detail": "id must be 1..63 characters of letters, digits, space, '.', '_' or '-'." + }, + { + "name": "createNodeGroup Off", + "ok": true, + "detail": "Created node group; interface identifiers: output Geometry=Socket_0" + }, + { + "name": "addNode circle", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode cube", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode iop", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode join", + "ok": true, + "detail": "Node added." + }, + { + "name": "linkSockets Off", + "ok": true, + "detail": "Linked circle.Mesh -> iop.Points." + }, + { + "name": "linkSockets Off", + "ok": true, + "detail": "Linked cube.Mesh -> iop.Instance." + }, + { + "name": "linkSockets Off", + "ok": true, + "detail": "Linked iop.Instances -> join.Geometry." + }, + { + "name": "linkSockets Off", + "ok": true, + "detail": "Linked circle.Mesh -> join.Geometry." + }, + { + "name": "linkSockets Off", + "ok": true, + "detail": "Linked join.Geometry -> gout.Socket_0." + }, + { + "name": "createObject ", + "ok": true, + "detail": "Blender object created." + }, + { + "name": "addModifier Off", + "ok": true, + "detail": "Geometry Nodes modifier set." + }, + { + "name": "local vertex bounds and world instance bounds are separate", + "ok": true, + "detail": { + "vertexCount": 4, + "edgeCount": 4, + "polygonCount": 0, + "instanceCount": 4, + "instancesComplete": true, + "positionsSkipped": false, + "nonFinite": false, + "vertexBoundsMin": [ + -1.0, + -1.0, + 0.0 + ], + "vertexBoundsMax": [ + 1.0, + 1.0, + 0.0 + ], + "vertexLocations": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + -0.0, + 1.0, + 0.0 + ], + [ + -1.0, + -0.0, + 0.0 + ], + [ + 0.0, + -1.0, + 0.0 + ] + ], + "instanceBoundsMin": [ + 99.0, + -1.0, + 0.0 + ], + "instanceBoundsMax": [ + 101.0, + 1.0, + 0.0 + ], + "instanceLocations": [ + [ + 101.0, + 0.0, + 0.0 + ], + [ + 100.0, + 1.0, + 0.0 + ], + [ + 99.0, + -0.0, + 0.0 + ], + [ + 100.0, + -1.0, + 0.0 + ] + ], + "truncated": false + } + }, + { + "name": "createNodeGroup Inf", + "ok": true, + "detail": "Created node group; interface identifiers: output Geometry=Socket_0" + }, + { + "name": "addNode s0", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode s1", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode s2", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode s3", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode s4", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode s5", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode cube", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode set", + "ok": true, + "detail": "Node added." + }, + { + "name": "linkSockets Inf", + "ok": true, + "detail": "Linked s0.Vector -> s1.Vector." + }, + { + "name": "linkSockets Inf", + "ok": true, + "detail": "Linked s1.Vector -> s2.Vector." + }, + { + "name": "linkSockets Inf", + "ok": true, + "detail": "Linked s2.Vector -> s3.Vector." + }, + { + "name": "linkSockets Inf", + "ok": true, + "detail": "Linked s3.Vector -> s4.Vector." + }, + { + "name": "linkSockets Inf", + "ok": true, + "detail": "Linked s4.Vector -> s5.Vector." + }, + { + "name": "linkSockets Inf", + "ok": true, + "detail": "Linked cube.Mesh -> set.Geometry." + }, + { + "name": "linkSockets Inf", + "ok": true, + "detail": "Linked s5.Vector -> set.Position." + }, + { + "name": "linkSockets Inf", + "ok": true, + "detail": "Linked set.Geometry -> gout.Socket_0." + }, + { + "name": "createObject ", + "ok": true, + "detail": "Blender object created." + }, + { + "name": "addModifier Inf", + "ok": true, + "detail": "Geometry Nodes modifier set." + }, + { + "name": "non-finite evaluated positions are flagged and not published", + "ok": true, + "detail": { + "vertexCount": 8, + "edgeCount": 12, + "polygonCount": 6, + "instanceCount": 0, + "instancesComplete": true, + "positionsSkipped": false, + "nonFinite": true, + "vertexBoundsMin": [], + "vertexBoundsMax": [], + "vertexLocations": [], + "instanceBoundsMin": [], + "instanceBoundsMax": [], + "instanceLocations": [], + "truncated": false + } + }, + { + "name": "createNodeGroup R", + "ok": true, + "detail": "Created node group; interface identifiers: output Geometry=Socket_0, input Count=Socket_1" + }, + { + "name": "addNode circle", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode cube", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode iop", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode m1", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode m2", + "ok": true, + "detail": "Node added." + }, + { + "name": "linkSockets R", + "ok": true, + "detail": "Linked gin.Socket_1 -> circle.Vertices." + }, + { + "name": "linkSockets R", + "ok": true, + "detail": "Linked circle.Mesh -> iop.Points." + }, + { + "name": "linkSockets R", + "ok": true, + "detail": "Linked cube.Mesh -> iop.Instance." + }, + { + "name": "linkSockets R", + "ok": true, + "detail": "Linked iop.Instances -> gout.Socket_0." + }, + { + "name": "linkSockets R", + "ok": true, + "detail": "Linked m1.Value -> m2.Value." + }, + { + "name": "createObject ", + "ok": true, + "detail": "Blender object created." + }, + { + "name": "addModifier R", + "ok": true, + "detail": "Geometry Nodes modifier set." + }, + { + "name": "graph evaluates before removal", + "ok": true, + "detail": null + }, + { + "name": "cycle m2->m1 refused", + "ok": true, + "detail": "Link m2 -> m1 would make a cycle." + }, + { + "name": "cycle m1->m1 refused", + "ok": true, + "detail": "Link m1 -> m1 would make a cycle." + }, + { + "name": "refused cycle left the link set alone", + "ok": true, + "detail": null + }, + { + "name": "unlinkSockets R", + "ok": true, + "detail": "Removed 1 link(s)." + }, + { + "name": "unlinked exactly one link", + "ok": true, + "detail": "Removed 1 link(s)." + }, + { + "name": "unlinkSockets R", + "ok": true, + "detail": "Removed 0 link(s)." + }, + { + "name": "unlink of nothing is accepted", + "ok": true, + "detail": "Removed 0 link(s)." + }, + { + "name": "unlinkSockets R", + "ok": true, + "detail": "Removed 1 link(s)." + }, + { + "name": "unlinking the instance changes the result", + "ok": true, + "detail": { + "vertexCount": 0, + "edgeCount": 0, + "polygonCount": 0, + "instanceCount": 0, + "instancesComplete": true, + "positionsSkipped": false, + "nonFinite": false, + "vertexBoundsMin": [], + "vertexBoundsMax": [], + "vertexLocations": [], + "instanceBoundsMin": [], + "instanceBoundsMax": [], + "instanceLocations": [], + "truncated": false + } + }, + { + "name": "linkSockets R", + "ok": true, + "detail": "Linked cube.Mesh -> iop.Instance." + }, + { + "name": "relinked", + "ok": true, + "detail": null + }, + { + "name": "removeNode cube", + "ok": true, + "detail": "Node removed." + }, + { + "name": "removeNode drops the node and its links", + "ok": true, + "detail": null + }, + { + "name": "group output node stays", + "ok": true, + "detail": "'gout' is the group's own input/output node and stays." + }, + { + "name": "removeNode of an absent id is accepted", + "ok": true, + "detail": null + }, + { + "name": "removeModifier RHost", + "ok": true, + "detail": "Modifier removed." + }, + { + "name": "removeModifier removes it; evaluated block gone", + "ok": true, + "detail": null + }, + { + "name": "non-Geometry-Nodes modifier is not removed", + "ok": true, + "detail": "'Sub' is not a Geometry Nodes modifier; only those are removed here." + }, + { + "name": "createNodeGroup C", + "ok": true, + "detail": "Created node group; interface identifiers: output Geometry=Socket_0" + }, + { + "name": "every closing link on a 60-node chain with skip links is refused", + "ok": true, + "detail": [ + 59, + 59, + 0.008 + ] + }, + { + "name": "createNodeGroup Mu", + "ok": true, + "detail": "Created node group; interface identifiers: output Geometry=Socket_0" + }, + { + "name": "addNode cube", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode m", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode iop", + "ok": true, + "detail": "Node added." + }, + { + "name": "linkSockets Mu", + "ok": true, + "detail": "Linked cube.Mesh -> iop.Points." + }, + { + "name": "refused link restores the displaced link's muted state", + "ok": true, + "detail": [ + "Link Value -> Points is not valid (type or field/single-value mismatch).", + [ + true + ] + ] + }, + { + "name": "createObject ", + "ok": true, + "detail": "Blender object created." + }, + { + "name": "hand-made Unicode modifier name is removable", + "ok": true, + "detail": "Modifier removed." + }, + { + "name": "createNodeGroup Heavy", + "ok": true, + "detail": "Created node group; interface identifiers: output Geometry=Socket_0" + }, + { + "name": "addNode grid", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode cube", + "ok": true, + "detail": "Node added." + }, + { + "name": "addNode iop", + "ok": true, + "detail": "Node added." + }, + { + "name": "linkSockets Heavy", + "ok": true, + "detail": "Linked grid.Mesh -> iop.Points." + }, + { + "name": "linkSockets Heavy", + "ok": true, + "detail": "Linked cube.Mesh -> iop.Instance." + }, + { + "name": "linkSockets Heavy", + "ok": true, + "detail": "Linked iop.Instances -> gout.Socket_0." + }, + { + "name": "createObject ", + "ok": true, + "detail": "Blender object created." + }, + { + "name": "addModifier Heavy", + "ok": true, + "detail": "Geometry Nodes modifier set." + }, + { + "name": "2000x2000 instanced grid: capture is bounded", + "ok": true, + "detail": [ + 1.2, + 99999, + false + ] + }, + { + "name": "createNodeGroup Heavy", + "ok": true, + "detail": "Created node group; interface identifiers: output Geometry=Socket_0" + }, + { + "name": "addNode grid", + "ok": true, + "detail": "Node added." + }, + { + "name": "linkSockets Heavy", + "ok": true, + "detail": "Linked grid.Mesh -> gout.Socket_0." + }, + { + "name": "createObject ", + "ok": true, + "detail": "Blender object created." + }, + { + "name": "addModifier Heavy", + "ok": true, + "detail": "Geometry Nodes modifier set." + }, + { + "name": "2000x2000 mesh grid: counts only, bounded", + "ok": true, + "detail": [ + 0.05, + 4000000 + ] + } + ], + "cycle_probe_seconds": 0.008, + "capture_2000_grid_instanced_seconds": 1.198, + "capture_2000_grid_mesh_seconds": 0.045 +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/gn_recreation.py b/surfaces/blender/tests/live/gn_recreation.py new file mode 100644 index 0000000..6ef8036 --- /dev/null +++ b/surfaces/blender/tests/live/gn_recreation.py @@ -0,0 +1,178 @@ +"""Recreate geometry-node setups through the Brokkr scene/object actions and compare with the native result. + + BROKKR_ADDON= \ + blender -b --factory-startup --python gn_recreation.py -- result.json + +Each setup is built twice: natively (geometry-nodes tree via bpy, evaluated) and through +BrokkrBlenderTarget.execute_command using only the actions that exist. Prints GAP lines where an +action that would be needed is refused or has no effect. Not part of the unittest run (needs Blender). +""" +import bpy, sys, os, json, types, math, random +from pathlib import Path +from mathutils import Vector + +ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() +pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)] +sys.modules["brokkr_bridge"] = pkg +from brokkr_bridge import blender_target as bt + +out = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else "gn_result.json" +R = {"blender": bpy.app.version_string, "setups": {}, "gaps": {}} + +def reset(): + bpy.ops.wm.read_factory_settings(use_empty=True) + return bt.BrokkrBlenderTarget(bpy) + +def act(t, **cmd): + cmd.setdefault("commandId", "c%d" % act.n); act.n += 1 + return t.execute_command(bpy.context, cmd) +act.n = 0 + +def gap(key, **detail): + R["gaps"][key] = detail; print("GAP", key, json.dumps(detail), flush=True) + +# --- native helpers --------------------------------------------------------------------- +def tree(name, extra_out=True): + t = bpy.data.node_groups.new(name, "GeometryNodeTree") + t.interface.new_socket("Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry") + gout = t.nodes.new("NodeGroupOutput") + return t, gout + +def host(name, gtree, mesh=None): + me = mesh or bpy.data.meshes.new(name) + ob = bpy.data.objects.new(name, me); bpy.context.scene.collection.objects.link(ob) + m = ob.modifiers.new("GN", "NODES"); m.node_group = gtree + return ob + +def evaluated_instances(ob): + dg = bpy.context.evaluated_depsgraph_get(); dg.update() + return [tuple(round(c, 5) for c in inst.matrix_world.translation) for inst in dg.object_instances if inst.is_instance] + +def evaluated_verts(ob): + dg = bpy.context.evaluated_depsgraph_get(); dg.update() + me = ob.evaluated_get(dg).to_mesh() + v = [tuple(round(c, 5) for c in p.co) for p in me.vertices]; ob.evaluated_get(dg).to_mesh_clear(); return v + +def brokkr_positions(prefix): + bpy.context.view_layer.update() # matrix_world of the last-edited object is stale until then + return sorted(tuple(round(c, 5) for c in o.matrix_world.translation) for o in bpy.data.objects if o.name.startswith(prefix)) + +# ========================================================================================= +# 1. Ring of instances (essentials-style array: Mesh Circle -> Instance on Points) +# ========================================================================================= +t = reset(); N, RAD = 8, 2.0 +g, gout = tree("Ring") +circ = g.nodes.new("GeometryNodeMeshCircle"); circ.inputs["Vertices"].default_value = N; circ.inputs["Radius"].default_value = RAD +cube = g.nodes.new("GeometryNodeMeshCube"); cube.inputs["Size"].default_value = (0.3, 0.3, 0.3) +iop = g.nodes.new("GeometryNodeInstanceOnPoints") +g.links.new(circ.outputs["Mesh"], iop.inputs["Points"]); g.links.new(cube.outputs["Mesh"], iop.inputs["Instance"]) +g.links.new(iop.outputs["Instances"], gout.inputs["Geometry"]) +ob = host("RingHost", g) +native = sorted(evaluated_instances(ob)) +bpy.data.objects.remove(ob) +acts = 0; fails = 0 +for i in range(N): + a = 2 * math.pi * i / N + r1 = act(t, action="createObject", objectType="MESH", name="Ring.%d" % i, size=0.3); acts += 1 + r2 = act(t, action="setObjectTransform", targetObjectName="Ring.%d" % i, location=[RAD * math.cos(a), RAD * math.sin(a), 0]); acts += 1 + fails += (r1["status"] != "accepted") + (r2["status"] != "accepted") +bro = brokkr_positions("Ring.") +ok = native == bro +R["setups"]["ring"] = {"native_instances": len(native), "brokkr_objects": len(bro), "positions_equal": ok, "actions": acts, "failed_actions": fails} +print("SETUP ring", R["setups"]["ring"]); print("RING native", native); print("RING brokkr", bro) +# size parity +cube_dim = bpy.data.objects["Ring.0"].dimensions[:] +R["setups"]["ring"]["brokkr_object_dimensions"] = [round(d, 4) for d in cube_dim] +# live-ness: the native ring re-evaluates when Count changes; the Brokkr one needs N more actions. +# GAP: any node-graph action +for aname, extra in (("createNodeGroup", {}), ("addModifier", {"modifierType": "NODES"}), ("addNode", {}), ("setModifierInput", {"socket": "Socket_2", "value": 12})): + r = act(t, action=aname, targetObjectName="Ring.0", **extra) + R["gaps"].setdefault("no_node_actions", {})[aname] = [r["status"], r["message"]] +print("GAP no_node_actions", R["gaps"]["no_node_actions"]) +# GAP: instances need one object each; no instancing/collection-instance action; mesh primitive is cube only +gap("no_primitive_choice", createObject_MESH="always primitive_cube_add; 'size' only", + repro="createObject objectType=MESH name=C -> verts=%d" % len(bpy.data.objects["Ring.0"].data.vertices)) +# GAP: setObjectCustomProperty cannot drive a modifier input +g2, go2 = tree("Param") +circ2 = g2.nodes.new("GeometryNodeMeshCircle") +g2.interface.new_socket("N", in_out="INPUT", socket_type="NodeSocketInt") +gi = g2.nodes.new("NodeGroupInput"); g2.links.new(gi.outputs["N"], circ2.inputs["Vertices"]) +g2.links.new(circ2.outputs["Mesh"], go2.inputs["Geometry"]) +hob = host("ParamHost", g2) +ident = [s.identifier for s in g2.interface.items_tree if s.item_type == "SOCKET" and s.in_out == "INPUT"][0] +getattr(hob.modifiers["GN"].properties.inputs, ident).__setattr__("value", 5) # inputs[ident] is a raw IDPropertyGroup with no .value +before = len(evaluated_verts(hob)) +r = act(t, action="setObjectCustomProperty", targetObjectName="ParamHost", propertyName=ident, value=12) +after = len(evaluated_verts(hob)) +snap = t.capture_snapshot(bpy.context) +ho = [o for o in snap["objects"] if o["name"] == "ParamHost"][0] +gap("custom_property_does_not_drive_modifier", receipt=r["status"], verts_before=before, verts_after=after, identifier=ident, + snapshot_modifier=ho["modifiers"], snapshot_mesh=ho["mesh"], + repro="setObjectCustomProperty on a GN host object -> accepted, evaluated vertex count unchanged; snapshot reports base mesh counts and no modifier inputs") +bpy.data.objects.remove(hob) + +# ========================================================================================= +# 2. Boundary step (example 2): pull points outside radius B back to the circle +# ========================================================================================= +t = reset(); B = 0.5; XS = [0.0, 2.0, 4.0] +g, gout = tree("Boundary") +line = g.nodes.new("GeometryNodeMeshLine"); line.inputs["Count"].default_value = 3 +line.inputs["Start Location"].default_value = (0, 0, 0); line.inputs["Offset"].default_value = (2, 0, 0) +pos = g.nodes.new("GeometryNodeInputPosition") +dist = g.nodes.new("ShaderNodeVectorMath"); dist.operation = "LENGTH" +cmp_ = g.nodes.new("FunctionNodeCompare"); cmp_.data_type = "FLOAT"; cmp_.operation = "GREATER_THAN"; cmp_.inputs[1].default_value = B +nrm = g.nodes.new("ShaderNodeVectorMath"); nrm.operation = "NORMALIZE" +sc = g.nodes.new("ShaderNodeVectorMath"); sc.operation = "SCALE"; sc.inputs["Scale"].default_value = B +sp = g.nodes.new("GeometryNodeSetPosition") +g.links.new(pos.outputs[0], dist.inputs[0]); g.links.new(dist.outputs["Value"], cmp_.inputs[0]) +g.links.new(pos.outputs[0], nrm.inputs[0]); g.links.new(nrm.outputs[0], sc.inputs[0]) +g.links.new(line.outputs["Mesh"], sp.inputs["Geometry"]); g.links.new(cmp_.outputs["Result"], sp.inputs["Selection"]) +g.links.new(sc.outputs[0], sp.inputs["Position"]); g.links.new(sp.outputs["Geometry"], gout.inputs["Geometry"]) +ob = host("BoundaryHost", g); native = sorted(evaluated_verts(ob)); bpy.data.objects.remove(ob) +acts = 0 +for i, x in enumerate(XS): + v = Vector((x, 0, 0)); nv = v if v.length <= B else v.normalized() * B # the *client* does the field math + act(t, action="createObject", objectType="EMPTY", name="P.%d" % i); act(t, action="setObjectTransform", targetObjectName="P.%d" % i, location=list(nv)); acts += 2 +bro = brokkr_positions("P.") +R["setups"]["boundary_step"] = {"native": native, "brokkr": bro, "equal": native == bro, "actions": acts, + "note": "equality needs the client to evaluate the field; Brokkr only carries the result"} +print("SETUP boundary_step", R["setups"]["boundary_step"]) +gap("no_field_evaluation", repro="no action takes an expression/field; boundary_step's per-element rule must be computed by the caller and sent as N setObjectTransform") + +# ========================================================================================= +# 3. Seeded scatter (grass-tuft front half): Distribute Points on Faces -> Instance on Points +# ========================================================================================= +t = reset(); SEED = 7 +g, gout = tree("Scatter") +grid = g.nodes.new("GeometryNodeMeshGrid"); grid.inputs["Size X"].default_value = 3; grid.inputs["Size Y"].default_value = 3 +dis = g.nodes.new("GeometryNodeDistributePointsOnFaces"); dis.distribute_method = "RANDOM" +dis.inputs["Density"].default_value = 4; dis.inputs["Seed"].default_value = SEED +cone = g.nodes.new("GeometryNodeMeshCone"); cone.inputs["Radius Bottom"].default_value = 0.05; cone.inputs["Depth"].default_value = 0.4 +iop = g.nodes.new("GeometryNodeInstanceOnPoints") +g.links.new(grid.outputs["Mesh"], dis.inputs["Mesh"]); g.links.new(dis.outputs["Points"], iop.inputs["Points"]) +g.links.new(cone.outputs["Mesh"], iop.inputs["Instance"]); g.links.new(iop.outputs["Instances"], gout.inputs["Geometry"]) +ob = host("ScatterHost", g); native = sorted(evaluated_instances(ob)) +# what Brokkr can see of that object +snap = t.capture_snapshot(bpy.context); so = [o for o in snap["objects"] if o["name"] == "ScatterHost"][0] +gap("snapshot_not_evaluated", brokkr_sees=so["mesh"], modifiers=so["modifiers"], evaluated_instances=len(native), + repro="host object with Distribute->InstanceOnPoints: snapshot mesh.vertexCount=0, no instance count, no positions") +# (a) replay the native points through actions (needs a side channel that is not Brokkr) +bpy.data.objects.remove(ob); acts = 0 +for i, p in enumerate(native): + act(t, action="createObject", objectType="MESH", name="S.%d" % i, size=0.1); act(t, action="setObjectTransform", targetObjectName="S.%d" % i, location=list(p)); acts += 2 +R["setups"]["scatter_replay"] = {"native_instances": len(native), "equal": brokkr_positions("S.") == native, "actions": acts, + "note": "positions were read with bpy depsgraph, not through any Brokkr surface"} +# (b) recreate from the seed with the caller's own RNG: does not match Blender's point hash +random.seed(SEED) +mine = sorted((round(random.uniform(-1.5, 1.5), 5), round(random.uniform(-1.5, 1.5), 5), 0.0) for _ in native) +R["setups"]["scatter_own_rng"] = {"count_equal": len(mine) == len(native), "positions_equal": mine == [(a, b, 0.0) for a, b, _ in native] or mine == native} +print("SETUP scatter", R["setups"]["scatter_replay"], R["setups"]["scatter_own_rng"]) +gap("no_seed_parity", repro="Distribute Points on Faces seed=7 density=4 on a 3x3 grid: positions are Blender's hash; only reading them back (not offered) reproduces them") +# --- render check: the Brokkr scene still renders under the existing actions +act(t, action="createObject", objectType="CAMERA", name="Cam", location=[0, -6, 4]); act(t, action="setCamera", targetObjectName="Cam", active=True, lens=35) +os.makedirs(os.environ.get("BROKKR_RUN", "."), exist_ok=True) +t.configure_action_dirs(os.environ.get("BROKKR_RUN", "."), os.environ.get("BROKKR_RUN", ".")) +r = act(t, action="renderStill", outputPath="scatter_replay.png", engine="BLENDER_WORKBENCH", resolutionX=64, resolutionY=64, cameraName="Cam") +R["setups"]["scatter_replay"]["render"] = [r["status"], r["message"]] +json.dump(R, open(out, "w"), indent=1, default=str) +print("DONE", out) diff --git a/surfaces/blender/tests/live/gn_recreation.result.json b/surfaces/blender/tests/live/gn_recreation.result.json new file mode 100644 index 0000000..24b4332 --- /dev/null +++ b/surfaces/blender/tests/live/gn_recreation.result.json @@ -0,0 +1,141 @@ +{ + "blender": "5.2.3 LTS", + "setups": { + "ring": { + "native_instances": 8, + "brokkr_objects": 8, + "positions_equal": true, + "actions": 16, + "failed_actions": 0, + "brokkr_object_dimensions": [ + 0.3, + 0.3, + 0.3 + ] + }, + "boundary_step": { + "native": [ + [ + 0.0, + 0.0, + 0.0 + ], + [ + 0.5, + 0.0, + 0.0 + ], + [ + 0.5, + 0.0, + 0.0 + ] + ], + "brokkr": [ + [ + 0.0, + 0.0, + 0.0 + ], + [ + 0.5, + 0.0, + 0.0 + ], + [ + 0.5, + 0.0, + 0.0 + ] + ], + "equal": true, + "actions": 6, + "note": "equality needs the client to evaluate the field; Brokkr only carries the result" + }, + "scatter_replay": { + "native_instances": 38, + "equal": true, + "actions": 76, + "note": "positions were read with bpy depsgraph, not through any Brokkr surface", + "render": [ + "accepted", + "Rendered still to scatter_replay.png." + ] + }, + "scatter_own_rng": { + "count_equal": true, + "positions_equal": false + } + }, + "gaps": { + "no_node_actions": { + "createNodeGroup": [ + "failed", + "Unsupported Blender command action: createNodeGroup" + ], + "addModifier": [ + "failed", + "Unsupported Blender command action: addModifier" + ], + "addNode": [ + "failed", + "Unsupported Blender command action: addNode" + ], + "setModifierInput": [ + "failed", + "Unsupported Blender command action: setModifierInput" + ] + }, + "no_primitive_choice": { + "createObject_MESH": "always primitive_cube_add; 'size' only", + "repro": "createObject objectType=MESH name=C -> verts=8" + }, + "custom_property_does_not_drive_modifier": { + "receipt": "accepted", + "verts_before": 5, + "verts_after": 5, + "identifier": "Socket_1", + "snapshot_modifier": [ + { + "name": "GN", + "type": "NODES", + "showViewport": true, + "showRender": true + } + ], + "snapshot_mesh": { + "vertexCount": 0, + "edgeCount": 0, + "polygonCount": 0, + "uvLayerCount": 0, + "shapeKeyCount": 0 + }, + "repro": "setObjectCustomProperty on a GN host object -> accepted, evaluated vertex count unchanged; snapshot reports base mesh counts and no modifier inputs" + }, + "no_field_evaluation": { + "repro": "no action takes an expression/field; boundary_step's per-element rule must be computed by the caller and sent as N setObjectTransform" + }, + "snapshot_not_evaluated": { + "brokkr_sees": { + "vertexCount": 0, + "edgeCount": 0, + "polygonCount": 0, + "uvLayerCount": 0, + "shapeKeyCount": 0 + }, + "modifiers": [ + { + "name": "GN", + "type": "NODES", + "showViewport": true, + "showRender": true + } + ], + "evaluated_instances": 38, + "repro": "host object with Distribute->InstanceOnPoints: snapshot mesh.vertexCount=0, no instance count, no positions" + }, + "no_seed_parity": { + "repro": "Distribute Points on Faces seed=7 density=4 on a 3x3 grid: positions are Blender's hash; only reading them back (not offered) reproduces them" + } + } +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py new file mode 100644 index 0000000..4c333f1 --- /dev/null +++ b/surfaces/blender/tests/test_node_actions.py @@ -0,0 +1,722 @@ +"""Node-graph action tests. No Blender: a fake bpy with just enough node-tree surface. + +Run: python3 -m unittest discover -s surfaces/blender/tests -v +The real API is exercised by tests/live/gn_actions.py. +""" +from __future__ import annotations + +import sys +import types +import unittest +import unittest.mock +from pathlib import Path + +ADDON = Path(__file__).resolve().parents[1] / "brokkr_bridge" +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(ADDON)] +sys.modules.setdefault("brokkr_bridge", package) + +from brokkr_bridge import blender_target as bt # noqa: E402 +from brokkr_bridge import node_actions as na # noqa: E402 + +NS = types.SimpleNamespace + + +class Sock: + def __init__(self, identifier, name, kind="VALUE", default=0.0): + self.identifier, self.name, self.type, self.enabled = identifier, name, kind, True + self.default_value, self.is_linked = default, False + + +class Node(dict): + """A node; ID properties are the dict part.""" + + counter = 1000 + + def as_pointer(self): + return self.pointer + + PROPS = {"operation": NS(type="ENUM", is_readonly=False), "flag": NS(type="BOOLEAN", is_readonly=False), + "filepath": NS(type="STRING", is_readonly=False), "location": NS(type="FLOAT", is_readonly=False)} + + def __init__(self, idname): + super().__init__() + self.bl_idname, self.location, self.label, self.operation, self.flag = idname, [0, 0], "", "ADD", False + Node.counter += 1 + self.pointer = Node.counter + self.bl_rna = NS(properties=self.PROPS) + self.inputs = [Sock("A", "A"), Sock("Size", "Size", "VECTOR", (1.0, 1.0, 1.0)), Sock("B", "Dup"), Sock("B_VEC", "Dup")] + self.outputs = [Sock("Out", "Out")] + for socket in self.inputs + self.outputs: + socket.node = self + + def __setattr__(self, key, value): + if key == "operation" and value not in ("ADD", "MULTIPLY"): + raise TypeError("enum not found") + object.__setattr__(self, key, value) + + +class Nodes(list): + def new(self, idname): + if idname.endswith("Missing"): + raise RuntimeError("Node type undefined") + node = Node(idname) + self.append(node) + return node + + def remove(self, node): + list.remove(self, node) + + +class Proxy: + """A fresh wrapper per access, as bpy hands out: equal by pointer, with a different id() each time.""" + + def __init__(self, node): + self._node = node + + def as_pointer(self): + return self._node.pointer + + def __getattr__(self, name): + return getattr(self._node, name) + + def __eq__(self, other): + return getattr(other, "pointer", None) == self._node.pointer or (isinstance(other, Proxy) and other._node is self._node) + + __hash__ = None + + +class Links(list): + def __init__(self, valid=True): + super().__init__() + self.valid = valid + + def new(self, a, b): + for old in [l for l in self if l.to_socket is b]: # a single-link input loses its old link, as in Blender + list.remove(self, old) + link = NS(from_socket=a, to_socket=b, from_node=Proxy(a.node), to_node=Proxy(b.node), is_muted=False, is_valid=self.valid(a, b) if callable(self.valid) else self.valid) + self.append(link) + return link + + def remove(self, link): + list.remove(self, link) + + +class Interface: + def __init__(self): + self.items_tree = [] + + def new_socket(self, name, in_out, socket_type): + item = NS(item_type="SOCKET", name=name, in_out=in_out, socket_type=socket_type, identifier=f"Socket_{len(self.items_tree)}", default_value=None) + self.items_tree.append(item) + return item + + +class Tree: + bl_idname = "GeometryNodeTree" + library = None + + def __init__(self, name): + self.name, self.nodes, self.links, self.interface = name, Nodes(), Links(), Interface() + + +class Groups(dict): + def new(self, name, kind): + self[name] = Tree(name) + return self[name] + + def remove(self, tree): + del self[tree.name] + + +class Inputs: + def __init__(self): + self.values = {} + + def __getattr__(self, identifier): + return self.values.setdefault(identifier, NS(value=None)) + + +class Modifiers(list): + refuses = False + + def get(self, name): + return next((m for m in self if m.name == name), None) + + def remove(self, modifier): + list.remove(self, modifier) + + def new(self, name, kind): + if self.refuses: + return None # Blender returns None for object types without modifiers + m = NS(name=name, type=kind, node_group=None, properties=NS(inputs=Inputs())) + self.append(m) + return m + + +class Obj: + def __init__(self, name): + self.name, self.type, self.data, self.modifiers, self.tagged = name, "MESH", None, Modifiers(), 0 + + def update_tag(self): + self.tagged += 1 + + def get(self, key, default=None): + return default + + def __setitem__(self, key, value): + self.custom = (key, value) + + +class FakeBpy: + def __init__(self): + self.data = NS(node_groups=Groups(), objects={"Host": Obj("Host")}) + + +class NodeActionTests(unittest.TestCase): + def setUp(self): + self.bpy = FakeBpy() + self.target = bt.BrokkrBlenderTarget(self.bpy) + self.n = 0 + + def run_action(self, **command): + self.n += 1 + command.setdefault("commandId", f"c{self.n}") + return self.target.execute_command(None, command) + + def accepted(self, **command): + receipt = self.run_action(**command) + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + return receipt + + def refused(self, **command): + receipt = self.run_action(**command) + self.assertEqual(receipt["status"], "failed", receipt["message"]) + return receipt + + def group(self, interface=None): + self.accepted(action="createNodeGroup", treeKey="G", interface=interface or [{"inOut": "OUTPUT", "name": "Geometry", "type": "Geometry"}, {"inOut": "INPUT", "name": "Count", "type": "Int", "default": 8}]) + return self.bpy.data.node_groups["G"] + + # createNodeGroup + def test_group_gets_interface_and_stamped_group_nodes(self): + receipt = self.accepted(action="createNodeGroup", treeKey="G", interface=[{"inOut": "INPUT", "name": "Count", "type": "Int", "default": 8}]) + tree = self.bpy.data.node_groups["G"] + self.assertEqual([n.get("brokkr_id") for n in tree.nodes], ["gin", "gout"]) + self.assertEqual(tree.interface.items_tree[0].default_value, 8) + self.assertIn("Count=Socket_0", receipt["message"]) + + def test_group_refusals_create_nothing(self): + for interface in (None, [], "x", [{"inOut": "SIDEWAYS", "name": "a", "type": "Int"}], [{"inOut": "INPUT", "name": "a", "type": "Mesh"}], + [{"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Float"}], + [{"inOut": "INPUT", "name": "a", "type": "Int", "default": 1.5}], [{"inOut": "INPUT", "name": "a", "type": "Vector", "default": [1, 2]}]): + self.refused(action="createNodeGroup", treeKey="G", interface=interface) + self.refused(action="createNodeGroup", treeKey="../x", interface=[{"inOut": "INPUT", "name": "a", "type": "Int"}]) + self.refused(action="createNodeGroup", treeKind="material", treeKey="G", interface=[{"inOut": "INPUT", "name": "a", "type": "Int"}]) + self.assertEqual(len(self.bpy.data.node_groups), 0) + + def test_group_that_exists_is_not_overwritten(self): + self.group() + self.refused(action="createNodeGroup", treeKey="G", interface=[{"inOut": "INPUT", "name": "a", "type": "Int"}]) + self.assertEqual(len(self.bpy.data.node_groups["G"].interface.items_tree), 2) + + # addNode + def test_add_node_applies_properties_then_inputs_and_stamps_id(self): + tree = self.group() + self.accepted(action="addNode", treeKey="G", id="m", blIdname="ShaderNodeMath", location=[10, 20], properties={"operation": "MULTIPLY"}, inputs={"A": 3, "Size": [1, 2, 3]}) + node = tree.nodes[-1] + self.assertEqual((node.operation, node.location, node.inputs[0].default_value, node.inputs[1].default_value), ("MULTIPLY", [10.0, 20.0], 3.0, (1.0, 2.0, 3.0))) + + def test_add_node_refusals_leave_no_node(self): + tree = self.group() + before = len(tree.nodes) + cases = [dict(blIdname="GeometryNodeImportOBJ"), dict(blIdname="GeometryNodeBake"), dict(blIdname="NodeGroupInput"), dict(blIdname="bpy.ops"), + dict(blIdname="ShaderNodeMissing"), dict(blIdname="ShaderNodeMath", properties={"operation": "NOPE"}), + dict(blIdname="ShaderNodeMath", properties={"filepath": "/etc/passwd"}), dict(blIdname="ShaderNodeMath", properties={"location": 1.0}), + dict(blIdname="ShaderNodeMath", properties={"missing": 1}), dict(blIdname="ShaderNodeMath", inputs={"Dup": 1}), + dict(blIdname="ShaderNodeMath", inputs={"Nope": 1}), dict(blIdname="ShaderNodeMath", inputs={"A": float("nan")}), + dict(blIdname="ShaderNodeMath", inputs={"A": True}), dict(blIdname="ShaderNodeMath", inputs={"A": 1e12}), + dict(blIdname="ShaderNodeMath", inputs={"Size": [1, 2]}), dict(blIdname="ShaderNodeMath", location=[1])] + for case in cases: + self.refused(action="addNode", treeKey="G", id="x", **case) + self.assertEqual(len(tree.nodes), before) + + def test_string_and_reserved_properties_are_refused_by_rule(self): + self.group() + for name in ("filepath", "location"): + receipt = self.refused(action="addNode", treeKey="G", id="x", blIdname="ShaderNodeMath", properties={name: "v"}) + self.assertIn("no settable property", receipt["message"]) + + def test_add_node_refuses_bad_ids_duplicates_and_missing_tree(self): + self.group() + for bad in ("", "a b", "x" * 64, "../x", None): + self.refused(action="addNode", treeKey="G", id=bad, blIdname="ShaderNodeMath") + self.refused(action="addNode", treeKey="G", id="gin", blIdname="ShaderNodeMath") + self.refused(action="addNode", treeKey="Nope", id="a", blIdname="ShaderNodeMath") + + def test_node_cap(self): + tree = self.group() + for i in range(na.MAX_NODES - 2): + tree.nodes.new("ShaderNodeMath") + self.refused(action="addNode", treeKey="G", id="over", blIdname="ShaderNodeMath") + + def test_linked_library_group_is_read_only(self): + tree = self.group() + tree.library = NS(filepath="lib.blend") + self.refused(action="addNode", treeKey="G", id="a", blIdname="ShaderNodeMath") + + # access rules, pinned by literals + def test_each_denied_node_family_is_refused_alone(self): + tree = self.group() + denied = ["GeometryNodeImportOBJ", "GeometryNodeExportPLY", "ShaderNodeScript", "GeometryNodeBake", "GeometryNodeGroup", + "GeometryNodeSimulationInput", "GeometryNodeRepeatInput", "GeometryNodeForeachGeometryElementInput", + "GeometryNodeViewer", "ShaderNodeTexImage", "ShaderNodeTexEnvironment", "GeometryNodeImageTexture", + "GeometryNodeInputImage", "ShaderNodeTexIES"] + before = len(tree.nodes) + for idname in denied: + self.refused(action="addNode", treeKey="G", id="x", blIdname=idname) + self.assertEqual(len(tree.nodes), before) + + def test_legitimate_node_families_are_allowed(self): + for i, idname in enumerate(["ShaderNodeMath", "GeometryNodeMeshGrid", "FunctionNodeCompare", "GeometryNodeSetPosition", "ShaderNodeTexNoise"]): + self.group() if i == 0 else None + self.accepted(action="addNode", treeKey="G", id=f"n{i}", blIdname=idname) + + def test_idname_must_be_a_whole_known_prefixed_name(self): + self.group() + for bad in ("Foo", "ShaderNode", "xShaderNodeMath", "ShaderNodeMath\n", "ShaderNode Math", "ShaderNode_Math", "CompositorNodeMath", "ShaderNodeMath;", "", None, 5): + self.refused(action="addNode", treeKey="G", id="x", blIdname=bad) + + def test_node_cap_is_exactly_500(self): + tree = self.group() + for _ in range(497): + tree.nodes.new("ShaderNodeMath") + self.assertEqual(len(tree.nodes), 499) + self.accepted(action="addNode", treeKey="G", id="last", blIdname="ShaderNodeMath") + self.assertEqual(len(tree.nodes), 500) + self.refused(action="addNode", treeKey="G", id="over", blIdname="ShaderNodeMath") + + def test_interface_cap_is_exactly_64(self): + def sockets(count): + return [{"inOut": "INPUT", "name": f"s{i}", "type": "Int"} for i in range(count)] + self.accepted(action="createNodeGroup", treeKey="A", interface=sockets(64)) + self.refused(action="createNodeGroup", treeKey="B", interface=sockets(65)) + self.refused(action="createNodeGroup", treeKey="C", interface=[]) + + def test_int_limit_is_exactly_4096(self): + self.group() + self.accepted(action="addModifier", objectName="Host", modifierName="GN", treeKey="G") + for value in (4096, -4096): + self.accepted(action="setModifierInput", objectName="Host", modifierName="GN", socket="Count", value=value) + for value in (4097, -4097): + self.refused(action="setModifierInput", objectName="Host", modifierName="GN", socket="Count", value=value) + self.accepted(action="addNode", treeKey="G", id="ok", blIdname="ShaderNodeMath", inputs={"A": 4097}) # a float input has no int cap + + def test_value_limit_is_exactly_one_billion(self): + self.group() + self.accepted(action="addNode", treeKey="G", id="a", blIdname="ShaderNodeMath", inputs={"A": 1e9}) + self.accepted(action="addNode", treeKey="G", id="b", blIdname="ShaderNodeMath", inputs={"A": -1e9}) + self.refused(action="addNode", treeKey="G", id="c", blIdname="ShaderNodeMath", inputs={"A": 1000000001}) + self.refused(action="addNode", treeKey="G", id="d", blIdname="ShaderNodeMath", inputs={"Size": [0, 0, -1000000001]}) + self.accepted(action="addNode", treeKey="G", id="e", blIdname="ShaderNodeMath", location=[1e9, -1e9]) + self.refused(action="addNode", treeKey="G", id="f", blIdname="ShaderNodeMath", location=[1000000001, 0]) + + def test_modifier_cap_is_exactly_8(self): + self.group() + for i in range(8): + self.accepted(action="addModifier", objectName="Host", modifierName=f"m{i}", treeKey="G") + self.refused(action="addModifier", objectName="Host", modifierName="m8", treeKey="G") + self.accepted(action="addModifier", objectName="Host", modifierName="m3", treeKey="G") # reuse is not growth + + def test_location_must_be_two_finite_numbers(self): + tree = self.group() + for bad in ([1, 2, 3], "ab", 5, [1, float("nan")], [1, "2"], [True, 1]): + self.refused(action="addNode", treeKey="G", id="x", blIdname="ShaderNodeMath", location=bad) + self.assertEqual(len(tree.nodes), 2) + + def test_readonly_node_property_is_refused_and_untouched(self): + self.group() + with unittest.mock.patch.dict(Node.PROPS, {"flag": NS(type="BOOLEAN", is_readonly=True)}): + self.refused(action="addNode", treeKey="G", id="x", blIdname="ShaderNodeMath", properties={"flag": True}) + self.assertEqual(len(self.bpy.data.node_groups["G"].nodes), 2) + + def test_input_without_a_default_or_with_a_link_is_refused(self): + tree = self.group() + original = Nodes.new + + def linked(nodes, idname): + node = original(nodes, idname) + node.inputs[0].is_linked = True + return node + with unittest.mock.patch.object(Nodes, "new", linked): + self.refused(action="addNode", treeKey="G", id="x", blIdname="ShaderNodeMath", inputs={"A": 1}) + self.assertEqual(len(tree.nodes), 2) + + def bare(nodes, idname): + node = original(nodes, idname) + del node.inputs[0].default_value + return node + with unittest.mock.patch.object(Nodes, "new", bare): + self.refused(action="addNode", treeKey="G", id="y", blIdname="ShaderNodeMath", inputs={"A": 1}) + self.assertEqual(len(tree.nodes), 2) + + def test_create_node_group_that_fails_midway_leaves_no_group(self): + original = Nodes.new + + def failing(nodes, idname): + if idname == "NodeGroupOutput": + raise RuntimeError("boom") + return original(nodes, idname) + with unittest.mock.patch.object(Nodes, "new", failing): + self.refused(action="createNodeGroup", treeKey="Half", interface=[{"inOut": "INPUT", "name": "a", "type": "Int"}]) + self.assertNotIn("Half", self.bpy.data.node_groups) + self.accepted(action="createNodeGroup", treeKey="Half", interface=[{"inOut": "INPUT", "name": "a", "type": "Int"}]) + + def test_add_modifier_will_not_take_over_a_foreign_modifier(self): + self.group() + host = self.bpy.data.objects["Host"] + foreign = host.modifiers.new("Mine", "SUBSURF") + self.refused(action="addModifier", objectName="Host", modifierName="Mine", treeKey="G") + self.assertIsNone(foreign.node_group) + self.assertEqual(len(host.modifiers), 1) + + def test_set_modifier_input_only_drives_geometry_nodes_modifiers(self): + tree = self.group() + host = self.bpy.data.objects["Host"] + foreign = host.modifiers.new("Mine", "SUBSURF") + foreign.node_group = tree + self.refused(action="setModifierInput", objectName="Host", modifierName="Mine", socket="Count", value=1) + self.assertEqual(foreign.properties.inputs.values, {}) + self.assertEqual(host.tagged, 0) + + def test_blender_capabilities_include_everything_the_daemon_advertises_for_this_cut(self): + # brokkr-daemon/src/main.rs lists the same names (and asserts them in its own test); a capability + # added to one side only fails one of the two tests. + for name in ("asset.import.gltf", "camera.write", "light.write", "world.write", "render.still", "nodegraph.geometry.write", "geometry.evaluated.read"): + self.assertIn(name, bt.CAPABILITIES) + + # linkSockets + def test_link_by_identifier_and_by_unique_name(self): + tree = self.group() + self.accepted(action="addNode", treeKey="G", id="a", blIdname="ShaderNodeMath") + self.accepted(action="addNode", treeKey="G", id="b", blIdname="ShaderNodeMath") + self.accepted(action="linkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="b", toSocket="A") + self.accepted(action="linkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="b", toSocket="Size") + self.assertEqual(len(tree.links), 2) + self.refused(action="linkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="b", toSocket="Dup") # name shared by two sockets + self.refused(action="linkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="zzz", toSocket="A") + self.assertEqual(len(tree.links), 2) + + def test_unavailable_socket_is_not_addressable_by_name(self): + tree = self.group() + self.accepted(action="addNode", treeKey="G", id="a", blIdname="ShaderNodeMath") + self.accepted(action="addNode", treeKey="G", id="b", blIdname="ShaderNodeMath") + tree.nodes[-1].inputs[3].enabled = False + self.accepted(action="linkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="b", toSocket="Dup") + + def test_invalid_link_is_refused_and_removed(self): + tree = self.group() + tree.links.valid = False + self.accepted(action="addNode", treeKey="G", id="a", blIdname="ShaderNodeMath") + self.accepted(action="addNode", treeKey="G", id="b", blIdname="ShaderNodeMath") + receipt = self.refused(action="linkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="b", toSocket="A") + self.assertIn("not valid", receipt["message"]) # past the cycle check: Blender was asked and said no + self.assertEqual(len(tree.links), 0) + + # addModifier / setModifierInput + def test_modifier_assigns_group_and_reuses_by_name(self): + self.group() + host = self.bpy.data.objects["Host"] + self.accepted(action="addModifier", objectName="Host", modifierName="GN", treeKey="G") + self.accepted(action="addModifier", objectName="Host", modifierName="GN", treeKey="G") + self.assertEqual(len(host.modifiers), 1) + self.assertIs(host.modifiers[0].node_group, self.bpy.data.node_groups["G"]) + self.refused(action="addModifier", objectName="Host", modifierType="SUBSURF", treeKey="G") + self.refused(action="addModifier", objectName="Nope", treeKey="G") + self.refused(action="addModifier", objectName="Host", treeKey="Nope") + + def test_modifier_cap(self): + self.group() + for i in range(na.MAX_MODIFIERS): + self.accepted(action="addModifier", objectName="Host", modifierName=f"m{i}", treeKey="G") + self.refused(action="addModifier", objectName="Host", modifierName="extra", treeKey="G") + + def test_set_modifier_input_writes_value_through_the_struct_and_tags(self): + self.group() + host = self.bpy.data.objects["Host"] + self.accepted(action="addModifier", objectName="Host", modifierName="GN", treeKey="G") + tags = host.tagged + self.accepted(action="setModifierInput", objectName="Host", modifierName="GN", socket="Count", value=12) + self.assertEqual(host.modifiers[0].properties.inputs.Socket_1.value, 12) + self.assertEqual(host.tagged, tags + 1) + self.accepted(action="setModifierInput", objectName="Host", modifierName="GN", socket="Socket_1", value=3) + self.assertEqual(host.modifiers[0].properties.inputs.Socket_1.value, 3) + + def test_set_modifier_input_refusals_change_nothing(self): + self.group() + host = self.bpy.data.objects["Host"] + self.accepted(action="addModifier", objectName="Host", modifierName="GN", treeKey="G") + for socket, value in (("Count", 1.5), ("Count", "x"), ("Count", True), ("Count", None), ("Count", 1e12), ("Nope", 1), ("Geometry", 1), ("", 1)): + self.refused(action="setModifierInput", objectName="Host", modifierName="GN", socket=socket, value=value) + self.refused(action="setModifierInput", objectName="Host", modifierName="other", socket="Count", value=1) + self.assertEqual(host.modifiers[0].properties.inputs.values, {}) + + def test_set_modifier_input_by_name_needs_a_unique_name(self): + tree = self.group([{"inOut": "INPUT", "name": "Dup", "type": "Int"}]) + tree.interface.new_socket("Dup", in_out="INPUT", socket_type="NodeSocketFloat") # a hand-made group can repeat a name + host = self.bpy.data.objects["Host"] + self.accepted(action="addModifier", objectName="Host", modifierName="GN", treeKey="G") + self.refused(action="setModifierInput", objectName="Host", modifierName="GN", socket="Dup", value=1) + self.accepted(action="setModifierInput", objectName="Host", modifierName="GN", socket="Socket_1", value=1.5) + self.assertEqual(host.modifiers[0].properties.inputs.Socket_1.value, 1.5) + + # removal, unlinking, cycles + def chain(self): + tree = self.group() + for node_id in ("a", "b", "c"): + self.accepted(action="addNode", treeKey="G", id=node_id, blIdname="ShaderNodeMath") + return tree + + def test_cycles_and_self_links_are_refused_and_change_nothing(self): + tree = self.chain() + self.accepted(action="linkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="b", toSocket="A") + self.accepted(action="linkSockets", treeKey="G", fromNode="b", fromSocket="Out", toNode="c", toSocket="A") + before = list(tree.links) + for src, dst in (("c", "a"), ("b", "a"), ("a", "a"), ("c", "b")): + receipt = self.refused(action="linkSockets", treeKey="G", fromNode=src, fromSocket="Out", toNode=dst, toSocket="Size") + self.assertIn("cycle", receipt["message"]) + self.assertEqual(list(tree.links), before) + self.accepted(action="linkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="Size") # a forward skip is no cycle + + def test_cycle_detection_survives_fresh_node_wrappers_on_long_chains(self): + tree = self.group() + ids = [f"n{i}" for i in range(12)] + for node_id in ids: + self.accepted(action="addNode", treeKey="G", id=node_id, blIdname="ShaderNodeMath") + for a, b in zip(ids, ids[1:]): + self.accepted(action="linkSockets", treeKey="G", fromNode=a, fromSocket="Out", toNode=b, toSocket="A") + # a diamond ladder: every rung reachable two ways + for a, b in zip(ids[:-2], ids[2:]): + self.accepted(action="linkSockets", treeKey="G", fromNode=a, fromSocket="Out", toNode=b, toSocket="Size") + count = len(tree.links) + for head in ids[:-1]: + self.refused(action="linkSockets", treeKey="G", fromNode=ids[-1], fromSocket="Out", toNode=head, toSocket="Size") + self.assertEqual(len(tree.links), count) + + def test_cycle_through_a_later_branch_is_found(self): + tree = self.group() + for node_id in "abcd": + self.accepted(action="addNode", treeKey="G", id=node_id, blIdname="ShaderNodeMath") + for src, dst in (("a", "b"), ("a", "c"), ("c", "d")): + self.accepted(action="linkSockets", treeKey="G", fromNode=src, fromSocket="Out", toNode=dst, toSocket="A") + self.refused(action="linkSockets", treeKey="G", fromNode="d", fromSocket="Out", toNode="a", toSocket="A") + + def test_cycle_walk_visits_each_node_once_on_a_ladder(self): + tree = self.group() + ids = [f"n{i}" for i in range(40)] + for node_id in ids: + self.accepted(action="addNode", treeKey="G", id=node_id, blIdname="ShaderNodeMath") + for a, b in zip(ids, ids[1:]): + tree.links.new(tree.nodes[2 + ids.index(a)].outputs[0], tree.nodes[2 + ids.index(b)].inputs[0]) + for a, b in zip(ids, ids[2:]): + tree.links.new(tree.nodes[2 + ids.index(a)].outputs[0], tree.nodes[2 + ids.index(b)].inputs[1]) + calls = [] + real = na.node_key + with unittest.mock.patch.object(na, "node_key", lambda n: calls.append(1) or real(n)): + self.assertFalse(na.reaches(tree, tree.nodes[2], NS(pointer=-1, as_pointer=lambda: -1))) + self.assertLess(len(calls), 4 * len(tree.links)) + + def test_remove_node(self): + tree = self.chain() + self.accepted(action="removeNode", treeKey="G", id="b") + self.assertEqual([n.get("brokkr_id") for n in tree.nodes], ["gin", "gout", "a", "c"]) + again = self.accepted(action="removeNode", treeKey="G", id="b") + self.assertIn("already absent", again["message"]) + for keep in ("gin", "gout"): + self.refused(action="removeNode", treeKey="G", id=keep) + self.refused(action="removeNode", treeKey="Nope", id="a") + self.refused(action="removeNode", treeKey="G", id="a b") + + def test_unlink_removes_only_the_matching_links(self): + tree = self.chain() + self.accepted(action="linkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A") + self.accepted(action="linkSockets", treeKey="G", fromNode="b", fromSocket="Out", toNode="c", toSocket="Size") + self.refused(action="unlinkSockets", treeKey="G", fromNode="zzz", fromSocket="Out", toNode="c", toSocket="A") + self.assertIn("Removed 0", self.accepted(action="unlinkSockets", treeKey="G", fromNode="b", fromSocket="Out", toNode="c", toSocket="A")["message"]) + self.assertEqual(len(tree.links), 2) + self.assertIn("Removed 1", self.accepted(action="unlinkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A")["message"]) + self.assertEqual(len(tree.links), 1) + self.accepted(action="unlinkSockets", treeKey="G", toNode="c", toSocket="Size") + self.assertEqual(len(tree.links), 0) + self.refused(action="unlinkSockets", treeKey="G", fromNode="a", toNode="c", toSocket="A") # a source node needs its socket + + def test_remove_modifier_takes_only_geometry_nodes_modifiers(self): + self.group() + host = self.bpy.data.objects["Host"] + self.accepted(action="addModifier", objectName="Host", modifierName="GN", treeKey="G") + host.modifiers.new("Sub", "SUBSURF") + tags = host.tagged + self.refused(action="removeModifier", objectName="Host", modifierName="Sub") + self.assertEqual([m.name for m in host.modifiers], ["GN", "Sub"]) + self.accepted(action="removeModifier", objectName="Host", modifierName="GN") + self.assertEqual([m.name for m in host.modifiers], ["Sub"]) + self.assertEqual(host.tagged, tags + 1) + self.assertIn("already absent", self.accepted(action="removeModifier", objectName="Host", modifierName="GN")["message"]) + self.refused(action="removeModifier", objectName="Nope", modifierName="GN") + for bad in (["x"], "x" * 256, "a\0b", 5): + self.refused(action="removeModifier", objectName="Host", modifierName=bad) + host.modifiers.new("Gé x/y", "NODES") # made by hand: any name Blender allows can be removed + self.accepted(action="removeModifier", objectName="Host", modifierName="Gé x/y") + self.assertEqual([m.name for m in host.modifiers], ["Sub"]) + + # setObjectCustomProperty on a Geometry Nodes host + def test_custom_property_naming_a_modifier_input_identifier_is_refused(self): + self.group() + host = self.bpy.data.objects["Host"] + self.accepted(action="addModifier", objectName="Host", modifierName="GN", treeKey="G") + for name in ("Socket_1", "customProperties.Socket_1"): + receipt = self.refused(action="setObjectCustomProperty", targetObjectName="Host", propertyName=name, value=3) + self.assertIn("setModifierInput", receipt["message"]) + self.assertFalse(hasattr(host, "custom")) + + def test_custom_property_sharing_only_a_display_name_is_an_ordinary_property(self): + self.group() + host = self.bpy.data.objects["Host"] + self.accepted(action="addModifier", objectName="Host", modifierName="GN", treeKey="G") + self.accepted(action="setObjectCustomProperty", targetObjectName="Host", propertyName="Count", value=3) + self.assertEqual(host.custom, ("Count", 3)) + + def test_other_custom_properties_on_the_same_object_still_work(self): + self.group() + host = self.bpy.data.objects["Host"] + self.accepted(action="addModifier", objectName="Host", modifierName="GN", treeKey="G") + self.accepted(action="setObjectCustomProperty", targetObjectName="Host", propertyName="tag", value=3) + self.assertEqual(host.custom, ("tag", 3)) + + # review fixes + def test_refused_link_restores_the_link_it_displaced(self): + tree = self.group() + self.accepted(action="addNode", treeKey="G", id="a", blIdname="ShaderNodeMath") + self.accepted(action="addNode", treeKey="G", id="b", blIdname="ShaderNodeMath") + self.accepted(action="addNode", treeKey="G", id="c", blIdname="ShaderNodeMath") + self.accepted(action="linkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A") + tree.links.valid = lambda a, b: a is not tree.nodes[3].outputs[0] # b.Out -> anything is invalid + self.refused(action="linkSockets", treeKey="G", fromNode="b", fromSocket="Out", toNode="c", toSocket="A") + self.assertEqual([(l.from_socket, l.to_socket) for l in tree.links], [(tree.nodes[2].outputs[0], tree.nodes[4].inputs[0])]) + + def test_refused_link_restores_the_displaced_link_muted_state(self): + tree = self.group() + for node_id in ("a", "b", "c"): + self.accepted(action="addNode", treeKey="G", id=node_id, blIdname="ShaderNodeMath") + self.accepted(action="linkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A") + tree.links[0].is_muted = True + tree.links.valid = lambda a, b: False + self.refused(action="linkSockets", treeKey="G", fromNode="b", fromSocket="Out", toNode="c", toSocket="A") + self.assertEqual([l.is_muted for l in tree.links], [True]) + + def test_ints_are_capped_and_patterns_reject_trailing_newlines(self): + self.group() + self.accepted(action="addNode", treeKey="G", id="ok", blIdname="ShaderNodeMath") + self.refused(action="addNode", treeKey="G", id="a\n", blIdname="ShaderNodeMath") + self.refused(action="createNodeGroup", treeKey="T\n", interface=[{"inOut": "INPUT", "name": "a", "type": "Int"}]) + self.refused(action="createNodeGroup", treeKey="H", interface=[{"inOut": "INPUT", "name": "a", "type": "Int", "default": na.MAX_INT + 1}]) + self.accepted(action="createNodeGroup", treeKey="H", interface=[{"inOut": "INPUT", "name": "a", "type": "Int", "default": na.MAX_INT}]) + + def test_modifier_on_an_object_type_without_modifiers_is_a_clear_refusal(self): + self.group() + host = self.bpy.data.objects["Host"] + host.modifiers.refuses = True + host.type = "CAMERA" + receipt = self.refused(action="addModifier", objectName="Host", treeKey="G") + self.assertIn("CAMERA", receipt["message"]) + + # snapshot + def snapshot_fixture(self, coords, instances): + host = self.bpy.data.objects["Host"] + host.modifiers.new("GN", "NODES") + + class Verts(list): + def foreach_get(self_inner, name, buffer): + flat = [c for v in self_inner for c in v.co] + buffer[:] = type(buffer)("f", flat) + + mesh = NS(vertices=Verts(NS(co=c) for c in coords), edges=[1], polygons=[]) + evaluated = NS(to_mesh=lambda: mesh, to_mesh_clear=lambda: None) + host.evaluated_get = lambda dg: evaluated + self.bpy.context = NS(evaluated_depsgraph_get=lambda: NS(update=lambda: None, object_instances=instances)) + return host + + @staticmethod + def instance(parent, point, is_instance=True): + return NS(is_instance=is_instance, parent=NS(original=parent) if parent else None, matrix_world=NS(translation=point)) + + def evaluated(self, host): + return self.target._evaluated_snapshot(host, self.target._instance_scan()) + + def test_evaluated_snapshot_reports_counts_separate_bounds_and_cap(self): + host = self.bpy.data.objects["Host"] + n = bt.EVALUATED_POSITION_CAP + 2 + other = Obj("other") + instances = [self.instance(host, (0.0, 5.0 + i, 0.0)) for i in range(n)] + [self.instance(other, (9.0, 9.0, 9.0)), self.instance(None, (8.0, 8.0, 8.0), False)] + host = self.snapshot_fixture([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (2.0, 0.0, 0.0)], instances) + data = self.evaluated(host) + self.assertEqual((data["vertexCount"], data["edgeCount"], data["instanceCount"]), (3, 1, n)) + self.assertEqual((data["vertexBoundsMin"], data["vertexBoundsMax"]), ([0.0, 0.0, 0.0], [2.0, 0.0, 0.0])) + self.assertEqual((data["instanceBoundsMin"], data["instanceBoundsMax"]), ([0.0, 5.0, 0.0], [0.0, 5.0 + n - 1, 0.0])) + self.assertEqual((len(data["instanceLocations"]), len(data["vertexLocations"]), data["truncated"]), (bt.EVALUATED_POSITION_CAP, 3, True)) + self.assertFalse(data["nonFinite"]) + + def test_non_finite_positions_are_flagged_not_published(self): + host = self.snapshot_fixture([(0.0, 0.0, 0.0), (float("inf"), 0.0, 0.0)], []) + data = self.evaluated(host) + self.assertTrue(data["nonFinite"]) + self.assertEqual((data["vertexLocations"], data["vertexBoundsMin"], data["vertexBoundsMax"]), ([], [], [])) + host = self.snapshot_fixture([(0.0, 0.0, 0.0)], [self.instance(host, (float("nan"), 0.0, 0.0))]) + data = self.evaluated(host) + self.assertTrue(data["nonFinite"] and data["instanceLocations"] == [] and data["instanceBoundsMin"] == []) + + def test_a_huge_evaluated_mesh_reports_counts_only(self): + host = self.snapshot_fixture([(0.0, 0.0, 0.0)] * 3, []) + with unittest.mock.patch.object(bt, "EVALUATED_VERTEX_LIMIT", 2): + data = self.evaluated(host) + self.assertEqual((data["vertexCount"], data["positionsSkipped"], data["vertexLocations"], data["vertexBoundsMin"]), (3, True, [], [])) + + def test_per_object_snapshots_reuse_the_one_scan(self): + host = self.snapshot_fixture([(0.0, 0.0, 0.0)], []) + calls = [] + get = self.bpy.context.evaluated_depsgraph_get + self.bpy.context.evaluated_depsgraph_get = lambda: calls.append(1) or get() + scan = self.target._instance_scan() + for _ in range(3): + self.target._evaluated_snapshot(host, scan) + self.assertEqual(len(calls), 1) + + def test_instance_scan_stops_at_the_limit_and_says_so(self): + host = self.bpy.data.objects["Host"] + visited = [] + + def many(): + for i in range(50): + visited.append(i) + yield self.instance(host, (float(i), 0.0, 0.0)) + + host = self.snapshot_fixture([(0.0, 0.0, 0.0)], many()) + with unittest.mock.patch.object(bt, "EVALUATED_INSTANCE_SCAN_LIMIT", 10): + scan = self.target._instance_scan() + data = self.target._evaluated_snapshot(host, scan) + self.assertEqual((data["instanceCount"], data["instancesComplete"]), (10, False)) + other = Obj("Other") + other.modifiers.new("GN", "NODES") + other.evaluated_get = host.evaluated_get + self.assertIsNone(self.target._evaluated_snapshot(other, scan)["instanceCount"]) # never reached: unknown, not 0 + self.assertLessEqual(len(visited), 11) # the generator is abandoned, not drained + host = self.snapshot_fixture([(0.0, 0.0, 0.0)], [self.instance(host, (1.0, 0.0, 0.0))]) + self.assertTrue(self.evaluated(host)["instancesComplete"]) + + def test_object_without_modifiers_has_no_evaluated_block(self): + self.assertIsNone(self.target._evaluated_snapshot(self.bpy.data.objects["Host"], None)) + self.assertIsNone(self.target._evaluated_snapshot(self.bpy.data.objects["Host"], (None, {}, True))) + + +if __name__ == "__main__": + unittest.main() From ece40040f46fb3e4221725861d855f4210320f0a Mon Sep 17 00:00:00 2001 From: Libby Date: Tue, 10 Nov 2026 14:31:06 +0000 Subject: [PATCH 004/223] blender: createObject refuses unknown objectType and non-cube meshType TEXT and CURVE used to fall through to an EMPTY with an accepted receipt. Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/blender_target.py | 12 +++++- surfaces/blender/docs/install.md | 4 ++ surfaces/blender/tests/test_scene_actions.py | 41 ++++++++++++++++++- 3 files changed, 54 insertions(+), 3 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 628c199..dcae328 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -34,6 +34,8 @@ SYNC_VAR_SCHEMA = "brokkr.sync.var.v0" SYNC_TIMELINE_BINDING_SCHEMA = "brokkr.sync.timeline_binding.v0" SYNC_RECEIPT_SCHEMA = "brokkr.sync.receipt.v0" +CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY") + EVALUATED_POSITION_CAP = 256 EVALUATED_VERTEX_LIMIT = 1_000_000 EVALUATED_INSTANCE_SCAN_LIMIT = 100_000 # depsgraph items visited per capture; iterating one in Python costs ~5 us @@ -518,6 +520,14 @@ class BrokkrBlenderTarget: def _create_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: object_type = command.get("objectType", "EMPTY") + if not isinstance(object_type, str) or object_type not in CREATABLE_OBJECT_TYPES: + shown = object_type if isinstance(object_type, str) else repr(object_type) + raise sa.ActionRefused( + f"objectType {shown!r} cannot be created; allowed: {', '.join(CREATABLE_OBJECT_TYPES)}.") + mesh_type = command.get("meshType") + if object_type == "MESH" and mesh_type is not None and ( + not isinstance(mesh_type, str) or mesh_type.upper() != "CUBE"): + raise sa.ActionRefused(f"meshType {mesh_type!r} is not available; a MESH is a CUBE.") name = command.get("name") or f"Brokkr {object_type.title()}" location = _vector(command.get("location"), 3, (0.0, 0.0, 0.0)) @@ -527,7 +537,7 @@ class BrokkrBlenderTarget: self.bpy.ops.object.light_add(type=command.get("lightType", "POINT"), location=location) elif object_type == "CAMERA": self.bpy.ops.object.camera_add(location=location) - else: + else: # EMPTY self.bpy.ops.object.empty_add(type=command.get("emptyDisplayType", "PLAIN_AXES"), location=location) obj = context.object diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 6548af4..04d5a1e 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -116,6 +116,10 @@ Admitted command actions: Scene action fields (all other keys are ignored; a refused intent changes nothing and gets a `failed` receipt whose message names the rule): +- `createObject`: optional `objectType` (`MESH`, `LIGHT`, `CAMERA`, `EMPTY`; default `EMPTY`), + `name`, `location`. Any other `objectType` (for example `TEXT` or `CURVE`) is refused with + the allowed set named. A `MESH` is a cube (`size`); a `meshType` other than `CUBE` + (case-insensitive) is refused rather than ignored. - `importGltf`: `filepath`, `.gltf` or `.glb`, relative to the add-on preference `Import Directory` (absolute paths, `..` and symlinks that resolve outside it are refused). Empty `Import Directory` disables the action. Needs Blender's glTF add-on. diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index 6244188..aa4b498 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -86,7 +86,19 @@ class FakeBpy: worlds=NS(get=lambda name: None, new=self.new_world), ) self.path = NS(abspath=lambda p: p) - self.ops = NS(import_scene=NS(gltf=self.import_gltf), render=NS(render=self.render_still)) + self.created = [] + self.app = NS(background=False) + add = lambda kind: (lambda **kw: self.add_object(kind, kw)) + self.ops = NS(import_scene=NS(gltf=self.import_gltf), render=NS(render=self.render_still), + mesh=NS(primitive_cube_add=add("MESH")), object=NS(light_add=add("LIGHT"), + camera_add=add("CAMERA"), empty_add=add("EMPTY"))) + self.on_add = lambda obj: None + + def add_object(self, kind, kwargs): + self.created.append((kind, kwargs)) + obj = NS(name=kind.title(), type=kind) + self.data.objects[obj.name] = obj + self.on_add(obj) def new_world(self, name): background = NS(inputs={"Color": NS(default_value=None), "Strength": NS(default_value=None)}) @@ -117,7 +129,8 @@ class ActionTests(unittest.TestCase): self.bpy = FakeBpy() self.target = bt.BrokkrBlenderTarget(self.bpy) self.target.configure_action_dirs(str(self.root / "in"), str(self.root / "out")) - self.context = NS(scene=self.bpy.scene) + self.context = NS(scene=self.bpy.scene, object=None) + self.bpy.on_add = lambda obj: setattr(self.context, "object", obj) def run_action(self, **command): command.setdefault("commandId", "c1") @@ -238,6 +251,30 @@ class ActionTests(unittest.TestCase): self.target.configure_action_dirs(str(self.root / "in"), "") self.assertEqual(self.run_action(action="renderStill", outputPath="a.png")["status"], "failed") + # createObject + def test_create_object_makes_the_four_admitted_types(self): + for kind in ("MESH", "LIGHT", "CAMERA", "EMPTY"): + receipt = self.run_action(action="createObject", objectType=kind, name="N") + self.assertEqual(receipt["status"], "accepted", kind) + self.assertEqual(self.bpy.created[-1][0], kind) + self.assertEqual(self.run_action(action="createObject", objectType="MESH", meshType="cube")["status"], "accepted") + + def test_create_object_refuses_other_types_naming_the_type_and_the_allowed_set(self): + for kind in ("TEXT", "CURVE", "mesh", "", None, 3): + receipt = self.run_action(action="createObject", objectType=kind) + self.assertEqual(receipt["status"], "failed", kind) + for allowed in ("MESH", "LIGHT", "CAMERA", "EMPTY"): + self.assertIn(allowed, receipt["message"]) + self.assertIn(repr(kind) if not isinstance(kind, str) else kind, receipt["message"]) + self.assertEqual(self.bpy.created, []) + + def test_create_object_refuses_a_mesh_type_other_than_cube(self): + for mesh_type in ("CYLINDER", "", 1): + receipt = self.run_action(action="createObject", objectType="MESH", meshType=mesh_type) + self.assertEqual(receipt["status"], "failed", mesh_type) + self.assertIn("CUBE", receipt["message"]) + self.assertEqual(self.bpy.created, []) + # importGltf: names def test_import_refuses_drive_unc_extended_stream_and_device_names(self): for name in ("C:foo.glb", "C:\\x\\model.glb", "\\\\host\\share\\model.glb", "\\\\?\\C:\\model.glb", From 6b7d6ae9e2db549313eab38e59c1990b323e2e6f Mon Sep 17 00:00:00 2001 From: Libby Date: Tue, 10 Nov 2026 14:31:58 +0000 Subject: [PATCH 005/223] blender: renderStill refuses GL engines headless when libEGL is not loadable BLENDER_WORKBENCH and BLENDER_EEVEE aborted the whole Blender process inside bpy.ops.render.render with no receipt. The probe is cached, Linux only, and a module-level function so tests replace it. Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/blender_target.py | 26 ++++++++++ surfaces/blender/docs/install.md | 7 ++- surfaces/blender/tests/test_scene_actions.py | 48 +++++++++++++++++++ 3 files changed, 80 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index dcae328..641928f 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -1,5 +1,7 @@ from __future__ import annotations +import ctypes +import functools import json import math import os @@ -36,6 +38,11 @@ SYNC_RECEIPT_SCHEMA = "brokkr.sync.receipt.v0" CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY") +# Engines that draw through the GL stack. A headless Linux Blender without libEGL aborts the whole +# process inside bpy.ops.render.render for these (no receipt); CYCLES renders on the CPU. +GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT") +GL_RUNTIME_LIBRARY = "libEGL.so.1" + EVALUATED_POSITION_CAP = 256 EVALUATED_VERTEX_LIMIT = 1_000_000 EVALUATED_INSTANCE_SCAN_LIMIT = 100_000 # depsgraph items visited per capture; iterating one in Python costs ~5 us @@ -751,6 +758,12 @@ class BrokkrBlenderTarget: render.engine = engine except TypeError: raise sa.ActionRefused(f"engine {engine} is not available in this Blender.") from None + if render.engine in GL_RENDER_ENGINES and getattr(getattr(self.bpy, "app", None), "background", False): + missing = missing_gl_library() + if missing: + raise sa.ActionRefused( + f"engine {render.engine} needs {missing}, which this headless Blender cannot load " + "(rendering would abort the process); use engine CYCLES.") if width is not None: render.resolution_x = width if height is not None: @@ -1033,6 +1046,19 @@ def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: return cultmesh_py, cultcache_py +@functools.lru_cache(maxsize=None) +def missing_gl_library() -> str | None: + """The GL runtime library this host cannot load, or None. Probed once, on Linux only: on + Windows and macOS a failed GPU render is not a headless-EGL abort.""" + if not sys.platform.startswith("linux"): + return None + try: + ctypes.CDLL(GL_RUNTIME_LIBRARY) + except OSError: + return GL_RUNTIME_LIBRARY + return None + + def _now() -> str: return datetime.now(timezone.utc).isoformat() diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 04d5a1e..6f3ad73 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -137,7 +137,12 @@ gets a `failed` receipt whose message names the rule): `engine` (any engine of the running Blender, case-insensitive), `resolutionX`, `resolutionY` (whole numbers, 1 to 16384), `cameraName`. Engine, resolution, camera, file path and format are restored after the render. The render blocks - Blender's UI until it finishes. + Blender's UI until it finishes. In a background (`-b`) Blender on Linux, the GL + engines `BLENDER_WORKBENCH`, `BLENDER_EEVEE` and `BLENDER_EEVEE_NEXT` are refused + with a `failed` receipt when `libEGL.so.1` cannot be loaded (probed once), because + rendering would abort the whole process with no receipt; `CYCLES` renders on the + CPU. The check applies to the scene's engine when `engine` is omitted. No such + check runs on Windows or macOS. The scene actions were run against Blender 5.2.3 LTS headless with `surfaces/blender/tests/live/headless_smoke.py` (usage in its docstring). One real diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index aa4b498..88ff453 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -275,6 +275,54 @@ class ActionTests(unittest.TestCase): self.assertIn("CUBE", receipt["message"]) self.assertEqual(self.bpy.created, []) + # renderStill: GPU engines without a GL runtime + def test_render_still_refuses_gpu_engines_headless_when_the_gl_library_is_missing(self): + self.bpy.app.background = True + for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT", "blender_workbench"): + self.bpy.scene.render.ENGINES = FakeRender.ENGINES + ("BLENDER_EEVEE_NEXT",) + with mock.patch.object(bt, "missing_gl_library", return_value="libEGL.so.1"): + receipt = self.run_action(action="renderStill", outputPath="a.png", engine=engine) + self.assertEqual(receipt["status"], "failed", engine) + self.assertIn("libEGL.so.1", receipt["message"]) + self.assertIn("CYCLES", receipt["message"]) + self.assertEqual(self.bpy.rendered, []) + self.assertEqual(self.bpy.scene.render.engine, "BLENDER_EEVEE") + + def test_render_still_refuses_the_scene_engine_too_and_leaves_no_folder(self): + self.bpy.app.background = True # scene engine is BLENDER_EEVEE + with mock.patch.object(bt, "missing_gl_library", return_value="libEGL.so.1"): + receipt = self.run_action(action="renderStill", outputPath="shots/a.png") + self.assertEqual(receipt["status"], "failed") + self.assertFalse((self.root / "out" / "shots").exists()) + + def test_render_still_gl_check_spares_cycles_foreground_and_a_present_library(self): + probe = mock.Mock(return_value="libEGL.so.1") + with mock.patch.object(bt, "missing_gl_library", probe): + self.bpy.app.background = True + self.assertEqual(self.run_action(action="renderStill", outputPath="a.png", engine="CYCLES")["status"], "accepted") + probe.assert_not_called() + self.bpy.app.background = False + self.assertEqual(self.run_action(action="renderStill", outputPath="b.png", engine="BLENDER_WORKBENCH")["status"], "accepted") + probe.assert_not_called() + self.bpy.app.background = True + probe.return_value = None + self.assertEqual(self.run_action(action="renderStill", outputPath="c.png", engine="BLENDER_WORKBENCH")["status"], "accepted") + + def test_missing_gl_library_probes_only_on_linux_and_only_once(self): + bt.missing_gl_library.cache_clear() + with mock.patch.object(bt.sys, "platform", "win32"), mock.patch.object(bt.ctypes, "CDLL", side_effect=OSError) as cdll: + self.assertIsNone(bt.missing_gl_library()) + cdll.assert_not_called() + bt.missing_gl_library.cache_clear() + with mock.patch.object(bt.sys, "platform", "linux"), mock.patch.object(bt.ctypes, "CDLL", side_effect=OSError) as cdll: + self.assertEqual(bt.missing_gl_library(), "libEGL.so.1") + self.assertEqual(bt.missing_gl_library(), "libEGL.so.1") + cdll.assert_called_once_with("libEGL.so.1") + bt.missing_gl_library.cache_clear() + with mock.patch.object(bt.sys, "platform", "linux"), mock.patch.object(bt.ctypes, "CDLL"): + self.assertIsNone(bt.missing_gl_library()) + bt.missing_gl_library.cache_clear() + # importGltf: names def test_import_refuses_drive_unc_extended_stream_and_device_names(self): for name in ("C:foo.glb", "C:\\x\\model.glb", "\\\\host\\share\\model.glb", "\\\\?\\C:\\model.glb", From 8cebec6f3c6397b54024de831463f8e4dcee87ae Mon Sep 17 00:00:00 2001 From: Libby Date: Tue, 10 Nov 2026 18:00:37 +0000 Subject: [PATCH 006/223] Blender assignMaterial: colour, idempotent slot, malformed colour refused (#6) --- .../blender/brokkr_bridge/blender_target.py | 16 +- .../blender/brokkr_bridge/scene_actions.py | 26 +++- surfaces/blender/docs/install.md | 9 ++ .../blender/tests/live/material_colour.py | 55 +++++++ .../blender/tests/test_material_actions.py | 147 ++++++++++++++++++ 5 files changed, 247 insertions(+), 6 deletions(-) create mode 100644 surfaces/blender/tests/live/material_colour.py create mode 100644 surfaces/blender/tests/test_material_actions.py diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 628c199..3d86317 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -610,12 +610,22 @@ class BrokkrBlenderTarget: if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") + if not (obj.data and hasattr(obj.data, "materials")): + return self._receipt(command, "failed", "Target object cannot receive materials.", obj.name) + rgba = sa.color_rgba(command) # refused before anything is created or changed material_name = command.get("materialName") or "Brokkr Material" material = self.bpy.data.materials.get(material_name) or self.bpy.data.materials.new(material_name) - if obj.data and hasattr(obj.data, "materials"): + if rgba is not None: + if not material.use_nodes or material.node_tree is None: + material.use_nodes = True + nodes = material.node_tree.nodes + principled = nodes.get("Principled BSDF") or next( + (n for n in nodes if n.bl_idname == "ShaderNodeBsdfPrincipled"), None) or nodes.new("ShaderNodeBsdfPrincipled") + principled.inputs["Base Color"].default_value = rgba + material.diffuse_color = rgba + if not any(slot is not None and slot.name == material.name for slot in obj.data.materials): obj.data.materials.append(material) - return self._receipt(command, "accepted", "Blender material assigned.", obj.name) - return self._receipt(command, "failed", "Target object cannot receive materials.", obj.name) + return self._receipt(command, "accepted", "Blender material assigned.", obj.name) def _import_gltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: name = str(command.get("filepath") or "") diff --git a/surfaces/blender/brokkr_bridge/scene_actions.py b/surfaces/blender/brokkr_bridge/scene_actions.py index ef0ada7..415185c 100644 --- a/surfaces/blender/brokkr_bridge/scene_actions.py +++ b/surfaces/blender/brokkr_bridge/scene_actions.py @@ -187,6 +187,15 @@ def integer(command: dict[str, Any], key: str, low: int, high: int) -> int | Non return int(value) +def unit_component(key: str, item: Any) -> float: + """One colour component: a number in [0, 1]. The range test comes first: it also refuses nan and inf, + and a huge int (10**400) never reaches math.isfinite, which would raise OverflowError instead of + naming the field.""" + if isinstance(item, bool) or not isinstance(item, (int, float)) or not 0.0 <= item <= 1.0: + raise ActionRefused(f"{key} components must be numbers between 0 and 1.") + return float(item) + + def color(command: dict[str, Any], key: str = "color") -> tuple[float, float, float] | None: """Linear RGB, three finite numbers in [0, 1], or None when absent.""" if key not in command or command[key] is None: @@ -196,12 +205,23 @@ def color(command: dict[str, Any], key: str = "color") -> tuple[float, float, fl raise ActionRefused(f"{key} must be three numbers [r, g, b].") parts = [] for item in value: - if isinstance(item, bool) or not isinstance(item, (int, float)) or not math.isfinite(item) or not 0.0 <= item <= 1.0: - raise ActionRefused(f"{key} components must be numbers between 0 and 1.") - parts.append(float(item)) + parts.append(unit_component(key, item)) return (parts[0], parts[1], parts[2]) +def color_rgba(command: dict[str, Any], key: str = "color") -> tuple[float, float, float, float] | None: + """Linear RGB or RGBA, finite numbers in [0, 1] (RGB gets alpha 1), or None when absent.""" + if key not in command or command[key] is None: + return None + value = command[key] + if not isinstance(value, (list, tuple)) or len(value) not in (3, 4): + raise ActionRefused(f"{key} must be [r, g, b] or [r, g, b, a].") + parts = [] + for item in value: + parts.append(unit_component(key, item)) + return (parts[0], parts[1], parts[2], parts[3] if len(parts) == 4 else 1.0) + + def choice(command: dict[str, Any], key: str, allowed: Iterable[str]) -> str | None: if key not in command or command[key] is None: return None diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 6548af4..3d01134 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -128,6 +128,15 @@ gets a `failed` receipt whose message names the rule): `color` (linear `[r, g, b]`, each 0 to 1), `lightType` (`POINT`, `SUN`, `SPOT`, `AREA`). - `setWorld`: optional `worldName` (default: the scene's world, created if there is none), `color` (`[r, g, b]`), `strength`. Edits the world's Background node. +- `assignMaterial`: `targetObjectName` (an object with material slots, such as a mesh); + optional `materialName` (default `Brokkr Material`; an existing material of that name + is reused) and `color` (linear `[r, g, b]` or `[r, g, b, a]`, each a finite number 0 + to 1; alpha defaults to 1). `color` sets the Principled BSDF Base Color (the node tree + is created if the material has none) and `diffuse_color`; a malformed `color` is + refused naming the field and nothing is created or changed (`"color": null` counts as absent). Without `color` an + existing material's colour is left as it is. Idempotent per (object, material): if the + object already has a slot with that material no second slot is added. Other keys are + ignored, as for every action. - `renderStill`: `outputPath` relative to the preference `Render Output Directory`, ending `.png`, `.jpg` or `.exr` (same containment rules as import); optional `engine` (any engine of the running Blender, case-insensitive), `resolutionX`, diff --git a/surfaces/blender/tests/live/material_colour.py b/surfaces/blender/tests/live/material_colour.py new file mode 100644 index 0000000..4b43135 --- /dev/null +++ b/surfaces/blender/tests/live/material_colour.py @@ -0,0 +1,55 @@ +"""Live proof of assignMaterial colour and idempotence on real bpy. + + BROKKR_ADDON= \ + blender -b --factory-startup --python material_colour.py -- result.json + +Exit status is non-zero if any check fails. +""" +import bpy, sys, os, json, types +from pathlib import Path + +ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() +pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)] +sys.modules["brokkr_bridge"] = pkg +from brokkr_bridge import blender_target as bt + +out = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else "material_colour_result.json" +R = {"blender": bpy.app.version_string, "checks": []} + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}); print("CHECK", "ok " if ok else "FAIL", name, detail if not ok else "", flush=True) + +bpy.ops.wm.read_factory_settings(use_empty=True) +t = bt.BrokkrBlenderTarget(bpy) +bpy.ops.mesh.primitive_cube_add() +cube = bpy.context.active_object +N = [0] +def act(**cmd): + N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]); cmd["action"] = "assignMaterial"; cmd["targetObjectName"] = cube.name + return t.execute_command(bpy.context, cmd) + +def base(): + return tuple(round(c, 6) for c in bpy.data.materials["oxide red"].node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value) + +r = act(materialName="oxide red", color=[0.56, 0.2, 0.12]) +check("oxide red accepted", r["status"] == "accepted", r["message"]) +check("principled base color", base() == (0.56, 0.2, 0.12, 1.0), base()) +m = bpy.data.materials["oxide red"] +check("diffuse_color", tuple(round(c, 6) for c in m.diffuse_color) == (0.56, 0.2, 0.12, 1.0), tuple(m.diffuse_color)) +check("one slot", len(cube.material_slots) == 1, len(cube.material_slots)) +r = act(materialName="oxide red", color=[0.56, 0.2, 0.12]) +check("repeat accepted", r["status"] == "accepted", r["message"]) +check("repeat keeps one slot", len(cube.material_slots) == 1, len(cube.material_slots)) +r = act(materialName="oxide red") +check("no color leaves colour", r["status"] == "accepted" and base() == (0.56, 0.2, 0.12, 1.0), base()) +r = act(materialName="oxide red", color=[0.1, 0.2, 0.3, 0.5]) +check("rgba recolours", base() == (0.1, 0.2, 0.3, 0.5) and len(cube.material_slots) == 1, base()) +for bad in ([1, 2], [2, 0, 0], [float("nan"), 0, 0], "red"): + r = act(materialName="oxide red", color=bad) + check("bad colour refused %r" % (bad,), r["status"] == "failed" and "color" in r["message"], r["message"]) +check("refusals left colour", base() == (0.1, 0.2, 0.3, 0.5), base()) +r = act(materialName="never made", color=[7, 0, 0]) +check("refusal creates no material", "never made" not in bpy.data.materials) + +json.dump(R, open(out, "w"), indent=1) +sys.exit(0 if all(c["ok"] for c in R["checks"]) else 1) diff --git a/surfaces/blender/tests/test_material_actions.py b/surfaces/blender/tests/test_material_actions.py new file mode 100644 index 0000000..9ecc2ec --- /dev/null +++ b/surfaces/blender/tests/test_material_actions.py @@ -0,0 +1,147 @@ +"""assignMaterial tests. No Blender: a fake bpy with materials, slots and a Principled node. + +Run: python3 -m unittest discover -s surfaces/blender/tests -v +The real API is exercised by tests/live/material_colour.py. +""" +from __future__ import annotations + +import sys +import types +import unittest +from pathlib import Path + +ADDON = Path(__file__).resolve().parents[1] / "brokkr_bridge" +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(ADDON)] +sys.modules.setdefault("brokkr_bridge", package) + +from brokkr_bridge import blender_target as bt # noqa: E402 + +NS = types.SimpleNamespace + + +class Nodes(dict): + def new(self, idname): + node = NS(bl_idname=idname, inputs={"Base Color": NS(default_value=(0.8, 0.8, 0.8, 1.0))}) + self["Principled BSDF"] = node + return node + + +class Material: + def __init__(self, name): + self.name, self.diffuse_color, self.node_tree = name, (0.8, 0.8, 0.8, 1.0), None + self._use_nodes = False + + @property + def use_nodes(self): + return self._use_nodes + + @use_nodes.setter + def use_nodes(self, value): # Blender creates the default tree, with a Principled BSDF, on first use + self._use_nodes = value + if value and self.node_tree is None: + self.node_tree = NS(nodes=Nodes()) + self.node_tree.nodes.new("ShaderNodeBsdfPrincipled") + + +class Materials(dict): + def new(self, name): + self[name] = Material(name) + return self[name] + + +class FakeBpy: + def __init__(self): + self.mesh = NS(name="Cube", type="MESH", data=NS(materials=[])) + self.empty = NS(name="Empty", type="EMPTY", data=None) + self.data = NS(objects={"Cube": self.mesh, "Empty": self.empty}, materials=Materials()) + + +class MaterialTests(unittest.TestCase): + def setUp(self): + self.bpy = FakeBpy() + self.target = bt.BrokkrBlenderTarget(self.bpy) + + def assign(self, **fields): + return self.target.execute_command(NS(), {"commandId": "c1", "action": "assignMaterial", + "targetObjectName": "Cube", **fields}) + + def base_color(self, name="oxide red"): + return tuple(self.bpy.data.materials[name].node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value) + + def test_rgb_colour_sets_base_color_and_diffuse_with_alpha_one(self): + receipt = self.assign(materialName="oxide red", color=[0.56, 0.2, 0.12]) + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + material = self.bpy.data.materials["oxide red"] + self.assertEqual(self.base_color(), (0.56, 0.2, 0.12, 1.0)) + self.assertEqual(tuple(material.diffuse_color), (0.56, 0.2, 0.12, 1.0)) + self.assertTrue(material.use_nodes) + self.assertEqual(self.bpy.mesh.data.materials, [material]) + + def test_rgba_colour_keeps_its_alpha(self): + self.assign(materialName="glass", color=[0.1, 0.2, 0.3, 0.5]) + self.assertEqual(self.base_color("glass"), (0.1, 0.2, 0.3, 0.5)) + self.assertEqual(tuple(self.bpy.data.materials["glass"].diffuse_color), (0.1, 0.2, 0.3, 0.5)) + + def test_the_colour_limits_themselves_are_accepted(self): + self.assign(materialName="black", color=[0, 0, 0]) + self.assertEqual(self.base_color("black"), (0.0, 0.0, 0.0, 1.0)) + self.assign(materialName="white", color=[1, 1, 1, 1]) + self.assertEqual(self.base_color("white"), (1.0, 1.0, 1.0, 1.0)) + self.assign(materialName="clear", color=[1.0, 0.0, 0.5, 0]) + self.assertEqual(self.base_color("clear"), (1.0, 0.0, 0.5, 0.0)) + + def test_an_explicit_null_colour_is_no_colour(self): + self.assertEqual(self.assign(materialName="plain", color=None)["status"], "accepted") + self.assertEqual(tuple(self.bpy.data.materials["plain"].diffuse_color), (0.8, 0.8, 0.8, 1.0)) + + def test_no_colour_leaves_a_new_material_at_blender_defaults(self): + self.assertEqual(self.assign(materialName="plain")["status"], "accepted") + self.assertEqual(tuple(self.bpy.data.materials["plain"].diffuse_color), (0.8, 0.8, 0.8, 1.0)) + + def test_malformed_colour_is_refused_naming_color_and_changes_nothing(self): + for bad in ([1], [1, 0], [0, 0, 0, 1, 1], "red", 0.5, {"r": 1}, ["a", 0, 0], [True, 0, 0], [None, 0, 0], + [float("nan"), 0, 0], [float("inf"), 0, 0], [-0.1, 0, 0], [1.1, 0, 0], [0, 0, 0, 2], + [1.0000001, 0, 0], [-1e-9, 0, 0], [0, 0, 0, 1.0000001], [10**400, 0, 0], [0, -10**400, 0]): + receipt = self.assign(materialName="oxide red", color=bad) + self.assertEqual(receipt["status"], "failed", bad) + self.assertIn("color", receipt["message"], bad) + self.assertEqual(dict(self.bpy.data.materials), {}) + self.assertEqual(self.bpy.mesh.data.materials, []) + + def test_assigning_twice_keeps_one_slot(self): + self.assign(materialName="oxide red", color=[0.5, 0.1, 0.1]) + self.assign(materialName="oxide red", color=[0.5, 0.1, 0.1]) + self.assertEqual(len(self.bpy.mesh.data.materials), 1) + self.assign(materialName="charcoal") + self.assertEqual([m.name for m in self.bpy.mesh.data.materials], ["oxide red", "charcoal"]) + + def test_reusing_a_material_recolours_only_when_colour_is_given(self): + self.assign(materialName="oxide red", color=[0.5, 0.1, 0.1]) + self.assign(materialName="oxide red") + self.assertEqual(self.base_color(), (0.5, 0.1, 0.1, 1.0)) + self.assign(materialName="oxide red", color=[0.9, 0.9, 0.9]) + self.assertEqual(self.base_color(), (0.9, 0.9, 0.9, 1.0)) + self.assertEqual(len(self.bpy.mesh.data.materials), 1) + + def test_refused_colour_on_an_existing_material_leaves_it_alone(self): + self.assign(materialName="oxide red", color=[0.5, 0.1, 0.1]) + self.assertEqual(self.assign(materialName="oxide red", color=[2, 0, 0])["status"], "failed") + self.assertEqual(self.base_color(), (0.5, 0.1, 0.1, 1.0)) + + def test_existing_tree_without_a_principled_node_gets_one(self): + material = self.bpy.data.materials.new("bare") + material.use_nodes = True + material.node_tree.nodes.clear() + self.assertEqual(self.assign(materialName="bare", color=[0.2, 0.3, 0.4])["status"], "accepted") + self.assertEqual(self.base_color("bare"), (0.2, 0.3, 0.4, 1.0)) + + def test_object_without_material_slots_is_refused(self): + receipt = self.target.execute_command(NS(), {"commandId": "c", "action": "assignMaterial", + "targetObjectName": "Empty", "color": [1, 0, 0]}) + self.assertEqual(receipt["status"], "failed") + self.assertEqual(dict(self.bpy.data.materials), {}) + + +if __name__ == "__main__": + unittest.main() From 730ceb9e0eae94ba660112443fefc56275472f34 Mon Sep 17 00:00:00 2001 From: Libby Date: Tue, 10 Nov 2026 18:01:28 +0000 Subject: [PATCH 007/223] Blender add-on: exportGltf action (#7) --- brokkr-daemon/src/main.rs | 2 + .../blender/brokkr_bridge/blender_target.py | 58 ++++++++ .../blender/brokkr_bridge/scene_actions.py | 2 +- surfaces/blender/docs/install.md | 11 ++ surfaces/blender/tests/test_scene_actions.py | 131 +++++++++++++++++- 5 files changed, 201 insertions(+), 3 deletions(-) diff --git a/brokkr-daemon/src/main.rs b/brokkr-daemon/src/main.rs index 3b05166..48600c5 100644 --- a/brokkr-daemon/src/main.rs +++ b/brokkr-daemon/src/main.rs @@ -245,6 +245,7 @@ fn build_provider_advertisement() -> ProviderAdvertisement { "selection.read", "selection.write", "asset.import.gltf", + "asset.export.gltf", "camera.write", "light.write", "world.write", @@ -1994,6 +1995,7 @@ mod tests { assert!(blender.capabilities.contains(&"material.assign")); for scene_and_graph in [ "asset.import.gltf", + "asset.export.gltf", "camera.write", "light.write", "world.write", diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 3d86317..faaaf11 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -52,6 +52,7 @@ CAPABILITIES = ( "selection.read", "selection.write", "asset.import.gltf", + "asset.export.gltf", "camera.write", "light.write", "world.write", @@ -499,6 +500,8 @@ class BrokkrBlenderTarget: return self._assign_material(context, command) if action == "importGltf": return self._import_gltf(context, command) + if action == "exportGltf": + return self._export_gltf(context, command) if action == "setCamera": return self._set_camera(context, command) if action == "setLight": @@ -646,6 +649,61 @@ class BrokkrBlenderTarget: added = sorted(set(self.bpy.data.objects.keys()) - before) return self._receipt(command, "accepted", f"Imported {len(added)} object(s) from {path.name}.", added[0] if added else "") + def _export_gltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + """Write the scene (or the named objects) as .glb or .gltf under the output directory.""" + name = command.get("filepath") + if not isinstance(name, str): + raise sa.ActionRefused("filepath must be a string.") + path = sa.resolve_inside(self.output_dir, name, "output", new_file=True) + suffix = path.suffix.lower() + if suffix not in sa.GLTF_EXTENSIONS: + raise sa.ActionRefused(f"Export path must end in {' or '.join(sa.GLTF_EXTENSIONS)}.") + options = {} + for field, key in (("extras", "export_extras"), ("yUp", "export_yup"), ("applyModifiers", "export_apply")): + value = command.get(field, True) + if not isinstance(value, bool): + raise sa.ActionRefused(f"{field} must be true or false.") + options[key] = value + names = command.get("selection") + chosen = [] + if names is not None: + if not isinstance(names, list) or not names or not all(isinstance(n, str) and n for n in names): + raise sa.ActionRefused("selection must be a non-empty list of object names.") + missing = [n for n in names if n not in self.bpy.data.objects] + if missing: + raise sa.ActionRefused(f"Selection object was not found: {missing[0]}") + chosen = [self.bpy.data.objects[n] for n in dict.fromkeys(names)] + # select_set raises for an object with no base in the view layer (another scene, an + # orphan, an excluded collection), and use_selection exports only selected layer objects. + off_layer = [o.name for o in chosen if o.name not in context.view_layer.objects] + if off_layer: + raise sa.ActionRefused(f"Selection object is not in the active view layer: {off_layer[0]}") + binary = path.with_suffix(".bin") + if suffix == ".gltf" and os.path.lexists(binary): + raise sa.ActionRefused("output path already exists; output actions never overwrite: " + binary.name) + path.parent.mkdir(parents=True, exist_ok=True) + # Re-check after the folders exist and just before use (residual TOCTOU as in renderStill). + if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: + raise sa.ActionRefused("Output path changed while it was being checked.") + # The selection is touched only when one was asked for, and only on view-layer objects. + objects = list(context.view_layer.objects.values()) if chosen else [] + saved = [(obj, obj.select_get()) for obj in objects] + try: + for obj in objects: + obj.select_set(obj in chosen) + result = self.bpy.ops.export_scene.gltf( + filepath=str(path), export_format="GLB" if suffix == ".glb" else "GLTF_SEPARATE", + use_selection=bool(chosen), **options) + finally: + for obj, state in saved: + if obj.name in self.bpy.data.objects: + obj.select_set(state) + if "FINISHED" not in result: + raise sa.ActionRefused(f"glTF export did not finish: {sorted(result)}") + if not path.is_file(): + raise sa.ActionRefused("glTF export wrote no file.") + return self._receipt(command, "accepted", f"Exported glTF to {path} ({path.stat().st_size} bytes).", "") + def _resolve_typed(self, command: dict[str, Any], object_type: str) -> Any: obj = self._resolve_object(command) if obj is None: diff --git a/surfaces/blender/brokkr_bridge/scene_actions.py b/surfaces/blender/brokkr_bridge/scene_actions.py index 415185c..98dcb40 100644 --- a/surfaces/blender/brokkr_bridge/scene_actions.py +++ b/surfaces/blender/brokkr_bridge/scene_actions.py @@ -98,7 +98,7 @@ def resolve_inside(root: str, candidate: str, label: str, *, new_file: bool = Fa except ValueError: raise ActionRefused(f"{label} path is outside the configured {label} directory.") from None if new_file and os.path.lexists(current): - raise ActionRefused(f"{label} path already exists; renderStill never overwrites or writes through an existing name.") + raise ActionRefused(f"{label} path already exists; output actions never overwrite or write through an existing name.") return current diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 3d01134..0de60b9 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -108,6 +108,7 @@ Admitted command actions: - `selectObject` - `assignMaterial` - `importGltf` +- `exportGltf` - `setCamera` - `setLight` - `setWorld` @@ -119,6 +120,16 @@ gets a `failed` receipt whose message names the rule): - `importGltf`: `filepath`, `.gltf` or `.glb`, relative to the add-on preference `Import Directory` (absolute paths, `..` and symlinks that resolve outside it are refused). Empty `Import Directory` disables the action. Needs Blender's glTF add-on. +- `exportGltf`: `filepath`, `.glb` (binary) or `.gltf` (separate `.bin`), relative to the + add-on preference `Render Output Directory` (the renderStill rules: no `..`, no links, and an + existing name, or an existing `.bin` beside a `.gltf`, is refused; there is no overwrite). + Optional `extras` (custom properties become node `extras`), `yUp`, `applyModifiers` + (each true by default, must be a boolean) and `selection` (a non-empty list of object + names; any name not found, or not in the active view layer, refuses the export; the + selection is touched only when one is given, and restored afterwards). Not checked: texture + files a `.gltf` export writes beside it (only the `.bin` is), and a link or swap made between the + check and the write (the same residual as renderStill). + The receipt message carries the written path and byte size. Needs Blender's glTF add-on. - `setCamera`: `targetObjectName` (a camera object); optional `lens` (mm), `cameraType` (`PERSP`, `ORTHO`, `PANO`), `panoramaType` (for example `EQUIRECTANGULAR`; read from the camera, or from `camera.cycles` before Blender 4.2), diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index 6244188..43b4020 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -86,7 +86,15 @@ class FakeBpy: worlds=NS(get=lambda name: None, new=self.new_world), ) self.path = NS(abspath=lambda p: p) - self.ops = NS(import_scene=NS(gltf=self.import_gltf), render=NS(render=self.render_still)) + self.exported = [] + self.export_result = {"FINISHED"} + self.export_writes = True + for o in self.data.objects.values(): + o.selected = o is self.mesh + o.select_get = (lambda o=o: o.selected) + o.select_set = (lambda state, o=o: setattr(o, "selected", state)) + self.ops = NS(import_scene=NS(gltf=self.import_gltf), render=NS(render=self.render_still), + export_scene=NS(gltf=self.export_gltf)) def new_world(self, name): background = NS(inputs={"Color": NS(default_value=None), "Strength": NS(default_value=None)}) @@ -99,6 +107,13 @@ class FakeBpy: self.imported.append(filepath) self.data.objects["Imported"] = NS(name="Imported", type="MESH", data=None) + def export_gltf(self, **kwargs): + kwargs["selected_at_call"] = sorted(o.name for o in self.data.objects.values() if o.selected) + self.exported.append(kwargs) + if self.export_writes: + Path(kwargs["filepath"]).write_bytes(b"x" * 10) + return self.export_result + def render_still(self, write_still): r = self.scene.render self.rendered.append((r.engine, r.resolution_x, r.resolution_y, r.filepath, @@ -117,7 +132,7 @@ class ActionTests(unittest.TestCase): self.bpy = FakeBpy() self.target = bt.BrokkrBlenderTarget(self.bpy) self.target.configure_action_dirs(str(self.root / "in"), str(self.root / "out")) - self.context = NS(scene=self.bpy.scene) + self.context = NS(scene=self.bpy.scene, view_layer=NS(objects=Objects(dict(self.bpy.data.objects.items())))) def run_action(self, **command): command.setdefault("commandId", "c1") @@ -206,6 +221,118 @@ class ActionTests(unittest.TestCase): self.assertEqual(self.run_action(action="setWorld", color=[9, 0, 0])["status"], "failed") self.assertIsNone(self.bpy.scene.world) + # exportGltf + def test_export_glb_defaults(self): + receipt = self.run_action(action="exportGltf", filepath="ship/a.glb") + self.assertEqual(receipt["status"], "accepted", receipt) + path = str(self.root / "out" / "ship" / "a.glb") + self.assertIn(path, receipt["message"]) + self.assertIn("10 bytes", receipt["message"]) + call = self.bpy.exported[0] + self.assertEqual({k: v for k, v in call.items() if k != "selected_at_call"}, + {"filepath": path, "export_format": "GLB", "export_extras": True, + "export_yup": True, "export_apply": True, "use_selection": False}) + + def test_export_gltf_suffix_is_separate_and_options_pass_through(self): + receipt = self.run_action(action="exportGltf", filepath="a.GLTF", extras=False, yUp=False, + applyModifiers=False) + self.assertEqual(receipt["status"], "accepted", receipt) + call = self.bpy.exported[0] + self.assertEqual((call["export_format"], call["export_extras"], call["export_yup"], call["export_apply"]), + ("GLTF_SEPARATE", False, False, False)) + + def test_export_selection_selects_exactly_those_then_restores(self): + receipt = self.run_action(action="exportGltf", filepath="a.glb", selection=["Cam", "Lamp"]) + self.assertEqual(receipt["status"], "accepted", receipt) + call = self.bpy.exported[0] + self.assertTrue(call["use_selection"]) + self.assertEqual(call["selected_at_call"], ["Cam", "Lamp"]) + self.assertEqual([o.name for o in self.bpy.data.objects.values() if o.selected], ["Cube"]) + + def test_export_without_a_selection_never_touches_selection(self): + def explode(*a, **k): + raise AssertionError("selection touched") + for o in self.bpy.data.objects.values(): + o.select_set = explode + o.select_get = explode + receipt = self.run_action(action="exportGltf", filepath="a.glb") + self.assertEqual(receipt["status"], "accepted", receipt) + self.assertFalse(self.bpy.exported[0]["use_selection"]) + + def test_export_selection_ignores_objects_outside_the_view_layer_and_refuses_naming_one(self): + def not_in_layer(state): + raise RuntimeError("Object can't be selected because it is not in View Layer") + other = NS(name="Other", type="MESH", data=None, selected=False, select_get=lambda: False, select_set=not_in_layer) + self.bpy.data.objects["Other"] = other + ok = self.run_action(action="exportGltf", filepath="a.glb", selection=["Cam"]) + self.assertEqual(ok["status"], "accepted", ok) + self.assertEqual(self.bpy.exported[0]["selected_at_call"], ["Cam"]) + refused = self.run_action(action="exportGltf", filepath="b.glb", selection=["Cam", "Other"]) + self.assertEqual(refused["status"], "failed") + self.assertIn("Other", refused["message"]) + self.assertIn("view layer", refused["message"]) + self.assertEqual(len(self.bpy.exported), 1) + self.assertFalse((self.root / "out" / "b.glb").exists()) + + def test_export_selection_restored_when_the_exporter_raises(self): + def boom(**kw): + raise RuntimeError("exporter blew up") + self.bpy.ops.export_scene.gltf = boom + receipt = self.run_action(action="exportGltf", filepath="a.glb", selection=["Cam"]) + self.assertEqual(receipt["status"], "failed") + self.assertIn("exporter blew up", receipt["message"]) + self.assertEqual([o.name for o in self.bpy.data.objects.values() if o.selected], ["Cube"]) + + def test_export_refusals_never_reach_bpy_or_disk(self): + (self.root / "out" / "taken.glb").write_bytes(b"old") + cases = [ + {"filepath": "a.obj"}, {"filepath": "a"}, {"filepath": ""}, {"filepath": 5}, + {"filepath": "../a.glb"}, {"filepath": str(self.root / "a.glb")}, + {"filepath": "taken.glb"}, + {"filepath": "a.glb", "selection": ["Nope"]}, + {"filepath": "a.glb", "selection": ["Cube", "Nope"]}, + {"filepath": "a.glb", "selection": []}, + {"filepath": "a.glb", "selection": "Cube"}, + {"filepath": "a.glb", "selection": [3]}, + {"filepath": "a.glb", "extras": "yes"}, + {"filepath": "a.glb", "yUp": 1}, + {"filepath": "a.glb", "applyModifiers": None}, + ] + for case in cases: + self.assertEqual(self.run_action(action="exportGltf", **case)["status"], "failed", case) + self.assertEqual(self.bpy.exported, []) + self.assertEqual((self.root / "out" / "taken.glb").read_bytes(), b"old") + self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["taken.glb"]) + self.assertIn("already exists", self.run_action(action="exportGltf", filepath="taken.glb")["message"]) + + def test_export_gltf_refuses_an_existing_bin_sibling(self): + (self.root / "out" / "a.bin").write_bytes(b"old") + self.assertEqual(self.run_action(action="exportGltf", filepath="a.gltf")["status"], "failed") + self.assertEqual(self.bpy.exported, []) + + def test_export_refuses_a_symlinked_folder(self): + os.symlink(self.root, self.root / "out" / "link") + self.assertEqual(self.run_action(action="exportGltf", filepath="link/a.glb")["status"], "failed") + self.assertEqual(self.bpy.exported, []) + + def test_export_disabled_without_output_dir(self): + self.target.configure_action_dirs(str(self.root / "in"), "") + self.assertEqual(self.run_action(action="exportGltf", filepath="a.glb")["status"], "failed") + + def test_export_cancelled_or_no_file_is_failed(self): + self.bpy.export_result = {"CANCELLED"} + self.assertEqual(self.run_action(action="exportGltf", filepath="a.glb")["status"], "failed") + self.bpy.export_result, self.bpy.export_writes = {"FINISHED"}, False + receipt = self.run_action(action="exportGltf", filepath="b.glb") + self.assertEqual((receipt["status"], receipt["message"]), ("failed", "glTF export wrote no file.")) + + def test_export_names_the_missing_selection_object(self): + receipt = self.run_action(action="exportGltf", filepath="a.glb", selection=["Cube", "Nope"]) + self.assertEqual(receipt["message"], "Selection object was not found: Nope") + + def test_export_is_advertised(self): + self.assertIn("asset.export.gltf", bt.CAPABILITIES) + # renderStill def test_render_still_writes_inside_output_dir_and_restores_settings(self): receipt = self.run_action(action="renderStill", outputPath="shots/a.png", engine="cycles", From 01d25c6bf98dc5683d64ea9beea50d31eee5762f Mon Sep 17 00:00:00 2001 From: Libby Date: Tue, 10 Nov 2026 23:13:57 +0000 Subject: [PATCH 008/223] Blender createObject: pin whitespace meshType refusal, document meshType and null objectType Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/docs/install.md | 5 +++-- surfaces/blender/tests/test_scene_actions.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 06ab1c9..f27093b 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -120,7 +120,8 @@ gets a `failed` receipt whose message names the rule): - `createObject`: optional `objectType` (`MESH`, `LIGHT`, `CAMERA`, `EMPTY`; default `EMPTY`), `name`, `location`. Any other `objectType` (for example `TEXT` or `CURVE`) is refused with the allowed set named. A `MESH` is a cube (`size`); a `meshType` other than `CUBE` - (case-insensitive) is refused rather than ignored. + (case-insensitive, no surrounding whitespace) is refused rather than ignored. + `meshType` is checked only when `objectType` is `MESH`; an explicit `objectType: null` is refused. - `importGltf`: `filepath`, `.gltf` or `.glb`, relative to the add-on preference `Import Directory` (absolute paths, `..` and symlinks that resolve outside it are refused). Empty `Import Directory` disables the action. Needs Blender's glTF add-on. @@ -159,7 +160,7 @@ gets a `failed` receipt whose message names the rule): camera, file path and format are restored after the render. The render blocks Blender's UI until it finishes. In a background (`-b`) Blender on Linux, the GL engines `BLENDER_WORKBENCH`, `BLENDER_EEVEE` and `BLENDER_EEVEE_NEXT` are refused - with a `failed` receipt when `libEGL.so.1` cannot be loaded (probed once), because + with a `failed` receipt when `libEGL.so.1` cannot be loaded (probed once and cached for the life of the process), because rendering would abort the whole process with no receipt; `CYCLES` renders on the CPU. The check applies to the scene's engine when `engine` is omitted. No such check runs on Windows or macOS. diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index 1235776..bb3a292 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -397,7 +397,7 @@ class ActionTests(unittest.TestCase): self.assertEqual(self.bpy.created, []) def test_create_object_refuses_a_mesh_type_other_than_cube(self): - for mesh_type in ("CYLINDER", "", 1): + for mesh_type in ("CYLINDER", "", 1, " CUBE", "CUBE "): receipt = self.run_action(action="createObject", objectType="MESH", meshType=mesh_type) self.assertEqual(receipt["status"], "failed", mesh_type) self.assertIn("CUBE", receipt["message"]) From f891404ee3d8cef450c8a725e5420566b5167b71 Mon Sep 17 00:00:00 2001 From: Libby Date: Tue, 10 Nov 2026 23:15:55 +0000 Subject: [PATCH 009/223] node-actions.md: point to the parked design tag Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/docs/node-actions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/surfaces/blender/docs/node-actions.md b/surfaces/blender/docs/node-actions.md index 3458b95..cdbb556 100644 --- a/surfaces/blender/docs/node-actions.md +++ b/surfaces/blender/docs/node-actions.md @@ -3,7 +3,7 @@ Command intents (`brokkr.blender.command_intent.v0`) that build and drive a Geometry Nodes graph. Owner: `brokkr_bridge/node_actions.py`; the target only dispatches. Every field is validated before `bpy` is touched; a refused intent is a `failed` receipt naming the rule and leaves the tree as it was. -Design and the parts not built yet: the design document lives in PR #3 (branch `libby/blender-node-graphs-design`), not in this tree. +Design and the parts not built yet: the design lives at tag `parked/blender-node-graphs-design` (branch `libby/blender-node-graphs-design`, PR #3, closed unmerged), not in this tree. | action | fields | rule | |---|---|---| From a371056f04ad5daee879cb5dc915f6b07132090b Mon Sep 17 00:00:00 2001 From: Eureka Date: Fri, 27 Nov 2026 18:59:16 +0000 Subject: [PATCH 010/223] Brokkr on MessagePack payloads: strict reads through cultcache-rs, pins at CultLib baf4ecf7 (#11) --- Cargo.lock | 134 +++++++++- brokkr-daemon/Cargo.toml | 2 +- brokkr-daemon/src/main.rs | 237 +++++++++++++----- .../blender/brokkr_bridge/blender_target.py | 51 +++- surfaces/blender/docs/install.md | 12 + surfaces/blender/tests/test_store_convert.py | 129 ++++++++++ tools/check.ps1 | 3 + 7 files changed, 486 insertions(+), 82 deletions(-) create mode 100644 surfaces/blender/tests/test_store_convert.py diff --git a/Cargo.lock b/Cargo.lock index 6736cc7..dabf833 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,15 @@ version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -29,6 +38,15 @@ version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "brokkr-daemon" version = "0.1.0" @@ -83,10 +101,29 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cultcache-rs" -version = "0.1.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=c2a9a6e526390808ef195759056fda0b9a55d8a3#c2a9a6e526390808ef195759056fda0b9a55d8a3" +version = "0.3.1" +source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb" dependencies = [ "anyhow", "chrono", @@ -97,20 +134,33 @@ dependencies = [ "serde", "serde_bytes", "serde_json", + "serde_stacker", + "sha2", + "stacker", "uuid", "windows-sys 0.59.0", ] [[package]] name = "cultcache-rs-derive" -version = "0.1.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=c2a9a6e526390808ef195759056fda0b9a55d8a3#c2a9a6e526390808ef195759056fda0b9a55d8a3" +version = "0.2.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb" dependencies = [ "proc-macro2", "quote", "syn", ] +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -179,6 +229,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "getrandom" version = "0.4.2" @@ -311,6 +371,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -342,6 +411,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "quote" version = "1.0.45" @@ -463,6 +542,28 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_stacker" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a" +dependencies = [ + "serde", + "serde_core", + "stacker", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -475,6 +576,19 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "syn" version = "2.0.117" @@ -499,6 +613,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -522,6 +642,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" diff --git a/brokkr-daemon/Cargo.toml b/brokkr-daemon/Cargo.toml index 5839b77..58bbccf 100644 --- a/brokkr-daemon/Cargo.toml +++ b/brokkr-daemon/Cargo.toml @@ -6,7 +6,7 @@ publish = false [dependencies] anyhow = "1" -cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c2a9a6e526390808ef195759056fda0b9a55d8a3", package = "cultcache-rs" } +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" } rmp-serde = "1.3" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/brokkr-daemon/src/main.rs b/brokkr-daemon/src/main.rs index 48600c5..f83e29b 100644 --- a/brokkr-daemon/src/main.rs +++ b/brokkr-daemon/src/main.rs @@ -767,7 +767,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { &source.local_position, ); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!("blender/commands/{command_id}"), &command, @@ -843,7 +843,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { "scale": source.local_scale, }); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!( "blender/commands/{}", @@ -874,7 +874,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { "visible": source.active_self, }); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!( "blender/commands/{}", @@ -924,7 +924,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { &parent_name, ); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!("blender/commands/{command_id}"), &command, @@ -961,7 +961,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { material, ); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!("blender/commands/{command_id}"), &command, @@ -1013,7 +1013,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { "value": property.value, }); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!( "blender/commands/{}", @@ -1368,8 +1368,8 @@ fn run_sync_once(args: &SyncArgs) -> Result { "sync/receipts/{}", receipt["receiptId"].as_str().unwrap_or("sync-receipt") ); - unity_store.put_json_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; - blender_store.put_json_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; + unity_store.put_messagepack_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; + blender_store.put_messagepack_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; report.receipts_written += 2; } @@ -1390,9 +1390,10 @@ impl MirrorStore { fn documents(&mut self) -> Result> { let mut documents = Vec::new(); for envelope in self.store.pull_all()? { - let value = decode_payload(&envelope).with_context(|| { - format!("failed to decode {} at {}", envelope.r#type, envelope.key) - })?; + let value = + cultcache_rs::decode_payload::(&envelope.payload).with_context(|| { + format!("failed to decode {} at {}", envelope.r#type, envelope.key) + })?; documents.push(CacheDocument { key: envelope.key, value, @@ -1401,17 +1402,6 @@ impl MirrorStore { Ok(documents) } - fn put_json_document(&mut self, schema: &str, key: &str, value: &Value) -> Result<()> { - let payload = serde_json::to_vec(value)?; - self.store.push(&CultCacheEnvelope { - key: key.to_string(), - r#type: schema.to_string(), - payload, - stored_at: chrono_like_now(), - schema_id: Some(schema.to_string()), - }) - } - fn put_messagepack_document(&mut self, schema: &str, key: &str, value: &Value) -> Result<()> { let payload = rmp_serde::to_vec(value)?; self.store.push(&CultCacheEnvelope { @@ -1420,21 +1410,11 @@ impl MirrorStore { payload, stored_at: chrono_like_now(), schema_id: Some(schema.to_string()), - }) + })?; + Ok(()) } } -fn decode_payload(envelope: &CultCacheEnvelope) -> Result { - serde_json::from_slice(&envelope.payload) - .or_else(|_| rmp_serde::from_slice(&envelope.payload)) - .with_context(|| { - format!( - "payload is neither MessagePack nor JSON for {}", - envelope.key - ) - }) -} - fn parse_object_binding(value: &Value) -> Option { Some(ObjectBinding { binding_id: field_string(value, 1, "bindingId")?, @@ -2699,7 +2679,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2714,7 +2694,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2729,7 +2709,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-transform", &json!({ @@ -2746,7 +2726,7 @@ mod tests { }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -2772,7 +2752,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2787,7 +2767,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2802,7 +2782,7 @@ mod tests { "authority": "unity-to-blender" }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ "objects": [] }), @@ -2815,12 +2795,12 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ "sceneObjects": [] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2834,7 +2814,7 @@ mod tests { "authority": "blender-to-unity" }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -2856,7 +2836,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2883,7 +2863,7 @@ mod tests { ] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-rig", &json!({ @@ -2898,7 +2878,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2913,7 +2893,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-parent", &json!({ @@ -2929,7 +2909,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -2963,7 +2943,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2979,7 +2959,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2994,7 +2974,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-material", &json!({ @@ -3010,7 +2990,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3033,7 +3013,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -3048,7 +3028,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -3063,7 +3043,7 @@ mod tests { "authority": "blender-to-unity" }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-active", &json!({ @@ -3079,7 +3059,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3106,7 +3086,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -3131,7 +3111,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -3146,7 +3126,7 @@ mod tests { "authority": "unity-to-blender" }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-component-speed", &json!({ @@ -3162,7 +3142,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3189,7 +3169,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -3204,7 +3184,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -3219,7 +3199,7 @@ mod tests { "authority": "blender-to-unity" }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-custom-intensity", &json!({ @@ -3235,7 +3215,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3261,7 +3241,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.timeline_binding.v0", "sync/bindings/timelines/timeline-camera", &json!({ @@ -3280,7 +3260,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3329,4 +3309,127 @@ mod tests { ); Ok(()) } + + fn raw_envelope(key: &str, payload: Vec) -> CultCacheEnvelope { + CultCacheEnvelope { + key: key.to_string(), + r#type: "brokkr.sync.receipt.v0".to_string(), + payload, + stored_at: chrono_like_now(), + schema_id: Some("brokkr.sync.receipt.v0".to_string()), + } + } + + #[test] + fn store_read_refuses_trailing_bytes() -> Result<()> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("store.ccmp"); + let mut raw = SingleFileMessagePackBackingStore::new(&path); + let clean = rmp_serde::to_vec(&json!({"a": 1}))?; + raw.push(&raw_envelope("k/clean", clean.clone()))?; + let documents = MirrorStore::open(&path)?.documents()?; + assert_eq!(documents.len(), 1); + assert_eq!(documents[0].value, json!({"a": 1})); + + let mut dirty = clean; + dirty.push(0xc0); + raw.push(&raw_envelope("k/dirty", dirty))?; + let message = format!("{:#}", MirrorStore::open(&path)?.documents().unwrap_err()); + assert!(message.contains("k/dirty"), "{message}"); + assert!(!message.to_lowercase().contains("c0"), "{message}"); + Ok(()) + } + + #[test] + fn store_read_refuses_json_payload() -> Result<()> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("store.ccmp"); + let receipt = json!({"schema": "brokkr.sync.receipt.v0", "status": "ok"}); + SingleFileMessagePackBackingStore::new(&path).push(&raw_envelope( + "sync/receipts/json", + serde_json::to_vec(&receipt)?, + ))?; + let message = format!("{:#}", MirrorStore::open(&path)?.documents().unwrap_err()); + assert!(message.contains("sync/receipts/json"), "{message}"); + Ok(()) + } + + #[test] + fn sync_once_writes_unity_active_state_to_blender_visibility_command() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_component_property_stores(&unity_path, &blender_path, "active-state")?; + + let report = run_sync_once(&SyncArgs { + unity_cache: unity_path, + blender_cache: blender_path.clone(), + dry_run: false, + })?; + + assert_eq!(report.blender_commands_written, 1, "{report:#?}"); + let command = MirrorStore::open(&blender_path)? + .documents()? + .into_iter() + .find(|document| document.key.starts_with("blender/commands/")) + .expect("Brokkr should emit a Blender visibility command"); + assert_eq!(command.value["action"], "setObjectVisibility"); + assert_eq!(command.value["targetObjectName"], "Cube"); + assert_eq!(command.value["visible"], true); + Ok(()) + } + + #[test] + fn dry_run_counts_active_state_command_but_writes_none() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_component_property_stores(&unity_path, &blender_path, "active-state")?; + + let report = run_sync_once(&SyncArgs { + unity_cache: unity_path, + blender_cache: blender_path.clone(), + dry_run: true, + })?; + + assert_eq!(report.blender_commands_written, 1, "{report:#?}"); + assert!( + MirrorStore::open(&blender_path)? + .documents()? + .iter() + .all(|document| !document.key.starts_with("blender/commands/")), + "a dry run must not write a command intent" + ); + Ok(()) + } + + #[test] + fn sync_once_writes_messagepack_receipts() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_sync_stores(&unity_path, &blender_path, "unity-to-blender")?; + run_sync_once(&SyncArgs { + unity_cache: unity_path.clone(), + blender_cache: blender_path.clone(), + dry_run: false, + })?; + + for path in [&unity_path, &blender_path] { + let store = SingleFileMessagePackBackingStore::new(path); + let envelopes = store.pull_all()?; + let receipt = envelopes + .iter() + .find(|envelope| envelope.r#type == "brokkr.sync.receipt.v0") + .expect("store should hold the daemon sync receipt"); + let lead = receipt.payload.first().copied().unwrap_or(0); + assert!( + (0x80..=0x8f).contains(&lead) || lead == 0xde || lead == 0xdf, + "receipt payload should be a MessagePack map, led by {lead:#04x}" + ); + assert!(serde_json::from_slice::(&receipt.payload).is_err()); + assert!(cultcache_rs::decode_payload::(&receipt.payload)?.is_object()); + } + Ok(()) + } } diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 0c49412..677f03d 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -1026,16 +1026,7 @@ class BrokkrBlenderTarget: return self._node, self._documents cultmesh, cultcache = _load_cultmesh(cultlib_py_src) - documents = { - "host_snapshot": cultcache.define_document_type(HOST_SNAPSHOT_SCHEMA), - "command_intent": cultcache.define_document_type(COMMAND_INTENT_SCHEMA), - "command_receipt": cultcache.define_document_type(COMMAND_RECEIPT_SCHEMA), - "sync_session": cultcache.define_document_type(SYNC_SESSION_SCHEMA), - "sync_object_binding": cultcache.define_document_type(SYNC_OBJECT_BINDING_SCHEMA), - "sync_var": cultcache.define_document_type(SYNC_VAR_SCHEMA), - "sync_timeline_binding": cultcache.define_document_type(SYNC_TIMELINE_BINDING_SCHEMA), - "sync_receipt": cultcache.define_document_type(SYNC_RECEIPT_SCHEMA), - } + documents = bridge_documents(cultcache) node = cultmesh.CultMesh.start_node(path, runtime_id=runtime_id) for document in documents.values(): node.database.register_document(document) @@ -1095,6 +1086,41 @@ class BrokkrBlenderTarget: }) +def bridge_documents(cultcache: Any) -> dict[str, Any]: + """The bridge's eight document definitions, under cultcache-py's default (MessagePack) payload codec.""" + return { + "host_snapshot": cultcache.define_document_type(HOST_SNAPSHOT_SCHEMA), + "command_intent": cultcache.define_document_type(COMMAND_INTENT_SCHEMA), + "command_receipt": cultcache.define_document_type(COMMAND_RECEIPT_SCHEMA), + "sync_session": cultcache.define_document_type(SYNC_SESSION_SCHEMA), + "sync_object_binding": cultcache.define_document_type(SYNC_OBJECT_BINDING_SCHEMA), + "sync_var": cultcache.define_document_type(SYNC_VAR_SCHEMA), + "sync_timeline_binding": cultcache.define_document_type(SYNC_TIMELINE_BINDING_SCHEMA), + "sync_receipt": cultcache.define_document_type(SYNC_RECEIPT_SCHEMA), + } + + +def convert_store(source: str, destination: str, cultlib_py_src: str = "") -> int: + """Write the records of a bridge store to a new MessagePack file and return the count converted. + JSON payloads (the old default) are converted; MessagePack payloads, such as records the new daemon already + appended to the old store, are carried through. The destination must not exist and the source is never written: + stop every writer, convert, then swap the files.""" + _cultmesh, cultcache = _load_cultmesh(cultlib_py_src) + json_codec, msgpack_codec = cultcache.JSON_PAYLOAD_CODEC, cultcache.MESSAGEPACK_PAYLOAD_CODEC + + def decode_either(payload: bytes) -> Any: + # A JSON object or array never starts like a MessagePack map or array, so a payload JSON refuses is MessagePack. + try: + return json_codec.decode(payload) + except Exception: + return msgpack_codec.decode(payload) + + either = cultcache.PayloadCodec("JSON or MessagePack", json_codec.encode, decode_either) + return cultcache.convert( + cultcache.SingleFileMessagePackBackingStore(source), destination, bridge_documents(cultcache).values(), + source_codec=either) + + def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: packages = Path(cultlib_py_src or DEFAULT_CULTLIB_PY_SRC) for name in CULTLIB_PY_PACKAGES: @@ -1111,6 +1137,11 @@ def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: "Brokkr Blender target requires CultLib's Python packages. Set CultLib Python Source " "to the CultLib packages directory or install cultcache-py, cultnet-py and cultmesh-py into Blender's Python." ) from exc + if not hasattr(cultcache_py, "convert"): + raise RuntimeError( + "Brokkr Blender target requires CultLib's cultcache-py with the MessagePack payload default " + "(CultLib main after the py-msgpack-default merge); the cultcache-py found here predates it. " + "Update the CultLib checkout named by CultLib Python Source.") return cultmesh_py, cultcache_py diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index f27093b..3b3a93d 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -16,6 +16,18 @@ directory; the add-on puts each package's `src` on `sys.path`: F:/Projects/CultLib/packages ``` +That CultLib checkout must carry cultcache-py's MessagePack payload default +(CultLib main after the py-msgpack-default merge); the add-on refuses an older +one. A `.brokkr/blender-editor.ccmp` written under the JSON default is +converted into a new file, never in place: close Blender, stop the daemon, +convert, check the new file opens, then swap it in for the original: + +```text +py -3 -c "import sys; sys.path.insert(0, r'/surfaces/blender/brokkr_bridge'); import blender_target as t; print(t.convert_store(r'/blender-editor.ccmp', r'/blender-editor.mp.ccmp'))" +``` + +The command prints the record count and leaves the source unwritten. Records a new daemon already appended (MessagePack) are carried into the new file. + The default node cache is: ```text diff --git a/surfaces/blender/tests/test_store_convert.py b/surfaces/blender/tests/test_store_convert.py new file mode 100644 index 0000000..17d6506 --- /dev/null +++ b/surfaces/blender/tests/test_store_convert.py @@ -0,0 +1,129 @@ +"""convert_store and the CultLib guard. No Blender, no bpy. + +Run: CULTLIB_PACKAGES= python3 -m unittest discover -s surfaces/blender/tests -v +Needs the msgpack package and CultLib main with cultcache-py's MessagePack payload default. +""" +from __future__ import annotations + +import hashlib +import os +import sys +import tempfile +import types +import unittest +from pathlib import Path + +ADDON = Path(__file__).resolve().parents[1] / "brokkr_bridge" +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(ADDON)] +sys.modules.setdefault("brokkr_bridge", package) + +from brokkr_bridge import blender_target as bt # noqa: E402 + +PACKAGES = os.environ.get("CULTLIB_PACKAGES", "") + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +@unittest.skipUnless(PACKAGES and Path(PACKAGES).is_dir(), "set CULTLIB_PACKAGES to CultLib's packages directory") +class ConvertStoreTests(unittest.TestCase): + def setUp(self): + self.cultmesh, self.cultcache = bt._load_cultmesh(PACKAGES) + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.dir = Path(self.temp.name) + self.source = self.dir / "blender-editor.ccmp" + self.records = {} + old_definitions = [ + self.cultcache.define_document_type(d.type, payload_codec=self.cultcache.JSON_PAYLOAD_CODEC) + for d in bt.bridge_documents(self.cultcache).values() + ] + node = self.cultmesh.CultMesh.start_node(str(self.source), runtime_id="brokkr-test") + for definition in old_definitions: + node.database.register_document(definition) + key = f"test/{definition.type}" + value = {"schema": definition.type, "id": key, "n": 7, "nested": {"a": [1, 2, "é"]}} + node.database.put(definition, key, value) + self.records[(definition.type, key)] = value + # What the old daemon wrote: a raw JSON receipt envelope. + receipt = {"schema": bt.SYNC_RECEIPT_SCHEMA, "receiptId": "r1", "status": "ok"} + store = self.cultcache.SingleFileMessagePackBackingStore(self.source) + import json + store.push(self.cultcache.CultCacheEnvelope( + key="sync/receipts/r1", type=bt.SYNC_RECEIPT_SCHEMA, payload=json.dumps(receipt).encode(), + stored_at="2026-11-27T00:00:00Z", schema_id=bt.SYNC_RECEIPT_SCHEMA)) + self.records[(bt.SYNC_RECEIPT_SCHEMA, "sync/receipts/r1")] = receipt + + def test_converted_store_opens_under_default(self): + import msgpack + before = sha256(self.source) + destination = self.dir / "blender-editor.mp.ccmp" + count = bt.convert_store(str(self.source), str(destination), PACKAGES) + self.assertEqual(count, len(self.records)) + self.assertEqual(sha256(self.source), before) + + node = self.cultmesh.CultMesh.start_node(str(destination), runtime_id="brokkr-test-new") + documents = bt.bridge_documents(self.cultcache) + for document in documents.values(): + node.database.register_document(document) + node.database.pull() + snapshot = node.database.snapshot() + for (schema, key), value in self.records.items(): + self.assertEqual(snapshot[schema][key], value, (schema, key)) + for envelope in self.cultcache.SingleFileMessagePackBackingStore(destination).pull_all(): + decoded = msgpack.unpackb(envelope.payload, raw=False) # raises ExtraData on a trailing byte + self.assertIsInstance(decoded, dict, envelope.key) + + def test_mixed_store_converts_json_and_carries_messagepack(self): + import msgpack + # What the new daemon appends to an old store before the operator converts it. + appended = {"schema": bt.SYNC_RECEIPT_SCHEMA, "receiptId": "r2", "status": "ok"} + self.cultcache.SingleFileMessagePackBackingStore(self.source).push(self.cultcache.CultCacheEnvelope( + key="sync/receipts/r2", type=bt.SYNC_RECEIPT_SCHEMA, payload=msgpack.packb(appended), + stored_at="2026-11-27T01:00:00Z", schema_id=bt.SYNC_RECEIPT_SCHEMA)) + before = sha256(self.source) + destination = self.dir / "mixed.mp.ccmp" + self.assertEqual(bt.convert_store(str(self.source), str(destination), PACKAGES), len(self.records) + 1) + self.assertEqual(sha256(self.source), before) + node = self.cultmesh.CultMesh.start_node(str(destination), runtime_id="brokkr-test-mixed") + for document in bt.bridge_documents(self.cultcache).values(): + node.database.register_document(document) + node.database.pull() + snapshot = node.database.snapshot() + self.assertEqual(snapshot[bt.SYNC_RECEIPT_SCHEMA]["sync/receipts/r2"], appended) + for (schema, key), value in self.records.items(): + self.assertEqual(snapshot[schema][key], value, (schema, key)) + + def test_convert_store_writes_only_a_new_file(self): + destination = self.dir / "new.ccmp" + bt.convert_store(str(self.source), str(destination), PACKAGES) + source_bytes, destination_bytes = self.source.read_bytes(), destination.read_bytes() + with self.assertRaises(Exception) as caught: + bt.convert_store(str(self.source), str(destination), PACKAGES) + self.assertIn("destination_exists", str(caught.exception)) + self.assertEqual(self.source.read_bytes(), source_bytes) + self.assertEqual(destination.read_bytes(), destination_bytes) + + +class LoadGuardTests(unittest.TestCase): + def test_load_cultmesh_refuses_json_default_cultcache(self): + names = ("cultcache_py", "cultmesh_py") + saved = {name: sys.modules.get(name) for name in names} + try: + sys.modules["cultcache_py"] = types.ModuleType("cultcache_py") # no convert + sys.modules["cultmesh_py"] = types.ModuleType("cultmesh_py") + with self.assertRaises(RuntimeError) as caught: + bt._load_cultmesh("") + self.assertIn("MessagePack payload default", str(caught.exception)) + finally: + for name, module in saved.items(): + if module is None: + sys.modules.pop(name, None) + else: + sys.modules[name] = module + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/check.ps1 b/tools/check.ps1 index c5d8dbb..e0aba41 100644 --- a/tools/check.ps1 +++ b/tools/check.ps1 @@ -88,6 +88,9 @@ try { } & $pythonExe -c "import sys, tempfile; sys.path.insert(0, r'surfaces\blender\brokkr_bridge'); import blender_target; cultmesh, cultcache = blender_target._load_cultmesh(r'$cultLibPackages'); doc = cultcache.define_document_type('brokkr.check.v0'); node = cultmesh.CultMesh.start_node(tempfile.NamedTemporaryFile(suffix='.ccmp').name, runtime_id='brokkr-check'); node.database.register_document(doc); node.database.put(doc, 'check', {'ok': True}); assert node.database.snapshot()['brokkr.check.v0']['check']['ok'] is True; server = cultmesh.CultMesh.serve_node(node, host='127.0.0.1', port=0); assert server.port > 0; server.stop()" Assert-NativeSuccess "Blender adapter CultMesh import" + $env:CULTLIB_PACKAGES = $cultLibPackages + & $pythonExe -m unittest discover -s surfaceslender ests + Assert-NativeSuccess "Blender adapter unit tests" } finally { Pop-Location From 04954c05006d6adcefb6db5a51f88cec036ac14e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:02:26 +0100 Subject: [PATCH 011/223] Live collaboration target: invariants, probes, identity table Target document for the brokkr-live campaign: the agent works in the same live Blender scene the operator is looking at. Records the Blender 5.3 timer-undo and viewport-capture probes the invariants stand on, and the identity, lifecycle and authority table for every kind the layer adds. Co-Authored-By: Claude Opus 5.5 --- docs/live-collab-target.md | 203 ++++++++++++++++++ docs/research/live-collab/probe_look.py | 68 ++++++ docs/research/live-collab/probe_timer_undo.py | 146 +++++++++++++ 3 files changed, 417 insertions(+) create mode 100644 docs/live-collab-target.md create mode 100644 docs/research/live-collab/probe_look.py create mode 100644 docs/research/live-collab/probe_timer_undo.py diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md new file mode 100644 index 0000000..acbdb07 --- /dev/null +++ b/docs/live-collab-target.md @@ -0,0 +1,203 @@ +# Brokkr live collaboration: target + +Campaign `brokkr-live` (Nibu's mind). Working branch `nibu/live-collab-target`, base +`origin/main` 5e279b2. This document holds the rationale, the design truths the +campaign produces, and the identity, lifecycle and authority table. The typed +`target` in the mind holds the labelled invariants and the not-in-scope list; the +text below is their source. + +## Why + +Operator, 2026-11-27: Brokkr "is meant to give an agent hands into the same Blender +scene I'm looking at, enabling live collaboration work". Brokkr already runs inside +her live Blender: a `depsgraph_update_post` handler publishes a host snapshot and a +persistent 1 s `bpy.app.timers` callback drains command intents +(`surfaces/blender/brokkr_bridge/__init__.py:610-647`, `:668-671`). What it lacks is +everything that makes two people in one scene a collaboration rather than a remote +control: + +- an agent edit is not an undo step (research `nibu-body:research:blender-live-collab.brokkr-undo`); +- nobody can tell who made an edit: the Blender side reads no `requestedBy` + (`.brokkr-attribution-gate`); +- the human cannot stop an agent except by unticking a preference, and a queued intent + still runs if she ticks it back; +- the agent sees names and counts, not the viewport and not the Edit Mode selection + (`.brokkr-perception`); +- nothing stops an agent intent planned against an old scene from overwriting what she + did since; +- the agent has no hands: `brokkr-ctl` has no source (`.brokkr-no-agent-surface`). + +Its strengths stay: typed, validated actions with no free-form Python, path +confinement, loopback bind and an optional session token (`.brokkr-security`). + +## Prior art the design stands on + +- **mcp-for-blender's `UserEditRecorder`** (`.mcp4b-human-edits`): buffers human + operator and undo/redo events with `undo_post`/`redo_post` handlers, attributes events + during an agent command to the agent, and hands the agent the human's activity before + its next action. We take the idea (the agent learns what the human did) and drop the + trajectory log: the snapshot carries per-object human-edit sequence numbers instead. +- **blender-copilot** (`.copilot-undo-cancel`): one undo step per agent turn, a Stop + button, visible turns and an undo receipt, no approval gate. Its Stop cannot interrupt + a blocking native call. We take all four and accept the same limit. +- **Multi-User** (`.humans-multiuser`) and the paid collab add-ons (`.humans-others`): + presence of the other party in the 3D view, rights and object locks. We take presence + as a panel, derived from intents and receipts; human-to-human replication is theirs, + not ours. +- **Blender Lab MCP and mcp-for-blender** (`.lab-official`, `.mcp4b-perception-safe`): + viewport screenshots as perception; arbitrary code with a weak or default-off + sandbox, and no undo. The perception we copy; the code path is fork Q1. +- **ceeyang/blender_mcp** (`.ceeyang-159`): 159 typed tools, every write undoable. The + existence proof that a typed vocabulary can be wide. +- The brush-tree campaign's `one-commit-primitive` (Libby's mind): a stale base is + refused, never merged. The conflict rule below is the same rule applied to a live scene. + +## What probing established (Blender 5.3.0, Starfire, GUI, `--factory-startup`) + +Probe scripts: `docs/research/live-collab/probe_timer_undo.py` and `probe_look.py`. +Each step runs in its own timer tick, as Brokkr's drain does. + +1. **A write from a timer with no undo push is not a step, and it survives undo.** The + cube moved to x=1 with no push; one `ed.undo` left it at x=1. The next push captured + it, so the agent's write became part of the next step, whoever made it (case A). The + vendor warning (`.undo-timer-warning`) is real for unpushed writes, and the failure is + worse than "not undoable": the edit is misattributed. +2. **An explicit `ed.undo_push` from a timer makes a correct step.** x=2 pushed, x=3 + pushed; undo gave 2, undo gave 1 (the earlier step), redo gave 2 (case B). +3. **An UNDO-flagged operator called from a timer pushes its own step.** A sphere added + by `primitive_uv_sphere_add` vanished on one undo with no explicit push (case C). An + action that calls two operators therefore makes two steps unless told otherwise. +4. **Operators called with `undo=False` push nothing; one explicit push then covers + them.** Cube and cone added with `("EXEC_DEFAULT", False)`, one push, one undo removed + both, a second undo changed nothing (case E). This is the mechanism for "one intent, + one step". +5. **Edit Mode:** a bmesh write plus push in Edit Mode is reverted by one undo, and that + undo also left Edit Mode (the agent had entered it in the same probe); the mesh kept + its original vertex (case D). Mode entry and the agent step are not cleanly separable + when the agent itself changed mode. Not yet probed: the human in Edit Mode and the + agent writing. +6. **Driving `ed.undo`/`ed.redo` programmatically from timers crashed Blender 2 of 2 + times** in the long sequence (A through E in one session), with + `EXCEPTION_ACCESS_VIOLATION` in UI draw code after a memfile undo + (`outliner_draw_restrictbuts`, then `psys_get_current` from the properties editor). The + short sequences (C alone, D alone, E alone) did not crash. Cause not isolated; the + probe's own `temp_override` with a captured region is a suspect. +7. **The agent can see what the human sees.** `bpy.ops.screen.screenshot_area` on the + 3D view from a timer: 7 of 7 `FINISHED`, median 72.5 ms over runs 2-7 at 1574x888, + about 609 KB PNG, and it captured the splash screen over the viewport, so it is the + human's view, overlays and popups included. Each capture stalls her UI for that long. +8. **Edit Mode selection reads live** through `bmesh.from_edit_mesh` without leaving Edit + Mode: selected vertices `[0, 3]`, 0.013 ms, mode still `EDIT_MESH`. + +Not yet probed, and owed before the cut that depends on it: whether depsgraph updates +caused by an agent intent arrive inside the timer callback or after it returns (this +decides how human edits are told from agent edits); and whether a human Ctrl+Z inside a +pending agent intent's base window can be detected reliably by `undo_post`. + +## Design truths + +**One agent turn primitive.** Every agent mutation in Blender goes through one function +in the add-on: admit (sink enabled, `requestedBy` present, id unused, base fresh), run +the action with every operator called `undo=False`, push exactly one undo step labelled +`Brokkr : `, write the receipt. A refusal or a +failure pushes nothing and leaves the scene as it was. Typed actions, the node actions, +and `run` if Q1 keeps it, all use it; there is no second writer. + +**Undo belongs to the human.** Blender's one linear stack is the shared history. The +agent's steps sit in it, labelled, between hers; she undoes them with Ctrl+Z like her +own. The agent never calls `ed.undo` or `ed.redo` (probe 6); an agent that wants to back +out sends a new compensating intent, which is one more step. Undoing an agent step that +sits under later human steps is not offered: Blender's stack is linear and per-user undo +is out of scope. + +**Stop is one control, and only the human holds it.** The Brokkr panel's Stop turns the +command sink off and gives every pending intent a `stopped` receipt without running it. +An action already running finishes (a blocking native call cannot be interrupted, as in +blender-copilot); it is one undo step, so Stop plus Ctrl+Z always returns her scene. No +intent can turn the sink on. Re-enabling is a fresh decision, and intents queued before +Stop never run. + +**The agent sees her view and her edits.** `look` is a read intent: it captures her 3D +view to a scratch PNG named by command id (ruling `brush-tree:ruling:look-files-are-scratch`) +and returns the path; it pushes no undo step. The snapshot gains the Edit Mode selection +and a Blender session id plus human-edit sequence numbers: one counter for the session, +the last sequence at which the human touched each object, and the last sequence at which +she undid or redid. The agent reads "what changed since I last looked" from those. + +**A human edit is never silently overwritten.** Every mutating intent names the base +sequence it was planned against. If the human touched any datablock the intent targets +since that base, or undid or redid since it, or the session id changed, the intent is +refused with a `conflict` receipt naming what changed, and nothing is applied. The +agent looks again and re-plans. Granularity is fork Q3. + +**Presence is derived.** The panel shows which agents have intents or receipts in the +last minutes, the running or last intent with its one-line `note`, and the recent +receipts with their undo labels. It reads the intent and receipt documents; it owns no +state of its own. + +**Hands are a CLI.** `brokkr-ctl blender` (Rust, ruling `brush-tree:ruling:fitting-home-ruled`) +writes intents and reads receipts and snapshots through the Blender mirror store +(`brush-tree:ruling:blender-transport-ruled`), prints plain text or paths, and its +`--help` is the schema (`brush-tree:ruling:cli-not-mcp`, `:help-is-the-schema`). It owns +no state, policy or ledger (brush-tree target invariant `brokkr-authority-holds`). + +## Authority map + +- **Owner.** The add-on's agent turn primitive owns whether and how an agent intent + changes the live scene. Blender owns scene truth and the undo stack. The human owns + the sink toggle, Stop, and undo. +- **Inputs.** Intent documents; the snapshot's human-edit sequences; the sink toggle. +- **Outputs.** One undo step per accepted mutating intent; one receipt per intent; + the refreshed snapshot; look PNG paths. +- **Derived state.** Presence (from intents and receipts). Human-edit sequences + (from depsgraph and undo handlers, observations only). Look PNGs (telemetry). +- **Forbidden writers.** `execute_command` called outside the primitive; operators + called with undo on inside an agent action; any raw RNA write by an agent without the + closing push; `ed.undo`/`ed.redo` from add-on code; the debug-mirror JSON import + (`blender_target.py` `_import_debug_command_files`) as a second door for intents; + `brokkr-ctl` opening the store to decide anything. +- **Shared paths.** brokkr-ctl intents, panel buttons that act on the scene, sync-organ + intents from `brokkr-daemon sync-once`, and replayed intents use the one primitive. +- **Deletion line.** The debug-mirror intent import goes before the primitive lands; + `drain_commands` stops calling `execute_command` directly. + +## Identity, lifecycle and authority + +| Persistent kind | What names it | What happens to it over time | Who decides | +|---|---|---|---| +| Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `baseSeq`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (Unity F6 A, `brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written, as today. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | +| Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, conflict, stopped, failed, `undoLabel`, `lookPath`, and for `run` the script text and SHA-256) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. The only proof an intent ran. | The primitive alone. Callers and the panel read. | +| Agent identity `requestedBy` | `/` stated by the caller (brokkr-ctl takes it from `EUREKA_INSTANCE` and a flag) | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | +| Agent undo step | Blender undo stack entry labelled `Brokkr : ` | Pushed once per accepted mutating intent; lives as Blender's stack does (step limit, file load); never persisted by Brokkr. | Blender owns the stack. The primitive pushes. Only the human undoes or redoes. | +| Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads; every older base is then stale. | The add-on alone. | +| Human-edit sequences (snapshot fields: `humanEditSeq`, per-object `lastHumanEditSeq`, `lastUndoSeq`) | Integers within a session id | Monotonic within a session; reset with it. Observations, never scene truth. | The add-on's depsgraph and undo handlers alone. | +| Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, the sequences above, sink state) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | +| Command sink toggle (the existing `auto_drain_commands` preference) | Add-on preference, echoed in the snapshot | Off by default. Stop turns it off; only the human turns it on. | The human only. No intent writes it. | +| Script toggle (only if Q1 = b) | A second add-on preference, echoed in the snapshot | Off by default, independent of the sink. | The human only. | +| Look PNG | `/look/{commandId}.png` | Pruned by count; never read back as truth. | The primitive writes; `brush-tree:ruling:look-files-are-scratch` governs. | + +## Not in scope + +Human-to-human replication or several Blender instances in one session (Multi-User's +domain). Agents on another host reaching the operator's Blender: the transport is not +widened beyond what the add-on serves today. Per-user or selective undo. An approval gate +before each agent action (unless Q2 rules otherwise). A 3D-view overlay of the agent's +presence; the panel carries presence in this revision. The Unity surface and +`brokkr-command`. The brush-tree vocabulary, Geometry.Csg and OpenSCAD text (brush-tree +owns them). Agent-initiated save and quit (`brush-tree:ruling:run-admitted-when-enabled` +keeps them off the allowed list). Asset libraries and generators. An MCP server. + +## Open forks (draft questions; Self admits) + +- **Q1. Free-form Python.** Today the Blender add-on has no script action. Libby's + Defaulted ruling `brush-tree:ruling:run-admitted-when-enabled` would add `run`, admitted + whenever agent commands are on. Options: (a) typed actions only; (b) `run` behind its + own off-by-default toggle, one undo step, script text in the receipt; (c) the Defaulted + ruling as written. Recommend (b). +- **Q2. Act then undo, or approve first.** Recommend act then undo, with Stop. +- **Q3. Conflict granularity.** (a) any human edit since the base refuses; (b) only edits to + the intent's targets, plus any undo or redo. Recommend (b), after the depsgraph + attribution probe. +- **Q4. Who builds `brokkr-ctl blender`.** Recommend this campaign builds the session + subcommands in Rust per Libby's rulings, and brush-tree adds its tree commands to the + same binary later. diff --git a/docs/research/live-collab/probe_look.py b/docs/research/live-collab/probe_look.py new file mode 100644 index 0000000..1e8851c --- /dev/null +++ b/docs/research/live-collab/probe_look.py @@ -0,0 +1,68 @@ +"""Probe: can a timer callback capture the 3D viewport the human sees, and read Edit Mode selection? + +blender --factory-startup --python probe_look.py -- +""" +import json +import os +import statistics +import sys +import time +import traceback + +import bmesh +import bpy + +args = sys.argv[sys.argv.index("--") + 1:] +OUT, PNG_DIR = args[0], args[1] +log = {"blender": bpy.app.version_string} + + +def ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + region = next(r for r in area.regions if r.type == "WINDOW") + return win, area, region + + +def run(): + win, area, region = ctx() + log["view3d_px"] = [region.width, region.height] + times = [] + for n in range(7): + path = os.path.join(PNG_DIR, f"look-{n}.png") + t = time.perf_counter() + with bpy.context.temp_override(window=win, area=area, region=region): + r = bpy.ops.screen.screenshot_area(filepath=path) + times.append((time.perf_counter() - t) * 1000) + log.setdefault("results", []).append(list(r)) + log["screenshot_ms"] = [round(x, 1) for x in times] + log["screenshot_ms_median"] = round(statistics.median(times[1:]), 1) + log["png_bytes"] = os.path.getsize(os.path.join(PNG_DIR, "look-6.png")) + # Edit Mode selection read, live, without leaving Edit Mode. + with bpy.context.temp_override(window=win, area=area, region=region): + bpy.ops.object.mode_set(mode="EDIT") + bpy.ops.mesh.select_all(action="DESELECT") + bm = bmesh.from_edit_mesh(bpy.data.objects["Cube"].data) + bm.verts.ensure_lookup_table() + bm.verts[0].select = True + bm.verts[3].select = True + bm.select_flush_mode() + t = time.perf_counter() + sel = [v.index for v in bmesh.from_edit_mesh(bpy.data.objects["Cube"].data).verts if v.select] + log["edit_selection_read_ms"] = round((time.perf_counter() - t) * 1000, 3) + log["edit_selected_verts"] = sel + log["mode_after_read"] = bpy.context.mode + + +def tick(): + try: + run() + except Exception: + log["error"] = traceback.format_exc() + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/docs/research/live-collab/probe_timer_undo.py b/docs/research/live-collab/probe_timer_undo.py new file mode 100644 index 0000000..57886fb --- /dev/null +++ b/docs/research/live-collab/probe_timer_undo.py @@ -0,0 +1,146 @@ +"""Probe: do edits made from a bpy.app.timers callback land on Blender's undo stack? + +Run in GUI Blender: blender --factory-startup --python probe_timer_undo.py -- [cases, e.g. AB] +Each step is its own timer tick so the event loop runs between steps, as it does +for Brokkr's 1 s drain. Results are written to the JSON path, then Blender quits. +""" +import json +import sys +import traceback + +import bmesh +import bpy + +OUT = sys.argv[sys.argv.index("--") + 1] +log = {"blender": bpy.app.version_string, "background": bpy.app.background, "steps": []} + + +def win_ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + return bpy.context.temp_override(window=win, area=area, region=area.regions[-1]) + + +def cube(): + return bpy.data.objects.get("Cube") + + +def state(tag): + c = cube() + s = { + "tag": tag, + "cube_x": round(c.location.x, 3) if c else None, + "objects": sorted(o.name for o in bpy.data.objects), + "mode": bpy.context.mode, + "mesh_v0_z": round(c.data.vertices[0].co.z, 3) if c else None, + } + if c and c.mode == "EDIT": + bm = bmesh.from_edit_mesh(c.data) + bm.verts.ensure_lookup_table() + s["edit_v0_z"] = round(bm.verts[0].co.z if bm.verts else 0, 3) + log["steps"].append(s) + return s + + +def push(msg): + with win_ctx(): + r = bpy.ops.ed.undo_push(message=msg) + log["steps"].append({"tag": f"undo_push:{msg}", "result": list(r)}) + + +def undo(): + with win_ctx(): + r = bpy.ops.ed.undo() + log["steps"].append({"tag": "undo", "result": list(r)}) + + +def redo(): + with win_ctx(): + r = bpy.ops.ed.redo() + log["steps"].append({"tag": "redo", "result": list(r)}) + + +# Case A: raw RNA write from a timer, no push. Does Ctrl+Z see it as its own step? +# Case B: RNA write then an explicit undo_push from the timer. +# Case C: an UNDO-flagged operator called from a timer, no explicit push. +# Case D: Edit Mode bmesh write from a timer then undo_push. +# Case E: two operators called with undo=False, then one explicit undo_push. +ONLY = sys.argv[sys.argv.index("--") + 2] if len(sys.argv) > sys.argv.index("--") + 2 else "ABCDE" +steps = [ + lambda: (push("baseline"), state("A0 baseline")), + lambda: (setattr(cube().location, "x", 1.0), state("A1 raw write x=1, no push")), + lambda: (undo(), state("A2 after one undo")), + lambda: (push("rebase-B"), state("B0")), + lambda: (setattr(cube().location, "x", 2.0), push("agent: x=2"), state("B1 x=2 pushed")), + lambda: (setattr(cube().location, "x", 3.0), push("agent: x=3"), state("B2 x=3 pushed")), + lambda: (undo(), state("B3 after undo (expect x=2)")), + lambda: (undo(), state("B4 after second undo (expect x=0)")), + lambda: (redo(), state("B5 after redo (expect x=2)")), + lambda: (push("rebase-C"), state("C0")), + lambda: (_add_sphere(), state("C1 op add sphere, no push")), + lambda: (undo(), state("C2 after undo (sphere gone?)")), + lambda: (bpy.context.view_layer.objects.__setattr__("active", cube()), cube().select_set(True), push("rebase-D"), state("D0")), + lambda: (_edit_enter(), state("D1 edit mode")), + lambda: (_edit_write(), push("agent: edit v0"), state("D2 v0 moved, pushed")), + lambda: (undo(), state("D3 after undo (expect v0 back)")), + lambda: (undo(), state("D4 after second undo")), + lambda: (_edit_exit(), push("rebase-E"), state("E0")), + lambda: (_two_ops_one_step(), push("agent: two ops"), state("E1 two ops undo=False + one push")), + lambda: (undo(), state("E2 after one undo (expect both gone)")), + lambda: (undo(), state("E3 after second undo (expect no change)")), +] + + +def _add_sphere(): + with win_ctx(): + bpy.ops.mesh.primitive_uv_sphere_add(location=(5, 0, 0)) + + +def _edit_exit(): + if bpy.context.mode != "OBJECT": + with win_ctx(): + bpy.ops.object.mode_set(mode="OBJECT") + + +def _two_ops_one_step(): + with win_ctx(): + bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, location=(0, 4, 0)) + bpy.ops.mesh.primitive_cone_add("EXEC_DEFAULT", False, location=(0, -4, 0)) + + +def _edit_enter(): + with win_ctx(): + bpy.ops.object.mode_set(mode="EDIT") + + +def _edit_write(): + c = cube() + bm = bmesh.from_edit_mesh(c.data) + bm.verts.ensure_lookup_table() + bm.verts[0].co.z += 5.0 + bmesh.update_edit_mesh(c.data) + + +i = 0 +_all = steps +steps = [f for f, c in zip(_all, "AAABBBBBBCCCDDDDDEEEE") if c in ONLY] + + +def tick(): + global i + if i < len(steps): + try: + steps[i]() + except Exception: + log["steps"].append({"tag": f"step {i} error", "error": traceback.format_exc()}) + i += 1 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + return 0.3 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=2.0) From 48c0aeee6d702c28da79fd275042d95455eb557e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:07:37 +0100 Subject: [PATCH 012/223] Live collab: depsgraph timing probe Records when depsgraph updates from an agent edit in a timer arrive and which ids they name, for the human-edit detection fork (Q3). Co-Authored-By: Claude Opus 5.5 --- .../live-collab/probe_depsgraph_timing.py | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 docs/research/live-collab/probe_depsgraph_timing.py diff --git a/docs/research/live-collab/probe_depsgraph_timing.py b/docs/research/live-collab/probe_depsgraph_timing.py new file mode 100644 index 0000000..d763e07 --- /dev/null +++ b/docs/research/live-collab/probe_depsgraph_timing.py @@ -0,0 +1,134 @@ +"""Probe: when do depsgraph updates caused by an agent edit in a timer arrive, and what do they name? + +blender --factory-startup --python probe_depsgraph_timing.py -- + +Each case runs in its own timer tick. AGENT is True only while the timer callback +runs the edit. depsgraph_update_post and undo_post log every call with AGENT's value, +the tick that was current, and the ids depsgraph.updates names. +""" +import json +import sys +import time +import traceback + +import bpy + +OUT = sys.argv[sys.argv.index("--") + 1] +log = {"blender": bpy.app.version_string, "events": []} +AGENT = False +TICK = "setup" +T0 = time.perf_counter() + + +def ev(kind, **kw): + log["events"].append({"kind": kind, "tick": TICK, "agent": AGENT, + "ms": round((time.perf_counter() - T0) * 1000, 1), **kw}) + + +@bpy.app.handlers.persistent +def on_depsgraph(scene, depsgraph): + ups = [] + for u in depsgraph.updates: + ups.append(f"{type(u.id).__name__}:{u.id.name}" + f"{'/T' if u.is_updated_transform else ''}{'/G' if u.is_updated_geometry else ''}") + ev("depsgraph", updates=ups) + + +@bpy.app.handlers.persistent +def on_undo(scene, *_): + ev("undo_post") + + +@bpy.app.handlers.persistent +def on_redo(scene, *_): + ev("redo_post") + + +def win_ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + region = next(r for r in area.regions if r.type == "WINDOW") + return bpy.context.temp_override(window=win, area=area, region=region) + + +def setup(): + # B follows A through a Copy Location constraint: an indirect dependent of A. + a = bpy.data.objects["Cube"] + with win_ctx(): + bpy.ops.mesh.primitive_cone_add("EXEC_DEFAULT", False, location=(0, 3, 0)) + b = bpy.context.active_object + b.name = "Follower" + c = b.constraints.new("COPY_LOCATION") + c.target = a + c.use_y = False + with win_ctx(): + bpy.ops.ed.undo_push(message="setup") + + +def agent(fn, flush): + global AGENT + AGENT = True + ev("turn_begin", flush=flush) + fn() + with win_ctx(): + bpy.ops.ed.undo_push(message=f"agent {TICK}") + if flush: + bpy.context.view_layer.update() + ev("turn_end") + AGENT = False + + +def move_a(x): + return lambda: setattr(bpy.data.objects["Cube"].location, "x", x) + + +def add_op(): + with win_ctx(): + bpy.ops.mesh.primitive_uv_sphere_add("EXEC_DEFAULT", False, location=(-4, 0, 0)) + + +def undo_once(): + with win_ctx(): + bpy.ops.ed.undo() + + +cases = [ + ("setup", setup), + ("idle1", lambda: None), + ("rna-noflush", lambda: agent(move_a(1.0), False)), + ("idle2", lambda: None), + ("rna-flush", lambda: agent(move_a(2.0), True)), + ("idle3", lambda: None), + ("op-noflush", lambda: agent(add_op, False)), + ("idle4", lambda: None), + ("op-flush", lambda: agent(add_op, True)), + ("idle5", lambda: None), + ("undo", undo_once), # stands in for a human Ctrl+Z (not an agent turn) + ("idle6", lambda: None), +] +i = 0 + + +def tick(): + global i, TICK + if i < len(cases): + TICK, fn = cases[i] + try: + fn() + except Exception: + ev("error", error=traceback.format_exc()) + TICK = f"after:{TICK}" + i += 1 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + return 0.5 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.handlers.depsgraph_update_post.append(on_depsgraph) +bpy.app.handlers.undo_post.append(on_undo) +bpy.app.handlers.redo_post.append(on_redo) +bpy.app.timers.register(tick, first_interval=2.0) From 714ae214788e8a1a28e3a2f43af417590a7daacb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:18:59 +0100 Subject: [PATCH 013/223] Live collab target r2: rulings in, phase two authoring surface Takes in the operator's 2026-11-27 rulings (no free-form Python, act then undo, last writer wins in the scene, brokkr-ctl blender built here) and adds phase two: scene collections as an authoring surface over a ship's .cc, opened at known record versions and pushed through AetherDb with a dry-run default and stale-version refusal. Records why neither variants' deltas nor CultNet carry the push today. Co-Authored-By: Claude Opus 5.5 --- docs/live-collab-target.md | 399 ++++++++++++++++++++++--------------- 1 file changed, 243 insertions(+), 156 deletions(-) diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index acbdb07..228ae83 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -4,200 +4,287 @@ Campaign `brokkr-live` (Nibu's mind). Working branch `nibu/live-collab-target`, `origin/main` 5e279b2. This document holds the rationale, the design truths the campaign produces, and the identity, lifecycle and authority table. The typed `target` in the mind holds the labelled invariants and the not-in-scope list; the -text below is their source. +text below is their source. Revision 2 adds phase two (the authoring surface) and +takes in the operator's rulings of 2026-11-27. + +Rulings in force: `brokkr-live:ruling:no-free-form-python`, `:act-then-undo`, +`:scene-last-writer-wins`, `:brokkr-ctl-blender-built-here`, +`:cc-is-hull-authority-scene-pushes-deltas`. ## Why Operator, 2026-11-27: Brokkr "is meant to give an agent hands into the same Blender -scene I'm looking at, enabling live collaboration work". Brokkr already runs inside -her live Blender: a `depsgraph_update_post` handler publishes a host snapshot and a -persistent 1 s `bpy.app.timers` callback drains command intents -(`surfaces/blender/brokkr_bridge/__init__.py:610-647`, `:668-671`). What it lacks is -everything that makes two people in one scene a collaboration rather than a remote -control: +scene I'm looking at, enabling live collaboration work". Her original vision for it: +"use Blender as an authoring environment, since it exposes typed access to all of the +assets we need over CultMesh. Certain collections within the Blender scene would +mirror their data into the exact documents Aetheria needs for its ships." -- an agent edit is not an undo step (research `nibu-body:research:blender-live-collab.brokkr-undo`); -- nobody can tell who made an edit: the Blender side reads no `requestedBy` - (`.brokkr-attribution-gate`); -- the human cannot stop an agent except by unticking a preference, and a queued intent - still runs if she ticks it back; -- the agent sees names and counts, not the viewport and not the Edit Mode selection - (`.brokkr-perception`); -- nothing stops an agent intent planned against an old scene from overwriting what she - did since; -- the agent has no hands: `brokkr-ctl` has no source (`.brokkr-no-agent-surface`). +So the campaign has two phases. **Phase one** makes the live session a collaboration: +the agent's edits are undoable and attributed, she can stop it, and it sees what she +sees. **Phase two** makes the scene an authoring surface over a ship's `.cc`: scene +collections map to the ship's records, the scene opens from the `.cc` at a known +revision, and pushes go back through AetherDb. -Its strengths stay: typed, validated actions with no free-form Python, path -confinement, loopback bind and an optional session token (`.brokkr-security`). +Brokkr already runs inside her live Blender: a `depsgraph_update_post` handler +publishes a host snapshot and a persistent 1 s `bpy.app.timers` callback drains +command intents (`surfaces/blender/brokkr_bridge/__init__.py:610-647`, `:668-671`). +What it lacks: an agent edit is not an undo step (`nibu-body:research:blender-live-collab.brokkr-undo`); +nobody can tell who made an edit (`.brokkr-attribution-gate`); the human can stop an +agent only by unticking a preference; the agent sees names and counts, not the viewport +or the Edit Mode selection (`.brokkr-perception`); and the agent has no hands, since +`brokkr-ctl` has no source (`.brokkr-no-agent-surface`). Its strengths stay: typed, +validated actions with no free-form Python, path confinement, loopback bind and an +optional session token (`.brokkr-security`). ## Prior art the design stands on -- **mcp-for-blender's `UserEditRecorder`** (`.mcp4b-human-edits`): buffers human - operator and undo/redo events with `undo_post`/`redo_post` handlers, attributes events - during an agent command to the agent, and hands the agent the human's activity before - its next action. We take the idea (the agent learns what the human did) and drop the - trajectory log: the snapshot carries per-object human-edit sequence numbers instead. +- **mcp-for-blender's `UserEditRecorder`** (`.mcp4b-human-edits`): the agent learns what + the human did between its actions. We keep the idea as snapshot fields, without a + trajectory log. - **blender-copilot** (`.copilot-undo-cancel`): one undo step per agent turn, a Stop - button, visible turns and an undo receipt, no approval gate. Its Stop cannot interrupt - a blocking native call. We take all four and accept the same limit. -- **Multi-User** (`.humans-multiuser`) and the paid collab add-ons (`.humans-others`): - presence of the other party in the 3D view, rights and object locks. We take presence - as a panel, derived from intents and receipts; human-to-human replication is theirs, - not ours. + button, visible turns and an undo receipt, no approval gate. Its Stop cannot + interrupt a blocking native call; ours cannot either. +- **Multi-User** (`.humans-multiuser`, `.humans-others`): presence of the other party. + We show presence in a panel; human-to-human replication is theirs. - **Blender Lab MCP and mcp-for-blender** (`.lab-official`, `.mcp4b-perception-safe`): - viewport screenshots as perception; arbitrary code with a weak or default-off - sandbox, and no undo. The perception we copy; the code path is fork Q1. -- **ceeyang/blender_mcp** (`.ceeyang-159`): 159 typed tools, every write undoable. The - existence proof that a typed vocabulary can be wide. -- The brush-tree campaign's `one-commit-primitive` (Libby's mind): a stale base is - refused, never merged. The conflict rule below is the same rule applied to a live scene. + viewport screenshots as perception. Their arbitrary-code path is refused here + (`no-free-form-python`). +- **ceeyang/blender_mcp** (`.ceeyang-159`): 159 typed tools, every write undoable; a + typed vocabulary can be wide. +- **Aetheria's ship package path** (Aetheria origin/master 6702b01bf, packager on + `nibu/hull-packager` 7101b5cec): `AetherDb ship-authoring` (create, stats, price, + product, regenerate with a dry-run default, validate, inspect) loads a `ship.cc` + through the game's own types; `tools/blender/package_hull.py` drives the + `aetheria_ships` add-on and AetherDb from a manifest; `tools/blender/aetheria_ships/ship_cc.py` + reads and writes `ship.cc` envelopes directly, with a layout revision hash for its + layout write. +- **CultCache compare-exchange and element ids** (CultLib origin/main baf4ecf7, + `src/GameCult.Caching/CultCache.cs:2228-2235` `Expect`/`ExpectUnchanged`; + `CultElementIds.cs`). `HardpointData.Id` is a `[CultElementId]` (Aetheria + `Assets/Scripts/ServerShared/ItemData.cs:648`). -## What probing established (Blender 5.3.0, Starfire, GUI, `--factory-startup`) +## What probing established -Probe scripts: `docs/research/live-collab/probe_timer_undo.py` and `probe_look.py`. -Each step runs in its own timer tick, as Brokkr's drain does. +Blender 5.3.0, Starfire, GUI, `--factory-startup`, each step in its own timer tick. +Scripts in `docs/research/live-collab/`. Research notes +`brokkr-live:research:live-collab-probes.*`. -1. **A write from a timer with no undo push is not a step, and it survives undo.** The - cube moved to x=1 with no push; one `ed.undo` left it at x=1. The next push captured - it, so the agent's write became part of the next step, whoever made it (case A). The - vendor warning (`.undo-timer-warning`) is real for unpushed writes, and the failure is - worse than "not undoable": the edit is misattributed. -2. **An explicit `ed.undo_push` from a timer makes a correct step.** x=2 pushed, x=3 - pushed; undo gave 2, undo gave 1 (the earlier step), redo gave 2 (case B). -3. **An UNDO-flagged operator called from a timer pushes its own step.** A sphere added - by `primitive_uv_sphere_add` vanished on one undo with no explicit push (case C). An - action that calls two operators therefore makes two steps unless told otherwise. -4. **Operators called with `undo=False` push nothing; one explicit push then covers - them.** Cube and cone added with `("EXEC_DEFAULT", False)`, one push, one undo removed - both, a second undo changed nothing (case E). This is the mechanism for "one intent, - one step". -5. **Edit Mode:** a bmesh write plus push in Edit Mode is reverted by one undo, and that - undo also left Edit Mode (the agent had entered it in the same probe); the mesh kept - its original vertex (case D). Mode entry and the agent step are not cleanly separable - when the agent itself changed mode. Not yet probed: the human in Edit Mode and the - agent writing. -6. **Driving `ed.undo`/`ed.redo` programmatically from timers crashed Blender 2 of 2 - times** in the long sequence (A through E in one session), with - `EXCEPTION_ACCESS_VIOLATION` in UI draw code after a memfile undo - (`outliner_draw_restrictbuts`, then `psys_get_current` from the properties editor). The - short sequences (C alone, D alone, E alone) did not crash. Cause not isolated; the - probe's own `temp_override` with a captured region is a suspect. -7. **The agent can see what the human sees.** `bpy.ops.screen.screenshot_area` on the - 3D view from a timer: 7 of 7 `FINISHED`, median 72.5 ms over runs 2-7 at 1574x888, - about 609 KB PNG, and it captured the splash screen over the viewport, so it is the - human's view, overlays and popups included. Each capture stalls her UI for that long. -8. **Edit Mode selection reads live** through `bmesh.from_edit_mesh` without leaving Edit - Mode: selected vertices `[0, 3]`, 0.013 ms, mode still `EDIT_MESH`. +1. **An unpushed write from a timer is not an undo step and survives undo**; the next + push absorbs it, so it is misattributed (`.timer-undo`, case A). +2. **An explicit `ed.undo_push` from a timer makes a correct step**, and undo and redo + walk it (case B). +3. **UNDO-flagged operators push their own step**; called `("EXEC_DEFAULT", False)` they + push none, and one explicit push covers several (cases C, E). This is how one intent + becomes one step. +4. **Edit Mode**: an agent bmesh write plus push is reverted by one undo, which also + left the Edit Mode the agent had entered (case D). +5. **Driving `ed.undo`/`ed.redo` from code crashed Blender 2 of 2 times** in the long + sequence, in UI draw after a memfile undo (`.programmatic-undo-crash`). +6. **The agent can see her view**: `screenshot_area` on her 3D view, median 72.5 ms at + 1574x888, about 609 KB, popups included; Edit Mode selection reads live without + leaving Edit Mode (`.look-capture`). +7. **Depsgraph updates from an agent edit arrive inside the timer turn** and name + indirect dependents; after an undo every object is listed and only the transform and + geometry flags show what changed (`.depsgraph-timing`). +8. **cultcache-rs writes the add-on's single-file `.ccmp` under the shared lock, and a + live cultmesh-py node pulls Rust writes**; no runtime has a directory store + (`.rust-store-writer`). -Not yet probed, and owed before the cut that depends on it: whether depsgraph updates -caused by an agent intent arrive inside the timer callback or after it returns (this -decides how human edits are told from agent edits); and whether a human Ctrl+Z inside a -pending agent intent's base window can be detected reliably by `undo_post`. +Not yet probed, owed before the cut that depends on it: the latency of one AetherDb +`ship-authoring` call on Starfire (phase two decides between a CLI call per push and a +resident service on that number); reading a record's stored version through AetherDb. -## Design truths +## Phase one: the live session **One agent turn primitive.** Every agent mutation in Blender goes through one function -in the add-on: admit (sink enabled, `requestedBy` present, id unused, base fresh), run -the action with every operator called `undo=False`, push exactly one undo step labelled -`Brokkr : `, write the receipt. A refusal or a -failure pushes nothing and leaves the scene as it was. Typed actions, the node actions, -and `run` if Q1 keeps it, all use it; there is no second writer. +in the add-on: admit (sink enabled, `requestedBy` present, id unused, action typed and +valid), run the action with every operator called `undo=False`, push exactly one undo +step labelled `Brokkr : `, write the receipt. A +refusal or a failure pushes nothing and leaves the scene unchanged. There is no second +writer and no script action (`no-free-form-python`): what the typed actions do not +cover waits for a new typed action. -**Undo belongs to the human.** Blender's one linear stack is the shared history. The -agent's steps sit in it, labelled, between hers; she undoes them with Ctrl+Z like her -own. The agent never calls `ed.undo` or `ed.redo` (probe 6); an agent that wants to back -out sends a new compensating intent, which is one more step. Undoing an agent step that -sits under later human steps is not offered: Blender's stack is linear and per-user undo -is out of scope. +**The agent acts; the human undoes** (`act-then-undo`). Admitted intents apply without +asking. Blender's one linear undo stack is the shared history; agent steps sit in it, +labelled, between hers, and she takes them back with Ctrl+Z. The agent never calls +`ed.undo` or `ed.redo` (probe 5); it backs out by sending a compensating intent. -**Stop is one control, and only the human holds it.** The Brokkr panel's Stop turns the -command sink off and gives every pending intent a `stopped` receipt without running it. -An action already running finishes (a blocking native call cannot be interrupted, as in -blender-copilot); it is one undo step, so Stop plus Ctrl+Z always returns her scene. No -intent can turn the sink on. Re-enabling is a fresh decision, and intents queued before -Stop never run. +**Last writer wins in the scene** (`scene-last-writer-wins`). An agent intent applies +even if she changed the scene since the agent looked. Her edit is never lost: it stays +in the undo history below the agent's step, and one Ctrl+Z takes the agent's step back. +This is scene-level only; the `.cc` keeps its revision refusal (phase two). + +**Stop is one control, and only the human holds it.** Stop turns the command sink off +and gives every pending intent a `stopped` receipt without running it. An action +already running finishes as one undo step, so Stop plus Ctrl+Z always returns her +scene. No intent can turn the sink on; intents queued before Stop never run. **The agent sees her view and her edits.** `look` is a read intent: it captures her 3D -view to a scratch PNG named by command id (ruling `brush-tree:ruling:look-files-are-scratch`) -and returns the path; it pushes no undo step. The snapshot gains the Edit Mode selection -and a Blender session id plus human-edit sequence numbers: one counter for the session, -the last sequence at which the human touched each object, and the last sequence at which -she undid or redid. The agent reads "what changed since I last looked" from those. +view to a scratch PNG named by command id (`brush-tree:ruling:look-files-are-scratch`) +and returns the path. The snapshot gains the Edit Mode selection, a Blender session id, +and human-edit sequence numbers (a session counter and, per object, the last sequence +at which she changed it, from depsgraph updates outside agent turns and flagged +transform, geometry or shading). These tell the agent what she did since it last +looked; they gate nothing. -**A human edit is never silently overwritten.** Every mutating intent names the base -sequence it was planned against. If the human touched any datablock the intent targets -since that base, or undid or redid since it, or the session id changed, the intent is -refused with a `conflict` receipt naming what changed, and nothing is applied. The -agent looks again and re-plans. Granularity is fork Q3. +**Presence is derived.** The panel shows active agents, the running or last intent with +its one-line `note`, and recent receipts with their undo labels, read from the intent +and receipt documents. -**Presence is derived.** The panel shows which agents have intents or receipts in the -last minutes, the running or last intent with its one-line `note`, and the recent -receipts with their undo labels. It reads the intent and receipt documents; it owns no -state of its own. +**Hands are a CLI** (`brokkr-ctl-blender-built-here`). `brokkr-ctl blender` is a Rust +binary in this repo (`brush-tree:ruling:fitting-home-ruled`) that writes intents and +reads receipts and snapshots in the add-on's single-file store (probe 8), prints plain +text or paths, and whose `--help` is the schema (`brush-tree:ruling:cli-not-mcp`, +`:help-is-the-schema`). It owns no state, policy or ledger. Libby's brush-tree adds its +tree commands to the same binary later. -**Hands are a CLI.** `brokkr-ctl blender` (Rust, ruling `brush-tree:ruling:fitting-home-ruled`) -writes intents and reads receipts and snapshots through the Blender mirror store -(`brush-tree:ruling:blender-transport-ruled`), prints plain text or paths, and its -`--help` is the schema (`brush-tree:ruling:cli-not-mcp`, `:help-is-the-schema`). It owns -no state, policy or ledger (brush-tree target invariant `brokkr-authority-holds`). +## Phase two: the authoring surface + +**The `.cc` is the authority; the scene is a surface over it** +(`cc-is-hull-authority-scene-pushes-deltas`). A ship's records live in its `ship.cc`: +`HullData`, `ShipAuthoring` (model asset, anchors, schematic lines) and its product +records (`ShipAuthoringStore.Load` returns exactly these three). A Blender scene may be +bound to one `ship.cc` as its authoring surface. The scene never becomes truth: it is an +edit buffer that opens from the store and pushes back to it. + +**Collections carry roles.** Scene collections are tagged with the role they author: +hull shape (the hull source and its raster), hardpoint rows (one object per row, +carrying `aetheria.id`, the `HardpointData` element id, and its kind, cell, footprint, +rotation, armor and arc), schematic lines, and anchors. Stats, price and product live on +the binding. These are the fields the packager manifest already names +(`tools/blender/package_hull.md`), so the manifest and a push describe a ship in one +vocabulary. + +**Open reads through the game's code.** Opening runs `AetherDb ship-authoring` to read +the three records and their stored versions, builds the tagged collections, and records +on the binding the version of each record it read. Nothing reads a `.cc` by scraping +envelopes (operator 2026-11-17). + +**A push is one AetherDb call, dry-run then apply.** The surface writes the authoring +state of its tagged collections (the manifest vocabulary, plus the record versions it +opened at) to a scratch request file and calls `AetherDb ship-authoring push +`. Without `apply` AetherDb loads the store, derives the records the request +describes, validates them, and prints the per-record, per-field changes; nothing is +written. With `apply` it does the same and writes under compare-exchange on each +record's stored version (`Expect`). One CLI call per push is the starting shape; a +resident service is built only if the measured latency of that call demands it. + +**A stale revision is refused, never merged.** If any record changed in the store since +the scene opened it (another push, a CLI `stats` call, a packager `--replace`), the push +is refused with the records named; the surface reopens and the author re-applies. On a +successful apply the binding takes the new versions. + +**One owner turns a hull into records.** AetherDb's ship-authoring code (C#, the game's +own types) is the only code that derives `HullData`, `ShipAuthoring` and product records +from authoring input, and the only writer of `.cc` stores. The packager and the +authoring surface both call it. The direct envelope writes in +`aetheria_ships/ship_cc.py` (`replace_lines`, `replace_visual`, `replace_layout`, and +the first Save Layout that creates `ship.cc`) and its `layout_revision` hash are +demoted: `ship_cc.py` keeps no write path and no revision of its own, and +`package_hull.py`'s Save Layout steps become push calls. Whether the request is +the delta of the ruling, or a whole-record replace, is fork Q5 below. + +**The agent's hands reach the surface through typed actions.** Open, push dry-run and +push apply are typed Brokkr actions like any other, admitted by the same primitive; a +push changes no scene state and so pushes no undo step. Whether an agent may apply, +not only dry-run, is fork Q7. + +### Variants and CultNet deltas: not the push primitive today + +The coordinator asked whether Libby's `variants` delta records, or CultNet's deltas, +are the primitive for the push. + +- **Variants** (`variants` target, Libby's mind): a variant is a persisted record stored + as a base reference plus sparse overrides (`CultVariantDelta`, `CultVariantOverride` + with `Set`/`Insert`/`Remove` at slot plus element-id paths, + `src/GameCult.Caching/CultVariants.cs:56-112`), resolved by the cache at load, and a + plain upsert at a variant's key is refused (`variants:ruling:q1-refuse-plain-upsert`). + It describes a second document defined against a base, not a change to the base. Its + nested paths and `Insert`/`Remove` are unbuilt (`variants:follow_up:remaining-variant-cuts`, + C2b), C# alone resolves it, and Aetheria catalog content is out of its scope. +- **CultNet** (`contracts/cultnet/`): the wire has whole-document `document-put` and + `document-put-raw`, `document-delete`, and `database-change-raw` (added, updated, + removed, with the whole document and a commit id). There is no delta message. The + "delta" in `cultnet-rs/src/replication.rs:97,789-829` and `cultmesh-py/node.py:1649-1660` + is a client-side reconciliation diff (predicted minus canonical, per top-level slot, + numeric subtraction) handed to the caller to smooth a prediction; it is never sent. +- **One mechanism?** Not today. They are two unrelated things that share a word. The + operator's recollection matches the plan, not the code: variants' fork ruling 4 + (`cultnet-deltas`) says variants travel on CultNet as deltas, and + `variants:ruling:hop-subscriptions-refuse-variants` holds CultNet off variants until + that cut (C5) lands. When it does, the override vocabulary will be both the stored + variant and the wire delta. +- **Consequence for the push.** The push invents no delta format. Its addressing is the + variants override vocabulary (slot plus element id; `HardpointData.Id` is already a + `[CultElementId]`) when CultLib can apply overrides to a record in place; until then + it is a whole-record replace of the records that changed, guarded by `Expect`. Fork Q5. ## Authority map -- **Owner.** The add-on's agent turn primitive owns whether and how an agent intent - changes the live scene. Blender owns scene truth and the undo stack. The human owns - the sink toggle, Stop, and undo. -- **Inputs.** Intent documents; the snapshot's human-edit sequences; the sink toggle. -- **Outputs.** One undo step per accepted mutating intent; one receipt per intent; - the refreshed snapshot; look PNG paths. -- **Derived state.** Presence (from intents and receipts). Human-edit sequences - (from depsgraph and undo handlers, observations only). Look PNGs (telemetry). -- **Forbidden writers.** `execute_command` called outside the primitive; operators - called with undo on inside an agent action; any raw RNA write by an agent without the - closing push; `ed.undo`/`ed.redo` from add-on code; the debug-mirror JSON import - (`blender_target.py` `_import_debug_command_files`) as a second door for intents; - `brokkr-ctl` opening the store to decide anything. +- **Owner.** Phase one: the add-on's agent turn primitive owns whether and how an agent + intent changes the live scene; Blender owns scene truth and the undo stack; the human + owns the sink toggle, Stop and undo. Phase two: the `ship.cc` owns the ship; + AetherDb's ship-authoring code alone derives and writes its records. +- **Inputs.** Intent documents and the sink toggle (phase one). The tagged collections, + the binding's opened versions and the request file (phase two). +- **Outputs.** One undo step per accepted mutating intent; one receipt per intent; the + refreshed snapshot; look PNG paths; AetherDb's dry-run diff or its write. +- **Derived state.** Presence; human-edit sequences; look PNGs; the scene's mapped + collections (an edit buffer over the `.cc`); the request file. +- **Forbidden writers.** `execute_command` called around the primitive; operators run + with undo on inside an agent action; unpushed agent writes; `ed.undo`/`ed.redo` from + add-on code; any agent-sent Python; the debug-mirror JSON import as a door for intents + (`blender_target.py` `_import_debug_command_files`); `brokkr-ctl` deciding anything; + `ship_cc.py`'s envelope writes and any other direct `.cc` writer; `layout_revision` + as a revision. - **Shared paths.** brokkr-ctl intents, panel buttons that act on the scene, sync-organ - intents from `brokkr-daemon sync-once`, and replayed intents use the one primitive. + intents and replayed intents use the one primitive. The packager, the authoring + surface's buttons and an agent's push intent use the one AetherDb push. - **Deletion line.** The debug-mirror intent import goes before the primitive lands; - `drain_commands` stops calling `execute_command` directly. + `drain_commands` stops calling `execute_command` directly. `ship_cc.py`'s write + functions and `layout_revision` go when the push lands. ## Identity, lifecycle and authority | Persistent kind | What names it | What happens to it over time | Who decides | |---|---|---|---| -| Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `baseSeq`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (Unity F6 A, `brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written, as today. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | -| Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, conflict, stopped, failed, `undoLabel`, `lookPath`, and for `run` the script text and SHA-256) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. The only proof an intent ran. | The primitive alone. Callers and the panel read. | -| Agent identity `requestedBy` | `/` stated by the caller (brokkr-ctl takes it from `EUREKA_INSTANCE` and a flag) | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | -| Agent undo step | Blender undo stack entry labelled `Brokkr : ` | Pushed once per accepted mutating intent; lives as Blender's stack does (step limit, file load); never persisted by Brokkr. | Blender owns the stack. The primitive pushes. Only the human undoes or redoes. | -| Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads; every older base is then stale. | The add-on alone. | -| Human-edit sequences (snapshot fields: `humanEditSeq`, per-object `lastHumanEditSeq`, `lastUndoSeq`) | Integers within a session id | Monotonic within a session; reset with it. Observations, never scene truth. | The add-on's depsgraph and undo handlers alone. | -| Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, the sequences above, sink state) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | -| Command sink toggle (the existing `auto_drain_commands` preference) | Add-on preference, echoed in the snapshot | Off by default. Stop turns it off; only the human turns it on. | The human only. No intent writes it. | -| Script toggle (only if Q1 = b) | A second add-on preference, echoed in the snapshot | Off by default, independent of the sink. | The human only. | -| Look PNG | `/look/{commandId}.png` | Pruned by count; never read back as truth. | The primitive writes; `brush-tree:ruling:look-files-are-scratch` governs. | +| Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (`brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | +| Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, stopped, failed, `undoLabel`, `lookPath`) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. | The primitive alone. Callers and the panel read. | +| Agent identity `requestedBy` | `/` stated by the caller | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | +| Agent undo step | Blender undo entry `Brokkr : ` | One per accepted mutating intent; lives as Blender's stack does; never persisted by Brokkr. | Blender owns the stack; the primitive pushes; only the human undoes or redoes. | +| Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads. | The add-on alone. | +| Human-edit sequences (snapshot: `humanEditSeq`, per-object `lastHumanEditSeq`) | Integers within a session id | Monotonic within a session; reset with it. Information for the agent; they gate nothing. | The add-on's depsgraph and undo handlers alone. | +| Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, sequences, sink state, authoring binding summary) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | +| Command sink toggle (`auto_drain_commands`) | Add-on preference, echoed in the snapshot | Off by default. Stop turns it off; only the human turns it on. | The human only. | +| Look PNG | `/look/{commandId}.png` | Pruned by count; never read back as truth. | The primitive writes; `look-files-are-scratch` governs. | +| Ship package store `ship.cc` (`HullData`, `ShipAuthoring`, product records) | Its path, `GameData/Mods//ship.cc`; records by their keys | Created by `ship-authoring create`; changed only by AetherDb commands, each write minting new stored versions (`variants:ruling:storedat-on-change`); replaced whole only by packager `--replace`. | AetherDb's ship-authoring code is the only writer. | +| Record version | The version CultCache's compare-exchange tests for each record key | Changes on every write that changes the record's bytes. | CultCache mints it; AetherDb reports it on open and tests it on apply. | +| Authoring binding | A custom property on the Blender scene: the `ship.cc` path relative to the `.blend`, the ship id, and the record versions opened at | Set on Open; versions replaced after each successful apply; cleared on Detach or reopen. Lives in the `.blend`. | Open, apply and Detach (human buttons or agent actions through the primitive) alone write it. | +| Collection role | A custom property on a collection: hull, hardpoints, lines or anchors | Set when the surface builds or the author tags a collection; removed on Detach. | The author; the surface's Open builds the defaults. | +| Hardpoint row identity | `aetheria.id` on the row's object, equal to `HardpointData.Id` (`[CultElementId]`) | Minted when the row is created; survives renames and moves; removing the object removes the row on the next push. | AetherDb mints for a new row; the surface carries it. | +| Push request | `/authoring/{commandId}.json`, manifest vocabulary plus opened versions | Written per push; pruned by count; never read back as state. | The surface writes; AetherDb alone interprets it. | ## Not in scope -Human-to-human replication or several Blender instances in one session (Multi-User's -domain). Agents on another host reaching the operator's Blender: the transport is not -widened beyond what the add-on serves today. Per-user or selective undo. An approval gate -before each agent action (unless Q2 rules otherwise). A 3D-view overlay of the agent's -presence; the panel carries presence in this revision. The Unity surface and -`brokkr-command`. The brush-tree vocabulary, Geometry.Csg and OpenSCAD text (brush-tree -owns them). Agent-initiated save and quit (`brush-tree:ruling:run-admitted-when-enabled` -keeps them off the allowed list). Asset libraries and generators. An MCP server. +Human-to-human replication or several Blender instances in one session. Agents on +another host reaching the operator's Blender. Per-user or selective undo. An approval +gate (`act-then-undo`). Stale-action refusal inside the live scene +(`scene-last-writer-wins`). Any agent-sent Python (`no-free-form-python`). A 3D-view +presence overlay. The Unity surface and `brokkr-command`. The brush-tree vocabulary, +Geometry.Csg and OpenSCAD text (brush-tree owns them). Agent-initiated save and quit. +Asset libraries and generators. An MCP server. Records outside a ship package +(catalog loadouts, factions) unless Q6 rules them in. A new delta wire format. ## Open forks (draft questions; Self admits) -- **Q1. Free-form Python.** Today the Blender add-on has no script action. Libby's - Defaulted ruling `brush-tree:ruling:run-admitted-when-enabled` would add `run`, admitted - whenever agent commands are on. Options: (a) typed actions only; (b) `run` behind its - own off-by-default toggle, one undo step, script text in the receipt; (c) the Defaulted - ruling as written. Recommend (b). -- **Q2. Act then undo, or approve first.** Recommend act then undo, with Stop. -- **Q3. Conflict granularity.** (a) any human edit since the base refuses; (b) only edits to - the intent's targets, plus any undo or redo. Recommend (b), after the depsgraph - attribution probe. -- **Q4. Who builds `brokkr-ctl blender`.** Recommend this campaign builds the session - subcommands in Rust per Libby's rulings, and brush-tree adds its tree commands to the - same binary later. +- **Q5. What a push carries.** (a) whole records that changed, under `Expect`, now; (b) + variants override paths applied in place, after CultLib builds in-place apply and + C2b; (c) (a) now with the request shaped so (b) replaces it without changing the + surface. Recommend (c). +- **Q6. Does a ship's loadout belong in its package?** A package holds hull, authoring + and products today; loadouts are catalog records. Recommend not in r2. +- **Q7. May an agent apply a push, or only dry-run?** A `.cc` write has no Ctrl+Z. + Recommend dry-run for agents, apply by her button. +- **Q8. Where the authoring surface lives.** (a) the `aetheria_ships` add-on in Aetheria, + with Brokkr giving the agent typed actions that call it; (b) Brokkr's add-on gains + Aetheria vocabulary. Recommend (a). From 847c28714bc58d37b2e8f30ae1cc1f6088121828 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:20:10 +0100 Subject: [PATCH 014/223] Live collab target r2: the push request is a stdin dump, as the material path Co-Authored-By: Claude Opus 5.5 --- docs/live-collab-target.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index 228ae83..13592ad 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -160,10 +160,11 @@ the three records and their stored versions, builds the tagged collections, and on the binding the version of each record it read. Nothing reads a `.cc` by scraping envelopes (operator 2026-11-17). -**A push is one AetherDb call, dry-run then apply.** The surface writes the authoring +**A push is one AetherDb call, dry-run then apply.** The surface pipes the authoring state of its tagged collections (the manifest vocabulary, plus the record versions it -opened at) to a scratch request file and calls `AetherDb ship-authoring push -`. Without `apply` AetherDb loads the store, derives the records the request +opened at) as a structural JSON dump on stdin to `AetherDb ship-authoring push `, +as the material path does (`aetheria-release:ruling:blender-dump-stdin`): never written +to disk, parsed and judged only in C#, so the schema exists once. Without `apply` AetherDb loads the store, derives the records the request describes, validates them, and prints the per-record, per-field changes; nothing is written. With `apply` it does the same and writes under compare-exchange on each record's stored version (`Expect`). One CLI call per push is the starting shape; a @@ -226,11 +227,11 @@ are the primitive for the push. owns the sink toggle, Stop and undo. Phase two: the `ship.cc` owns the ship; AetherDb's ship-authoring code alone derives and writes its records. - **Inputs.** Intent documents and the sink toggle (phase one). The tagged collections, - the binding's opened versions and the request file (phase two). + the binding's opened versions and the stdin dump (phase two). - **Outputs.** One undo step per accepted mutating intent; one receipt per intent; the refreshed snapshot; look PNG paths; AetherDb's dry-run diff or its write. - **Derived state.** Presence; human-edit sequences; look PNGs; the scene's mapped - collections (an edit buffer over the `.cc`); the request file. + collections (an edit buffer over the `.cc`); the stdin dump (a pipe, not state). - **Forbidden writers.** `execute_command` called around the primitive; operators run with undo on inside an agent action; unpushed agent writes; `ed.undo`/`ed.redo` from add-on code; any agent-sent Python; the debug-mirror JSON import as a door for intents @@ -262,7 +263,6 @@ are the primitive for the push. | Authoring binding | A custom property on the Blender scene: the `ship.cc` path relative to the `.blend`, the ship id, and the record versions opened at | Set on Open; versions replaced after each successful apply; cleared on Detach or reopen. Lives in the `.blend`. | Open, apply and Detach (human buttons or agent actions through the primitive) alone write it. | | Collection role | A custom property on a collection: hull, hardpoints, lines or anchors | Set when the surface builds or the author tags a collection; removed on Detach. | The author; the surface's Open builds the defaults. | | Hardpoint row identity | `aetheria.id` on the row's object, equal to `HardpointData.Id` (`[CultElementId]`) | Minted when the row is created; survives renames and moves; removing the object removes the row on the next push. | AetherDb mints for a new row; the surface carries it. | -| Push request | `/authoring/{commandId}.json`, manifest vocabulary plus opened versions | Written per push; pruned by count; never read back as state. | The surface writes; AetherDb alone interprets it. | ## Not in scope From bebc004f09fcfdb32937dd19553ca7383e7daee7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:32:47 +0100 Subject: [PATCH 015/223] Blender: one agent turn primitive, run_intent (live-2) Every intent is admitted (commandId unused, requestedBy /, typed action), run with operator undo off, pushed as one labelled undo step, and receipted with requestedBy, note and undoLabel. execute_command becomes the private _dispatch. A refusal before any write pushes nothing; a raise after one pushes a '(failed)' step. Live GUI test: Edit Mode object-level write is not reverted by one undo (reported). Co-Authored-By: Claude Sonnet 5.5 --- docs/live-collab-target.md | 4 +- .../blender/brokkr_bridge/blender_target.py | 152 +++++++++++----- .../blender/tests/live/agent_turn_undo.py | 170 ++++++++++++++++++ .../tests/live/agent_turn_undo.result.json | 167 +++++++++++++++++ surfaces/blender/tests/live/gn_actions.py | 4 +- surfaces/blender/tests/live/gn_recreation.py | 4 +- surfaces/blender/tests/live/headless_smoke.py | 2 +- .../blender/tests/live/material_colour.py | 2 +- surfaces/blender/tests/test_agent_turn.py | 90 ++++++++++ .../blender/tests/test_material_actions.py | 21 ++- surfaces/blender/tests/test_node_actions.py | 16 +- surfaces/blender/tests/test_scene_actions.py | 36 +++- 12 files changed, 604 insertions(+), 64 deletions(-) create mode 100644 surfaces/blender/tests/live/agent_turn_undo.py create mode 100644 surfaces/blender/tests/live/agent_turn_undo.result.json create mode 100644 surfaces/blender/tests/test_agent_turn.py diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index 13592ad..aee7181 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -100,7 +100,9 @@ resident service on that number); reading a record's stored version through Aeth in the add-on: admit (sink enabled, `requestedBy` present, id unused, action typed and valid), run the action with every operator called `undo=False`, push exactly one undo step labelled `Brokkr : `, write the receipt. A -refusal or a failure pushes nothing and leaves the scene unchanged. There is no second +refusal caught before any write pushes nothing and leaves the scene unchanged; an action +that fails after writing pushes one step labelled `(failed)`, so the partial write is one +undoable step. There is no second writer and no script action (`no-free-form-python`): what the typed actions do not cover waits for a new typed action. diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 677f03d..a3156c0 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -5,6 +5,7 @@ import functools import json import math import os +import re import sys import uuid from array import array @@ -43,6 +44,16 @@ CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY") GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT") GL_RUNTIME_LIBRARY = "libEGL.so.1" +# Actions that only read the scene and so push no undo step (live-5 adds look). +READ_ACTIONS: tuple[str, ...] = () +MUTATING_ACTIONS = ( + "createObject", "deleteObject", "setObjectTransform", "setObjectVisibility", "setObjectParent", + "setObjectCustomProperty", "selectObject", "assignMaterial", "importGltf", "exportGltf", + "setCamera", "setLight", "setWorld", "renderStill", +) +REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") +NOTE_LIMIT = 200 + EVALUATED_POSITION_CAP = 256 EVALUATED_VERTEX_LIMIT = 1_000_000 EVALUATED_INSTANCE_SCAN_LIMIT = 100_000 # depsgraph items visited per capture; iterating one in Python costs ~5 us @@ -92,6 +103,8 @@ class BrokkrBlenderTarget: self.import_dir: str = "" self.output_dir: str = "" self.nodes = na.NodeActions(bpy_module) + self.agent_turn = False # true only inside run_intent + self._receipted: set[str] = set() def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: """The directories importGltf and renderStill may touch; empty leaves that action disabled.""" @@ -133,9 +146,11 @@ class BrokkrBlenderTarget: snapshot = node.database.snapshot() commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] + self._receipted.update( + r.get("commandId", "") for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values()) for command_key, command in sorted(commands.items()): - receipt = self.execute_command(context, command) + receipt = self.run_intent(context, command) self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root) node.database.delete(documents["command_intent"], command_key) receipts.append(receipt) @@ -488,45 +503,89 @@ class BrokkrBlenderTarget: "collections": [self._collection_snapshot(collection) for collection in bpy.data.collections], } - def execute_command(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def run_intent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + """The one agent turn: admit, run with operator undo off, push one labelled undo step, receipt.""" + command_id = command.get("commandId") + requested_by = command.get("requestedBy") action = command.get("action", "") + denial = "" + if not isinstance(command_id, str) or not command_id: + denial = "Intent has no commandId." + elif command_id in self._receipted: + denial = f"commandId {command_id!r} was already receipted; ids are single-use." + elif not isinstance(requested_by, str) or not REQUESTED_BY_SHAPE.match(requested_by): + denial = "Intent has no requestedBy of the form '/'." + elif action not in MUTATING_ACTIONS and action not in READ_ACTIONS and action not in na.NodeActions.ACTIONS: + denial = f"Unsupported Blender command action: {action}" + if denial: + if isinstance(command_id, str) and command_id: + self._receipted.add(command_id) + return self._receipt(command, "denied", denial, "") + + label = f"Brokkr {requested_by}: {action} {command_id[:8]}" + push = action not in READ_ACTIONS + self.agent_turn = True try: - if action == "createObject": - return self._create_object(context, command) - if action == "deleteObject": - return self._delete_object(context, command) - if action == "setObjectTransform": - return self._set_object_transform(context, command) - if action == "setObjectVisibility": - return self._set_object_visibility(context, command) - if action == "setObjectParent": - return self._set_object_parent(context, command) - if action == "setObjectCustomProperty": - return self._set_object_custom_property(context, command) - if action == "selectObject": - return self._select_object(context, command) - if action == "assignMaterial": - return self._assign_material(context, command) - if action == "importGltf": - return self._import_gltf(context, command) - if action == "exportGltf": - return self._export_gltf(context, command) - if action == "setCamera": - return self._set_camera(context, command) - if action == "setLight": - return self._set_light(context, command) - if action == "setWorld": - return self._set_world(context, command) - if action == "renderStill": - return self._render_still(context, command) - if action in na.NodeActions.ACTIONS: - message, name = self.nodes.execute(action, command) - return self._receipt(command, "accepted", message, name) - return self._receipt(command, "failed", f"Unsupported Blender command action: {action}", "") - except sa.ActionRefused as error: - return self._receipt(command, "failed", str(error), "") - except Exception as error: - return self._receipt(command, "failed", str(error), "") + try: + receipt = self._dispatch(context, command) + if receipt["status"] != "accepted": + push = False # returned a refusal: it wrote nothing + except sa.ActionRefused as error: # raised before any write: nothing to push + receipt, push = self._receipt(command, "failed", str(error), ""), False + except Exception as error: # a partial write is one undoable step, not part of her next action + label += " (failed)" + receipt = self._receipt(command, "failed", str(error), "") + if push: + self._push_undo(label) + receipt["undoLabel"] = label + finally: + self.agent_turn = False + self._receipted.add(command_id) + return receipt + + def _push_undo(self, label: str) -> None: + windows = self.bpy.context.window_manager.windows + if windows: + with self.bpy.context.temp_override(window=windows[0]): + self.bpy.ops.ed.undo_push(message=label) + else: + self.bpy.ops.ed.undo_push(message=label) + + def _dispatch(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + """The action table. Only run_intent calls it; it owns refusal, failure and the undo step.""" + action = command.get("action", "") + if action == "createObject": + return self._create_object(context, command) + if action == "deleteObject": + return self._delete_object(context, command) + if action == "setObjectTransform": + return self._set_object_transform(context, command) + if action == "setObjectVisibility": + return self._set_object_visibility(context, command) + if action == "setObjectParent": + return self._set_object_parent(context, command) + if action == "setObjectCustomProperty": + return self._set_object_custom_property(context, command) + if action == "selectObject": + return self._select_object(context, command) + if action == "assignMaterial": + return self._assign_material(context, command) + if action == "importGltf": + return self._import_gltf(context, command) + if action == "exportGltf": + return self._export_gltf(context, command) + if action == "setCamera": + return self._set_camera(context, command) + if action == "setLight": + return self._set_light(context, command) + if action == "setWorld": + return self._set_world(context, command) + if action == "renderStill": + return self._render_still(context, command) + if action in na.NodeActions.ACTIONS: + message, name = self.nodes.execute(action, command) + return self._receipt(command, "accepted", message, name) + return self._receipt(command, "failed", f"Unsupported Blender command action: {action}", "") def _create_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: object_type = command.get("objectType", "EMPTY") @@ -542,13 +601,13 @@ class BrokkrBlenderTarget: location = _vector(command.get("location"), 3, (0.0, 0.0, 0.0)) if object_type == "MESH": - self.bpy.ops.mesh.primitive_cube_add(size=float(command.get("size", 1.0)), location=location) + self.bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, size=float(command.get("size", 1.0)), location=location) elif object_type == "LIGHT": - self.bpy.ops.object.light_add(type=command.get("lightType", "POINT"), location=location) + self.bpy.ops.object.light_add("EXEC_DEFAULT", False, type=command.get("lightType", "POINT"), location=location) elif object_type == "CAMERA": - self.bpy.ops.object.camera_add(location=location) + self.bpy.ops.object.camera_add("EXEC_DEFAULT", False, location=location) else: # EMPTY - self.bpy.ops.object.empty_add(type=command.get("emptyDisplayType", "PLAIN_AXES"), location=location) + self.bpy.ops.object.empty_add("EXEC_DEFAULT", False, type=command.get("emptyDisplayType", "PLAIN_AXES"), location=location) obj = context.object obj.name = name @@ -662,7 +721,7 @@ class BrokkrBlenderTarget: (sa.fingerprint([path]), sa.fingerprint(existing)) != checked: raise sa.ActionRefused("Import file changed while it was being checked.") before = set(self.bpy.data.objects.keys()) - self.bpy.ops.import_scene.gltf(filepath=str(path)) + self.bpy.ops.import_scene.gltf("EXEC_DEFAULT", False, filepath=str(path)) added = sorted(set(self.bpy.data.objects.keys()) - before) return self._receipt(command, "accepted", f"Imported {len(added)} object(s) from {path.name}.", added[0] if added else "") @@ -708,7 +767,7 @@ class BrokkrBlenderTarget: try: for obj in objects: obj.select_set(obj in chosen) - result = self.bpy.ops.export_scene.gltf( + result = self.bpy.ops.export_scene.gltf("EXEC_DEFAULT", False, filepath=str(path), export_format="GLB" if suffix == ".glb" else "GLTF_SEPARATE", use_selection=bool(chosen), **options) finally: @@ -848,7 +907,7 @@ class BrokkrBlenderTarget: path.parent.mkdir(parents=True, exist_ok=True) if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: raise sa.ActionRefused("Output path changed while it was being checked.") - self.bpy.ops.render.render(write_still=True) + self.bpy.ops.render.render("EXEC_DEFAULT", False, write_still=True) finally: (render.engine, render.resolution_x, render.resolution_y, render.filepath, render.image_settings.file_format, scene.camera) = saved @@ -1013,6 +1072,9 @@ class BrokkrBlenderTarget: "status": status, "message": message, "objectName": object_name, + "requestedBy": command["requestedBy"] if isinstance(command.get("requestedBy"), str) else "", + "note": command["note"][:NOTE_LIMIT] if isinstance(command.get("note"), str) else "", + "undoLabel": "", "observedAt": _now(), } diff --git a/surfaces/blender/tests/live/agent_turn_undo.py b/surfaces/blender/tests/live/agent_turn_undo.py new file mode 100644 index 0000000..c41ca89 --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_undo.py @@ -0,0 +1,170 @@ +"""Live proof, in GUI Blender, that every agent intent is one undo step. + + BROKKR_ADDON= \ + blender --factory-startup --python agent_turn_undo.py -- + +Writes .result.json beside , then quits Blender. Each step is its own timer tick so the +event loop runs between steps, as it does for Brokkr's 1 s drain (probe_timer_undo.py pattern). +Undo is read only here, by this driver; the add-on never calls ed.undo or ed.redo. +Exit status is not meaningful in a GUI session: read the "ok" fields of the result. +""" +import json +import os +import sys +import traceback +import types +from pathlib import Path + +import bpy + +ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() +pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)] +sys.modules["brokkr_bridge"] = pkg +from brokkr_bridge import blender_target as bt + +OUT = sys.argv[sys.argv.index("--") + 1] +R = {"blender": bpy.app.version_string, "background": bpy.app.background, "checks": [], "steps": []} +target = bt.BrokkrBlenderTarget(bpy) +N = [0] + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + w = bpy.context.window_manager.windows[0] + return bpy.context.temp_override(window=w) + + +def intent(**cmd): + N[0] += 1 + cmd.setdefault("commandId", "%08d-live-agent-turn" % N[0]) + cmd.setdefault("requestedBy", "nibu/hands") + r = target.run_intent(bpy.context, cmd) + R["steps"].append({"intent": cmd["action"], "status": r["status"], "undoLabel": r["undoLabel"], "message": r["message"]}) + return r + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def push(msg): + with win(): + bpy.ops.ed.undo_push(message=msg) + + +def loc(name): + o = bpy.data.objects.get(name) + return None if o is None else [round(v, 3) for v in o.location] + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +S = {} + + +def s_baseline(): + push("driver baseline") + S["objects0"] = names() + + +def s_create(): + r = intent(action="createObject", objectType="MESH", name="AgentCube", location=[3, 0, 0]) + check("createObject accepted with undoLabel", r["status"] == "accepted" and r["undoLabel"].startswith("Brokkr nibu/hands: createObject "), r["undoLabel"]) + + +def s_transform(): + intent(action="setObjectTransform", objectName="AgentCube", location=[3, 2, 0]) + check("transform applied", loc("AgentCube") == [3.0, 2.0, 0.0], loc("AgentCube")) + + +def s_undo_transform(): + undo() + check("one undo reverts only the transform step", "AgentCube" in names() and loc("AgentCube") == [3.0, 0.0, 0.0], + {"objects": names(), "loc": loc("AgentCube")}) + + +def s_undo_create(): + undo() + check("one undo reverts createObject (cube_add, rename, location) together", names() == S["objects0"], names()) + + +def s_denied_setup(): + intent(action="createObject", objectType="MESH", name="AgentCube2", location=[0, 5, 0]) + r = intent(action="createObject", objectType="MESH", requestedBy="", name="Intruder") + check("denied intent: status denied, scene unchanged", r["status"] == "denied" and "Intruder" not in names(), r["status"]) + check("denied intent: no undoLabel", r["undoLabel"] == "", r["undoLabel"]) + + +def s_denied_undo(): + undo() + check("denied intent pushed nothing: one undo removes the preceding accepted intent", names() == S["objects0"], names()) + + +def s_edit_enter(): + cube = bpy.data.objects["Cube"] + bpy.context.view_layer.objects.active = cube + cube.select_set(True) + with win(): + bpy.ops.object.mode_set(mode="EDIT") + S["loc0"] = loc("Cube") + push("driver edit-mode baseline") + R["editMode"] = {"mode_before": bpy.context.mode, "loc_before": S["loc0"]} + + +def s_edit_agent(): + r = intent(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + R["editMode"].update(mode_after_intent=bpy.context.mode, loc_after_intent=loc("Cube"), receipt=r["status"], undoLabel=r["undoLabel"]) + check("edit mode: agent transform applied", loc("Cube") == [0.0, 0.0, 5.0], loc("Cube")) + + +def s_edit_undo(): + undo() + R["editMode"].update(mode_after_undo=bpy.context.mode, loc_after_undo=loc("Cube")) + check("edit mode: one undo reverts the agent transform", loc("Cube") == S["loc0"], R["editMode"]) + + +def s_edit_undo_again(): + """Diagnostic, not a check: where does the object-level write sit relative to Edit Mode steps?""" + undo() + R["editMode"].update(mode_after_second_undo=bpy.context.mode, loc_after_second_undo=loc("Cube")) + + +def s_exit(): + if bpy.context.mode != "OBJECT": + with win(): + bpy.ops.object.mode_set(mode="OBJECT") + + +steps = [s_baseline, s_create, s_transform, s_undo_transform, s_undo_create, s_denied_setup, s_denied_undo, + s_edit_enter, s_edit_agent, s_edit_undo, s_edit_undo_again, s_exit] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not any("error" in s for s in R["steps"]) + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1) + + +def tick(): + global i + if i < len(steps): + try: + steps[i]() + except Exception: + R["steps"].append({"step": steps[i].__name__, "error": traceback.format_exc()}) + i += 1 + write() + return 0.5 + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=2.0) diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json new file mode 100644 index 0000000..5ae93a7 --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -0,0 +1,167 @@ +{ + "blender": "5.3.0", + "background": false, + "checks": [ + { + "name": "createObject accepted with undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: createObject 00000001" + }, + { + "name": "transform applied", + "ok": true, + "detail": [ + 3.0, + 2.0, + 0.0 + ] + }, + { + "name": "one undo reverts only the transform step", + "ok": true, + "detail": { + "objects": [ + "AgentCube", + "Camera", + "Cube", + "Light" + ], + "loc": [ + 3.0, + 0.0, + 0.0 + ] + } + }, + { + "name": "one undo reverts createObject (cube_add, rename, location) together", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] + }, + { + "name": "denied intent: status denied, scene unchanged", + "ok": true, + "detail": "denied" + }, + { + "name": "denied intent: no undoLabel", + "ok": true, + "detail": "" + }, + { + "name": "denied intent pushed nothing: one undo removes the preceding accepted intent", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] + }, + { + "name": "edit mode: agent transform applied", + "ok": true, + "detail": [ + 0.0, + 0.0, + 5.0 + ] + }, + { + "name": "edit mode: one undo reverts the agent transform", + "ok": false, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 5.0 + ], + "receipt": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 5.0 + ], + "mode_after_second_undo": "OBJECT", + "loc_after_second_undo": [ + 0.0, + 0.0, + 0.0 + ] + } + } + ], + "steps": [ + { + "intent": "createObject", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject 00000001", + "message": "Blender object created." + }, + { + "intent": "setObjectTransform", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000002", + "message": "Blender object transform updated." + }, + { + "intent": "createObject", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject 00000003", + "message": "Blender object created." + }, + { + "intent": "createObject", + "status": "denied", + "undoLabel": "", + "message": "Intent has no requestedBy of the form '/'." + }, + { + "intent": "setObjectTransform", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", + "message": "Blender object transform updated." + } + ], + "ok": false, + "editMode": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 5.0 + ], + "receipt": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 5.0 + ], + "mode_after_second_undo": "OBJECT", + "loc_after_second_undo": [ + 0.0, + 0.0, + 0.0 + ] + } +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/gn_actions.py b/surfaces/blender/tests/live/gn_actions.py index 1d9e329..62df949 100644 --- a/surfaces/blender/tests/live/gn_actions.py +++ b/surfaces/blender/tests/live/gn_actions.py @@ -4,7 +4,7 @@ blender -b --factory-startup --python gn_actions.py -- result.json Each native tree is built with bpy as the reference and evaluated with the depsgraph. The Brokkr side -uses BrokkrBlenderTarget.execute_command for every build step and capture_snapshot().objects[].evaluated +uses BrokkrBlenderTarget.run_intent for every build step and capture_snapshot().objects[].evaluated for every read: no bpy call touches the Brokkr-built scene except the harness's own reference trees. Exit status is non-zero if any check fails. """ @@ -29,7 +29,7 @@ def fresh(): N = [0] def act(t, **cmd): N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]) - r = t.execute_command(bpy.context, cmd) + r = t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) if r["status"] != "accepted": print("REFUSED", cmd["action"], r["message"], flush=True) return r diff --git a/surfaces/blender/tests/live/gn_recreation.py b/surfaces/blender/tests/live/gn_recreation.py index 6ef8036..f8127d9 100644 --- a/surfaces/blender/tests/live/gn_recreation.py +++ b/surfaces/blender/tests/live/gn_recreation.py @@ -4,7 +4,7 @@ blender -b --factory-startup --python gn_recreation.py -- result.json Each setup is built twice: natively (geometry-nodes tree via bpy, evaluated) and through -BrokkrBlenderTarget.execute_command using only the actions that exist. Prints GAP lines where an +BrokkrBlenderTarget.run_intent using only the actions that exist. Prints GAP lines where an action that would be needed is refused or has no effect. Not part of the unittest run (needs Blender). """ import bpy, sys, os, json, types, math, random @@ -25,7 +25,7 @@ def reset(): def act(t, **cmd): cmd.setdefault("commandId", "c%d" % act.n); act.n += 1 - return t.execute_command(bpy.context, cmd) + return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) act.n = 0 def gap(key, **detail): diff --git a/surfaces/blender/tests/live/headless_smoke.py b/surfaces/blender/tests/live/headless_smoke.py index 085df0c..1d21601 100644 --- a/surfaces/blender/tests/live/headless_smoke.py +++ b/surfaces/blender/tests/live/headless_smoke.py @@ -43,7 +43,7 @@ results = [] def run(label, **cmd): cmd.setdefault("commandId", label) try: - r = target.execute_command(bpy.context, cmd) + r = target.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) except Exception: r = {"status": "EXCEPTION", "message": traceback.format_exc()} print("RESULT", label, r["status"], r.get("message", "").replace("\n", " | ")[:400], flush=True) diff --git a/surfaces/blender/tests/live/material_colour.py b/surfaces/blender/tests/live/material_colour.py index 4b43135..07c2f4d 100644 --- a/surfaces/blender/tests/live/material_colour.py +++ b/surfaces/blender/tests/live/material_colour.py @@ -26,7 +26,7 @@ cube = bpy.context.active_object N = [0] def act(**cmd): N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]); cmd["action"] = "assignMaterial"; cmd["targetObjectName"] = cube.name - return t.execute_command(bpy.context, cmd) + return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) def base(): return tuple(round(c, 6) for c in bpy.data.materials["oxide red"].node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value) diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py new file mode 100644 index 0000000..353f709 --- /dev/null +++ b/surfaces/blender/tests/test_agent_turn.py @@ -0,0 +1,90 @@ +"""run_intent: admission, one labelled undo step, receipts. A fake bpy records ops calls.""" +from __future__ import annotations + +import re +import unittest +import unittest.mock +from pathlib import Path + +import test_scene_actions as ts + +bt = ts.bt +SOURCE = Path(bt.__file__) + + +class AgentTurnTests(unittest.TestCase): + """Reuses the scene fixture (fake bpy, temp import/output dirs).""" + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + + def test_intent_without_requested_by_is_denied(self): + receipt = self.run_action(action="createObject", objectType="EMPTY", requestedBy="") + self.assertEqual(receipt["status"], "denied") + self.assertEqual(self.bpy.created, []) + self.assertEqual(self.bpy.undo.pushes, []) + receipt = self.run_action(action="createObject", objectType="EMPTY", requestedBy="nibu") + self.assertEqual(receipt["status"], "denied") + self.assertEqual(self.bpy.created, []) + + def test_unknown_action_is_denied(self): + self.assertEqual(self.run_action(action="runPython")["status"], "denied") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_reused_command_id_is_denied(self): + first = self.run_action(action="createObject", objectType="EMPTY", commandId="same-id-1") + self.assertEqual(first["status"], "accepted") + second = self.run_action(action="createObject", objectType="EMPTY", commandId="same-id-1") + self.assertEqual(second["status"], "denied") + self.assertEqual(len(self.bpy.created), 1) + self.assertEqual(len(self.bpy.undo.pushes), 1) + + def test_accepted_receipt_carries_undo_label(self): + receipt = self.run_action(action="createObject", objectType="EMPTY", + commandId="abcdef0123456789", requestedBy="nibu/hands", note="x" * 300) + label = "Brokkr nibu/hands: createObject abcdef01" + self.assertEqual(self.bpy.undo.pushes, [label]) + self.assertEqual(receipt["undoLabel"], label) + self.assertEqual(receipt["requestedBy"], "nibu/hands") + self.assertEqual(len(receipt["note"]), 200) + + def test_refusal_pushes_nothing(self): + receipt = self.run_action(action="createObject", objectType="BOGUS") + self.assertEqual(receipt["status"], "failed") + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_read_action_pushes_nothing(self): + with unittest.mock.patch.object(bt, "READ_ACTIONS", ("createObject",)): + self.run_action(action="createObject", objectType="EMPTY") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_raise_after_admission_pushes_failed_step(self): + def boom(*a, **kw): + raise RuntimeError("half done") + self.bpy.ops.object.empty_add = boom + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="deadbeef99") + self.assertEqual(receipt["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, ["Brokkr nibu/hands: createObject deadbeef (failed)"]) + + def test_agent_turn_flag_is_scoped(self): + seen = [] + original = self.bpy.ops.object.empty_add + self.bpy.ops.object.empty_add = lambda *a, **kw: (seen.append(self.target.agent_turn), original(*a, **kw))[1] + self.run_action(action="createObject", objectType="EMPTY") + self.assertEqual(seen, [True]) + self.assertFalse(self.target.agent_turn) + + def test_operators_called_with_undo_false(self): + self.assertEqual(self.run_action(action="exportGltf", filepath="o.glb")["status"], "accepted") + self.assertEqual(self.run_action(action="importGltf", filepath="model.glb")["status"], "accepted") + self.assertEqual(self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES")["status"], "accepted") + for kind in ("MESH", "LIGHT", "CAMERA", "EMPTY"): + self.assertEqual(self.run_action(action="createObject", objectType=kind)["status"], "accepted") + # the fake ops assert ("EXEC_DEFAULT", False); the source pattern pins the spelling too + bad = re.findall(r'bpy\.ops\.(?:mesh|object|import_scene|export_scene|render)\.[a-z_]+\((?!"EXEC_DEFAULT", False)', + SOURCE.read_text(encoding="utf-8")) + self.assertEqual(bad, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/blender/tests/test_material_actions.py b/surfaces/blender/tests/test_material_actions.py index 9ecc2ec..0caa663 100644 --- a/surfaces/blender/tests/test_material_actions.py +++ b/surfaces/blender/tests/test_material_actions.py @@ -5,6 +5,9 @@ The real API is exercised by tests/live/material_colour.py. """ from __future__ import annotations +import contextlib +import itertools + import sys import types import unittest @@ -50,11 +53,25 @@ class Materials(dict): return self[name] +IDS = itertools.count() + + +class FakeUndo: + """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" + def __init__(self, bpy): + self.pushes = [] + bpy.context = NS(window_manager=NS(windows=[object()]), temp_override=lambda **kw: contextlib.nullcontext()) + ops = getattr(bpy, "ops", None) or NS() + ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) + bpy.ops = ops + + class FakeBpy: def __init__(self): self.mesh = NS(name="Cube", type="MESH", data=NS(materials=[])) self.empty = NS(name="Empty", type="EMPTY", data=None) self.data = NS(objects={"Cube": self.mesh, "Empty": self.empty}, materials=Materials()) + self.undo = FakeUndo(self) class MaterialTests(unittest.TestCase): @@ -63,7 +80,7 @@ class MaterialTests(unittest.TestCase): self.target = bt.BrokkrBlenderTarget(self.bpy) def assign(self, **fields): - return self.target.execute_command(NS(), {"commandId": "c1", "action": "assignMaterial", + return self.target.run_intent(NS(), {"commandId": f"c{next(IDS)}", "requestedBy": "nibu/hands", "action": "assignMaterial", "targetObjectName": "Cube", **fields}) def base_color(self, name="oxide red"): @@ -137,7 +154,7 @@ class MaterialTests(unittest.TestCase): self.assertEqual(self.base_color("bare"), (0.2, 0.3, 0.4, 1.0)) def test_object_without_material_slots_is_refused(self): - receipt = self.target.execute_command(NS(), {"commandId": "c", "action": "assignMaterial", + receipt = self.target.run_intent(NS(), {"commandId": f"c{next(IDS)}", "requestedBy": "nibu/hands", "action": "assignMaterial", "targetObjectName": "Empty", "color": [1, 0, 0]}) self.assertEqual(receipt["status"], "failed") self.assertEqual(dict(self.bpy.data.materials), {}) diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index 4c333f1..eac602f 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -5,6 +5,8 @@ The real API is exercised by tests/live/gn_actions.py. """ from __future__ import annotations +import contextlib + import sys import types import unittest @@ -168,9 +170,20 @@ class Obj: self.custom = (key, value) +class FakeUndo: + """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" + def __init__(self, bpy): + self.pushes = [] + bpy.context = NS(window_manager=NS(windows=[object()]), temp_override=lambda **kw: contextlib.nullcontext()) + ops = getattr(bpy, "ops", None) or NS() + ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) + bpy.ops = ops + + class FakeBpy: def __init__(self): self.data = NS(node_groups=Groups(), objects={"Host": Obj("Host")}) + self.undo = FakeUndo(self) class NodeActionTests(unittest.TestCase): @@ -182,7 +195,8 @@ class NodeActionTests(unittest.TestCase): def run_action(self, **command): self.n += 1 command.setdefault("commandId", f"c{self.n}") - return self.target.execute_command(None, command) + command.setdefault("requestedBy", "nibu/hands") + return self.target.run_intent(None, command) def accepted(self, **command): receipt = self.run_action(**command) diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index bb3a292..c60b657 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -4,6 +4,7 @@ Run: python3 -m unittest discover -s surfaces/blender/tests -v """ from __future__ import annotations +import contextlib import json import os import struct @@ -69,6 +70,16 @@ class Objects(dict): """bpy.data.objects: a mapping with keys() and get().""" +class FakeUndo: + """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" + def __init__(self, bpy): + self.pushes = [] + bpy.context = NS(window_manager=NS(windows=[object()]), temp_override=lambda **kw: contextlib.nullcontext()) + ops = getattr(bpy, "ops", None) or NS() + ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) + bpy.ops = ops + + class FakeBpy: def __init__(self): self.imported = [] @@ -95,14 +106,16 @@ class FakeBpy: o.selected = o is self.mesh o.select_get = (lambda o=o: o.selected) o.select_set = (lambda state, o=o: setattr(o, "selected", state)) - add = lambda kind: (lambda **kw: self.add_object(kind, kw)) + add = lambda kind: (lambda mode, undo, **kw: self.add_object(kind, kw, (mode, undo))) self.ops = NS(import_scene=NS(gltf=self.import_gltf), render=NS(render=self.render_still), export_scene=NS(gltf=self.export_gltf), mesh=NS(primitive_cube_add=add("MESH")), object=NS(light_add=add("LIGHT"), camera_add=add("CAMERA"), empty_add=add("EMPTY"))) self.on_add = lambda obj: None + self.undo = FakeUndo(self) - def add_object(self, kind, kwargs): + def add_object(self, kind, kwargs, call=("EXEC_DEFAULT", False)): + assert call == ("EXEC_DEFAULT", False), call # operators run with undo off self.created.append((kind, kwargs)) obj = NS(name=kind.title(), type=kind) self.data.objects[obj.name] = obj @@ -115,18 +128,21 @@ class FakeBpy: world.background = background return world - def import_gltf(self, filepath): + def import_gltf(self, mode, undo, filepath): + assert (mode, undo) == ("EXEC_DEFAULT", False) self.imported.append(filepath) self.data.objects["Imported"] = NS(name="Imported", type="MESH", data=None) - def export_gltf(self, **kwargs): + def export_gltf(self, mode, undo, **kwargs): + assert (mode, undo) == ("EXEC_DEFAULT", False) kwargs["selected_at_call"] = sorted(o.name for o in self.data.objects.values() if o.selected) self.exported.append(kwargs) if self.export_writes: Path(kwargs["filepath"]).write_bytes(b"x" * 10) return self.export_result - def render_still(self, write_still): + def render_still(self, mode, undo, write_still): + assert (mode, undo) == ("EXEC_DEFAULT", False) r = self.scene.render self.rendered.append((r.engine, r.resolution_x, r.resolution_y, r.filepath, r.image_settings.file_format, self.scene.camera)) @@ -149,8 +165,10 @@ class ActionTests(unittest.TestCase): self.bpy.on_add = lambda obj: setattr(self.context, "object", obj) def run_action(self, **command): - command.setdefault("commandId", "c1") - return self.target.execute_command(self.context, command) + self.n = getattr(self, "n", 0) + 1 + command.setdefault("commandId", f"c{self.n:07d}") + command.setdefault("requestedBy", "nibu/hands") + return self.target.run_intent(self.context, command) # importGltf def test_import_inside_the_import_dir_runs(self): @@ -289,7 +307,7 @@ class ActionTests(unittest.TestCase): self.assertFalse((self.root / "out" / "b.glb").exists()) def test_export_selection_restored_when_the_exporter_raises(self): - def boom(**kw): + def boom(*a, **kw): raise RuntimeError("exporter blew up") self.bpy.ops.export_scene.gltf = boom receipt = self.run_action(action="exportGltf", filepath="a.glb", selection=["Cam"]) @@ -362,7 +380,7 @@ class ActionTests(unittest.TestCase): self.assertIsNone(self.bpy.scene.camera) def test_render_still_restores_settings_when_the_render_fails(self): - def boom(write_still): + def boom(*a, **kw): raise RuntimeError("render failed") self.bpy.ops.render.render = boom self.assertEqual(self.run_action(action="renderStill", outputPath="a.png", engine="CYCLES")["status"], "failed") From 6464915fa42e5eb3dee1114bb7a7f7aeed0202e2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:35:25 +0100 Subject: [PATCH 016/223] Blender: refuse object-level intents while an object is in Edit Mode Ruling brokkr-live:ruling:object-intents-refused-in-edit-mode. The guard denies before any write, so nothing is pushed and her mode is untouched. Live check measured in Blender 5.3.0: refused, scene and undo stack unchanged. Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/blender_target.py | 12 +++ .../blender/tests/live/agent_turn_undo.py | 31 +++++--- .../tests/live/agent_turn_undo.result.json | 76 +++++++++++-------- surfaces/blender/tests/test_agent_turn.py | 13 ++++ 4 files changed, 90 insertions(+), 42 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index a3156c0..3b9a81a 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -51,6 +51,9 @@ MUTATING_ACTIONS = ( "setObjectCustomProperty", "selectObject", "assignMaterial", "importGltf", "exportGltf", "setCamera", "setLight", "setWorld", "renderStill", ) +# While an object is in Edit Mode, undo steps are edit-mesh steps and an object-level write is not +# reverted by one undo (brokkr-live:ruling:object-intents-refused-in-edit-mode). These touch no object. +EDIT_MODE_SAFE_ACTIONS = ("setWorld", "exportGltf", "renderStill") REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") NOTE_LIMIT = 200 @@ -517,6 +520,9 @@ class BrokkrBlenderTarget: denial = "Intent has no requestedBy of the form '/'." elif action not in MUTATING_ACTIONS and action not in READ_ACTIONS and action not in na.NodeActions.ACTIONS: denial = f"Unsupported Blender command action: {action}" + elif action not in EDIT_MODE_SAFE_ACTIONS and self._edit_mode_object() is not None: + denial = (f"Object {self._edit_mode_object()!r} is in Edit Mode: object-level intents are refused " + "until she leaves it; nothing was changed.") if denial: if isinstance(command_id, str) and command_id: self._receipted.add(command_id) @@ -543,6 +549,12 @@ class BrokkrBlenderTarget: self._receipted.add(command_id) return receipt + def _edit_mode_object(self) -> str | None: + for obj in self.bpy.data.objects.values(): + if getattr(obj, "mode", "OBJECT") == "EDIT": + return obj.name + return None + def _push_undo(self, label: str) -> None: windows = self.bpy.context.window_manager.windows if windows: diff --git a/surfaces/blender/tests/live/agent_turn_undo.py b/surfaces/blender/tests/live/agent_turn_undo.py index c41ca89..75716ee 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.py +++ b/surfaces/blender/tests/live/agent_turn_undo.py @@ -15,6 +15,7 @@ import traceback import types from pathlib import Path +import bmesh import bpy ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() @@ -68,6 +69,11 @@ def names(): S = {} +def vz(): + bm = bmesh.from_edit_mesh(bpy.data.objects["Cube"].data); bm.verts.ensure_lookup_table() + return round(bm.verts[0].co.z, 3) + + def s_baseline(): push("driver baseline") S["objects0"] = names() @@ -114,25 +120,28 @@ def s_edit_enter(): bpy.ops.object.mode_set(mode="EDIT") S["loc0"] = loc("Cube") push("driver edit-mode baseline") + S["z0"] = vz() + bm = bmesh.from_edit_mesh(cube.data); bm.verts.ensure_lookup_table(); bm.verts[0].co.z += 5.0 + bmesh.update_edit_mesh(cube.data) + push("her edit-mesh edit") R["editMode"] = {"mode_before": bpy.context.mode, "loc_before": S["loc0"]} def s_edit_agent(): r = intent(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) - R["editMode"].update(mode_after_intent=bpy.context.mode, loc_after_intent=loc("Cube"), receipt=r["status"], undoLabel=r["undoLabel"]) - check("edit mode: agent transform applied", loc("Cube") == [0.0, 0.0, 5.0], loc("Cube")) + R["editMode"].update(mode_after_intent=bpy.context.mode, loc_after_intent=loc("Cube"), receipt=r["status"], + message=r["message"], undoLabel=r["undoLabel"]) + check("edit mode: object-level intent refused, scene and her mode unchanged", + r["status"] == "denied" and "Edit Mode" in r["message"] and r["undoLabel"] == "" + and loc("Cube") == S["loc0"] and bpy.context.mode == "EDIT_MESH", R["editMode"]) def s_edit_undo(): + """One undo must revert her edit-mesh step: a step pushed by the refused intent would have taken it.""" undo() - R["editMode"].update(mode_after_undo=bpy.context.mode, loc_after_undo=loc("Cube")) - check("edit mode: one undo reverts the agent transform", loc("Cube") == S["loc0"], R["editMode"]) - - -def s_edit_undo_again(): - """Diagnostic, not a check: where does the object-level write sit relative to Edit Mode steps?""" - undo() - R["editMode"].update(mode_after_second_undo=bpy.context.mode, loc_after_second_undo=loc("Cube")) + R["editMode"].update(mode_after_undo=bpy.context.mode, loc_after_undo=loc("Cube"), z_before=S["z0"] + 5.0, z_after_undo=vz()) + check("edit mode: undo stack unchanged by the refused intent (one undo reverts her edit-mesh step)", + vz() == S["z0"] and loc("Cube") == S["loc0"], R["editMode"]) def s_exit(): @@ -142,7 +151,7 @@ def s_exit(): steps = [s_baseline, s_create, s_transform, s_undo_transform, s_undo_create, s_denied_setup, s_denied_undo, - s_edit_enter, s_edit_agent, s_edit_undo, s_edit_undo_again, s_exit] + s_edit_enter, s_edit_agent, s_edit_undo, s_exit] i = 0 diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json index 5ae93a7..455335f 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.result.json +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -62,17 +62,8 @@ ] }, { - "name": "edit mode: agent transform applied", + "name": "edit mode: object-level intent refused, scene and her mode unchanged", "ok": true, - "detail": [ - 0.0, - 0.0, - 5.0 - ] - }, - { - "name": "edit mode: one undo reverts the agent transform", - "ok": false, "detail": { "mode_before": "EDIT_MESH", "loc_before": [ @@ -84,22 +75,48 @@ "loc_after_intent": [ 0.0, 0.0, - 5.0 + 0.0 ], - "receipt": "accepted", - "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", "mode_after_undo": "EDIT_MESH", "loc_after_undo": [ 0.0, 0.0, - 5.0 + 0.0 ], - "mode_after_second_undo": "OBJECT", - "loc_after_second_undo": [ + "z_before": 6.0, + "z_after_undo": 1.0 + } + }, + { + "name": "edit mode: undo stack unchanged by the refused intent (one undo reverts her edit-mesh step)", + "ok": true, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ 0.0, 0.0, 0.0 - ] + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 } } ], @@ -130,12 +147,12 @@ }, { "intent": "setObjectTransform", - "status": "accepted", - "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", - "message": "Blender object transform updated." + "status": "denied", + "undoLabel": "", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." } ], - "ok": false, + "ok": true, "editMode": { "mode_before": "EDIT_MESH", "loc_before": [ @@ -147,21 +164,18 @@ "loc_after_intent": [ 0.0, 0.0, - 5.0 + 0.0 ], - "receipt": "accepted", - "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", "mode_after_undo": "EDIT_MESH", "loc_after_undo": [ - 0.0, - 0.0, - 5.0 - ], - "mode_after_second_undo": "OBJECT", - "loc_after_second_undo": [ 0.0, 0.0, 0.0 - ] + ], + "z_before": 6.0, + "z_after_undo": 1.0 } } \ No newline at end of file diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 353f709..db950a6 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -26,6 +26,19 @@ class AgentTurnTests(unittest.TestCase): self.assertEqual(receipt["status"], "denied") self.assertEqual(self.bpy.created, []) + def test_object_intent_is_refused_while_an_object_is_in_edit_mode(self): + self.bpy.mesh.mode = "EDIT" + receipt = self.run_action(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + self.assertEqual(receipt["status"], "denied") + self.assertIn("Edit Mode", receipt["message"]) + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + self.assertEqual(self.bpy.created, []) + self.assertEqual(self.bpy.mesh.mode, "EDIT") # the agent never changes her mode + self.assertEqual(self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES")["status"], "accepted") + self.bpy.mesh.mode = "OBJECT" + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted") + def test_unknown_action_is_denied(self): self.assertEqual(self.run_action(action="runPython")["status"], "denied") self.assertEqual(self.bpy.undo.pushes, []) From 8f8c92e7c906286532d7e31f4849920166195e5a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 19:09:48 +0100 Subject: [PATCH 017/223] Blender agent turn: Soul s1 fixes Edit Mode refuses setWorld and exportGltf too (only renderStill stays); exportGltf and renderStill push no undo step; receipts are write-once (a reused id's denial goes under .denied); a raise in the undo push is a failed receipt and never re-runs; pin the four surviving branches; queue-level live harness through the node and the add-on timer. Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/blender_target.py | 31 ++- .../blender/tests/live/agent_turn_queue.py | 225 ++++++++++++++++++ .../tests/live/agent_turn_queue.result.json | 196 +++++++++++++++ .../blender/tests/live/agent_turn_undo.py | 34 ++- .../tests/live/agent_turn_undo.result.json | 131 ++++++++++ surfaces/blender/tests/test_agent_turn.py | 96 ++++++++ surfaces/blender/tests/test_scene_actions.py | 5 +- 7 files changed, 708 insertions(+), 10 deletions(-) create mode 100644 surfaces/blender/tests/live/agent_turn_queue.py create mode 100644 surfaces/blender/tests/live/agent_turn_queue.result.json diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 3b9a81a..2528bbc 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -51,9 +51,13 @@ MUTATING_ACTIONS = ( "setObjectCustomProperty", "selectObject", "assignMaterial", "importGltf", "exportGltf", "setCamera", "setLight", "setWorld", "renderStill", ) -# While an object is in Edit Mode, undo steps are edit-mesh steps and an object-level write is not -# reverted by one undo (brokkr-live:ruling:object-intents-refused-in-edit-mode). These touch no object. -EDIT_MODE_SAFE_ACTIONS = ("setWorld", "exportGltf", "renderStill") +# Actions that change no scene state: they push no undo step (exportGltf restores its selection; +# renderStill restores its settings). +NO_SCENE_CHANGE_ACTIONS = ("exportGltf", "renderStill") +# While an object is in Edit Mode, undo steps are edit-mesh steps, so a scene write is not reverted by +# one undo, and some operators leave Edit Mode (brokkr-live:ruling:object-intents-refused-in-edit-mode). +# Anything that writes scene state or changes her mode is refused; renderStill does neither. +EDIT_MODE_SAFE_ACTIONS = ("renderStill",) REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") NOTE_LIMIT = 200 @@ -153,8 +157,12 @@ class BrokkrBlenderTarget: r.get("commandId", "") for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values()) for command_key, command in sorted(commands.items()): + reused = command.get("commandId") in self._receipted receipt = self.run_intent(context, command) - self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root) + # Receipts are write-once: a reused id's denial goes under '.denied', never over the + # original. The sender learns of it by reading that key (and the drain's returned list). + self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root, + key_suffix=".denied" if reused else "") node.database.delete(documents["command_intent"], command_key) receipts.append(receipt) @@ -166,8 +174,9 @@ class BrokkrBlenderTarget: cultlib_py_src: str, receipt: dict[str, Any], debug_mirror_root: str = "", + key_suffix: str = "", ) -> None: - command_id = receipt.get("commandId") or uuid.uuid4().hex + command_id = (receipt.get("commandId") or uuid.uuid4().hex) + key_suffix node, documents = self._open_node(cache_path, cultlib_py_src) node.database.put(documents["command_receipt"], f"blender/receipts/{command_id}", receipt) if debug_mirror_root: @@ -529,7 +538,7 @@ class BrokkrBlenderTarget: return self._receipt(command, "denied", denial, "") label = f"Brokkr {requested_by}: {action} {command_id[:8]}" - push = action not in READ_ACTIONS + push = action not in READ_ACTIONS and action not in NO_SCENE_CHANGE_ACTIONS self.agent_turn = True try: try: @@ -542,8 +551,14 @@ class BrokkrBlenderTarget: label += " (failed)" receipt = self._receipt(command, "failed", str(error), "") if push: - self._push_undo(label) - receipt["undoLabel"] = label + try: + self._push_undo(label) + receipt["undoLabel"] = label + except Exception as error: # the write stands; the intent is receipted, never re-run + receipt = self._receipt( + command, "failed", + f"{receipt['message']} The undo step could not be pushed ({error}); the change stands " + "but is not one undo step.", receipt["objectName"]) finally: self.agent_turn = False self._receipted.add(command_id) diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py new file mode 100644 index 0000000..e44669a --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -0,0 +1,225 @@ +"""Live proof, in GUI Blender with the add-on enabled, that intents arriving through the node queue +are drained by the add-on's own 1 s timer as one undo step each, with write-once receipts. + + BROKKR_USER_SCRIPTS= (also BLENDER_USER_SCRIPTS) + BROKKR_SCRATCH= + BROKKR_PYLIBS= + blender --factory-startup --python agent_turn_queue.py -- + +Intents are put into the node database as brokkr-ctl does (no debug-mirror files). Writes +.result.json, then quits Blender. Undo is read only here, by this driver. +""" +import json +import os +import sys +import traceback +from pathlib import Path + +import bpy + +if os.environ.get("BROKKR_PYLIBS"): + sys.path.insert(0, os.environ["BROKKR_PYLIBS"]) +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +OUT = sys.argv[sys.argv.index("--") + 1] +R = {"blender": bpy.app.version_string, "checks": [], "receipts": {}} + +bpy.ops.preferences.addon_enable(module="brokkr_bridge") +import brokkr_bridge as addon # noqa: E402 +from brokkr_bridge import blender_target as bt # noqa: E402 + +prefs = bpy.context.preferences.addons["brokkr_bridge"].preferences +CACHE = str(SCRATCH / "queue.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.debug_mirror_root = "" # the debug-mirror door is not used here +prefs.output_dir = str(SCRATCH / "out") +prefs.import_dir = "" +prefs.auto_drain_commands = True +(SCRATCH / "out").mkdir(exist_ok=True) +adapter = addon.target() + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + return bpy.context.temp_override(window=bpy.context.window_manager.windows[0]) + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def push(msg): + with win(): + bpy.ops.ed.undo_push(message=msg) + + +def node(): + return adapter._open_node(CACHE, prefs.cultlib_py_src) + + +def queue(cid, **cmd): + n, docs = node() + cmd.update(commandId=cid, schema=bt.COMMAND_INTENT_SCHEMA) + n.database.put(docs["command_intent"], f"blender/commands/{cid}", cmd) + + +def receipt(key): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{key}") + + +def pending(): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {}) + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +S = {} +WAIT = {"ticks": 0} + + +def until(pred, limit=24): + """A step that repeats each tick until pred() holds (the add-on's timer drains meanwhile).""" + def step(): + WAIT["ticks"] += 1 + if pred(): + WAIT["ticks"] = 0 + return True + if WAIT["ticks"] > limit: + raise TimeoutError("drain did not receipt in time") + return False + return step + + +def once(fn): + def step(): + fn() + return True + return step + + +def drained(*ids): + return lambda: all(receipt(i) for i in ids) + + +def q1(): + push("driver baseline") + queue("aaaaaaaa-0001", action="createObject", objectType="MESH", name="QCube", location=[4, 0, 0], + requestedBy="nibu/hands", note="queue test") + + +def q1_check(): + r = receipt("aaaaaaaa-0001") + R["receipts"]["q1"] = r + S["q1_label"] = r and r.get("undoLabel") + check("queue: createObject drained by the add-on timer, accepted, labelled, attributed", + r and r["status"] == "accepted" and r["undoLabel"] == "Brokkr nibu/hands: createObject aaaaaaaa" + and r["requestedBy"] == "nibu/hands" and r["note"] == "queue test" and "QCube" in names(), r) + check("queue: intent removed from the queue after the drain", "blender/commands/aaaaaaaa-0001" not in pending(), list(pending())) + + +def q2(): + queue("aaaaaaaa-0001", action="createObject", objectType="MESH", name="QReuse", requestedBy="nibu/hands") + + +def q2_check(): + orig = receipt("aaaaaaaa-0001") + denial = receipt("aaaaaaaa-0001.denied") + R["receipts"]["q2_original"], R["receipts"]["q2_denial"] = orig, denial + check("queue: reused id leaves the original receipt untouched (write-once)", + orig["status"] == "accepted" and orig["undoLabel"] == S["q1_label"], orig) + check("queue: reused id reported under .denied, nothing created", + denial and denial["status"] == "denied" and "QReuse" not in names(), denial) + + +def q3(): + queue("aaaaaaaa-0003", action="createObject", objectType="MESH", name="QNoOwner") + + +def q3_check(): + r = receipt("aaaaaaaa-0003") + R["receipts"]["q3"] = r + check("queue: intent without requestedBy denied, scene unchanged", r["status"] == "denied" and "QNoOwner" not in names(), r) + + +def q4(): + queue("aaaaaaaa-0004", action="createObject", objectType="MESH", name="QOne", location=[0, 6, 0], requestedBy="nibu/hands") + queue("aaaaaaaa-0005", action="createObject", objectType="MESH", name="QTwo", location=[0, 8, 0], requestedBy="nibu/imagination") + + +def q4_undo_two(): + undo() + after_one = names() + undo() + after_two = names() + check("queue: two intents drained together are two undo steps, last first", + "QTwo" not in after_one and "QOne" in after_one and "QOne" not in after_two, [after_one, after_two]) + + +def q5_edit(): + cube = bpy.data.objects["Cube"] + bpy.context.view_layer.objects.active = cube + cube.select_set(True) + with win(): + bpy.ops.object.mode_set(mode="EDIT") + push("driver edit baseline") + queue("aaaaaaaa-0006", action="setWorld", color=[1, 0, 0], requestedBy="nibu/hands") + queue("aaaaaaaa-0007", action="exportGltf", filepath="edit.glb", requestedBy="nibu/hands") + queue("aaaaaaaa-0008", action="setObjectTransform", objectName="Cube", location=[0, 0, 9], requestedBy="nibu/hands") + + +def q5_check(): + rs = [receipt(k) for k in ("aaaaaaaa-0006", "aaaaaaaa-0007", "aaaaaaaa-0008")] + R["receipts"]["q5"] = rs + check("queue: in Edit Mode setWorld, exportGltf and an object write are all denied, her mode kept", + all(r["status"] == "denied" and r["undoLabel"] == "" for r in rs) and bpy.context.mode == "EDIT_MESH" + and not (SCRATCH / "out" / "edit.glb").exists(), [r["message"] for r in rs]) + + +def q5_exit(): + with win(): + bpy.ops.object.mode_set(mode="OBJECT") + check("queue: add-on drain reports no error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + + +steps = [ + once(q1), until(drained("aaaaaaaa-0001")), once(q1_check), + once(q2), until(lambda: receipt("aaaaaaaa-0001.denied")), once(q2_check), + once(q3), until(drained("aaaaaaaa-0003")), once(q3_check), + once(q4), until(drained("aaaaaaaa-0004", "aaaaaaaa-0005")), once(q4_undo_two), + once(q5_edit), until(drained("aaaaaaaa-0006", "aaaaaaaa-0007", "aaaaaaaa-0008")), once(q5_check), once(q5_exit), +] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def tick(): + global i + if i < len(steps): + try: + if steps[i](): + i += 1 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + i = len(steps) + write() + return 0.5 + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json new file mode 100644 index 0000000..a040d56 --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -0,0 +1,196 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "queue: createObject drained by the add-on timer, accepted, labelled, attributed", + "ok": true, + "detail": { + "action": "createObject", + "commandId": "aaaaaaaa-0001", + "message": "Blender object created.", + "note": "queue test", + "objectName": "QCube", + "observedAt": "2026-11-27T18:07:31.682454+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + } + }, + { + "name": "queue: intent removed from the queue after the drain", + "ok": true, + "detail": [] + }, + { + "name": "queue: reused id leaves the original receipt untouched (write-once)", + "ok": true, + "detail": { + "action": "createObject", + "commandId": "aaaaaaaa-0001", + "message": "Blender object created.", + "note": "queue test", + "objectName": "QCube", + "observedAt": "2026-11-27T18:07:31.682454+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + } + }, + { + "name": "queue: reused id reported under .denied, nothing created", + "ok": true, + "detail": { + "action": "createObject", + "commandId": "aaaaaaaa-0001", + "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:07:33.680885+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + } + }, + { + "name": "queue: intent without requestedBy denied, scene unchanged", + "ok": true, + "detail": { + "action": "createObject", + "commandId": "aaaaaaaa-0003", + "message": "Intent has no requestedBy of the form '/'.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:07:35.693748+00:00", + "requestedBy": "", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + } + }, + { + "name": "queue: two intents drained together are two undo steps, last first", + "ok": true, + "detail": [ + [ + "Camera", + "Cube", + "Light", + "QCube", + "QOne" + ], + [ + "Camera", + "Cube", + "Light", + "QCube" + ] + ] + }, + { + "name": "queue: in Edit Mode setWorld, exportGltf and an object write are all denied, her mode kept", + "ok": true, + "detail": [ + "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + ] + }, + { + "name": "queue: add-on drain reports no error", + "ok": true, + "detail": "" + } + ], + "receipts": { + "q1": { + "action": "createObject", + "commandId": "aaaaaaaa-0001", + "message": "Blender object created.", + "note": "queue test", + "objectName": "QCube", + "observedAt": "2026-11-27T18:07:31.682454+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + }, + "q2_original": { + "action": "createObject", + "commandId": "aaaaaaaa-0001", + "message": "Blender object created.", + "note": "queue test", + "objectName": "QCube", + "observedAt": "2026-11-27T18:07:31.682454+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + }, + "q2_denial": { + "action": "createObject", + "commandId": "aaaaaaaa-0001", + "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:07:33.680885+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + }, + "q3": { + "action": "createObject", + "commandId": "aaaaaaaa-0003", + "message": "Intent has no requestedBy of the form '/'.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:07:35.693748+00:00", + "requestedBy": "", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + }, + "q5": [ + { + "action": "setWorld", + "commandId": "aaaaaaaa-0006", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:07:39.773004+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + }, + { + "action": "exportGltf", + "commandId": "aaaaaaaa-0007", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:07:39.867526+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + }, + { + "action": "setObjectTransform", + "commandId": "aaaaaaaa-0008", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:07:39.950112+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + } + ] + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/agent_turn_undo.py b/surfaces/blender/tests/live/agent_turn_undo.py index 75716ee..9a9dc1b 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.py +++ b/surfaces/blender/tests/live/agent_turn_undo.py @@ -11,6 +11,7 @@ Exit status is not meaningful in a GUI session: read the "ok" fields of the resu import json import os import sys +import tempfile import traceback import types from pathlib import Path @@ -27,6 +28,8 @@ OUT = sys.argv[sys.argv.index("--") + 1] R = {"blender": bpy.app.version_string, "background": bpy.app.background, "checks": [], "steps": []} target = bt.BrokkrBlenderTarget(bpy) N = [0] +OUTDIR = tempfile.mkdtemp(prefix="brokkr-live2-") +target.configure_action_dirs("", OUTDIR) def check(name, ok, detail=None): @@ -136,6 +139,21 @@ def s_edit_agent(): and loc("Cube") == S["loc0"] and bpy.context.mode == "EDIT_MESH", R["editMode"]) +def s_edit_others(): + """Anything that writes scene state or changes her mode is refused in Edit Mode; renderStill does neither.""" + world0 = bpy.context.scene.world + rw = intent(action="setWorld", color=[1, 0, 0], strength=2.0) + rx = intent(action="exportGltf", filepath="edit.glb") + rr = intent(action="renderStill", outputPath="edit.png", engine="CYCLES", resolutionX=8, resolutionY=8) + R["editMode"].update(setWorld=rw["status"], exportGltf=rx["status"], renderStill=rr["status"], + mode_after_others=bpy.context.mode) + check("edit mode: setWorld and exportGltf denied, world untouched, no file written", + rw["status"] == "denied" and rx["status"] == "denied" and bpy.context.scene.world == world0 + and "edit.glb" not in os.listdir(OUTDIR), R["editMode"]) + check("edit mode: renderStill accepted, pushes nothing, her mode kept", + rr["status"] == "accepted" and rr["undoLabel"] == "" and bpy.context.mode == "EDIT_MESH", R["editMode"]) + + def s_edit_undo(): """One undo must revert her edit-mesh step: a step pushed by the refused intent would have taken it.""" undo() @@ -150,8 +168,22 @@ def s_exit(): bpy.ops.object.mode_set(mode="OBJECT") +def s_noop_setup(): + intent(action="createObject", objectType="MESH", name="AgentCube3", location=[0, -5, 0]) + rx = intent(action="exportGltf", filepath="object.glb") + rr = intent(action="renderStill", outputPath="object.png", engine="CYCLES", resolutionX=8, resolutionY=8) + check("exportGltf and renderStill accepted with no undoLabel", + rx["status"] == "accepted" and rr["status"] == "accepted" and rx["undoLabel"] == "" and rr["undoLabel"] == "", + [rx["message"], rr["message"]]) + + +def s_noop_undo(): + undo() + check("no-op actions pushed no step: one undo removes the preceding createObject", "AgentCube3" not in names(), names()) + + steps = [s_baseline, s_create, s_transform, s_undo_transform, s_undo_create, s_denied_setup, s_denied_undo, - s_edit_enter, s_edit_agent, s_edit_undo, s_exit] + s_edit_enter, s_edit_agent, s_edit_others, s_edit_undo, s_exit, s_noop_setup, s_noop_undo] i = 0 diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json index 455335f..7e8e590 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.result.json +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -80,6 +80,76 @@ "receipt": "denied", "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 + } + }, + { + "name": "edit mode: setWorld and exportGltf denied, world untouched, no file written", + "ok": true, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 + } + }, + { + "name": "edit mode: renderStill accepted, pushes nothing, her mode kept", + "ok": true, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", "mode_after_undo": "EDIT_MESH", "loc_after_undo": [ 0.0, @@ -109,6 +179,10 @@ "receipt": "denied", "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", "mode_after_undo": "EDIT_MESH", "loc_after_undo": [ 0.0, @@ -118,6 +192,23 @@ "z_before": 6.0, "z_after_undo": 1.0 } + }, + { + "name": "exportGltf and renderStill accepted with no undoLabel", + "ok": true, + "detail": [ + "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-yk0g4dyg\\object.glb (3484 bytes).", + "Rendered still to object.png." + ] + }, + { + "name": "no-op actions pushed no step: one undo removes the preceding createObject", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] } ], "steps": [ @@ -150,6 +241,42 @@ "status": "denied", "undoLabel": "", "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "intent": "setWorld", + "status": "denied", + "undoLabel": "", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "intent": "exportGltf", + "status": "denied", + "undoLabel": "", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "intent": "renderStill", + "status": "accepted", + "undoLabel": "", + "message": "Rendered still to edit.png." + }, + { + "intent": "createObject", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject 00000009", + "message": "Blender object created." + }, + { + "intent": "exportGltf", + "status": "accepted", + "undoLabel": "", + "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-yk0g4dyg\\object.glb (3484 bytes)." + }, + { + "intent": "renderStill", + "status": "accepted", + "undoLabel": "", + "message": "Rendered still to object.png." } ], "ok": true, @@ -169,6 +296,10 @@ "receipt": "denied", "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", "mode_after_undo": "EDIT_MESH", "loc_after_undo": [ 0.0, diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index db950a6..4874644 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -98,6 +98,102 @@ class AgentTurnTests(unittest.TestCase): SOURCE.read_text(encoding="utf-8")) self.assertEqual(bad, []) + # fix batch s1 + def test_world_and_export_are_refused_in_edit_mode_render_is_not(self): + self.bpy.mesh.mode = "EDIT" + for action, fields in (("setWorld", {}), ("exportGltf", {"filepath": "o.glb"})): + receipt = self.run_action(action=action, **fields) + self.assertEqual(receipt["status"], "denied", action) + self.assertIn("Edit Mode", receipt["message"]) + self.assertEqual(self.bpy.exported, []) + self.assertEqual(self.bpy.undo.pushes, []) + self.assertEqual(self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES")["status"], "accepted") + + def test_export_and_render_push_no_undo_step(self): + self.assertEqual(self.run_action(action="exportGltf", filepath="o.glb")["status"], "accepted") + receipt = self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES") + self.assertEqual(receipt["status"], "accepted") + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_returned_failed_receipt_pushes_nothing(self): + receipt = self.run_action(action="setObjectTransform", objectName="NoSuchObject", location=[1, 2, 3]) + self.assertEqual(receipt["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_denied_id_is_recorded_as_receipted(self): + self.bpy.mesh.mode = "EDIT" + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY", commandId="denied-1")["status"], "denied") + self.bpy.mesh.mode = "OBJECT" + again = self.run_action(action="createObject", objectType="EMPTY", commandId="denied-1") + self.assertEqual(again["status"], "denied") + self.assertIn("single-use", again["message"]) + self.assertEqual(self.bpy.created, []) + + def test_undo_push_runs_under_the_first_window(self): + self.run_action(action="createObject", objectType="EMPTY") + self.assertEqual(self.bpy.undo.overrides, [{"window": self.bpy.undo.window}]) + + def test_push_failure_is_a_failed_receipt_and_never_reruns(self): + def broken(message): + raise RuntimeError("no undo stack") + self.bpy.ops.ed.undo_push = broken + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="push-fail-1") + self.assertEqual(receipt["status"], "failed") + self.assertIn("no undo stack", receipt["message"]) + self.assertEqual(receipt["undoLabel"], "") + again = self.run_action(action="createObject", objectType="EMPTY", commandId="push-fail-1") + self.assertEqual(again["status"], "denied") + self.assertEqual(len(self.bpy.created), 1) + + +class FakeNode: + """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" + def __init__(self, intents, receipts=()): + self.docs = {bt.COMMAND_INTENT_SCHEMA: dict(intents), bt.COMMAND_RECEIPT_SCHEMA: dict(receipts)} + self.puts = [] + self.deleted = [] + self.database = self + + def snapshot(self): + return {k: dict(v) for k, v in self.docs.items()} + + def put(self, document, key, value): + self.puts.append((key, value)) + + def delete(self, document, key): + self.deleted.append(key) + + +class DrainTests(unittest.TestCase): + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + + def drain(self, node): + docs = {"command_intent": "i", "command_receipt": "r"} + with unittest.mock.patch.object(self.target, "_open_node", return_value=(node, docs)): + return self.target.drain_commands(self.context, "cache", "src") + + def intent(self, cid, **fields): + return {"commandId": cid, "requestedBy": "nibu/hands", "action": "createObject", "objectType": "EMPTY", **fields} + + def test_drain_seeds_receipted_from_persisted_receipts(self): + old = {"blender/receipts/old-1": {"commandId": "old-1", "status": "accepted"}} + node = FakeNode({"blender/commands/old-1": self.intent("old-1")}, old) + receipts = self.drain(node) + self.assertEqual(receipts[0]["status"], "denied") + self.assertEqual(self.bpy.created, []) + + def test_reused_id_never_overwrites_the_original_receipt(self): + node = FakeNode({"blender/commands/a": self.intent("dup-1"), "blender/commands/b": self.intent("dup-1")}) + self.drain(node) + keys = [k for k, _ in node.puts] + self.assertEqual(keys.count("blender/receipts/dup-1"), 1) + self.assertEqual(dict(node.puts)["blender/receipts/dup-1"]["status"], "accepted") + denial = dict(node.puts)["blender/receipts/dup-1.denied"] + self.assertEqual(denial["status"], "denied") + self.assertEqual(sorted(node.deleted), ["blender/commands/a", "blender/commands/b"]) + if __name__ == "__main__": unittest.main() diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index c60b657..6c73c67 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -74,7 +74,10 @@ class FakeUndo: """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" def __init__(self, bpy): self.pushes = [] - bpy.context = NS(window_manager=NS(windows=[object()]), temp_override=lambda **kw: contextlib.nullcontext()) + self.overrides = [] + self.window = object() + bpy.context = NS(window_manager=NS(windows=[self.window]), + temp_override=lambda **kw: (self.overrides.append(kw), contextlib.nullcontext())[1]) ops = getattr(bpy, "ops", None) or NS() ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) bpy.ops = ops From a975f99a907f7832fa15cdb81b319285a4ef1c93 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:02:26 +0100 Subject: [PATCH 018/223] Live collaboration target: invariants, probes, identity table Target document for the brokkr-live campaign: the agent works in the same live Blender scene the operator is looking at. Records the Blender 5.3 timer-undo and viewport-capture probes the invariants stand on, and the identity, lifecycle and authority table for every kind the layer adds. Co-Authored-By: Claude Opus 5.5 --- docs/live-collab-target.md | 203 ++++++++++++++++++ docs/research/live-collab/probe_look.py | 68 ++++++ docs/research/live-collab/probe_timer_undo.py | 146 +++++++++++++ 3 files changed, 417 insertions(+) create mode 100644 docs/live-collab-target.md create mode 100644 docs/research/live-collab/probe_look.py create mode 100644 docs/research/live-collab/probe_timer_undo.py diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md new file mode 100644 index 0000000..acbdb07 --- /dev/null +++ b/docs/live-collab-target.md @@ -0,0 +1,203 @@ +# Brokkr live collaboration: target + +Campaign `brokkr-live` (Nibu's mind). Working branch `nibu/live-collab-target`, base +`origin/main` 5e279b2. This document holds the rationale, the design truths the +campaign produces, and the identity, lifecycle and authority table. The typed +`target` in the mind holds the labelled invariants and the not-in-scope list; the +text below is their source. + +## Why + +Operator, 2026-11-27: Brokkr "is meant to give an agent hands into the same Blender +scene I'm looking at, enabling live collaboration work". Brokkr already runs inside +her live Blender: a `depsgraph_update_post` handler publishes a host snapshot and a +persistent 1 s `bpy.app.timers` callback drains command intents +(`surfaces/blender/brokkr_bridge/__init__.py:610-647`, `:668-671`). What it lacks is +everything that makes two people in one scene a collaboration rather than a remote +control: + +- an agent edit is not an undo step (research `nibu-body:research:blender-live-collab.brokkr-undo`); +- nobody can tell who made an edit: the Blender side reads no `requestedBy` + (`.brokkr-attribution-gate`); +- the human cannot stop an agent except by unticking a preference, and a queued intent + still runs if she ticks it back; +- the agent sees names and counts, not the viewport and not the Edit Mode selection + (`.brokkr-perception`); +- nothing stops an agent intent planned against an old scene from overwriting what she + did since; +- the agent has no hands: `brokkr-ctl` has no source (`.brokkr-no-agent-surface`). + +Its strengths stay: typed, validated actions with no free-form Python, path +confinement, loopback bind and an optional session token (`.brokkr-security`). + +## Prior art the design stands on + +- **mcp-for-blender's `UserEditRecorder`** (`.mcp4b-human-edits`): buffers human + operator and undo/redo events with `undo_post`/`redo_post` handlers, attributes events + during an agent command to the agent, and hands the agent the human's activity before + its next action. We take the idea (the agent learns what the human did) and drop the + trajectory log: the snapshot carries per-object human-edit sequence numbers instead. +- **blender-copilot** (`.copilot-undo-cancel`): one undo step per agent turn, a Stop + button, visible turns and an undo receipt, no approval gate. Its Stop cannot interrupt + a blocking native call. We take all four and accept the same limit. +- **Multi-User** (`.humans-multiuser`) and the paid collab add-ons (`.humans-others`): + presence of the other party in the 3D view, rights and object locks. We take presence + as a panel, derived from intents and receipts; human-to-human replication is theirs, + not ours. +- **Blender Lab MCP and mcp-for-blender** (`.lab-official`, `.mcp4b-perception-safe`): + viewport screenshots as perception; arbitrary code with a weak or default-off + sandbox, and no undo. The perception we copy; the code path is fork Q1. +- **ceeyang/blender_mcp** (`.ceeyang-159`): 159 typed tools, every write undoable. The + existence proof that a typed vocabulary can be wide. +- The brush-tree campaign's `one-commit-primitive` (Libby's mind): a stale base is + refused, never merged. The conflict rule below is the same rule applied to a live scene. + +## What probing established (Blender 5.3.0, Starfire, GUI, `--factory-startup`) + +Probe scripts: `docs/research/live-collab/probe_timer_undo.py` and `probe_look.py`. +Each step runs in its own timer tick, as Brokkr's drain does. + +1. **A write from a timer with no undo push is not a step, and it survives undo.** The + cube moved to x=1 with no push; one `ed.undo` left it at x=1. The next push captured + it, so the agent's write became part of the next step, whoever made it (case A). The + vendor warning (`.undo-timer-warning`) is real for unpushed writes, and the failure is + worse than "not undoable": the edit is misattributed. +2. **An explicit `ed.undo_push` from a timer makes a correct step.** x=2 pushed, x=3 + pushed; undo gave 2, undo gave 1 (the earlier step), redo gave 2 (case B). +3. **An UNDO-flagged operator called from a timer pushes its own step.** A sphere added + by `primitive_uv_sphere_add` vanished on one undo with no explicit push (case C). An + action that calls two operators therefore makes two steps unless told otherwise. +4. **Operators called with `undo=False` push nothing; one explicit push then covers + them.** Cube and cone added with `("EXEC_DEFAULT", False)`, one push, one undo removed + both, a second undo changed nothing (case E). This is the mechanism for "one intent, + one step". +5. **Edit Mode:** a bmesh write plus push in Edit Mode is reverted by one undo, and that + undo also left Edit Mode (the agent had entered it in the same probe); the mesh kept + its original vertex (case D). Mode entry and the agent step are not cleanly separable + when the agent itself changed mode. Not yet probed: the human in Edit Mode and the + agent writing. +6. **Driving `ed.undo`/`ed.redo` programmatically from timers crashed Blender 2 of 2 + times** in the long sequence (A through E in one session), with + `EXCEPTION_ACCESS_VIOLATION` in UI draw code after a memfile undo + (`outliner_draw_restrictbuts`, then `psys_get_current` from the properties editor). The + short sequences (C alone, D alone, E alone) did not crash. Cause not isolated; the + probe's own `temp_override` with a captured region is a suspect. +7. **The agent can see what the human sees.** `bpy.ops.screen.screenshot_area` on the + 3D view from a timer: 7 of 7 `FINISHED`, median 72.5 ms over runs 2-7 at 1574x888, + about 609 KB PNG, and it captured the splash screen over the viewport, so it is the + human's view, overlays and popups included. Each capture stalls her UI for that long. +8. **Edit Mode selection reads live** through `bmesh.from_edit_mesh` without leaving Edit + Mode: selected vertices `[0, 3]`, 0.013 ms, mode still `EDIT_MESH`. + +Not yet probed, and owed before the cut that depends on it: whether depsgraph updates +caused by an agent intent arrive inside the timer callback or after it returns (this +decides how human edits are told from agent edits); and whether a human Ctrl+Z inside a +pending agent intent's base window can be detected reliably by `undo_post`. + +## Design truths + +**One agent turn primitive.** Every agent mutation in Blender goes through one function +in the add-on: admit (sink enabled, `requestedBy` present, id unused, base fresh), run +the action with every operator called `undo=False`, push exactly one undo step labelled +`Brokkr : `, write the receipt. A refusal or a +failure pushes nothing and leaves the scene as it was. Typed actions, the node actions, +and `run` if Q1 keeps it, all use it; there is no second writer. + +**Undo belongs to the human.** Blender's one linear stack is the shared history. The +agent's steps sit in it, labelled, between hers; she undoes them with Ctrl+Z like her +own. The agent never calls `ed.undo` or `ed.redo` (probe 6); an agent that wants to back +out sends a new compensating intent, which is one more step. Undoing an agent step that +sits under later human steps is not offered: Blender's stack is linear and per-user undo +is out of scope. + +**Stop is one control, and only the human holds it.** The Brokkr panel's Stop turns the +command sink off and gives every pending intent a `stopped` receipt without running it. +An action already running finishes (a blocking native call cannot be interrupted, as in +blender-copilot); it is one undo step, so Stop plus Ctrl+Z always returns her scene. No +intent can turn the sink on. Re-enabling is a fresh decision, and intents queued before +Stop never run. + +**The agent sees her view and her edits.** `look` is a read intent: it captures her 3D +view to a scratch PNG named by command id (ruling `brush-tree:ruling:look-files-are-scratch`) +and returns the path; it pushes no undo step. The snapshot gains the Edit Mode selection +and a Blender session id plus human-edit sequence numbers: one counter for the session, +the last sequence at which the human touched each object, and the last sequence at which +she undid or redid. The agent reads "what changed since I last looked" from those. + +**A human edit is never silently overwritten.** Every mutating intent names the base +sequence it was planned against. If the human touched any datablock the intent targets +since that base, or undid or redid since it, or the session id changed, the intent is +refused with a `conflict` receipt naming what changed, and nothing is applied. The +agent looks again and re-plans. Granularity is fork Q3. + +**Presence is derived.** The panel shows which agents have intents or receipts in the +last minutes, the running or last intent with its one-line `note`, and the recent +receipts with their undo labels. It reads the intent and receipt documents; it owns no +state of its own. + +**Hands are a CLI.** `brokkr-ctl blender` (Rust, ruling `brush-tree:ruling:fitting-home-ruled`) +writes intents and reads receipts and snapshots through the Blender mirror store +(`brush-tree:ruling:blender-transport-ruled`), prints plain text or paths, and its +`--help` is the schema (`brush-tree:ruling:cli-not-mcp`, `:help-is-the-schema`). It owns +no state, policy or ledger (brush-tree target invariant `brokkr-authority-holds`). + +## Authority map + +- **Owner.** The add-on's agent turn primitive owns whether and how an agent intent + changes the live scene. Blender owns scene truth and the undo stack. The human owns + the sink toggle, Stop, and undo. +- **Inputs.** Intent documents; the snapshot's human-edit sequences; the sink toggle. +- **Outputs.** One undo step per accepted mutating intent; one receipt per intent; + the refreshed snapshot; look PNG paths. +- **Derived state.** Presence (from intents and receipts). Human-edit sequences + (from depsgraph and undo handlers, observations only). Look PNGs (telemetry). +- **Forbidden writers.** `execute_command` called outside the primitive; operators + called with undo on inside an agent action; any raw RNA write by an agent without the + closing push; `ed.undo`/`ed.redo` from add-on code; the debug-mirror JSON import + (`blender_target.py` `_import_debug_command_files`) as a second door for intents; + `brokkr-ctl` opening the store to decide anything. +- **Shared paths.** brokkr-ctl intents, panel buttons that act on the scene, sync-organ + intents from `brokkr-daemon sync-once`, and replayed intents use the one primitive. +- **Deletion line.** The debug-mirror intent import goes before the primitive lands; + `drain_commands` stops calling `execute_command` directly. + +## Identity, lifecycle and authority + +| Persistent kind | What names it | What happens to it over time | Who decides | +|---|---|---|---| +| Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `baseSeq`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (Unity F6 A, `brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written, as today. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | +| Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, conflict, stopped, failed, `undoLabel`, `lookPath`, and for `run` the script text and SHA-256) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. The only proof an intent ran. | The primitive alone. Callers and the panel read. | +| Agent identity `requestedBy` | `/` stated by the caller (brokkr-ctl takes it from `EUREKA_INSTANCE` and a flag) | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | +| Agent undo step | Blender undo stack entry labelled `Brokkr : ` | Pushed once per accepted mutating intent; lives as Blender's stack does (step limit, file load); never persisted by Brokkr. | Blender owns the stack. The primitive pushes. Only the human undoes or redoes. | +| Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads; every older base is then stale. | The add-on alone. | +| Human-edit sequences (snapshot fields: `humanEditSeq`, per-object `lastHumanEditSeq`, `lastUndoSeq`) | Integers within a session id | Monotonic within a session; reset with it. Observations, never scene truth. | The add-on's depsgraph and undo handlers alone. | +| Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, the sequences above, sink state) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | +| Command sink toggle (the existing `auto_drain_commands` preference) | Add-on preference, echoed in the snapshot | Off by default. Stop turns it off; only the human turns it on. | The human only. No intent writes it. | +| Script toggle (only if Q1 = b) | A second add-on preference, echoed in the snapshot | Off by default, independent of the sink. | The human only. | +| Look PNG | `/look/{commandId}.png` | Pruned by count; never read back as truth. | The primitive writes; `brush-tree:ruling:look-files-are-scratch` governs. | + +## Not in scope + +Human-to-human replication or several Blender instances in one session (Multi-User's +domain). Agents on another host reaching the operator's Blender: the transport is not +widened beyond what the add-on serves today. Per-user or selective undo. An approval gate +before each agent action (unless Q2 rules otherwise). A 3D-view overlay of the agent's +presence; the panel carries presence in this revision. The Unity surface and +`brokkr-command`. The brush-tree vocabulary, Geometry.Csg and OpenSCAD text (brush-tree +owns them). Agent-initiated save and quit (`brush-tree:ruling:run-admitted-when-enabled` +keeps them off the allowed list). Asset libraries and generators. An MCP server. + +## Open forks (draft questions; Self admits) + +- **Q1. Free-form Python.** Today the Blender add-on has no script action. Libby's + Defaulted ruling `brush-tree:ruling:run-admitted-when-enabled` would add `run`, admitted + whenever agent commands are on. Options: (a) typed actions only; (b) `run` behind its + own off-by-default toggle, one undo step, script text in the receipt; (c) the Defaulted + ruling as written. Recommend (b). +- **Q2. Act then undo, or approve first.** Recommend act then undo, with Stop. +- **Q3. Conflict granularity.** (a) any human edit since the base refuses; (b) only edits to + the intent's targets, plus any undo or redo. Recommend (b), after the depsgraph + attribution probe. +- **Q4. Who builds `brokkr-ctl blender`.** Recommend this campaign builds the session + subcommands in Rust per Libby's rulings, and brush-tree adds its tree commands to the + same binary later. diff --git a/docs/research/live-collab/probe_look.py b/docs/research/live-collab/probe_look.py new file mode 100644 index 0000000..1e8851c --- /dev/null +++ b/docs/research/live-collab/probe_look.py @@ -0,0 +1,68 @@ +"""Probe: can a timer callback capture the 3D viewport the human sees, and read Edit Mode selection? + +blender --factory-startup --python probe_look.py -- +""" +import json +import os +import statistics +import sys +import time +import traceback + +import bmesh +import bpy + +args = sys.argv[sys.argv.index("--") + 1:] +OUT, PNG_DIR = args[0], args[1] +log = {"blender": bpy.app.version_string} + + +def ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + region = next(r for r in area.regions if r.type == "WINDOW") + return win, area, region + + +def run(): + win, area, region = ctx() + log["view3d_px"] = [region.width, region.height] + times = [] + for n in range(7): + path = os.path.join(PNG_DIR, f"look-{n}.png") + t = time.perf_counter() + with bpy.context.temp_override(window=win, area=area, region=region): + r = bpy.ops.screen.screenshot_area(filepath=path) + times.append((time.perf_counter() - t) * 1000) + log.setdefault("results", []).append(list(r)) + log["screenshot_ms"] = [round(x, 1) for x in times] + log["screenshot_ms_median"] = round(statistics.median(times[1:]), 1) + log["png_bytes"] = os.path.getsize(os.path.join(PNG_DIR, "look-6.png")) + # Edit Mode selection read, live, without leaving Edit Mode. + with bpy.context.temp_override(window=win, area=area, region=region): + bpy.ops.object.mode_set(mode="EDIT") + bpy.ops.mesh.select_all(action="DESELECT") + bm = bmesh.from_edit_mesh(bpy.data.objects["Cube"].data) + bm.verts.ensure_lookup_table() + bm.verts[0].select = True + bm.verts[3].select = True + bm.select_flush_mode() + t = time.perf_counter() + sel = [v.index for v in bmesh.from_edit_mesh(bpy.data.objects["Cube"].data).verts if v.select] + log["edit_selection_read_ms"] = round((time.perf_counter() - t) * 1000, 3) + log["edit_selected_verts"] = sel + log["mode_after_read"] = bpy.context.mode + + +def tick(): + try: + run() + except Exception: + log["error"] = traceback.format_exc() + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/docs/research/live-collab/probe_timer_undo.py b/docs/research/live-collab/probe_timer_undo.py new file mode 100644 index 0000000..57886fb --- /dev/null +++ b/docs/research/live-collab/probe_timer_undo.py @@ -0,0 +1,146 @@ +"""Probe: do edits made from a bpy.app.timers callback land on Blender's undo stack? + +Run in GUI Blender: blender --factory-startup --python probe_timer_undo.py -- [cases, e.g. AB] +Each step is its own timer tick so the event loop runs between steps, as it does +for Brokkr's 1 s drain. Results are written to the JSON path, then Blender quits. +""" +import json +import sys +import traceback + +import bmesh +import bpy + +OUT = sys.argv[sys.argv.index("--") + 1] +log = {"blender": bpy.app.version_string, "background": bpy.app.background, "steps": []} + + +def win_ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + return bpy.context.temp_override(window=win, area=area, region=area.regions[-1]) + + +def cube(): + return bpy.data.objects.get("Cube") + + +def state(tag): + c = cube() + s = { + "tag": tag, + "cube_x": round(c.location.x, 3) if c else None, + "objects": sorted(o.name for o in bpy.data.objects), + "mode": bpy.context.mode, + "mesh_v0_z": round(c.data.vertices[0].co.z, 3) if c else None, + } + if c and c.mode == "EDIT": + bm = bmesh.from_edit_mesh(c.data) + bm.verts.ensure_lookup_table() + s["edit_v0_z"] = round(bm.verts[0].co.z if bm.verts else 0, 3) + log["steps"].append(s) + return s + + +def push(msg): + with win_ctx(): + r = bpy.ops.ed.undo_push(message=msg) + log["steps"].append({"tag": f"undo_push:{msg}", "result": list(r)}) + + +def undo(): + with win_ctx(): + r = bpy.ops.ed.undo() + log["steps"].append({"tag": "undo", "result": list(r)}) + + +def redo(): + with win_ctx(): + r = bpy.ops.ed.redo() + log["steps"].append({"tag": "redo", "result": list(r)}) + + +# Case A: raw RNA write from a timer, no push. Does Ctrl+Z see it as its own step? +# Case B: RNA write then an explicit undo_push from the timer. +# Case C: an UNDO-flagged operator called from a timer, no explicit push. +# Case D: Edit Mode bmesh write from a timer then undo_push. +# Case E: two operators called with undo=False, then one explicit undo_push. +ONLY = sys.argv[sys.argv.index("--") + 2] if len(sys.argv) > sys.argv.index("--") + 2 else "ABCDE" +steps = [ + lambda: (push("baseline"), state("A0 baseline")), + lambda: (setattr(cube().location, "x", 1.0), state("A1 raw write x=1, no push")), + lambda: (undo(), state("A2 after one undo")), + lambda: (push("rebase-B"), state("B0")), + lambda: (setattr(cube().location, "x", 2.0), push("agent: x=2"), state("B1 x=2 pushed")), + lambda: (setattr(cube().location, "x", 3.0), push("agent: x=3"), state("B2 x=3 pushed")), + lambda: (undo(), state("B3 after undo (expect x=2)")), + lambda: (undo(), state("B4 after second undo (expect x=0)")), + lambda: (redo(), state("B5 after redo (expect x=2)")), + lambda: (push("rebase-C"), state("C0")), + lambda: (_add_sphere(), state("C1 op add sphere, no push")), + lambda: (undo(), state("C2 after undo (sphere gone?)")), + lambda: (bpy.context.view_layer.objects.__setattr__("active", cube()), cube().select_set(True), push("rebase-D"), state("D0")), + lambda: (_edit_enter(), state("D1 edit mode")), + lambda: (_edit_write(), push("agent: edit v0"), state("D2 v0 moved, pushed")), + lambda: (undo(), state("D3 after undo (expect v0 back)")), + lambda: (undo(), state("D4 after second undo")), + lambda: (_edit_exit(), push("rebase-E"), state("E0")), + lambda: (_two_ops_one_step(), push("agent: two ops"), state("E1 two ops undo=False + one push")), + lambda: (undo(), state("E2 after one undo (expect both gone)")), + lambda: (undo(), state("E3 after second undo (expect no change)")), +] + + +def _add_sphere(): + with win_ctx(): + bpy.ops.mesh.primitive_uv_sphere_add(location=(5, 0, 0)) + + +def _edit_exit(): + if bpy.context.mode != "OBJECT": + with win_ctx(): + bpy.ops.object.mode_set(mode="OBJECT") + + +def _two_ops_one_step(): + with win_ctx(): + bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, location=(0, 4, 0)) + bpy.ops.mesh.primitive_cone_add("EXEC_DEFAULT", False, location=(0, -4, 0)) + + +def _edit_enter(): + with win_ctx(): + bpy.ops.object.mode_set(mode="EDIT") + + +def _edit_write(): + c = cube() + bm = bmesh.from_edit_mesh(c.data) + bm.verts.ensure_lookup_table() + bm.verts[0].co.z += 5.0 + bmesh.update_edit_mesh(c.data) + + +i = 0 +_all = steps +steps = [f for f, c in zip(_all, "AAABBBBBBCCCDDDDDEEEE") if c in ONLY] + + +def tick(): + global i + if i < len(steps): + try: + steps[i]() + except Exception: + log["steps"].append({"tag": f"step {i} error", "error": traceback.format_exc()}) + i += 1 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + return 0.3 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=2.0) From 3213ee3d864e5f46afaf2ac79e15943a1801d41f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:07:37 +0100 Subject: [PATCH 019/223] Live collab: depsgraph timing probe Records when depsgraph updates from an agent edit in a timer arrive and which ids they name, for the human-edit detection fork (Q3). Co-Authored-By: Claude Opus 5.5 --- .../live-collab/probe_depsgraph_timing.py | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 docs/research/live-collab/probe_depsgraph_timing.py diff --git a/docs/research/live-collab/probe_depsgraph_timing.py b/docs/research/live-collab/probe_depsgraph_timing.py new file mode 100644 index 0000000..d763e07 --- /dev/null +++ b/docs/research/live-collab/probe_depsgraph_timing.py @@ -0,0 +1,134 @@ +"""Probe: when do depsgraph updates caused by an agent edit in a timer arrive, and what do they name? + +blender --factory-startup --python probe_depsgraph_timing.py -- + +Each case runs in its own timer tick. AGENT is True only while the timer callback +runs the edit. depsgraph_update_post and undo_post log every call with AGENT's value, +the tick that was current, and the ids depsgraph.updates names. +""" +import json +import sys +import time +import traceback + +import bpy + +OUT = sys.argv[sys.argv.index("--") + 1] +log = {"blender": bpy.app.version_string, "events": []} +AGENT = False +TICK = "setup" +T0 = time.perf_counter() + + +def ev(kind, **kw): + log["events"].append({"kind": kind, "tick": TICK, "agent": AGENT, + "ms": round((time.perf_counter() - T0) * 1000, 1), **kw}) + + +@bpy.app.handlers.persistent +def on_depsgraph(scene, depsgraph): + ups = [] + for u in depsgraph.updates: + ups.append(f"{type(u.id).__name__}:{u.id.name}" + f"{'/T' if u.is_updated_transform else ''}{'/G' if u.is_updated_geometry else ''}") + ev("depsgraph", updates=ups) + + +@bpy.app.handlers.persistent +def on_undo(scene, *_): + ev("undo_post") + + +@bpy.app.handlers.persistent +def on_redo(scene, *_): + ev("redo_post") + + +def win_ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + region = next(r for r in area.regions if r.type == "WINDOW") + return bpy.context.temp_override(window=win, area=area, region=region) + + +def setup(): + # B follows A through a Copy Location constraint: an indirect dependent of A. + a = bpy.data.objects["Cube"] + with win_ctx(): + bpy.ops.mesh.primitive_cone_add("EXEC_DEFAULT", False, location=(0, 3, 0)) + b = bpy.context.active_object + b.name = "Follower" + c = b.constraints.new("COPY_LOCATION") + c.target = a + c.use_y = False + with win_ctx(): + bpy.ops.ed.undo_push(message="setup") + + +def agent(fn, flush): + global AGENT + AGENT = True + ev("turn_begin", flush=flush) + fn() + with win_ctx(): + bpy.ops.ed.undo_push(message=f"agent {TICK}") + if flush: + bpy.context.view_layer.update() + ev("turn_end") + AGENT = False + + +def move_a(x): + return lambda: setattr(bpy.data.objects["Cube"].location, "x", x) + + +def add_op(): + with win_ctx(): + bpy.ops.mesh.primitive_uv_sphere_add("EXEC_DEFAULT", False, location=(-4, 0, 0)) + + +def undo_once(): + with win_ctx(): + bpy.ops.ed.undo() + + +cases = [ + ("setup", setup), + ("idle1", lambda: None), + ("rna-noflush", lambda: agent(move_a(1.0), False)), + ("idle2", lambda: None), + ("rna-flush", lambda: agent(move_a(2.0), True)), + ("idle3", lambda: None), + ("op-noflush", lambda: agent(add_op, False)), + ("idle4", lambda: None), + ("op-flush", lambda: agent(add_op, True)), + ("idle5", lambda: None), + ("undo", undo_once), # stands in for a human Ctrl+Z (not an agent turn) + ("idle6", lambda: None), +] +i = 0 + + +def tick(): + global i, TICK + if i < len(cases): + TICK, fn = cases[i] + try: + fn() + except Exception: + ev("error", error=traceback.format_exc()) + TICK = f"after:{TICK}" + i += 1 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + return 0.5 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.handlers.depsgraph_update_post.append(on_depsgraph) +bpy.app.handlers.undo_post.append(on_undo) +bpy.app.handlers.redo_post.append(on_redo) +bpy.app.timers.register(tick, first_interval=2.0) From e271dcc9cf6e8ff5fa61a34694a28d6c9eef7d0e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:18:59 +0100 Subject: [PATCH 020/223] Live collab target r2: rulings in, phase two authoring surface Takes in the operator's 2026-11-27 rulings (no free-form Python, act then undo, last writer wins in the scene, brokkr-ctl blender built here) and adds phase two: scene collections as an authoring surface over a ship's .cc, opened at known record versions and pushed through AetherDb with a dry-run default and stale-version refusal. Records why neither variants' deltas nor CultNet carry the push today. Co-Authored-By: Claude Opus 5.5 --- docs/live-collab-target.md | 399 ++++++++++++++++++++++--------------- 1 file changed, 243 insertions(+), 156 deletions(-) diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index acbdb07..228ae83 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -4,200 +4,287 @@ Campaign `brokkr-live` (Nibu's mind). Working branch `nibu/live-collab-target`, `origin/main` 5e279b2. This document holds the rationale, the design truths the campaign produces, and the identity, lifecycle and authority table. The typed `target` in the mind holds the labelled invariants and the not-in-scope list; the -text below is their source. +text below is their source. Revision 2 adds phase two (the authoring surface) and +takes in the operator's rulings of 2026-11-27. + +Rulings in force: `brokkr-live:ruling:no-free-form-python`, `:act-then-undo`, +`:scene-last-writer-wins`, `:brokkr-ctl-blender-built-here`, +`:cc-is-hull-authority-scene-pushes-deltas`. ## Why Operator, 2026-11-27: Brokkr "is meant to give an agent hands into the same Blender -scene I'm looking at, enabling live collaboration work". Brokkr already runs inside -her live Blender: a `depsgraph_update_post` handler publishes a host snapshot and a -persistent 1 s `bpy.app.timers` callback drains command intents -(`surfaces/blender/brokkr_bridge/__init__.py:610-647`, `:668-671`). What it lacks is -everything that makes two people in one scene a collaboration rather than a remote -control: +scene I'm looking at, enabling live collaboration work". Her original vision for it: +"use Blender as an authoring environment, since it exposes typed access to all of the +assets we need over CultMesh. Certain collections within the Blender scene would +mirror their data into the exact documents Aetheria needs for its ships." -- an agent edit is not an undo step (research `nibu-body:research:blender-live-collab.brokkr-undo`); -- nobody can tell who made an edit: the Blender side reads no `requestedBy` - (`.brokkr-attribution-gate`); -- the human cannot stop an agent except by unticking a preference, and a queued intent - still runs if she ticks it back; -- the agent sees names and counts, not the viewport and not the Edit Mode selection - (`.brokkr-perception`); -- nothing stops an agent intent planned against an old scene from overwriting what she - did since; -- the agent has no hands: `brokkr-ctl` has no source (`.brokkr-no-agent-surface`). +So the campaign has two phases. **Phase one** makes the live session a collaboration: +the agent's edits are undoable and attributed, she can stop it, and it sees what she +sees. **Phase two** makes the scene an authoring surface over a ship's `.cc`: scene +collections map to the ship's records, the scene opens from the `.cc` at a known +revision, and pushes go back through AetherDb. -Its strengths stay: typed, validated actions with no free-form Python, path -confinement, loopback bind and an optional session token (`.brokkr-security`). +Brokkr already runs inside her live Blender: a `depsgraph_update_post` handler +publishes a host snapshot and a persistent 1 s `bpy.app.timers` callback drains +command intents (`surfaces/blender/brokkr_bridge/__init__.py:610-647`, `:668-671`). +What it lacks: an agent edit is not an undo step (`nibu-body:research:blender-live-collab.brokkr-undo`); +nobody can tell who made an edit (`.brokkr-attribution-gate`); the human can stop an +agent only by unticking a preference; the agent sees names and counts, not the viewport +or the Edit Mode selection (`.brokkr-perception`); and the agent has no hands, since +`brokkr-ctl` has no source (`.brokkr-no-agent-surface`). Its strengths stay: typed, +validated actions with no free-form Python, path confinement, loopback bind and an +optional session token (`.brokkr-security`). ## Prior art the design stands on -- **mcp-for-blender's `UserEditRecorder`** (`.mcp4b-human-edits`): buffers human - operator and undo/redo events with `undo_post`/`redo_post` handlers, attributes events - during an agent command to the agent, and hands the agent the human's activity before - its next action. We take the idea (the agent learns what the human did) and drop the - trajectory log: the snapshot carries per-object human-edit sequence numbers instead. +- **mcp-for-blender's `UserEditRecorder`** (`.mcp4b-human-edits`): the agent learns what + the human did between its actions. We keep the idea as snapshot fields, without a + trajectory log. - **blender-copilot** (`.copilot-undo-cancel`): one undo step per agent turn, a Stop - button, visible turns and an undo receipt, no approval gate. Its Stop cannot interrupt - a blocking native call. We take all four and accept the same limit. -- **Multi-User** (`.humans-multiuser`) and the paid collab add-ons (`.humans-others`): - presence of the other party in the 3D view, rights and object locks. We take presence - as a panel, derived from intents and receipts; human-to-human replication is theirs, - not ours. + button, visible turns and an undo receipt, no approval gate. Its Stop cannot + interrupt a blocking native call; ours cannot either. +- **Multi-User** (`.humans-multiuser`, `.humans-others`): presence of the other party. + We show presence in a panel; human-to-human replication is theirs. - **Blender Lab MCP and mcp-for-blender** (`.lab-official`, `.mcp4b-perception-safe`): - viewport screenshots as perception; arbitrary code with a weak or default-off - sandbox, and no undo. The perception we copy; the code path is fork Q1. -- **ceeyang/blender_mcp** (`.ceeyang-159`): 159 typed tools, every write undoable. The - existence proof that a typed vocabulary can be wide. -- The brush-tree campaign's `one-commit-primitive` (Libby's mind): a stale base is - refused, never merged. The conflict rule below is the same rule applied to a live scene. + viewport screenshots as perception. Their arbitrary-code path is refused here + (`no-free-form-python`). +- **ceeyang/blender_mcp** (`.ceeyang-159`): 159 typed tools, every write undoable; a + typed vocabulary can be wide. +- **Aetheria's ship package path** (Aetheria origin/master 6702b01bf, packager on + `nibu/hull-packager` 7101b5cec): `AetherDb ship-authoring` (create, stats, price, + product, regenerate with a dry-run default, validate, inspect) loads a `ship.cc` + through the game's own types; `tools/blender/package_hull.py` drives the + `aetheria_ships` add-on and AetherDb from a manifest; `tools/blender/aetheria_ships/ship_cc.py` + reads and writes `ship.cc` envelopes directly, with a layout revision hash for its + layout write. +- **CultCache compare-exchange and element ids** (CultLib origin/main baf4ecf7, + `src/GameCult.Caching/CultCache.cs:2228-2235` `Expect`/`ExpectUnchanged`; + `CultElementIds.cs`). `HardpointData.Id` is a `[CultElementId]` (Aetheria + `Assets/Scripts/ServerShared/ItemData.cs:648`). -## What probing established (Blender 5.3.0, Starfire, GUI, `--factory-startup`) +## What probing established -Probe scripts: `docs/research/live-collab/probe_timer_undo.py` and `probe_look.py`. -Each step runs in its own timer tick, as Brokkr's drain does. +Blender 5.3.0, Starfire, GUI, `--factory-startup`, each step in its own timer tick. +Scripts in `docs/research/live-collab/`. Research notes +`brokkr-live:research:live-collab-probes.*`. -1. **A write from a timer with no undo push is not a step, and it survives undo.** The - cube moved to x=1 with no push; one `ed.undo` left it at x=1. The next push captured - it, so the agent's write became part of the next step, whoever made it (case A). The - vendor warning (`.undo-timer-warning`) is real for unpushed writes, and the failure is - worse than "not undoable": the edit is misattributed. -2. **An explicit `ed.undo_push` from a timer makes a correct step.** x=2 pushed, x=3 - pushed; undo gave 2, undo gave 1 (the earlier step), redo gave 2 (case B). -3. **An UNDO-flagged operator called from a timer pushes its own step.** A sphere added - by `primitive_uv_sphere_add` vanished on one undo with no explicit push (case C). An - action that calls two operators therefore makes two steps unless told otherwise. -4. **Operators called with `undo=False` push nothing; one explicit push then covers - them.** Cube and cone added with `("EXEC_DEFAULT", False)`, one push, one undo removed - both, a second undo changed nothing (case E). This is the mechanism for "one intent, - one step". -5. **Edit Mode:** a bmesh write plus push in Edit Mode is reverted by one undo, and that - undo also left Edit Mode (the agent had entered it in the same probe); the mesh kept - its original vertex (case D). Mode entry and the agent step are not cleanly separable - when the agent itself changed mode. Not yet probed: the human in Edit Mode and the - agent writing. -6. **Driving `ed.undo`/`ed.redo` programmatically from timers crashed Blender 2 of 2 - times** in the long sequence (A through E in one session), with - `EXCEPTION_ACCESS_VIOLATION` in UI draw code after a memfile undo - (`outliner_draw_restrictbuts`, then `psys_get_current` from the properties editor). The - short sequences (C alone, D alone, E alone) did not crash. Cause not isolated; the - probe's own `temp_override` with a captured region is a suspect. -7. **The agent can see what the human sees.** `bpy.ops.screen.screenshot_area` on the - 3D view from a timer: 7 of 7 `FINISHED`, median 72.5 ms over runs 2-7 at 1574x888, - about 609 KB PNG, and it captured the splash screen over the viewport, so it is the - human's view, overlays and popups included. Each capture stalls her UI for that long. -8. **Edit Mode selection reads live** through `bmesh.from_edit_mesh` without leaving Edit - Mode: selected vertices `[0, 3]`, 0.013 ms, mode still `EDIT_MESH`. +1. **An unpushed write from a timer is not an undo step and survives undo**; the next + push absorbs it, so it is misattributed (`.timer-undo`, case A). +2. **An explicit `ed.undo_push` from a timer makes a correct step**, and undo and redo + walk it (case B). +3. **UNDO-flagged operators push their own step**; called `("EXEC_DEFAULT", False)` they + push none, and one explicit push covers several (cases C, E). This is how one intent + becomes one step. +4. **Edit Mode**: an agent bmesh write plus push is reverted by one undo, which also + left the Edit Mode the agent had entered (case D). +5. **Driving `ed.undo`/`ed.redo` from code crashed Blender 2 of 2 times** in the long + sequence, in UI draw after a memfile undo (`.programmatic-undo-crash`). +6. **The agent can see her view**: `screenshot_area` on her 3D view, median 72.5 ms at + 1574x888, about 609 KB, popups included; Edit Mode selection reads live without + leaving Edit Mode (`.look-capture`). +7. **Depsgraph updates from an agent edit arrive inside the timer turn** and name + indirect dependents; after an undo every object is listed and only the transform and + geometry flags show what changed (`.depsgraph-timing`). +8. **cultcache-rs writes the add-on's single-file `.ccmp` under the shared lock, and a + live cultmesh-py node pulls Rust writes**; no runtime has a directory store + (`.rust-store-writer`). -Not yet probed, and owed before the cut that depends on it: whether depsgraph updates -caused by an agent intent arrive inside the timer callback or after it returns (this -decides how human edits are told from agent edits); and whether a human Ctrl+Z inside a -pending agent intent's base window can be detected reliably by `undo_post`. +Not yet probed, owed before the cut that depends on it: the latency of one AetherDb +`ship-authoring` call on Starfire (phase two decides between a CLI call per push and a +resident service on that number); reading a record's stored version through AetherDb. -## Design truths +## Phase one: the live session **One agent turn primitive.** Every agent mutation in Blender goes through one function -in the add-on: admit (sink enabled, `requestedBy` present, id unused, base fresh), run -the action with every operator called `undo=False`, push exactly one undo step labelled -`Brokkr : `, write the receipt. A refusal or a -failure pushes nothing and leaves the scene as it was. Typed actions, the node actions, -and `run` if Q1 keeps it, all use it; there is no second writer. +in the add-on: admit (sink enabled, `requestedBy` present, id unused, action typed and +valid), run the action with every operator called `undo=False`, push exactly one undo +step labelled `Brokkr : `, write the receipt. A +refusal or a failure pushes nothing and leaves the scene unchanged. There is no second +writer and no script action (`no-free-form-python`): what the typed actions do not +cover waits for a new typed action. -**Undo belongs to the human.** Blender's one linear stack is the shared history. The -agent's steps sit in it, labelled, between hers; she undoes them with Ctrl+Z like her -own. The agent never calls `ed.undo` or `ed.redo` (probe 6); an agent that wants to back -out sends a new compensating intent, which is one more step. Undoing an agent step that -sits under later human steps is not offered: Blender's stack is linear and per-user undo -is out of scope. +**The agent acts; the human undoes** (`act-then-undo`). Admitted intents apply without +asking. Blender's one linear undo stack is the shared history; agent steps sit in it, +labelled, between hers, and she takes them back with Ctrl+Z. The agent never calls +`ed.undo` or `ed.redo` (probe 5); it backs out by sending a compensating intent. -**Stop is one control, and only the human holds it.** The Brokkr panel's Stop turns the -command sink off and gives every pending intent a `stopped` receipt without running it. -An action already running finishes (a blocking native call cannot be interrupted, as in -blender-copilot); it is one undo step, so Stop plus Ctrl+Z always returns her scene. No -intent can turn the sink on. Re-enabling is a fresh decision, and intents queued before -Stop never run. +**Last writer wins in the scene** (`scene-last-writer-wins`). An agent intent applies +even if she changed the scene since the agent looked. Her edit is never lost: it stays +in the undo history below the agent's step, and one Ctrl+Z takes the agent's step back. +This is scene-level only; the `.cc` keeps its revision refusal (phase two). + +**Stop is one control, and only the human holds it.** Stop turns the command sink off +and gives every pending intent a `stopped` receipt without running it. An action +already running finishes as one undo step, so Stop plus Ctrl+Z always returns her +scene. No intent can turn the sink on; intents queued before Stop never run. **The agent sees her view and her edits.** `look` is a read intent: it captures her 3D -view to a scratch PNG named by command id (ruling `brush-tree:ruling:look-files-are-scratch`) -and returns the path; it pushes no undo step. The snapshot gains the Edit Mode selection -and a Blender session id plus human-edit sequence numbers: one counter for the session, -the last sequence at which the human touched each object, and the last sequence at which -she undid or redid. The agent reads "what changed since I last looked" from those. +view to a scratch PNG named by command id (`brush-tree:ruling:look-files-are-scratch`) +and returns the path. The snapshot gains the Edit Mode selection, a Blender session id, +and human-edit sequence numbers (a session counter and, per object, the last sequence +at which she changed it, from depsgraph updates outside agent turns and flagged +transform, geometry or shading). These tell the agent what she did since it last +looked; they gate nothing. -**A human edit is never silently overwritten.** Every mutating intent names the base -sequence it was planned against. If the human touched any datablock the intent targets -since that base, or undid or redid since it, or the session id changed, the intent is -refused with a `conflict` receipt naming what changed, and nothing is applied. The -agent looks again and re-plans. Granularity is fork Q3. +**Presence is derived.** The panel shows active agents, the running or last intent with +its one-line `note`, and recent receipts with their undo labels, read from the intent +and receipt documents. -**Presence is derived.** The panel shows which agents have intents or receipts in the -last minutes, the running or last intent with its one-line `note`, and the recent -receipts with their undo labels. It reads the intent and receipt documents; it owns no -state of its own. +**Hands are a CLI** (`brokkr-ctl-blender-built-here`). `brokkr-ctl blender` is a Rust +binary in this repo (`brush-tree:ruling:fitting-home-ruled`) that writes intents and +reads receipts and snapshots in the add-on's single-file store (probe 8), prints plain +text or paths, and whose `--help` is the schema (`brush-tree:ruling:cli-not-mcp`, +`:help-is-the-schema`). It owns no state, policy or ledger. Libby's brush-tree adds its +tree commands to the same binary later. -**Hands are a CLI.** `brokkr-ctl blender` (Rust, ruling `brush-tree:ruling:fitting-home-ruled`) -writes intents and reads receipts and snapshots through the Blender mirror store -(`brush-tree:ruling:blender-transport-ruled`), prints plain text or paths, and its -`--help` is the schema (`brush-tree:ruling:cli-not-mcp`, `:help-is-the-schema`). It owns -no state, policy or ledger (brush-tree target invariant `brokkr-authority-holds`). +## Phase two: the authoring surface + +**The `.cc` is the authority; the scene is a surface over it** +(`cc-is-hull-authority-scene-pushes-deltas`). A ship's records live in its `ship.cc`: +`HullData`, `ShipAuthoring` (model asset, anchors, schematic lines) and its product +records (`ShipAuthoringStore.Load` returns exactly these three). A Blender scene may be +bound to one `ship.cc` as its authoring surface. The scene never becomes truth: it is an +edit buffer that opens from the store and pushes back to it. + +**Collections carry roles.** Scene collections are tagged with the role they author: +hull shape (the hull source and its raster), hardpoint rows (one object per row, +carrying `aetheria.id`, the `HardpointData` element id, and its kind, cell, footprint, +rotation, armor and arc), schematic lines, and anchors. Stats, price and product live on +the binding. These are the fields the packager manifest already names +(`tools/blender/package_hull.md`), so the manifest and a push describe a ship in one +vocabulary. + +**Open reads through the game's code.** Opening runs `AetherDb ship-authoring` to read +the three records and their stored versions, builds the tagged collections, and records +on the binding the version of each record it read. Nothing reads a `.cc` by scraping +envelopes (operator 2026-11-17). + +**A push is one AetherDb call, dry-run then apply.** The surface writes the authoring +state of its tagged collections (the manifest vocabulary, plus the record versions it +opened at) to a scratch request file and calls `AetherDb ship-authoring push +`. Without `apply` AetherDb loads the store, derives the records the request +describes, validates them, and prints the per-record, per-field changes; nothing is +written. With `apply` it does the same and writes under compare-exchange on each +record's stored version (`Expect`). One CLI call per push is the starting shape; a +resident service is built only if the measured latency of that call demands it. + +**A stale revision is refused, never merged.** If any record changed in the store since +the scene opened it (another push, a CLI `stats` call, a packager `--replace`), the push +is refused with the records named; the surface reopens and the author re-applies. On a +successful apply the binding takes the new versions. + +**One owner turns a hull into records.** AetherDb's ship-authoring code (C#, the game's +own types) is the only code that derives `HullData`, `ShipAuthoring` and product records +from authoring input, and the only writer of `.cc` stores. The packager and the +authoring surface both call it. The direct envelope writes in +`aetheria_ships/ship_cc.py` (`replace_lines`, `replace_visual`, `replace_layout`, and +the first Save Layout that creates `ship.cc`) and its `layout_revision` hash are +demoted: `ship_cc.py` keeps no write path and no revision of its own, and +`package_hull.py`'s Save Layout steps become push calls. Whether the request is +the delta of the ruling, or a whole-record replace, is fork Q5 below. + +**The agent's hands reach the surface through typed actions.** Open, push dry-run and +push apply are typed Brokkr actions like any other, admitted by the same primitive; a +push changes no scene state and so pushes no undo step. Whether an agent may apply, +not only dry-run, is fork Q7. + +### Variants and CultNet deltas: not the push primitive today + +The coordinator asked whether Libby's `variants` delta records, or CultNet's deltas, +are the primitive for the push. + +- **Variants** (`variants` target, Libby's mind): a variant is a persisted record stored + as a base reference plus sparse overrides (`CultVariantDelta`, `CultVariantOverride` + with `Set`/`Insert`/`Remove` at slot plus element-id paths, + `src/GameCult.Caching/CultVariants.cs:56-112`), resolved by the cache at load, and a + plain upsert at a variant's key is refused (`variants:ruling:q1-refuse-plain-upsert`). + It describes a second document defined against a base, not a change to the base. Its + nested paths and `Insert`/`Remove` are unbuilt (`variants:follow_up:remaining-variant-cuts`, + C2b), C# alone resolves it, and Aetheria catalog content is out of its scope. +- **CultNet** (`contracts/cultnet/`): the wire has whole-document `document-put` and + `document-put-raw`, `document-delete`, and `database-change-raw` (added, updated, + removed, with the whole document and a commit id). There is no delta message. The + "delta" in `cultnet-rs/src/replication.rs:97,789-829` and `cultmesh-py/node.py:1649-1660` + is a client-side reconciliation diff (predicted minus canonical, per top-level slot, + numeric subtraction) handed to the caller to smooth a prediction; it is never sent. +- **One mechanism?** Not today. They are two unrelated things that share a word. The + operator's recollection matches the plan, not the code: variants' fork ruling 4 + (`cultnet-deltas`) says variants travel on CultNet as deltas, and + `variants:ruling:hop-subscriptions-refuse-variants` holds CultNet off variants until + that cut (C5) lands. When it does, the override vocabulary will be both the stored + variant and the wire delta. +- **Consequence for the push.** The push invents no delta format. Its addressing is the + variants override vocabulary (slot plus element id; `HardpointData.Id` is already a + `[CultElementId]`) when CultLib can apply overrides to a record in place; until then + it is a whole-record replace of the records that changed, guarded by `Expect`. Fork Q5. ## Authority map -- **Owner.** The add-on's agent turn primitive owns whether and how an agent intent - changes the live scene. Blender owns scene truth and the undo stack. The human owns - the sink toggle, Stop, and undo. -- **Inputs.** Intent documents; the snapshot's human-edit sequences; the sink toggle. -- **Outputs.** One undo step per accepted mutating intent; one receipt per intent; - the refreshed snapshot; look PNG paths. -- **Derived state.** Presence (from intents and receipts). Human-edit sequences - (from depsgraph and undo handlers, observations only). Look PNGs (telemetry). -- **Forbidden writers.** `execute_command` called outside the primitive; operators - called with undo on inside an agent action; any raw RNA write by an agent without the - closing push; `ed.undo`/`ed.redo` from add-on code; the debug-mirror JSON import - (`blender_target.py` `_import_debug_command_files`) as a second door for intents; - `brokkr-ctl` opening the store to decide anything. +- **Owner.** Phase one: the add-on's agent turn primitive owns whether and how an agent + intent changes the live scene; Blender owns scene truth and the undo stack; the human + owns the sink toggle, Stop and undo. Phase two: the `ship.cc` owns the ship; + AetherDb's ship-authoring code alone derives and writes its records. +- **Inputs.** Intent documents and the sink toggle (phase one). The tagged collections, + the binding's opened versions and the request file (phase two). +- **Outputs.** One undo step per accepted mutating intent; one receipt per intent; the + refreshed snapshot; look PNG paths; AetherDb's dry-run diff or its write. +- **Derived state.** Presence; human-edit sequences; look PNGs; the scene's mapped + collections (an edit buffer over the `.cc`); the request file. +- **Forbidden writers.** `execute_command` called around the primitive; operators run + with undo on inside an agent action; unpushed agent writes; `ed.undo`/`ed.redo` from + add-on code; any agent-sent Python; the debug-mirror JSON import as a door for intents + (`blender_target.py` `_import_debug_command_files`); `brokkr-ctl` deciding anything; + `ship_cc.py`'s envelope writes and any other direct `.cc` writer; `layout_revision` + as a revision. - **Shared paths.** brokkr-ctl intents, panel buttons that act on the scene, sync-organ - intents from `brokkr-daemon sync-once`, and replayed intents use the one primitive. + intents and replayed intents use the one primitive. The packager, the authoring + surface's buttons and an agent's push intent use the one AetherDb push. - **Deletion line.** The debug-mirror intent import goes before the primitive lands; - `drain_commands` stops calling `execute_command` directly. + `drain_commands` stops calling `execute_command` directly. `ship_cc.py`'s write + functions and `layout_revision` go when the push lands. ## Identity, lifecycle and authority | Persistent kind | What names it | What happens to it over time | Who decides | |---|---|---|---| -| Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `baseSeq`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (Unity F6 A, `brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written, as today. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | -| Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, conflict, stopped, failed, `undoLabel`, `lookPath`, and for `run` the script text and SHA-256) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. The only proof an intent ran. | The primitive alone. Callers and the panel read. | -| Agent identity `requestedBy` | `/` stated by the caller (brokkr-ctl takes it from `EUREKA_INSTANCE` and a flag) | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | -| Agent undo step | Blender undo stack entry labelled `Brokkr : ` | Pushed once per accepted mutating intent; lives as Blender's stack does (step limit, file load); never persisted by Brokkr. | Blender owns the stack. The primitive pushes. Only the human undoes or redoes. | -| Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads; every older base is then stale. | The add-on alone. | -| Human-edit sequences (snapshot fields: `humanEditSeq`, per-object `lastHumanEditSeq`, `lastUndoSeq`) | Integers within a session id | Monotonic within a session; reset with it. Observations, never scene truth. | The add-on's depsgraph and undo handlers alone. | -| Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, the sequences above, sink state) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | -| Command sink toggle (the existing `auto_drain_commands` preference) | Add-on preference, echoed in the snapshot | Off by default. Stop turns it off; only the human turns it on. | The human only. No intent writes it. | -| Script toggle (only if Q1 = b) | A second add-on preference, echoed in the snapshot | Off by default, independent of the sink. | The human only. | -| Look PNG | `/look/{commandId}.png` | Pruned by count; never read back as truth. | The primitive writes; `brush-tree:ruling:look-files-are-scratch` governs. | +| Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (`brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | +| Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, stopped, failed, `undoLabel`, `lookPath`) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. | The primitive alone. Callers and the panel read. | +| Agent identity `requestedBy` | `/` stated by the caller | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | +| Agent undo step | Blender undo entry `Brokkr : ` | One per accepted mutating intent; lives as Blender's stack does; never persisted by Brokkr. | Blender owns the stack; the primitive pushes; only the human undoes or redoes. | +| Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads. | The add-on alone. | +| Human-edit sequences (snapshot: `humanEditSeq`, per-object `lastHumanEditSeq`) | Integers within a session id | Monotonic within a session; reset with it. Information for the agent; they gate nothing. | The add-on's depsgraph and undo handlers alone. | +| Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, sequences, sink state, authoring binding summary) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | +| Command sink toggle (`auto_drain_commands`) | Add-on preference, echoed in the snapshot | Off by default. Stop turns it off; only the human turns it on. | The human only. | +| Look PNG | `/look/{commandId}.png` | Pruned by count; never read back as truth. | The primitive writes; `look-files-are-scratch` governs. | +| Ship package store `ship.cc` (`HullData`, `ShipAuthoring`, product records) | Its path, `GameData/Mods//ship.cc`; records by their keys | Created by `ship-authoring create`; changed only by AetherDb commands, each write minting new stored versions (`variants:ruling:storedat-on-change`); replaced whole only by packager `--replace`. | AetherDb's ship-authoring code is the only writer. | +| Record version | The version CultCache's compare-exchange tests for each record key | Changes on every write that changes the record's bytes. | CultCache mints it; AetherDb reports it on open and tests it on apply. | +| Authoring binding | A custom property on the Blender scene: the `ship.cc` path relative to the `.blend`, the ship id, and the record versions opened at | Set on Open; versions replaced after each successful apply; cleared on Detach or reopen. Lives in the `.blend`. | Open, apply and Detach (human buttons or agent actions through the primitive) alone write it. | +| Collection role | A custom property on a collection: hull, hardpoints, lines or anchors | Set when the surface builds or the author tags a collection; removed on Detach. | The author; the surface's Open builds the defaults. | +| Hardpoint row identity | `aetheria.id` on the row's object, equal to `HardpointData.Id` (`[CultElementId]`) | Minted when the row is created; survives renames and moves; removing the object removes the row on the next push. | AetherDb mints for a new row; the surface carries it. | +| Push request | `/authoring/{commandId}.json`, manifest vocabulary plus opened versions | Written per push; pruned by count; never read back as state. | The surface writes; AetherDb alone interprets it. | ## Not in scope -Human-to-human replication or several Blender instances in one session (Multi-User's -domain). Agents on another host reaching the operator's Blender: the transport is not -widened beyond what the add-on serves today. Per-user or selective undo. An approval gate -before each agent action (unless Q2 rules otherwise). A 3D-view overlay of the agent's -presence; the panel carries presence in this revision. The Unity surface and -`brokkr-command`. The brush-tree vocabulary, Geometry.Csg and OpenSCAD text (brush-tree -owns them). Agent-initiated save and quit (`brush-tree:ruling:run-admitted-when-enabled` -keeps them off the allowed list). Asset libraries and generators. An MCP server. +Human-to-human replication or several Blender instances in one session. Agents on +another host reaching the operator's Blender. Per-user or selective undo. An approval +gate (`act-then-undo`). Stale-action refusal inside the live scene +(`scene-last-writer-wins`). Any agent-sent Python (`no-free-form-python`). A 3D-view +presence overlay. The Unity surface and `brokkr-command`. The brush-tree vocabulary, +Geometry.Csg and OpenSCAD text (brush-tree owns them). Agent-initiated save and quit. +Asset libraries and generators. An MCP server. Records outside a ship package +(catalog loadouts, factions) unless Q6 rules them in. A new delta wire format. ## Open forks (draft questions; Self admits) -- **Q1. Free-form Python.** Today the Blender add-on has no script action. Libby's - Defaulted ruling `brush-tree:ruling:run-admitted-when-enabled` would add `run`, admitted - whenever agent commands are on. Options: (a) typed actions only; (b) `run` behind its - own off-by-default toggle, one undo step, script text in the receipt; (c) the Defaulted - ruling as written. Recommend (b). -- **Q2. Act then undo, or approve first.** Recommend act then undo, with Stop. -- **Q3. Conflict granularity.** (a) any human edit since the base refuses; (b) only edits to - the intent's targets, plus any undo or redo. Recommend (b), after the depsgraph - attribution probe. -- **Q4. Who builds `brokkr-ctl blender`.** Recommend this campaign builds the session - subcommands in Rust per Libby's rulings, and brush-tree adds its tree commands to the - same binary later. +- **Q5. What a push carries.** (a) whole records that changed, under `Expect`, now; (b) + variants override paths applied in place, after CultLib builds in-place apply and + C2b; (c) (a) now with the request shaped so (b) replaces it without changing the + surface. Recommend (c). +- **Q6. Does a ship's loadout belong in its package?** A package holds hull, authoring + and products today; loadouts are catalog records. Recommend not in r2. +- **Q7. May an agent apply a push, or only dry-run?** A `.cc` write has no Ctrl+Z. + Recommend dry-run for agents, apply by her button. +- **Q8. Where the authoring surface lives.** (a) the `aetheria_ships` add-on in Aetheria, + with Brokkr giving the agent typed actions that call it; (b) Brokkr's add-on gains + Aetheria vocabulary. Recommend (a). From 561562626f4f69867fbefd3d9a2ed74b8f26ae4c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:20:10 +0100 Subject: [PATCH 021/223] Live collab target r2: the push request is a stdin dump, as the material path Co-Authored-By: Claude Opus 5.5 --- docs/live-collab-target.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index 228ae83..13592ad 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -160,10 +160,11 @@ the three records and their stored versions, builds the tagged collections, and on the binding the version of each record it read. Nothing reads a `.cc` by scraping envelopes (operator 2026-11-17). -**A push is one AetherDb call, dry-run then apply.** The surface writes the authoring +**A push is one AetherDb call, dry-run then apply.** The surface pipes the authoring state of its tagged collections (the manifest vocabulary, plus the record versions it -opened at) to a scratch request file and calls `AetherDb ship-authoring push -`. Without `apply` AetherDb loads the store, derives the records the request +opened at) as a structural JSON dump on stdin to `AetherDb ship-authoring push `, +as the material path does (`aetheria-release:ruling:blender-dump-stdin`): never written +to disk, parsed and judged only in C#, so the schema exists once. Without `apply` AetherDb loads the store, derives the records the request describes, validates them, and prints the per-record, per-field changes; nothing is written. With `apply` it does the same and writes under compare-exchange on each record's stored version (`Expect`). One CLI call per push is the starting shape; a @@ -226,11 +227,11 @@ are the primitive for the push. owns the sink toggle, Stop and undo. Phase two: the `ship.cc` owns the ship; AetherDb's ship-authoring code alone derives and writes its records. - **Inputs.** Intent documents and the sink toggle (phase one). The tagged collections, - the binding's opened versions and the request file (phase two). + the binding's opened versions and the stdin dump (phase two). - **Outputs.** One undo step per accepted mutating intent; one receipt per intent; the refreshed snapshot; look PNG paths; AetherDb's dry-run diff or its write. - **Derived state.** Presence; human-edit sequences; look PNGs; the scene's mapped - collections (an edit buffer over the `.cc`); the request file. + collections (an edit buffer over the `.cc`); the stdin dump (a pipe, not state). - **Forbidden writers.** `execute_command` called around the primitive; operators run with undo on inside an agent action; unpushed agent writes; `ed.undo`/`ed.redo` from add-on code; any agent-sent Python; the debug-mirror JSON import as a door for intents @@ -262,7 +263,6 @@ are the primitive for the push. | Authoring binding | A custom property on the Blender scene: the `ship.cc` path relative to the `.blend`, the ship id, and the record versions opened at | Set on Open; versions replaced after each successful apply; cleared on Detach or reopen. Lives in the `.blend`. | Open, apply and Detach (human buttons or agent actions through the primitive) alone write it. | | Collection role | A custom property on a collection: hull, hardpoints, lines or anchors | Set when the surface builds or the author tags a collection; removed on Detach. | The author; the surface's Open builds the defaults. | | Hardpoint row identity | `aetheria.id` on the row's object, equal to `HardpointData.Id` (`[CultElementId]`) | Minted when the row is created; survives renames and moves; removing the object removes the row on the next push. | AetherDb mints for a new row; the surface carries it. | -| Push request | `/authoring/{commandId}.json`, manifest vocabulary plus opened versions | Written per push; pruned by count; never read back as state. | The surface writes; AetherDb alone interprets it. | ## Not in scope From a6184b61582f5d1d94bdafe6b13fda15102d2d91 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 19:34:27 +0100 Subject: [PATCH 022/223] Blender agent turn: Soul s2 fixes and a stock-Blender install commandId is validated (short key-safe string) before the reused check and any receipt key; a bad id is denied under a fresh key naming the queue key and leaves the queue. The add-on ships as an extension with a bundled msgpack wheel; _load_cultmesh names the module it lacks; NO_SCENE_CHANGE_ACTIONS is pinned; the queue harness runs in a stock Blender without PYLIBS. Co-Authored-By: Claude Sonnet 5.5 --- .../brokkr_bridge/blender_manifest.toml | 15 +++++ .../blender/brokkr_bridge/blender_target.py | 36 ++++++++--- .../msgpack-1.2.2-cp313-cp313-win_amd64.whl | Bin 0 -> 72206 bytes surfaces/blender/docs/install.md | 21 +++++++ .../blender/tests/live/agent_turn_queue.py | 54 +++++++++++++--- .../tests/live/agent_turn_queue.result.json | 59 ++++++++++++++---- surfaces/blender/tests/test_agent_turn.py | 47 ++++++++++++++ 7 files changed, 206 insertions(+), 26 deletions(-) create mode 100644 surfaces/blender/brokkr_bridge/blender_manifest.toml create mode 100644 surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl diff --git a/surfaces/blender/brokkr_bridge/blender_manifest.toml b/surfaces/blender/brokkr_bridge/blender_manifest.toml new file mode 100644 index 0000000..ec5feed --- /dev/null +++ b/surfaces/blender/brokkr_bridge/blender_manifest.toml @@ -0,0 +1,15 @@ +schema_version = "1.0.0" +id = "brokkr_bridge" +version = "0.2.0" +name = "Brokkr Bridge" +tagline = "Brokkr command intents, receipts and snapshots over CultMesh" +maintainer = "GameCult " +type = "add-on" +blender_version_min = "5.3.0" +platforms = ["windows-x64"] +license = ["SPDX:GPL-3.0-or-later"] +# CultLib's cultnet-py and cultcache-py import msgpack; Blender's Python does not ship it. The wheel is +# the installed msgpack 1.2.2 CPython 3.13 Windows build (Blender 5.3 runs Python 3.13). The C extension +# matters: CultLib at baf4ecf7 fails on msgpack's pure-Python fallback (object_pairs_hook gets a generator). +# Linux and macOS wheels are not bundled yet. +wheels = ["./wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl"] diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 2528bbc..3ed2dcf 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -59,6 +59,9 @@ NO_SCENE_CHANGE_ACTIONS = ("exportGltf", "renderStill") # Anything that writes scene state or changes her mode is refused; renderStill does neither. EDIT_MODE_SAFE_ACTIONS = ("renderStill",) REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") +# A commandId becomes part of a receipt key, so it is a short string of key-safe characters ('.' is left +# out: it separates the '.denied' suffix). +COMMAND_ID_SHAPE = re.compile(r"^[A-Za-z0-9_-]{1,128}$") NOTE_LIMIT = 200 EVALUATED_POSITION_CAP = 256 @@ -154,11 +157,18 @@ class BrokkrBlenderTarget: commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] self._receipted.update( - r.get("commandId", "") for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values()) + r["commandId"] for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values() + if isinstance(r.get("commandId"), str)) for command_key, command in sorted(commands.items()): - reused = command.get("commandId") in self._receipted + command_id = command.get("commandId") + valid = _valid_command_id(command_id) + reused = valid and command_id in self._receipted receipt = self.run_intent(context, command) + if not valid: + # No safe key exists for this id: the denial is receipted under a fresh key and names the + # queue key, so the intent leaves the queue and its sender can still find the refusal. + receipt["message"] += f" (queue key {command_key})" # Receipts are write-once: a reused id's denial goes under '.denied', never over the # original. The sender learns of it by reading that key (and the drain's returned list). self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root, @@ -521,8 +531,8 @@ class BrokkrBlenderTarget: requested_by = command.get("requestedBy") action = command.get("action", "") denial = "" - if not isinstance(command_id, str) or not command_id: - denial = "Intent has no commandId." + if not _valid_command_id(command_id): + denial = "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'." elif command_id in self._receipted: denial = f"commandId {command_id!r} was already receipted; ids are single-use." elif not isinstance(requested_by, str) or not REQUESTED_BY_SHAPE.match(requested_by): @@ -533,7 +543,7 @@ class BrokkrBlenderTarget: denial = (f"Object {self._edit_mode_object()!r} is in Edit Mode: object-level intents are refused " "until she leaves it; nothing was changed.") if denial: - if isinstance(command_id, str) and command_id: + if _valid_command_id(command_id): self._receipted.add(command_id) return self._receipt(command, "denied", denial, "") @@ -1094,7 +1104,7 @@ class BrokkrBlenderTarget: def _receipt(self, command: dict[str, Any], status: str, message: str, object_name: str) -> dict[str, Any]: return { "schema": COMMAND_RECEIPT_SCHEMA, - "commandId": command.get("commandId") or uuid.uuid4().hex, + "commandId": command["commandId"] if _valid_command_id(command.get("commandId")) else uuid.uuid4().hex, "action": command.get("action", ""), "status": status, "message": message, @@ -1222,9 +1232,15 @@ def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: import cultmesh_py # type: ignore import cultcache_py # type: ignore except ModuleNotFoundError as exc: + own = {name.replace("-", "_") for name in CULTLIB_PY_PACKAGES} + if exc.name in own: + raise RuntimeError( + "Brokkr Blender target requires CultLib's Python packages. Set CultLib Python Source " + "to the CultLib packages directory or install cultcache-py, cultnet-py and cultmesh-py into Blender's Python." + ) from exc raise RuntimeError( - "Brokkr Blender target requires CultLib's Python packages. Set CultLib Python Source " - "to the CultLib packages directory or install cultcache-py, cultnet-py and cultmesh-py into Blender's Python." + f"A CultLib Python package needs the module {exc.name!r}, which Blender's Python does not have. " + "Install the add-on as an extension (it bundles msgpack) or install that module into Blender's Python." ) from exc if not hasattr(cultcache_py, "convert"): raise RuntimeError( @@ -1255,6 +1271,10 @@ def _to_list(value: Any) -> list[float]: return [float(item) for item in value] +def _valid_command_id(value: Any) -> bool: + return isinstance(value, str) and COMMAND_ID_SHAPE.match(value) is not None + + def _vector(value: Any, size: int, fallback: Any) -> tuple[float, ...]: if value is None: return tuple(float(item) for item in fallback) diff --git a/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl b/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl new file mode 100644 index 0000000000000000000000000000000000000000..83a8682553e2b936e0c3cb72ecf267cd6ec8b371 GIT binary patch literal 72206 zcmY&;Q;aT58{|8-ZCht->x^yNwmoykwr$(CZQHi?+hi~Hzvxb<(|OWKRq~)pUJ3*h z6#xK0{k-&0blszJo zLxj-!IE-womWg+OYMwKHl6azUFXfs1yV%AHB%T_PGBCc;yraN@8< zK~4VkOyFTt@?>Xl%%8t;5r?*^LGa0m$&g`U zX#ZoLXWtugLeO>$hHG2L4V15#eLV1OaE5dg&)do|Jx(CA60`ekarMt@+2LXAhr_5I z;^!oKYt~ zAn(#=vy(yjH5`js%?BX=KjaufT=r=Fj~o{Nkpu1jBZrB*k%_&tg`KU_fAmOJlCdlN zfAm;~iEnrZiuWv+EYf95&UnIZch|0Bbv=qLdVl2}0m4;{cjffI@A7zb_hpITgn;ld zoWA|&>`zP;Q#-V5r-I3|s#oV>4x4+jH=yNMB--klVrCQSVs-Yp1>J!LdxS)BPz1RI|D!vnf8V zfh%&yM%9kWMI1~JPkX`(IOD{b4o7gBF0%tn=XStP!k<>%GbYU2_!G0O5a;mVfl0t%d*qmaqT-`2RuL`9Fw@HEirQ#gKn&`+f~%`_Ym} z>KlyOk`XZ=IL=u`FH1O1HS;LP(3%@wByXss4>251(_76< z&DaapDi-=8uxv&8<>Z3B@?!egfWtEE-!_kgIGh-7B zkWHhg^I_HShf7;&8PhQN^9H4^uF!mV_}&i_p7Cqw!fkMWB1F8Ek+G{#394!7iXFP^ zU41F<7{ttX8g@!4e~!r|uitHJO5&zsL#;~bC3fbrX%93Yw+A2$Snr*TT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LjeE~ z{0)JHg#JSK{FlDNaNoTWDgZz@>Ua6q@qYESw{mf@M#j+o3*ag`s/surfaces/blender/brokkr_brid The command prints the record count and leaves the source unwritten. Records a new daemon already appended (MessagePack) are carried into the new file. +### msgpack for a stock Blender + +CultLib's `cultnet-py` and `cultcache-py` import `msgpack`, and Blender's Python does +not ship it. Install Brokkr as an extension so Blender installs it for you: +`surfaces/blender/brokkr_bridge/blender_manifest.toml` lists the bundled wheel +`wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl`, which Blender unpacks into the extension's own +site-packages when the extension is enabled. Build and install it: + +```text +blender --command extension build --source-dir surfaces/blender/brokkr_bridge --output-dir +blender --command extension install-file --repo user_default --enable /brokkr_bridge-0.2.0.zip +``` + +The bundled wheel is msgpack 1.2.2 for CPython 3.13 on Windows x64 (Blender 5.3's Python), +repacked from the installed package with its Apache-2.0 licence; the extension is therefore +declared `windows-x64`, Blender 5.3 or newer. The C extension matters: CultLib at `baf4ecf7` +fails on msgpack's pure-Python fallback. Linux and macOS wheels are not bundled yet: there, +or in a plain add-on directory install, put `msgpack` into Blender's Python yourself. A +CultLib package missing a module is reported by that module's name, not as a missing +CultLib package. + The default node cache is: ```text diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py index e44669a..18fc00a 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.py +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -3,13 +3,17 @@ are drained by the add-on's own 1 s timer as one undo step each, with write-once BROKKR_USER_SCRIPTS= (also BLENDER_USER_SCRIPTS) BROKKR_SCRATCH= - BROKKR_PYLIBS= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + BROKKR_PYLIBS= blender --factory-startup --python agent_turn_queue.py -- Intents are put into the node database as brokkr-ctl does (no debug-mirror files). Writes .result.json, then quits Blender. Undo is read only here, by this driver. """ +import importlib import json import os import sys @@ -23,19 +27,28 @@ if os.environ.get("BROKKR_PYLIBS"): SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() SCRATCH.mkdir(parents=True, exist_ok=True) OUT = sys.argv[sys.argv.index("--") + 1] -R = {"blender": bpy.app.version_string, "checks": [], "receipts": {}} +R = {"blender": bpy.app.version_string, "module": os.environ.get("BROKKR_ADDON_MODULE", "brokkr_bridge"), + "pylibs": bool(os.environ.get("BROKKR_PYLIBS")), "checks": [], "receipts": {}} -bpy.ops.preferences.addon_enable(module="brokkr_bridge") -import brokkr_bridge as addon # noqa: E402 -from brokkr_bridge import blender_target as bt # noqa: E402 +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "brokkr_bridge") +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") -prefs = bpy.context.preferences.addons["brokkr_bridge"].preferences +try: + import msgpack + R["msgpack"] = msgpack.__file__ +except ImportError: + R["msgpack"] = None +prefs = bpy.context.preferences.addons[MODULE].preferences CACHE = str(SCRATCH / "queue.ccmp") prefs.cultmesh_cache_path = CACHE prefs.debug_mirror_root = "" # the debug-mirror door is not used here prefs.output_dir = str(SCRATCH / "out") prefs.import_dir = "" prefs.auto_drain_commands = True +if os.environ.get("BROKKR_CULTLIB"): + prefs.cultlib_py_src = os.environ["BROKKR_CULTLIB"] (SCRATCH / "out").mkdir(exist_ok=True) adapter = addon.target() @@ -73,6 +86,11 @@ def receipt(key): return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{key}") +def all_receipts(): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}) + + def pending(): n, _ = node() return n.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {}) @@ -190,11 +208,33 @@ def q5_exit(): check("queue: add-on drain reports no error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) +def q6(): + queue("bad-list", action="createObject", objectType="MESH", name="QBadList", requestedBy="nibu/hands") + queue("bad-int", action="createObject", objectType="MESH", name="QBadInt", requestedBy="nibu/hands") + n, docs = node() + for key in ("bad-list", "bad-int"): # overwrite the id with a non-string, as a hand-written put could + doc = dict(n.database.snapshot()[bt.COMMAND_INTENT_SCHEMA][f"blender/commands/{key}"]) + doc["commandId"] = ["x"] if key == "bad-list" else 7 + n.database.put(docs["command_intent"], f"blender/commands/{key}", doc) + queue("zzzzzzzz-good", action="createObject", objectType="MESH", name="QAfterBad", requestedBy="nibu/hands") + + +def q6_check(): + denials = [r for k, r in all_receipts().items() if "queue key blender/commands/bad-" in r.get("message", "")] + R["receipts"]["q6"] = denials + check("queue: a list id and an int id are denied under fresh keys, removed from the queue, drain not wedged", + len(denials) == 2 and all(r["status"] == "denied" and isinstance(r["commandId"], str) for r in denials) + and not pending() and "QBadList" not in names() and "QBadInt" not in names() + and receipt("zzzzzzzz-good")["status"] == "accepted" and "QAfterBad" in names() + and adapter.last_auto_drain_error == "", [adapter.last_auto_drain_error, list(pending())]) + + steps = [ once(q1), until(drained("aaaaaaaa-0001")), once(q1_check), once(q2), until(lambda: receipt("aaaaaaaa-0001.denied")), once(q2_check), once(q3), until(drained("aaaaaaaa-0003")), once(q3_check), once(q4), until(drained("aaaaaaaa-0004", "aaaaaaaa-0005")), once(q4_undo_two), + once(q6), until(drained("zzzzzzzz-good")), once(q6_check), once(q5_edit), until(drained("aaaaaaaa-0006", "aaaaaaaa-0007", "aaaaaaaa-0008")), once(q5_check), once(q5_exit), ] i = 0 diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json index a040d56..cbd7ce5 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.result.json +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -1,5 +1,7 @@ { "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "pylibs": false, "checks": [ { "name": "queue: createObject drained by the add-on timer, accepted, labelled, attributed", @@ -10,7 +12,7 @@ "message": "Blender object created.", "note": "queue test", "objectName": "QCube", - "observedAt": "2026-11-27T18:07:31.682454+00:00", + "observedAt": "2026-11-27T18:33:33.859109+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "accepted", @@ -31,7 +33,7 @@ "message": "Blender object created.", "note": "queue test", "objectName": "QCube", - "observedAt": "2026-11-27T18:07:31.682454+00:00", + "observedAt": "2026-11-27T18:33:33.859109+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "accepted", @@ -47,7 +49,7 @@ "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:33.680885+00:00", + "observedAt": "2026-11-27T18:33:35.854629+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -63,7 +65,7 @@ "message": "Intent has no requestedBy of the form '/'.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:35.693748+00:00", + "observedAt": "2026-11-27T18:33:37.862020+00:00", "requestedBy": "", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -89,6 +91,14 @@ ] ] }, + { + "name": "queue: a list id and an int id are denied under fresh keys, removed from the queue, drain not wedged", + "ok": true, + "detail": [ + "", + [] + ] + }, { "name": "queue: in Edit Mode setWorld, exportGltf and an object write are all denied, her mode kept", "ok": true, @@ -111,7 +121,7 @@ "message": "Blender object created.", "note": "queue test", "objectName": "QCube", - "observedAt": "2026-11-27T18:07:31.682454+00:00", + "observedAt": "2026-11-27T18:33:33.859109+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "accepted", @@ -123,7 +133,7 @@ "message": "Blender object created.", "note": "queue test", "objectName": "QCube", - "observedAt": "2026-11-27T18:07:31.682454+00:00", + "observedAt": "2026-11-27T18:33:33.859109+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "accepted", @@ -135,7 +145,7 @@ "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:33.680885+00:00", + "observedAt": "2026-11-27T18:33:35.854629+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -147,12 +157,38 @@ "message": "Intent has no requestedBy of the form '/'.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:35.693748+00:00", + "observedAt": "2026-11-27T18:33:37.862020+00:00", "requestedBy": "", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", "undoLabel": "" }, + "q6": [ + { + "action": "createObject", + "commandId": "8cdf6298074845bfa652d7136ec176f0", + "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:33:41.872393+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + }, + { + "action": "createObject", + "commandId": "cfdfef85da3a4c0398901d7ffef109af", + "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T18:33:41.884756+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "denied", + "undoLabel": "" + } + ], "q5": [ { "action": "setWorld", @@ -160,7 +196,7 @@ "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:39.773004+00:00", + "observedAt": "2026-11-27T18:33:43.881906+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -172,7 +208,7 @@ "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:39.867526+00:00", + "observedAt": "2026-11-27T18:33:43.894611+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -184,7 +220,7 @@ "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", "note": "", "objectName": "", - "observedAt": "2026-11-27T18:07:39.950112+00:00", + "observedAt": "2026-11-27T18:33:43.916685+00:00", "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", "status": "denied", @@ -192,5 +228,6 @@ } ] }, + "msgpack": "F:\\aeth-wt\\brokkr-live-2.res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 4874644..69e83fc 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -2,6 +2,8 @@ from __future__ import annotations import re +import sys +import tempfile import unittest import unittest.mock from pathlib import Path @@ -146,6 +148,36 @@ class AgentTurnTests(unittest.TestCase): self.assertEqual(again["status"], "denied") self.assertEqual(len(self.bpy.created), 1) + # fix batch s2 + def test_no_scene_change_set_is_exactly_export_and_render(self): + self.assertEqual(bt.NO_SCENE_CHANGE_ACTIONS, ("exportGltf", "renderStill")) + receipt = self.run_action(action="setWorld", color=[0.1, 0.2, 0.3]) + self.assertEqual(receipt["status"], "accepted") + self.assertEqual(len(self.bpy.undo.pushes), 1) + + def test_malformed_command_ids_are_denied_without_raising(self): + for bad in (["x"], 7, 1.5, {"a": 1}, "", "a/b", "x.denied", "has space", "a" * 200, None, True): + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId=bad) + self.assertEqual(receipt["status"], "denied", repr(bad)) + self.assertIsInstance(receipt["commandId"], str) + self.assertRegex(receipt["commandId"], bt.COMMAND_ID_SHAPE.pattern, repr(bad)) + self.assertEqual(self.bpy.created, []) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_load_cultmesh_names_the_missing_module(self): + root = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(root, ignore_errors=True)) + src = root / "cultmesh-py" / "src" / "cultmesh_py" + src.mkdir(parents=True) + (src / "__init__.py").write_text("import brokkr_no_such_dependency_xyz") + saved = {k: sys.modules.pop(k) for k in ("cultmesh_py", "cultcache_py") if k in sys.modules} + saved_path = list(sys.path) + self.addCleanup(lambda: (sys.modules.update(saved), sys.path[:] == saved_path or sys.path.__setitem__(slice(None), saved_path))) + with self.assertRaises(RuntimeError) as caught: + bt._load_cultmesh(str(root)) + self.assertIn("brokkr_no_such_dependency_xyz", str(caught.exception)) + self.assertNotIn("requires CultLib's Python packages", str(caught.exception)) + class FakeNode: """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" @@ -177,6 +209,21 @@ class DrainTests(unittest.TestCase): def intent(self, cid, **fields): return {"commandId": cid, "requestedBy": "nibu/hands", "action": "createObject", "objectType": "EMPTY", **fields} + def test_malformed_ids_in_the_queue_never_wedge_the_drain(self): + node = FakeNode({ + "blender/commands/a-list": self.intent(["x"]), + "blender/commands/b-int": self.intent(7), + "blender/commands/c-good": self.intent("good-1"), + }) + receipts = self.drain(node) # must not raise + self.assertEqual(sorted(node.deleted), sorted(node.docs[bt.COMMAND_INTENT_SCHEMA])) + self.assertEqual([r["status"] for r in receipts], ["denied", "denied", "accepted"]) + keys = [k for k, _ in node.puts] + self.assertTrue(all(isinstance(k, str) and "[" not in k for k in keys), keys) + self.assertIn("blender/receipts/good-1", keys) + bad = [v for k, v in node.puts if k != "blender/receipts/good-1"] + self.assertTrue(all("blender/commands/" in v["message"] for v in bad), [v["message"] for v in bad]) + def test_drain_seeds_receipted_from_persisted_receipts(self): old = {"blender/receipts/old-1": {"commandId": "old-1", "status": "accepted"}} node = FakeNode({"blender/commands/old-1": self.intent("old-1")}, old) From 57ca88ed381aa19a495564acd537a5fc5e32102b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:02:50 +0100 Subject: [PATCH 023/223] Blender agent turn: live harness results rerun on main a371056f (CultLib baf4ecf7 pins) Co-Authored-By: Claude Sonnet 5.5 --- .../tests/live/agent_turn_queue.result.json | 208 +++++++++--------- .../tests/live/agent_turn_undo.result.json | 4 +- 2 files changed, 106 insertions(+), 106 deletions(-) diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json index cbd7ce5..9d8a289 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.result.json +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -7,16 +7,16 @@ "name": "queue: createObject drained by the add-on timer, accepted, labelled, attributed", "ok": true, "detail": { - "action": "createObject", - "commandId": "aaaaaaaa-0001", - "message": "Blender object created.", - "note": "queue test", - "objectName": "QCube", - "observedAt": "2026-11-27T18:33:33.859109+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", + "observedAt": "2026-11-27T19:01:35.205337+00:00" } }, { @@ -28,48 +28,48 @@ "name": "queue: reused id leaves the original receipt untouched (write-once)", "ok": true, "detail": { - "action": "createObject", - "commandId": "aaaaaaaa-0001", - "message": "Blender object created.", - "note": "queue test", - "objectName": "QCube", - "observedAt": "2026-11-27T18:33:33.859109+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", + "observedAt": "2026-11-27T19:01:35.205337+00:00" } }, { "name": "queue: reused id reported under .denied, nothing created", "ok": true, "detail": { - "action": "createObject", - "commandId": "aaaaaaaa-0001", - "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:35.854629+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", "status": "denied", - "undoLabel": "" + "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:37.202231+00:00" } }, { "name": "queue: intent without requestedBy denied, scene unchanged", "ok": true, "detail": { - "action": "createObject", - "commandId": "aaaaaaaa-0003", - "message": "Intent has no requestedBy of the form '/'.", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:37.862020+00:00", - "requestedBy": "", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0003", + "action": "createObject", "status": "denied", - "undoLabel": "" + "message": "Intent has no requestedBy of the form '/'.", + "objectName": "", + "requestedBy": "", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:39.207926+00:00" } }, { @@ -116,115 +116,115 @@ ], "receipts": { "q1": { - "action": "createObject", - "commandId": "aaaaaaaa-0001", - "message": "Blender object created.", - "note": "queue test", - "objectName": "QCube", - "observedAt": "2026-11-27T18:33:33.859109+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", + "observedAt": "2026-11-27T19:01:35.205337+00:00" }, "q2_original": { - "action": "createObject", - "commandId": "aaaaaaaa-0001", - "message": "Blender object created.", - "note": "queue test", - "objectName": "QCube", - "observedAt": "2026-11-27T18:33:33.859109+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa" + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", + "observedAt": "2026-11-27T19:01:35.205337+00:00" }, "q2_denial": { - "action": "createObject", - "commandId": "aaaaaaaa-0001", - "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:35.854629+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", "status": "denied", - "undoLabel": "" + "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:37.202231+00:00" }, "q3": { - "action": "createObject", - "commandId": "aaaaaaaa-0003", - "message": "Intent has no requestedBy of the form '/'.", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:37.862020+00:00", - "requestedBy": "", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0003", + "action": "createObject", "status": "denied", - "undoLabel": "" + "message": "Intent has no requestedBy of the form '/'.", + "objectName": "", + "requestedBy": "", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:39.207926+00:00" }, "q6": [ { - "action": "createObject", - "commandId": "8cdf6298074845bfa652d7136ec176f0", - "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:41.872393+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "ae0a53d8d0584e54b1ce518cf7e8cf9d", + "action": "createObject", "status": "denied", - "undoLabel": "" + "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:43.220315+00:00" }, { - "action": "createObject", - "commandId": "cfdfef85da3a4c0398901d7ffef109af", - "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:41.884756+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "f5ce147da5e0466ab0771ac13135f4be", + "action": "createObject", "status": "denied", - "undoLabel": "" + "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:43.242934+00:00" } ], "q5": [ { - "action": "setWorld", + "schema": "brokkr.blender.command_receipt.v0", "commandId": "aaaaaaaa-0006", - "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:43.881906+00:00", - "requestedBy": "nibu/hands", - "schema": "brokkr.blender.command_receipt.v0", + "action": "setWorld", "status": "denied", - "undoLabel": "" + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:45.227825+00:00" }, { - "action": "exportGltf", + "schema": "brokkr.blender.command_receipt.v0", "commandId": "aaaaaaaa-0007", - "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:43.894611+00:00", - "requestedBy": "nibu/hands", - "schema": "brokkr.blender.command_receipt.v0", + "action": "exportGltf", "status": "denied", - "undoLabel": "" + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:45.250025+00:00" }, { - "action": "setObjectTransform", - "commandId": "aaaaaaaa-0008", - "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", - "note": "", - "objectName": "", - "observedAt": "2026-11-27T18:33:43.916685+00:00", - "requestedBy": "nibu/hands", "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0008", + "action": "setObjectTransform", "status": "denied", - "undoLabel": "" + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:01:45.281467+00:00" } ] }, diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json index 7e8e590..5468ce0 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.result.json +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -197,7 +197,7 @@ "name": "exportGltf and renderStill accepted with no undoLabel", "ok": true, "detail": [ - "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-yk0g4dyg\\object.glb (3484 bytes).", + "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-a4ak7h0p\\object.glb (3484 bytes).", "Rendered still to object.png." ] }, @@ -270,7 +270,7 @@ "intent": "exportGltf", "status": "accepted", "undoLabel": "", - "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-yk0g4dyg\\object.glb (3484 bytes)." + "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-a4ak7h0p\\object.glb (3484 bytes)." }, { "intent": "renderStill", From 68e1b654dda7384a417677d94b7bbe5d258a6398 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:35:30 +0100 Subject: [PATCH 024/223] brokkr-ctl blender: a Rust CLI that sends typed intents to the live add-on's store and reads receipts and the snapshot Workspace member brokkr-ctl; cultcache-rs moves to [workspace.dependencies] at the daemon's existing rev. Writes only blender/commands/; intents are attributed or refused; exit code derives from the receipt. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.toml | 6 +- brokkr-ctl/Cargo.toml | 14 + brokkr-ctl/src/blender.rs | 588 ++++++++++++++++++ brokkr-ctl/src/main.rs | 24 + brokkr-ctl/tests/cli.rs | 154 +++++ brokkr-daemon/Cargo.toml | 2 +- .../blender/tests/test_brokkr_ctl_interop.py | 73 +++ 7 files changed, 859 insertions(+), 2 deletions(-) create mode 100644 brokkr-ctl/Cargo.toml create mode 100644 brokkr-ctl/src/blender.rs create mode 100644 brokkr-ctl/src/main.rs create mode 100644 brokkr-ctl/tests/cli.rs create mode 100644 surfaces/blender/tests/test_brokkr_ctl_interop.py diff --git a/Cargo.toml b/Cargo.toml index 37f910c..c469605 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,10 @@ [workspace] resolver = "2" members = [ - "brokkr-daemon" + "brokkr-daemon", + "brokkr-ctl", ] +[workspace.dependencies] +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" } + diff --git a/brokkr-ctl/Cargo.toml b/brokkr-ctl/Cargo.toml new file mode 100644 index 0000000..cff9015 --- /dev/null +++ b/brokkr-ctl/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "brokkr-ctl" +version = "0.1.0" +edition = "2024" +publish = false + +[dependencies] +anyhow = "1" +cultcache-rs = { workspace = true } +serde_json = "1" +uuid = { version = "1", features = ["v4"] } + +[dev-dependencies] +tempfile = "3" diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs new file mode 100644 index 0000000..d054357 --- /dev/null +++ b/brokkr-ctl/src/blender.rs @@ -0,0 +1,588 @@ +//! `brokkr-ctl blender`: a caller of the Blender add-on's store. It writes one intent +//! document per `send` and reads receipts and the host snapshot. The add-on decides. + +use anyhow::{Context, Result, anyhow, bail}; +use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, SingleFileMessagePackBackingStore}; +use serde_json::{Map, Value}; +use std::path::PathBuf; +use std::thread; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +pub const INTENT_SCHEMA: &str = "brokkr.blender.command_intent.v0"; +pub const RECEIPT_SCHEMA: &str = "brokkr.blender.command_receipt.v0"; +pub const SNAPSHOT_SCHEMA: &str = "brokkr.blender.host_snapshot.v0"; +const INTENT_PREFIX: &str = "blender/commands/"; +const RECEIPT_PREFIX: &str = "blender/receipts/"; +const SNAPSHOT_KEY: &str = "blender/host/current"; +const RESERVED: [&str; 5] = ["schema", "commandId", "action", "requestedBy", "note"]; +const DEFAULT_TIMEOUT_SECS: f64 = 60.0; +const POLL: Duration = Duration::from_millis(200); + +/// What a receipt (or its absence) says; the exit code derives from it and from nothing else. +pub enum Outcome { + Accepted, + Failed, + Stopped, + Timeout, +} + +impl Outcome { + pub fn code(&self) -> i32 { + match self { + Outcome::Accepted => 0, + Outcome::Failed => 2, + Outcome::Stopped => 3, + Outcome::Timeout => 4, + } + } + + pub fn from_status(status: &str) -> Outcome { + match status { + "accepted" => Outcome::Accepted, + "stopped" => Outcome::Stopped, + _ => Outcome::Failed, // denied, failed, and any status this tool does not know + } + } +} + +#[derive(Default)] +struct Options { + store: Option, + agent: Option, + note: String, + sets: Vec, + no_wait: bool, + timeout: Option, + last: Option, + positional: Vec, +} + +fn parse(args: &[String]) -> Result { + let mut options = Options::default(); + let mut iter = args.iter(); + while let Some(arg) = iter.next() { + let mut value = |name: &str| { + iter.next() + .cloned() + .ok_or_else(|| anyhow!("{name} needs a value")) + }; + match arg.as_str() { + "--store" => options.store = Some(PathBuf::from(value("--store")?)), + "--agent" => options.agent = Some(value("--agent")?), + "--note" => options.note = value("--note")?, + "--set" => options.sets.push(value("--set")?), + "--no-wait" => options.no_wait = true, + "--timeout" => { + let raw = value("--timeout")?; + let secs: f64 = raw + .parse() + .map_err(|_| anyhow!("--timeout wants seconds, got {raw:?}"))?; + if !secs.is_finite() || secs < 0.0 { + bail!("--timeout wants a non-negative number of seconds"); + } + options.timeout = Some(secs); + } + "--last" => { + let raw = value("--last")?; + options.last = Some( + raw.parse() + .map_err(|_| anyhow!("--last wants a count, got {raw:?}"))?, + ); + } + flag if flag.starts_with("--") => bail!("unknown option {flag}"), + _ => options.positional.push(arg.clone()), + } + } + Ok(options) +} + +/// Runs one `blender` subcommand and returns the process exit code. +pub fn run(args: &[String]) -> Result { + let Some((sub, rest)) = args.split_first() else { + print!("{}", group_help()); + return Ok(1); + }; + if matches!(sub.as_str(), "--help" | "-h" | "help") { + print!("{}", group_help()); + return Ok(0); + } + if rest.iter().any(|arg| arg == "--help" || arg == "-h") { + print!("{}", if sub == "send" { send_help() } else { group_help() }); + return Ok(0); + } + let options = parse(rest)?; + match sub.as_str() { + "send" => send(&options), + "wait" => { + let id = one_positional(&options, "wait ")?; + let store = open_store(&options)?; + wait_for_receipt(&store, id, timeout(&options)) + } + "receipts" => receipts(&open_store(&options)?, options.last), + "status" => status(&open_store(&options)?), + other => bail!("unknown subcommand {other:?}; try `brokkr-ctl blender --help`"), + } +} + +fn one_positional<'a>(options: &'a Options, usage: &str) -> Result<&'a str> { + match options.positional.as_slice() { + [one] => Ok(one), + _ => bail!("usage: brokkr-ctl blender {usage}"), + } +} + +fn timeout(options: &Options) -> Duration { + Duration::from_secs_f64(options.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS)) +} + +/// The add-on creates its store; naming a path that is not there is a typo, not a request +/// to make a second store. +fn open_store(options: &Options) -> Result { + let path = options + .store + .clone() + .or_else(|| std::env::var_os("BROKKR_BLENDER_STORE").map(PathBuf::from)) + .ok_or_else(|| anyhow!("no store: pass --store or set BROKKR_BLENDER_STORE"))?; + if !path.is_file() { + bail!("store {} does not exist; the add-on creates it", path.display()); + } + // The store library stages writes beside the file and fails on a bare file name. + Ok(SingleFileMessagePackBackingStore::new(std::path::absolute(path)?)) +} + +fn requested_by(options: &Options) -> Result { + let instance = std::env::var("EUREKA_INSTANCE").unwrap_or_default(); + let agent = options + .agent + .clone() + .or_else(|| std::env::var("BROKKR_AGENT").ok()) + .unwrap_or_default(); + if instance.trim().is_empty() || agent.trim().is_empty() { + bail!("an intent must be attributed: set EUREKA_INSTANCE and pass --agent or set BROKKR_AGENT"); + } + Ok(format!("{}/{}", instance.trim(), agent.trim())) +} + +fn build_intent( + action: &str, + command_id: &str, + requested_by: &str, + note: &str, + sets: &[String], +) -> Result { + if action.is_empty() || !action.chars().all(|c| c.is_ascii_alphanumeric()) { + bail!("action must be letters and digits, e.g. createObject"); + } + let mut map = Map::new(); + for set in sets { + let (key, raw) = set + .split_once('=') + .ok_or_else(|| anyhow!("--set wants key=json, got {set:?}"))?; + if key.is_empty() || RESERVED.contains(&key) { + bail!("--set cannot name {key:?}: it is written by brokkr-ctl"); + } + let value: Value = serde_json::from_str(raw) + .with_context(|| format!("--set {key}: {raw:?} is not JSON (strings need quotes)"))?; + map.insert(key.to_string(), value); + } + map.insert("schema".into(), INTENT_SCHEMA.into()); + map.insert("commandId".into(), command_id.into()); + map.insert("action".into(), action.into()); + map.insert("requestedBy".into(), requested_by.into()); + map.insert("note".into(), note.into()); + Ok(Value::Object(map)) +} + +fn send(options: &Options) -> Result { + let action = one_positional(options, "send [--set key=json]...")?; + let requested_by = requested_by(options)?; + let mut store = open_store(options)?; + let command_id = uuid::Uuid::new_v4().simple().to_string(); + let intent = build_intent(action, &command_id, &requested_by, &options.note, &options.sets)?; + store.push(&CultCacheEnvelope { + key: format!("{INTENT_PREFIX}{command_id}"), + r#type: INTENT_SCHEMA.to_string(), + payload: serde_json::to_vec(&intent)?, + stored_at: iso_now(), + schema_id: Some(INTENT_SCHEMA.to_string()), + })?; + println!("commandId: {command_id}"); + if options.no_wait { + return Ok(0); + } + wait_for_receipt(&store, &command_id, timeout(options)) +} + +fn read_receipt(store: &SingleFileMessagePackBackingStore, id: &str) -> Result> { + let key = format!("{RECEIPT_PREFIX}{id}"); + for envelope in store.pull_all()? { + if envelope.key == key && envelope.r#type == RECEIPT_SCHEMA { + return Ok(Some(decode(&envelope)?)); + } + } + Ok(None) +} + +fn wait_for_receipt( + store: &SingleFileMessagePackBackingStore, + id: &str, + limit: Duration, +) -> Result { + let started = Instant::now(); + loop { + if let Some(receipt) = read_receipt(store, id)? { + print_fields(&receipt); + let status = receipt.get("status").and_then(Value::as_str).unwrap_or(""); + return Ok(Outcome::from_status(status).code()); + } + if started.elapsed() >= limit { + println!("status: timeout"); + return Ok(Outcome::Timeout.code()); + } + thread::sleep(POLL); + } +} + +fn receipts(store: &SingleFileMessagePackBackingStore, last: Option) -> Result { + let mut found = Vec::new(); + for envelope in store.pull_all()? { + if envelope.key.starts_with(RECEIPT_PREFIX) && envelope.r#type == RECEIPT_SCHEMA { + found.push(decode(&envelope)?); + } + } + found.sort_by_key(|receipt| { + receipt + .get("observedAt") + .and_then(Value::as_str) + .unwrap_or("") + .to_string() + }); + let skip = last.map_or(0, |n| found.len().saturating_sub(n)); + for (index, receipt) in found.iter().skip(skip).enumerate() { + if index > 0 { + println!(); + } + print_fields(receipt); + } + Ok(0) +} + +fn status(store: &SingleFileMessagePackBackingStore) -> Result { + for envelope in store.pull_all()? { + if envelope.key == SNAPSHOT_KEY && envelope.r#type == SNAPSHOT_SCHEMA { + let snapshot = decode(&envelope)?; + for key in [ + "observedAt", + "blenderVersion", + "projectPath", + "mode", + "activeScene", + "activeObjectName", + "selectedObjectNames", + "objectCount", + "sink", + ] { + if let Some(value) = snapshot.get(key) { + print_field(key, value); + } + } + return Ok(0); + } + } + bail!("the store holds no host snapshot yet; is the add-on's server running?") +} + +fn decode(envelope: &CultCacheEnvelope) -> Result { + serde_json::from_slice(&envelope.payload) + .with_context(|| format!("{} is not a JSON map payload", envelope.key)) +} + +fn print_fields(value: &Value) { + match value.as_object() { + Some(map) => map.iter().for_each(|(key, value)| print_field(key, value)), + None => println!("value: {value}"), + } +} + +fn print_field(key: &str, value: &Value) { + match value { + Value::String(text) => println!("{key}: {text}"), + other => println!("{key}: {other}"), + } +} + +/// UTC, microseconds, `+00:00`: the form the Python node stamps. +fn iso_now() -> String { + let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default(); + iso_from(now.as_secs() as i64, now.subsec_micros()) +} + +fn iso_from(secs: i64, micros: u32) -> String { + let days = secs.div_euclid(86_400); + let rem = secs.rem_euclid(86_400); + // Howard Hinnant's civil_from_days. + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{micros:06}+00:00", + rem / 3_600, + rem % 3_600 / 60, + rem % 60 + ) +} + +pub fn group_help() -> String { + "\ +brokkr-ctl blender: send typed intents to the live Blender add-on and read what it did. + + send [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs] + Write one intent, then wait for its receipt and print it. `send --help` lists actions. + wait [--timeout secs] Wait for a receipt and print it. + receipts [--last n] Print stored receipts, oldest first. + status Print the host snapshot summary. + +Every command needs --store or $BROKKR_BLENDER_STORE (the add-on's .ccmp). +send needs $EUREKA_INSTANCE and --agent or $BROKKR_AGENT; requestedBy is '/'. +Output is 'key: value' lines. Exit: 0 accepted, 2 denied or failed, 3 stopped, 4 timeout, +1 usage or store error. brokkr-ctl validates nothing about an action: the add-on does, and +its refusal comes back in the receipt. +" + .to_string() +} + +pub fn send_help() -> String { + let mut text = String::from( + "\ +brokkr-ctl blender send [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs] + +--set takes JSON: --set objectType='\"MESH\"' --set location='[0,0,1]'. brokkr-ctl writes schema, +commandId, action, requestedBy and note itself; --set cannot name them. Fields below are what the +add-on reads; it validates them and refuses in the receipt. Targets also accept objectName. + +actions: +", + ); + for (action, fields) in ACTIONS { + text.push_str(&format!(" {action}\n")); + for (name, kind, note) in *fields { + text.push_str(&format!(" {name}: {kind} {note}\n")); + } + } + text +} + +type Field = (&'static str, &'static str, &'static str); + +/// Help text only: what the add-on's `execute_command` dispatches and reads at the base commit. +const ACTIONS: &[(&str, &[Field])] = &[ + ( + "createObject", + &[ + ("objectType", "string", "MESH | LIGHT | CAMERA | EMPTY (default EMPTY)"), + ("name", "string", ""), + ("location", "[x,y,z]", ""), + ("size", "number", "MESH"), + ("meshType", "string", "CUBE"), + ("lightType", "string", "LIGHT"), + ("emptyDisplayType", "string", "EMPTY"), + ], + ), + ("deleteObject", &[("targetObjectName", "string", "")]), + ( + "setObjectTransform", + &[ + ("targetObjectName", "string", ""), + ("location", "[x,y,z]", ""), + ("rotationEuler", "[x,y,z]", "radians"), + ("scale", "[x,y,z]", ""), + ], + ), + ( + "setObjectVisibility", + &[("targetObjectName", "string", ""), ("visible", "bool", "")], + ), + ( + "setObjectParent", + &[ + ("targetObjectName", "string", ""), + ("parentObjectName", "string", "empty clears the parent"), + ], + ), + ( + "setObjectCustomProperty", + &[ + ("targetObjectName", "string", ""), + ("propertyName", "string", ""), + ("value", "json", ""), + ], + ), + ( + "selectObject", + &[("targetObjectName", "string", ""), ("clearSelection", "bool", "default true")], + ), + ( + "assignMaterial", + &[ + ("targetObjectName", "string", ""), + ("materialName", "string", ""), + ("color", "[r,g,b] or [r,g,b,a]", "linear, 0..1"), + ], + ), + ( + "importGltf", + &[("filepath", "string", "inside the add-on's import directory")], + ), + ( + "exportGltf", + &[ + ("filepath", "string", ".glb or .gltf inside the add-on's output directory"), + ("extras", "bool", ""), + ("yUp", "bool", ""), + ("applyModifiers", "bool", ""), + ("selection", "[string]", "object names"), + ], + ), + ( + "setCamera", + &[ + ("targetObjectName", "string", ""), + ("lens", "number", "mm"), + ("cameraType", "string", ""), + ("orthoScale", "number", ""), + ("clipStart", "number", ""), + ("clipEnd", "number", ""), + ("panoramaType", "string", ""), + ("active", "bool", "make it the scene camera"), + ], + ), + ( + "setLight", + &[ + ("targetObjectName", "string", ""), + ("energy", "number", ""), + ("color", "[r,g,b]", "linear, 0..1"), + ("lightType", "string", ""), + ], + ), + ( + "setWorld", + &[ + ("worldName", "string", ""), + ("color", "[r,g,b]", "linear, 0..1"), + ("strength", "number", ""), + ], + ), + ( + "renderStill", + &[ + ("outputPath", "string", "inside the add-on's output directory"), + ("engine", "string", ""), + ("resolutionX", "integer", ""), + ("resolutionY", "integer", ""), + ("cameraName", "string", ""), + ], + ), + ( + "createNodeGroup", + &[ + ("treeKey", "string", ""), + ("interface", "[{inOut,name,type,default?}]", "types: Geometry Float Int Bool Vector"), + ], + ), + ( + "addNode", + &[ + ("treeKey", "string", ""), + ("id", "string", "brokkr's key for the node"), + ("blIdname", "string", "GeometryNode*, FunctionNode* or ShaderNode*"), + ("location", "[x,y]", ""), + ("label", "string", ""), + ("properties", "object", "enum, bool, int or float node settings"), + ("inputs", "object", "unlinked input defaults"), + ], + ), + ("removeNode", &[("treeKey", "string", ""), ("id", "string", "")]), + ( + "linkSockets", + &[ + ("treeKey", "string", ""), + ("fromNode", "string", ""), + ("fromSocket", "string", ""), + ("toNode", "string", ""), + ("toSocket", "string", ""), + ], + ), + ( + "unlinkSockets", + &[ + ("treeKey", "string", ""), + ("toNode", "string", ""), + ("toSocket", "string", ""), + ("fromNode", "string", "optional"), + ("fromSocket", "string", "optional"), + ], + ), + ( + "addModifier", + &[ + ("objectName", "string", ""), + ("treeKey", "string", ""), + ("modifierName", "string", "default Brokkr GeoNodes"), + ], + ), + ( + "removeModifier", + &[("objectName", "string", ""), ("modifierName", "string", "")], + ), + ( + "setModifierInput", + &[ + ("objectName", "string", ""), + ("modifierName", "string", ""), + ("socket", "string", "identifier or unique interface name"), + ("value", "json", "Float, Int, Bool or Vector"), + ], + ), +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn iso_matches_the_python_form() { + assert_eq!(iso_from(0, 0), "1970-01-01T00:00:00.000000+00:00"); + assert_eq!(iso_from(1_795_800_558, 813_099), "2026-11-27T17:29:18.813099+00:00"); + } + + #[test] + fn intent_carries_reserved_fields_and_refuses_overrides() { + let sets = vec!["objectType=\"MESH\"".to_string(), "location=[0,0,1]".to_string()]; + let intent = build_intent("createObject", "abc", "nibu/hands", "n", &sets).unwrap(); + assert_eq!(intent["requestedBy"], "nibu/hands"); + assert_eq!(intent["objectType"], "MESH"); + assert_eq!(intent["location"][2], 1); + for bad in ["requestedBy=\"x\"", "commandId=\"x\"", "action=\"x\"", "novalue", "k=notjson"] { + assert!( + build_intent("createObject", "abc", "a/b", "", &[bad.to_string()]).is_err(), + "{bad}" + ); + } + assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err()); + } + + #[test] + fn statuses_map_to_exit_codes() { + for (status, code) in [("accepted", 0), ("denied", 2), ("failed", 2), ("stopped", 3), ("weird", 2)] { + assert_eq!(Outcome::from_status(status).code(), code, "{status}"); + } + assert_eq!(Outcome::Timeout.code(), 4); + } +} diff --git a/brokkr-ctl/src/main.rs b/brokkr-ctl/src/main.rs new file mode 100644 index 0000000..1fc3dd8 --- /dev/null +++ b/brokkr-ctl/src/main.rs @@ -0,0 +1,24 @@ +//! brokkr-ctl: command-line hands for Brokkr's creative-tool surfaces. + +mod blender; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let code = match args.split_first() { + Some((group, rest)) if group == "blender" => blender::run(rest), + Some((flag, _)) if matches!(flag.as_str(), "--help" | "-h" | "help") => { + print!( + "brokkr-ctl ...\n\ngroups:\n blender send intents to the live Blender add-on (`brokkr-ctl blender --help`)\n" + ); + Ok(0) + } + _ => Err(anyhow::anyhow!("usage: brokkr-ctl blender ...")), + }; + match code { + Ok(code) => std::process::exit(code), + Err(error) => { + eprintln!("error: {error:#}"); + std::process::exit(1); + } + } +} diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs new file mode 100644 index 0000000..a9cee07 --- /dev/null +++ b/brokkr-ctl/tests/cli.rs @@ -0,0 +1,154 @@ +//! brokkr-ctl against a real single-file store, read back through cultcache-rs. + +use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, SingleFileMessagePackBackingStore}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +const INTENT: &str = "brokkr.blender.command_intent.v0"; +const RECEIPT: &str = "brokkr.blender.command_receipt.v0"; + +fn envelope(schema: &str, key: &str, payload: &Value) -> CultCacheEnvelope { + CultCacheEnvelope { + key: key.to_string(), + r#type: schema.to_string(), + payload: serde_json::to_vec(payload).unwrap(), + stored_at: "2026-11-27T00:00:00.000000+00:00".to_string(), + schema_id: Some(schema.to_string()), + } +} + +/// A store the way the add-on leaves it: a file that already exists, holding other records. +fn store_with_receipts(dir: &Path, statuses: &[(&str, &str)]) -> PathBuf { + let path = dir.join("blender-editor.ccmp"); + let mut store = SingleFileMessagePackBackingStore::new(&path); + for (id, status) in statuses { + let receipt = json!({"schema": RECEIPT, "commandId": id, "status": status, "observedAt": "2026-11-27T00:00:00+00:00"}); + store + .push(&envelope(RECEIPT, &format!("blender/receipts/{id}"), &receipt)) + .unwrap(); + } + path +} + +fn ctl(store: &Path, args: &[&str], instance: Option<&str>) -> Output { + let mut command = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")); + command + .arg("blender") + .args(args) + .arg("--store") + .arg(store) + .env_remove("BROKKR_AGENT") + .env_remove("BROKKR_BLENDER_STORE") + .env_remove("EUREKA_INSTANCE"); + if let Some(instance) = instance { + command.env("EUREKA_INSTANCE", instance); + } + command.output().unwrap() +} + +fn stdout(output: &Output) -> String { + String::from_utf8_lossy(&output.stdout).into_owned() +} + +#[test] +fn send_writes_a_pullable_intent() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let output = ctl( + &path, + &["send", "createObject", "--set", "objectType=\"MESH\"", "--set", "location=[0,0,1]", "--note", "a cube", "--agent", "hands", "--no-wait"], + Some("nibu"), + ); + assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr)); + let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string(); + assert_eq!(id.len(), 32); + + let envelopes = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + let intent = envelopes + .iter() + .find(|e| e.key == format!("blender/commands/{id}")) + .expect("intent key"); + assert_eq!(intent.r#type, INTENT); + assert_eq!(intent.schema_id.as_deref(), Some(INTENT)); + let payload: Value = serde_json::from_slice(&intent.payload).unwrap(); + assert_eq!( + payload, + json!({"schema": INTENT, "commandId": id, "action": "createObject", "requestedBy": "nibu/hands", + "note": "a cube", "objectType": "MESH", "location": [0, 0, 1]}) + ); + assert!(envelopes.iter().any(|e| e.key == "blender/receipts/seed"), "other records survive the write"); +} + +#[test] +fn an_intent_without_instance_or_agent_is_refused_and_writes_nothing() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let before = std::fs::read(&path).unwrap(); + for (instance, agent) in [(None, Some("hands")), (Some("nibu"), None), (None, None), (Some(" "), Some("hands"))] { + let mut args = vec!["send", "createObject", "--no-wait"]; + if let Some(agent) = agent { + args.extend(["--agent", agent]); + } + let output = ctl(&path, &args, instance); + assert_eq!(output.status.code(), Some(1), "{instance:?} {agent:?}"); + } + assert_eq!(std::fs::read(&path).unwrap(), before); +} + +#[test] +fn a_missing_store_is_not_created() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("nope.ccmp"); + let output = ctl(&path, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(1)); + assert!(!path.exists()); +} + +#[test] +fn exit_code_follows_the_receipt() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts( + dir.path(), + &[("a", "accepted"), ("d", "denied"), ("f", "failed"), ("s", "stopped")], + ); + for (id, code) in [("a", 0), ("d", 2), ("f", 2), ("s", 3)] { + let output = ctl(&path, &["wait", id, "--timeout", "5"], None); + assert_eq!(output.status.code(), Some(code), "{id}"); + assert!(stdout(&output).contains(&format!("commandId: {id}"))); + } + let output = ctl(&path, &["wait", "missing", "--timeout", "0.3"], None); + assert_eq!(output.status.code(), Some(4)); + assert!(stdout(&output).contains("status: timeout")); +} + +#[test] +fn receipts_lists_the_last_n_oldest_first() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted"), ("b", "failed")]); + let output = ctl(&path, &["receipts"], None); + assert_eq!(output.status.code(), Some(0)); + let text = stdout(&output); + assert!(text.contains("commandId: a") && text.contains("commandId: b")); + let one = ctl(&path, &["receipts", "--last", "1"], None); + assert!(!stdout(&one).contains("commandId: a")); +} + +#[test] +fn status_without_a_snapshot_is_a_store_error() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + assert_eq!(ctl(&path, &["status"], None).status.code(), Some(1)); +} + +#[test] +fn send_help_lists_the_actions() { + let output = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")) + .args(["blender", "send", "--help"]) + .output() + .unwrap(); + let text = stdout(&output); + for action in ["createObject", "renderStill", "setModifierInput", "exportGltf"] { + assert!(text.contains(action), "{action}"); + } +} diff --git a/brokkr-daemon/Cargo.toml b/brokkr-daemon/Cargo.toml index 58bbccf..77fce12 100644 --- a/brokkr-daemon/Cargo.toml +++ b/brokkr-daemon/Cargo.toml @@ -6,7 +6,7 @@ publish = false [dependencies] anyhow = "1" -cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" } +cultcache-rs = { workspace = true } rmp-serde = "1.3" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/surfaces/blender/tests/test_brokkr_ctl_interop.py b/surfaces/blender/tests/test_brokkr_ctl_interop.py new file mode 100644 index 0000000..92bef5a --- /dev/null +++ b/surfaces/blender/tests/test_brokkr_ctl_interop.py @@ -0,0 +1,73 @@ +"""brokkr-ctl writes an intent a cultmesh-py node pulls as the same dict, and reads a node's receipt. + +No Blender. Needs CultLib's Python packages (CULTLIB_PACKAGES, the packages directory) and the built +binary (BROKKR_CTL, the path to brokkr-ctl or brokkr-ctl.exe); skipped when either is missing. +""" +from __future__ import annotations + +import os +import subprocess +import sys +import tempfile +import types +import unittest +from pathlib import Path + +ADDON = Path(__file__).resolve().parents[1] / "brokkr_bridge" +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(ADDON)] +sys.modules.setdefault("brokkr_bridge", package) + +from brokkr_bridge import blender_target as bt # noqa: E402 + +PACKAGES = os.environ.get("CULTLIB_PACKAGES", "") +CTL = os.environ.get("BROKKR_CTL", "") + + +@unittest.skipUnless(PACKAGES and Path(PACKAGES).is_dir(), "set CULTLIB_PACKAGES to CultLib's packages directory") +@unittest.skipUnless(CTL and Path(CTL).is_file(), "set BROKKR_CTL to the built brokkr-ctl binary") +class BrokkrCtlInterop(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.store = str(Path(self.tmp.name) / "blender-editor.ccmp") + self.cultmesh, self.cultcache = bt._load_cultmesh(PACKAGES) + self.node = self.cultmesh.CultMesh.start_node(self.store, runtime_id="addon") + self.intent = self.cultcache.define_document_type(bt.COMMAND_INTENT_SCHEMA) + self.receipt = self.cultcache.define_document_type(bt.COMMAND_RECEIPT_SCHEMA) + self.node.database.register_document(self.intent) + self.node.database.register_document(self.receipt) + # The add-on's own first write is what creates its store file. + self.node.database.put(self.receipt, "blender/receipts/seed", { + "schema": bt.COMMAND_RECEIPT_SCHEMA, "commandId": "seed", "status": "accepted"}) + + def ctl(self, *args): + env = dict(os.environ, EUREKA_INSTANCE="nibu") + env.pop("BROKKR_AGENT", None) + return subprocess.run([CTL, "blender", *args, "--store", self.store], env=env, + capture_output=True, text=True, timeout=60) + + def test_a_node_pulls_the_intent_as_the_dict_ctl_wrote(self): + sent = self.ctl("send", "createObject", "--set", 'objectType="MESH"', "--set", "location=[0,0,1]", + "--note", "a cube", "--agent", "hands", "--no-wait") + self.assertEqual(sent.returncode, 0, sent.stderr) + command_id = sent.stdout.split("commandId:")[1].split()[0] + self.node.database.pull() + got = self.node.database.snapshot()[bt.COMMAND_INTENT_SCHEMA][f"blender/commands/{command_id}"] + self.assertEqual(got, { + "schema": bt.COMMAND_INTENT_SCHEMA, "commandId": command_id, "action": "createObject", + "requestedBy": "nibu/hands", "note": "a cube", "objectType": "MESH", "location": [0, 0, 1]}) + # The node's own earlier record is still there after the Rust whole-store write. + self.assertIn("blender/receipts/seed", self.node.database.snapshot()[bt.COMMAND_RECEIPT_SCHEMA]) + + def test_ctl_reads_a_receipt_the_node_wrote(self): + self.node.database.put(self.receipt, "blender/receipts/r1", { + "schema": bt.COMMAND_RECEIPT_SCHEMA, "commandId": "r1", "action": "createObject", + "status": "failed", "message": "refused"}) + waited = self.ctl("wait", "r1", "--timeout", "5") + self.assertEqual(waited.returncode, 2, waited.stderr) + self.assertIn("message: refused", waited.stdout) + + +if __name__ == "__main__": + unittest.main() From ef7086971c268e6e3e0f4958e07ac012e17ca761 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 18:54:21 +0100 Subject: [PATCH 025/223] brokkr-ctl: time-ordered ids, stat-gated polling, parsed help flag, bounded timeout, absolute unlinked store, pinned survivors Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/Cargo.toml | 2 +- brokkr-ctl/src/blender.rs | 94 +++++++++++++++++---- brokkr-ctl/tests/cli.rs | 168 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 249 insertions(+), 15 deletions(-) diff --git a/brokkr-ctl/Cargo.toml b/brokkr-ctl/Cargo.toml index cff9015..ce74ab3 100644 --- a/brokkr-ctl/Cargo.toml +++ b/brokkr-ctl/Cargo.toml @@ -8,7 +8,7 @@ publish = false anyhow = "1" cultcache-rs = { workspace = true } serde_json = "1" -uuid = { version = "1", features = ["v4"] } +uuid = { version = "1", features = ["v7"] } [dev-dependencies] tempfile = "3" diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index d054357..c35148b 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -15,8 +15,11 @@ const INTENT_PREFIX: &str = "blender/commands/"; const RECEIPT_PREFIX: &str = "blender/receipts/"; const SNAPSHOT_KEY: &str = "blender/host/current"; const RESERVED: [&str; 5] = ["schema", "commandId", "action", "requestedBy", "note"]; -const DEFAULT_TIMEOUT_SECS: f64 = 60.0; +const DEFAULT_TIMEOUT_SECS: u64 = 60; const POLL: Duration = Duration::from_millis(200); +const MAX_TIMEOUT: Duration = Duration::from_secs(24 * 3600); +/// Even when the file looks unchanged, read it again this often. +const RECHECK: Duration = Duration::from_secs(5); /// What a receipt (or its absence) says; the exit code derives from it and from nothing else. pub enum Outcome { @@ -52,7 +55,8 @@ struct Options { note: String, sets: Vec, no_wait: bool, - timeout: Option, + timeout: Option, + help: bool, last: Option, positional: Vec, } @@ -72,15 +76,20 @@ fn parse(args: &[String]) -> Result { "--note" => options.note = value("--note")?, "--set" => options.sets.push(value("--set")?), "--no-wait" => options.no_wait = true, + "--help" | "-h" => options.help = true, "--timeout" => { let raw = value("--timeout")?; let secs: f64 = raw .parse() .map_err(|_| anyhow!("--timeout wants seconds, got {raw:?}"))?; - if !secs.is_finite() || secs < 0.0 { - bail!("--timeout wants a non-negative number of seconds"); - } - options.timeout = Some(secs); + options.timeout = Some( + Duration::try_from_secs_f64(secs) + .ok() + .filter(|limit| *limit <= MAX_TIMEOUT) + .ok_or_else(|| { + anyhow!("--timeout wants seconds between 0 and {}", MAX_TIMEOUT.as_secs()) + })?, + ); } "--last" => { let raw = value("--last")?; @@ -106,11 +115,11 @@ pub fn run(args: &[String]) -> Result { print!("{}", group_help()); return Ok(0); } - if rest.iter().any(|arg| arg == "--help" || arg == "-h") { + let options = parse(rest)?; + if options.help { print!("{}", if sub == "send" { send_help() } else { group_help() }); return Ok(0); } - let options = parse(rest)?; match sub.as_str() { "send" => send(&options), "wait" => { @@ -132,7 +141,7 @@ fn one_positional<'a>(options: &'a Options, usage: &str) -> Result<&'a str> { } fn timeout(options: &Options) -> Duration { - Duration::from_secs_f64(options.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS)) + options.timeout.unwrap_or(Duration::from_secs(DEFAULT_TIMEOUT_SECS)) } /// The add-on creates its store; naming a path that is not there is a typo, not a request @@ -143,11 +152,17 @@ fn open_store(options: &Options) -> Result { .clone() .or_else(|| std::env::var_os("BROKKR_BLENDER_STORE").map(PathBuf::from)) .ok_or_else(|| anyhow!("no store: pass --store or set BROKKR_BLENDER_STORE"))?; - if !path.is_file() { - bail!("store {} does not exist; the add-on creates it", path.display()); + // The add-on resolves its store against the blend file; ctl cannot know that, so it takes none. + if !path.is_absolute() { + bail!("store {} must be an absolute path", path.display()); } - // The store library stages writes beside the file and fails on a bare file name. - Ok(SingleFileMessagePackBackingStore::new(std::path::absolute(path)?)) + // A staged replace swaps the path itself, which would turn a link into a diverged copy. + let meta = std::fs::symlink_metadata(&path) + .map_err(|_| anyhow!("store {} does not exist; the add-on creates it", path.display()))?; + if meta.file_type().is_symlink() || !meta.is_file() { + bail!("store {} must be the add-on's regular file, not a link", path.display()); + } + Ok(SingleFileMessagePackBackingStore::new(path)) } fn requested_by(options: &Options) -> Result { @@ -197,7 +212,7 @@ fn send(options: &Options) -> Result { let action = one_positional(options, "send [--set key=json]...")?; let requested_by = requested_by(options)?; let mut store = open_store(options)?; - let command_id = uuid::Uuid::new_v4().simple().to_string(); + let command_id = uuid::Uuid::now_v7().simple().to_string(); let intent = build_intent(action, &command_id, &requested_by, &options.note, &options.sets)?; store.push(&CultCacheEnvelope { key: format!("{INTENT_PREFIX}{command_id}"), @@ -229,7 +244,16 @@ fn wait_for_receipt( limit: Duration, ) -> Result { let started = Instant::now(); + let mut gate = ChangeGate::new(store.path()); loop { + if !gate.should_read() { + if started.elapsed() >= limit { + println!("status: timeout"); + return Ok(Outcome::Timeout.code()); + } + thread::sleep(POLL); + continue; + } if let Some(receipt) = read_receipt(store, id)? { print_fields(&receipt); let status = receipt.get("status").and_then(Value::as_str).unwrap_or(""); @@ -243,6 +267,32 @@ fn wait_for_receipt( } } +/// Polling must not hold the store: a read takes the shared lock and an open handle, and on +/// Windows that can make the add-on's replace fail. So the file's stat is polled and the store +/// is read only after it changed (and every RECHECK as a backstop). +pub struct ChangeGate { + path: PathBuf, + seen: Option<(u64, Option)>, + last_read: Option, +} + +impl ChangeGate { + pub fn new(path: &std::path::Path) -> Self { + Self { path: path.to_path_buf(), seen: None, last_read: None } + } + + pub fn should_read(&mut self) -> bool { + let stamp = std::fs::metadata(&self.path).ok().map(|m| (m.len(), m.modified().ok())); + let stale = self.last_read.is_none_or(|at| at.elapsed() >= RECHECK); + if self.seen.is_none() || stamp != self.seen || stale { + self.seen = stamp; + self.last_read = Some(Instant::now()); + return true; + } + false + } +} + fn receipts(store: &SingleFileMessagePackBackingStore, last: Option) -> Result { let mut found = Vec::new(); for envelope in store.pull_all()? { @@ -578,6 +628,22 @@ mod tests { assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err()); } + #[test] + fn the_gate_reads_first_then_only_after_the_file_changes() { + let dir = std::env::temp_dir().join(format!("brokkr-gate-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("s.ccmp"); + std::fs::write(&file, b"one").unwrap(); + let mut gate = ChangeGate::new(&file); + assert!(gate.should_read()); + assert!(!gate.should_read()); + assert!(!gate.should_read()); + std::fs::write(&file, b"three").unwrap(); + assert!(gate.should_read()); + assert!(!gate.should_read()); + std::fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn statuses_map_to_exit_codes() { for (status, code) in [("accepted", 0), ("denied", 2), ("failed", 2), ("stopped", 3), ("weird", 2)] { diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index a9cee07..a6e2ced 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -152,3 +152,171 @@ fn send_help_lists_the_actions() { assert!(text.contains(action), "{action}"); } } + +fn envelope_at(schema: &str, key: &str, payload: &Value) -> CultCacheEnvelope { + envelope(schema, key, payload) +} + +fn push(path: &Path, entries: &[CultCacheEnvelope]) { + let mut store = SingleFileMessagePackBackingStore::new(path); + for entry in entries { + store.push(entry).unwrap(); + } +} + +#[test] +fn intents_sent_in_order_sort_in_send_order() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let mut sent = Vec::new(); + for _ in 0..8 { + let output = ctl(&path, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(0)); + sent.push(format!("blender/commands/{}", stdout(&output).trim().strip_prefix("commandId: ").unwrap())); + } + let mut sorted = sent.clone(); + sorted.sort(); + assert_eq!(sent, sorted, "the add-on drains by sorted key"); +} + +#[test] +fn an_absurd_timeout_is_a_usage_error_not_a_panic() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + for value in ["1e300", "inf", "nan", "-1", "abc"] { + let output = ctl(&path, &["wait", "x", "--timeout", value], None); + assert_eq!(output.status.code(), Some(1), "{value}"); + } +} + +#[test] +fn help_words_as_option_values_do_not_swallow_the_command() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let output = ctl( + &path, + &["send", "createObject", "--note", "-h", "--agent", "--help", "--no-wait"], + Some("nibu"), + ); + assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr)); + let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string(); + let found = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + let intent = found.iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap(); + let payload: Value = serde_json::from_slice(&intent.payload).unwrap(); + assert_eq!(payload["note"], "-h"); + assert_eq!(payload["requestedBy"], "nibu/--help"); + // a real help flag still prints help and sends nothing + let help = ctl(&path, &["send", "createObject", "--help"], Some("nibu")); + assert_eq!(help.status.code(), Some(0)); + assert!(stdout(&help).contains("actions:")); +} + +#[test] +fn a_relative_store_path_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let output = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")) + .current_dir(dir.path()) + .args(["blender", "receipts", "--store", path.file_name().unwrap().to_str().unwrap()]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("absolute")); +} + +#[test] +fn a_symlinked_store_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let link = dir.path().join("link.ccmp"); + #[cfg(windows)] + let made = std::os::windows::fs::symlink_file(&path, &link); + #[cfg(unix)] + let made = std::os::unix::fs::symlink(&path, &link); + if made.is_err() { + eprintln!("skipped: no symlink privilege"); + return; + } + assert_eq!(ctl(&link, &["receipts"], None).status.code(), Some(1)); +} + +#[test] +fn receipts_only_come_from_the_receipt_keys_and_type() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("real", "accepted")]); + let fake = json!({"commandId": "fake", "status": "accepted"}); + push( + &path, + &[ + envelope_at(RECEIPT, "elsewhere/fake", &fake), + envelope_at(INTENT, "blender/receipts/wrongtype", &fake), + ], + ); + let listed = stdout(&ctl(&path, &["receipts"], None)); + assert!(listed.contains("commandId: real")); + assert!(!listed.contains("fake"), "{listed}"); + let waited = ctl(&path, &["wait", "wrongtype", "--timeout", "0.3"], None); + assert_eq!(waited.status.code(), Some(4)); +} + +#[test] +fn receipts_sort_by_observed_time_not_by_key() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + push( + &path, + &[ + envelope_at(RECEIPT, "blender/receipts/a", &json!({"commandId": "a", "observedAt": "2026-11-27T10:00:02+00:00"})), + envelope_at(RECEIPT, "blender/receipts/b", &json!({"commandId": "b", "observedAt": "2026-11-27T10:00:01+00:00"})), + ], + ); + let text = stdout(&ctl(&path, &["receipts"], None)); + assert!(text.find("commandId: b").unwrap() < text.find("commandId: a").unwrap(), "{text}"); +} + +#[test] +fn status_prints_the_snapshot_summary() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + let snapshot = json!({"mode": "OBJECT", "activeScene": "Scene", "objectCount": 3, "selectedObjectNames": ["Cube"], "sink": {"enabled": true}}); + push(&path, &[envelope_at("brokkr.blender.host_snapshot.v0", "blender/host/current", &snapshot)]); + let output = ctl(&path, &["status"], None); + assert_eq!(output.status.code(), Some(0)); + let text = stdout(&output); + for line in ["mode: OBJECT", "activeScene: Scene", "objectCount: 3", "selectedObjectNames: [\"Cube\"]", "sink: {\"enabled\":true}"] { + assert!(text.contains(line), "{line} in {text}"); + } +} + +/// A pin, not a copy: every action the add-on dispatches is in `send --help`, and every help field +/// name is a string the add-on source mentions. The add-on has no machine-readable action table. +#[test] +fn help_names_every_dispatched_action_and_only_fields_the_addon_mentions() { + let addon = Path::new(env!("CARGO_MANIFEST_DIR")).join("../surfaces/blender/brokkr_bridge"); + let source: String = ["blender_target.py", "node_actions.py", "scene_actions.py"] + .iter() + .map(|file| std::fs::read_to_string(addon.join(file)).unwrap()) + .collect(); + let help = stdout( + &Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")).args(["blender", "send", "--help"]).output().unwrap(), + ); + let mut dispatched: Vec = source + .lines() + .filter_map(|line| line.trim().strip_prefix("if action == \"")) + .filter_map(|rest| rest.split('"').next()) + .map(String::from) + .collect(); + let actions_line = source.lines().find(|l| l.contains("ACTIONS = (\"")).unwrap(); + dispatched.extend(actions_line.split('"').skip(1).step_by(2).map(String::from)); + assert!(dispatched.len() >= 20, "{dispatched:?}"); + let listed: Vec<&str> = help.lines().filter_map(|l| l.strip_prefix(" ")).filter(|l| !l.starts_with(' ')).collect(); + for action in &dispatched { + assert!(listed.contains(&action.as_str()), "help lacks {action}"); + } + for action in &listed { + assert!(dispatched.iter().any(|d| d == action) || *action == "actions:", "help lists unknown {action}"); + } + for field in help.lines().filter_map(|l| l.strip_prefix(" ")).filter_map(|l| l.split(':').next()) { + assert!(source.contains(&format!("\"{field}\"")), "add-on never mentions {field}"); + } +} From 0f4ab2d0d95b3beca52c4c38858f1ce0aeb80edb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:08:02 +0100 Subject: [PATCH 026/223] brokkr-ctl on MessagePack payloads: reads through cultcache_rs::decode_payload, one MessagePack value per write, tests off JSON Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 12 ++++++++++++ brokkr-ctl/Cargo.toml | 1 + brokkr-ctl/src/blender.rs | 6 +++--- brokkr-ctl/tests/cli.rs | 17 ++++++++++++++--- 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index dabf833..f01e20a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -47,6 +47,18 @@ dependencies = [ "generic-array", ] +[[package]] +name = "brokkr-ctl" +version = "0.1.0" +dependencies = [ + "anyhow", + "cultcache-rs", + "rmp-serde", + "serde_json", + "tempfile", + "uuid", +] + [[package]] name = "brokkr-daemon" version = "0.1.0" diff --git a/brokkr-ctl/Cargo.toml b/brokkr-ctl/Cargo.toml index ce74ab3..4470cd6 100644 --- a/brokkr-ctl/Cargo.toml +++ b/brokkr-ctl/Cargo.toml @@ -7,6 +7,7 @@ publish = false [dependencies] anyhow = "1" cultcache-rs = { workspace = true } +rmp-serde = "1.3" serde_json = "1" uuid = { version = "1", features = ["v7"] } diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index c35148b..c342e91 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -217,7 +217,7 @@ fn send(options: &Options) -> Result { store.push(&CultCacheEnvelope { key: format!("{INTENT_PREFIX}{command_id}"), r#type: INTENT_SCHEMA.to_string(), - payload: serde_json::to_vec(&intent)?, + payload: rmp_serde::to_vec(&intent)?, stored_at: iso_now(), schema_id: Some(INTENT_SCHEMA.to_string()), })?; @@ -343,8 +343,8 @@ fn status(store: &SingleFileMessagePackBackingStore) -> Result { } fn decode(envelope: &CultCacheEnvelope) -> Result { - serde_json::from_slice(&envelope.payload) - .with_context(|| format!("{} is not a JSON map payload", envelope.key)) + cultcache_rs::decode_payload::(&envelope.payload) + .with_context(|| format!("{} is not one MessagePack value", envelope.key)) } fn print_fields(value: &Value) { diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index a6e2ced..072ae2a 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -12,7 +12,7 @@ fn envelope(schema: &str, key: &str, payload: &Value) -> CultCacheEnvelope { CultCacheEnvelope { key: key.to_string(), r#type: schema.to_string(), - payload: serde_json::to_vec(payload).unwrap(), + payload: rmp_serde::to_vec(payload).unwrap(), stored_at: "2026-11-27T00:00:00.000000+00:00".to_string(), schema_id: Some(schema.to_string()), } @@ -71,7 +71,7 @@ fn send_writes_a_pullable_intent() { .expect("intent key"); assert_eq!(intent.r#type, INTENT); assert_eq!(intent.schema_id.as_deref(), Some(INTENT)); - let payload: Value = serde_json::from_slice(&intent.payload).unwrap(); + let payload: Value = cultcache_rs::decode_payload(&intent.payload).unwrap(); assert_eq!( payload, json!({"schema": INTENT, "commandId": id, "action": "createObject", "requestedBy": "nibu/hands", @@ -202,7 +202,7 @@ fn help_words_as_option_values_do_not_swallow_the_command() { let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string(); let found = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); let intent = found.iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap(); - let payload: Value = serde_json::from_slice(&intent.payload).unwrap(); + let payload: Value = cultcache_rs::decode_payload(&intent.payload).unwrap(); assert_eq!(payload["note"], "-h"); assert_eq!(payload["requestedBy"], "nibu/--help"); // a real help flag still prints help and sends nothing @@ -320,3 +320,14 @@ fn help_names_every_dispatched_action_and_only_fields_the_addon_mentions() { assert!(source.contains(&format!("\"{field}\"")), "add-on never mentions {field}"); } } + +#[test] +fn a_json_payload_is_refused_not_guessed() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + let mut json_receipt = envelope(RECEIPT, "blender/receipts/j", &json!({"commandId": "j", "status": "accepted"})); + json_receipt.payload = serde_json::to_vec(&json!({"commandId": "j", "status": "accepted"})).unwrap(); + push(&path, &[json_receipt]); + let output = ctl(&path, &["wait", "j", "--timeout", "1"], None); + assert_eq!(output.status.code(), Some(1)); +} From 741e186c5a643b600c563d21eaf9a7d92b6fdb54 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:30:20 +0100 Subject: [PATCH 027/223] Blender: cut the debug-mirror JSON intent door; one admission shape fix Intents now enter only through the node (brokkr-ctl, a served peer, the sync organ). _import_debug_command_files, the debug-root glob in purge_command_intents and start_server's debug-root parameter are deleted; Debug Export Root stays export-only. Also live-2-lows: COMMAND_ID_SHAPE and REQUESTED_BY_SHAPE use fullmatch (a trailing newline passed), and _load_cultmesh's own-package set is pinned. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- docs/live-collab-target.md | 4 +- surfaces/blender/brokkr_bridge/__init__.py | 3 +- .../blender/brokkr_bridge/blender_target.py | 32 +++----- .../blender/brokkr_bridge/server_guard.py | 10 +-- surfaces/blender/docs/install.md | 19 +++-- .../blender/tests/live/agent_turn_queue.py | 13 +++- surfaces/blender/tests/test_agent_turn.py | 38 ++++++++++ surfaces/blender/tests/test_server_guard.py | 76 +++++++------------ 9 files changed, 101 insertions(+), 96 deletions(-) diff --git a/README.md b/README.md index c42f6ea..e0be8d0 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ broker. - `surfaces/unity/Packages/com.gamecult.brokkr`: Unity editor package scaffold. - `surfaces/blender/brokkr_bridge`: Blender add-on target backed by - CultLib's Python CultMesh node/server, with optional debug export/import + CultLib's Python CultMesh node/server, with an optional debug export probes. - `brokkr-command`: .NET CLI that writes one Unity command intent through the project's directory store and reports the editor's receipt (`docs/provider-contract.md`). diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index aee7181..fcfedaa 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -236,8 +236,8 @@ are the primitive for the push. collections (an edit buffer over the `.cc`); the stdin dump (a pipe, not state). - **Forbidden writers.** `execute_command` called around the primitive; operators run with undo on inside an agent action; unpushed agent writes; `ed.undo`/`ed.redo` from - add-on code; any agent-sent Python; the debug-mirror JSON import as a door for intents - (`blender_target.py` `_import_debug_command_files`); `brokkr-ctl` deciding anything; + add-on code; any agent-sent Python; any reader that turns a file under + the debug-mirror root into an intent (removed in cut-live-1); `brokkr-ctl` deciding anything; `ship_cc.py`'s envelope writes and any other direct `.cc` writer; `layout_revision` as a revision. - **Shared paths.** brokkr-ctl intents, panel buttons that act on the scene, sync-organ diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index e2bcbe8..8a81707 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -58,7 +58,7 @@ class BrokkrPreferences(bpy.types.AddonPreferences): name="Debug Export Root", subtype="DIR_PATH", default=DEFAULT_DEBUG_MIRROR_ROOT, - description="Optional JSON debug export/import root; CultMesh remains the mirror owner", + description="Optional JSON debug export root (export only); CultMesh remains the mirror owner", ) import_dir: bpy.props.StringProperty( @@ -476,7 +476,6 @@ class BROKKR_OT_start_server(bpy.types.Operator): prefs.serve_port, prefs.max_snapshot_documents, prefs.max_snapshot_bytes, - prefs.debug_mirror_root, prefs.allow_non_loopback, prefs.require_session_token, ) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 3ed2dcf..8684e8e 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -109,11 +109,11 @@ class BrokkrBlenderTarget: self._server: Any | None = None self._guard: SessionGuard | None = None self._cultmesh_module: str = "" - self._debug_mirror_root: str = "" self.import_dir: str = "" self.output_dir: str = "" self.nodes = na.NodeActions(bpy_module) self.agent_turn = False # true only inside run_intent + self._wrote = True # run_intent: false when an accepted action changed nothing self._receipted: set[str] = set() def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: @@ -150,9 +150,6 @@ class BrokkrBlenderTarget: debug_mirror_root: str = "", ) -> list[dict[str, Any]]: node, documents = self._open_node(cache_path, cultlib_py_src) - if debug_mirror_root: - self._import_debug_command_files(node, documents["command_intent"], debug_mirror_root) - snapshot = node.database.snapshot() commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] @@ -365,7 +362,6 @@ class BrokkrBlenderTarget: port: int, max_snapshot_documents: int, max_snapshot_bytes: int, - debug_mirror_root: str = "", allow_non_loopback: bool = False, require_token: bool = False, ) -> dict[str, Any]: @@ -391,8 +387,7 @@ class BrokkrBlenderTarget: self.stop_server() self._cultmesh_module = "" - self._debug_mirror_root = self.resolve_debug_mirror_root(debug_mirror_root) if debug_mirror_root else "" - purge_command_intents(node, documents["command_intent"], COMMAND_INTENT_SCHEMA, self._debug_mirror_root) + purge_command_intents(node, documents["command_intent"], COMMAND_INTENT_SCHEMA) cultmesh, _cultcache = _load_cultmesh(cultlib_py_src) self._cultmesh_module = str(getattr(cultmesh, "__file__", "") or "") verse_catalog = cultmesh.CultMesh.create_verse_catalog() @@ -463,7 +458,7 @@ class BrokkrBlenderTarget: finally: try: if was_running and self._node is not None: - purge_command_intents(self._node, self._documents["command_intent"], COMMAND_INTENT_SCHEMA, self._debug_mirror_root) + purge_command_intents(self._node, self._documents["command_intent"], COMMAND_INTENT_SCHEMA) finally: self._server = None self._server_key = None @@ -535,7 +530,7 @@ class BrokkrBlenderTarget: denial = "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'." elif command_id in self._receipted: denial = f"commandId {command_id!r} was already receipted; ids are single-use." - elif not isinstance(requested_by, str) or not REQUESTED_BY_SHAPE.match(requested_by): + elif not isinstance(requested_by, str) or not REQUESTED_BY_SHAPE.fullmatch(requested_by): denial = "Intent has no requestedBy of the form '/'." elif action not in MUTATING_ACTIONS and action not in READ_ACTIONS and action not in na.NodeActions.ACTIONS: denial = f"Unsupported Blender command action: {action}" @@ -550,11 +545,12 @@ class BrokkrBlenderTarget: label = f"Brokkr {requested_by}: {action} {command_id[:8]}" push = action not in READ_ACTIONS and action not in NO_SCENE_CHANGE_ACTIONS self.agent_turn = True + self._wrote = True try: try: receipt = self._dispatch(context, command) - if receipt["status"] != "accepted": - push = False # returned a refusal: it wrote nothing + if receipt["status"] != "accepted" or not self._wrote: + push = False # a refusal, or an accepted no-op: it wrote nothing except sa.ActionRefused as error: # raised before any write: nothing to push receipt, push = self._receipt(command, "failed", str(error), ""), False except Exception as error: # a partial write is one undoable step, not part of her next action @@ -621,6 +617,7 @@ class BrokkrBlenderTarget: return self._render_still(context, command) if action in na.NodeActions.ACTIONS: message, name = self.nodes.execute(action, command) + self._wrote = self.nodes.changed return self._receipt(command, "accepted", message, name) return self._receipt(command, "failed", f"Unsupported Blender command action: {action}", "") @@ -1136,17 +1133,6 @@ class BrokkrBlenderTarget: self._documents = documents return node, documents - def _import_debug_command_files(self, node: Any, command_document: Any, debug_mirror_root: str) -> None: - commands_root = Path(self.resolve_debug_mirror_root(debug_mirror_root)) / "blender" / "commands" - for command_path in sorted(commands_root.glob("*.json")): - with command_path.open("r", encoding="utf-8") as handle: - command = json.load(handle) - command_id = command.get("commandId") or command_path.stem - command["schema"] = command.get("schema") or COMMAND_INTENT_SCHEMA - command["commandId"] = command_id - node.database.put(command_document, f"blender/commands/{command_id}", command) - command_path.unlink(missing_ok=True) - def _write_debug_document(self, debug_mirror_root: str, relative_path: str, document: dict[str, Any]) -> None: path = Path(self.resolve_debug_mirror_root(debug_mirror_root)) / relative_path path.parent.mkdir(parents=True, exist_ok=True) @@ -1272,7 +1258,7 @@ def _to_list(value: Any) -> list[float]: def _valid_command_id(value: Any) -> bool: - return isinstance(value, str) and COMMAND_ID_SHAPE.match(value) is not None + return isinstance(value, str) and COMMAND_ID_SHAPE.fullmatch(value) is not None def _vector(value: Any, size: int, fallback: Any) -> tuple[float, ...]: diff --git a/surfaces/blender/brokkr_bridge/server_guard.py b/surfaces/blender/brokkr_bridge/server_guard.py index 0e9d111..0dbba80 100644 --- a/surfaces/blender/brokkr_bridge/server_guard.py +++ b/surfaces/blender/brokkr_bridge/server_guard.py @@ -12,7 +12,6 @@ from __future__ import annotations import hmac import ipaddress import secrets -from pathlib import Path from typing import Any PUT_SCHEMA_VERSIONS = ("cultnet.document_put_raw.v0", "cultnet.document_delete.v0") @@ -91,17 +90,12 @@ def guarded_server_class(base: type, guard: SessionGuard) -> type: return GuardedServer -def purge_command_intents(node: Any, command_document: Any, command_schema: str, debug_mirror_root: str) -> int: - """Delete every queued command intent from the node and every command JSON under - /blender/commands. Returns how many were removed.""" +def purge_command_intents(node: Any, command_document: Any, command_schema: str) -> int: + """Delete every queued command intent from the node. Returns how many were removed.""" removed = 0 if node is not None: node.database.pull() for key in list(node.database.snapshot().get(command_schema, {})): node.database.delete(command_document, key) removed += 1 - if debug_mirror_root: - for path in (Path(debug_mirror_root) / "blender" / "commands").glob("*.json"): - path.unlink(missing_ok=True) - removed += 1 return removed diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 29b1242..f29c195 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -65,8 +65,7 @@ after `Start Server`. Always on: - `Start Server` and `Stop Server` purge queued command intents: every - `brokkr.blender.command_intent.v0` record in the node and every - `blender/commands/*.json` under `Debug Export Root`. Intents queued before a + `brokkr.blender.command_intent.v0` record in the node. Intents queued before a start never run under the new session. - After `Start Server` the panel shows the bind address, port and the file `cultmesh_py` was actually loaded from (its `__file__`, not the preference). @@ -96,9 +95,11 @@ Run the tests (no Blender needed; `CULTLIB_PACKAGES` adds the real-server tests) CULTLIB_PACKAGES=F:/Projects/CultLib/packages python -m unittest discover -s surfaces/blender/tests -v ``` -`Debug Export Root` may still emit readable JSON probe files under -`.brokkr/blender-editor-debug`, but those files are debug/import glue. CultMesh -owns the mirror state. +`Debug Export Root` may still emit readable JSON snapshot and receipt files under +`.brokkr/blender-editor-debug`. They are export only: nothing reads them back, and +a JSON file placed there is never an intent. CultMesh owns the mirror state, and +intents enter only through the node (`brokkr-ctl blender send`, a served peer, the +sync organ). ## Local Smoke @@ -106,11 +107,13 @@ owns the mirror state. 2. Open `View3D > Sidebar > Brokkr`. 3. Click `Capture Snapshot`. 4. Inspect `.brokkr/blender-editor.ccmp`. -5. Drop a command intent JSON file into - `.brokkr/blender-editor-debug/blender/commands/{commandId}.json`. +5. Send an intent into the node: + `brokkr-ctl blender send createObject --set objectType='"EMPTY"' --agent --no-wait` + (needs `EUREKA_INSTANCE` and `--store `). 6. Click `Drain Commands`, or enable `Auto Drain Commands` to poll command intents once per second while the add-on is loaded. -7. Inspect `.brokkr/blender-editor.ccmp` or the optional debug export +7. Read the receipt with `brokkr-ctl blender wait --store `, or + inspect `.brokkr/blender-editor.ccmp` or the optional debug export at `.brokkr/blender-editor-debug/blender/receipts/{commandId}.json`. 8. Click `Start Server`. 9. Use the reported `cultnet://host:port` endpoint from a CultMesh/CultNet diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py index 18fc00a..f2b2d3c 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.py +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -10,7 +10,8 @@ are drained by the add-on's own 1 s timer as one undo step each, with write-once leave unset to prove a stock install> blender --factory-startup --python agent_turn_queue.py -- -Intents are put into the node database as brokkr-ctl does (no debug-mirror files). Writes +Intents are put into the node database as brokkr-ctl does; a command JSON dropped under the debug +root is never an intent. Writes .result.json, then quits Blender. Undo is read only here, by this driver. """ import importlib @@ -43,7 +44,7 @@ except ImportError: prefs = bpy.context.preferences.addons[MODULE].preferences CACHE = str(SCRATCH / "queue.ccmp") prefs.cultmesh_cache_path = CACHE -prefs.debug_mirror_root = "" # the debug-mirror door is not used here +prefs.debug_mirror_root = str(SCRATCH / "debug") # export only: q1 drops a command file there and it must stay inert prefs.output_dir = str(SCRATCH / "out") prefs.import_dir = "" prefs.auto_drain_commands = True @@ -130,6 +131,10 @@ def drained(*ids): def q1(): push("driver baseline") + door = SCRATCH / "debug" / "blender" / "commands" + door.mkdir(parents=True, exist_ok=True) + (door / "door-0001.json").write_text(json.dumps( + {"commandId": "door-0001", "requestedBy": "nibu/hands", "action": "createObject", "objectType": "MESH", "name": "QDoor"})) queue("aaaaaaaa-0001", action="createObject", objectType="MESH", name="QCube", location=[4, 0, 0], requestedBy="nibu/hands", note="queue test") @@ -141,6 +146,10 @@ def q1_check(): check("queue: createObject drained by the add-on timer, accepted, labelled, attributed", r and r["status"] == "accepted" and r["undoLabel"] == "Brokkr nibu/hands: createObject aaaaaaaa" and r["requestedBy"] == "nibu/hands" and r["note"] == "queue test" and "QCube" in names(), r) + check("queue: a command JSON under the debug root is inert (kept, never run, never receipted); the receipt export still lands", + (SCRATCH / "debug" / "blender" / "commands" / "door-0001.json").exists() and "QDoor" not in names() + and receipt("door-0001") is None and (SCRATCH / "debug" / "blender" / "receipts" / "aaaaaaaa-0001.json").exists(), + names()) check("queue: intent removed from the queue after the drain", "blender/commands/aaaaaaaa-0001" not in pending(), list(pending())) diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 69e83fc..02706de 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -164,6 +164,44 @@ class AgentTurnTests(unittest.TestCase): self.assertEqual(self.bpy.created, []) self.assertEqual(self.bpy.undo.pushes, []) + def test_trailing_newline_does_not_pass_the_id_shapes(self): + self.assertFalse(bt._valid_command_id("okid\n")) + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="okid\n") + self.assertEqual(receipt["status"], "denied") + receipt = self.run_action(action="createObject", objectType="EMPTY", requestedBy="nibu/hands\n") + self.assertEqual(receipt["status"], "denied") + self.assertEqual(self.bpy.created, []) + + def test_load_cultmesh_pins_its_own_package_set(self): + # an unrelated module named like a CultLib package is a missing dependency, not "CultLib is absent" + self.assertEqual(bt.CULTLIB_PY_PACKAGES, ("cultcache-py", "cultnet-py", "cultmesh-py")) + root = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(root, ignore_errors=True)) + src = root / "cultmesh-py" / "src" / "cultmesh_py" + src.mkdir(parents=True) + (src / "__init__.py").write_text("import cultnet_py") # an own package that is absent here + saved = {k: sys.modules.pop(k) for k in ("cultmesh_py", "cultcache_py", "cultnet_py") if k in sys.modules} + saved_path = list(sys.path) + self.addCleanup(lambda: (sys.modules.update(saved), sys.path.__setitem__(slice(None), saved_path))) + with self.assertRaises(RuntimeError) as caught: + bt._load_cultmesh(str(root)) + self.assertIn("requires CultLib's Python packages", str(caught.exception)) + + def test_debug_command_file_is_not_executed(self): + with tempfile.TemporaryDirectory() as tmp: + commands = Path(tmp) / "blender" / "commands" + commands.mkdir(parents=True) + door = commands / "door-1.json" + door.write_text('{"commandId": "door-1", "requestedBy": "nibu/hands", "action": "createObject", "objectType": "EMPTY"}') + node = FakeNode({}) + docs = {"command_intent": "i", "command_receipt": "r"} + with unittest.mock.patch.object(self.target, "_open_node", return_value=(node, docs)): + receipts = self.target.drain_commands(self.context, "cache", "src", tmp) + self.assertEqual(receipts, []) + self.assertEqual(node.puts, []) + self.assertEqual(self.bpy.created, []) + self.assertTrue(door.exists()) + def test_load_cultmesh_names_the_missing_module(self): root = Path(tempfile.mkdtemp()) self.addCleanup(lambda: __import__("shutil").rmtree(root, ignore_errors=True)) diff --git a/surfaces/blender/tests/test_server_guard.py b/surfaces/blender/tests/test_server_guard.py index 439cfe0..d726162 100644 --- a/surfaces/blender/tests/test_server_guard.py +++ b/surfaces/blender/tests/test_server_guard.py @@ -144,48 +144,29 @@ class FakeNode: class PurgeTests(unittest.TestCase): - def make_debug_root(self, tmp): - commands = Path(tmp) / "blender" / "commands" - commands.mkdir(parents=True) - (commands / "a.json").write_text("{}") - (commands / "b.json").write_text("{}") - (commands / "note.txt").write_text("keep") - receipts = Path(tmp) / "blender" / "receipts" - receipts.mkdir() - (receipts / "r.json").write_text("{}") - return commands, receipts + def test_purge_removes_queued_intents(self): + node = FakeNode(["c1", "c2"]) + removed = sg.purge_command_intents(node, "DOC", bt.COMMAND_INTENT_SCHEMA) + self.assertEqual(removed, 2) + self.assertEqual(node.database.deleted, [("DOC", "c1"), ("DOC", "c2")]) - def test_purge_removes_queued_intents_and_debug_command_files_only(self): - with tempfile.TemporaryDirectory() as tmp: - commands, receipts = self.make_debug_root(tmp) - node = FakeNode(["c1", "c2"]) - removed = sg.purge_command_intents(node, "DOC", bt.COMMAND_INTENT_SCHEMA, tmp) - self.assertEqual(removed, 4) - self.assertEqual(node.database.deleted, [("DOC", "c1"), ("DOC", "c2")]) - self.assertEqual(sorted(p.name for p in commands.iterdir()), ["note.txt"]) - self.assertTrue((receipts / "r.json").exists()) - - def test_purge_without_a_debug_root_or_node_is_quiet(self): - self.assertEqual(sg.purge_command_intents(None, "DOC", bt.COMMAND_INTENT_SCHEMA, ""), 0) + def test_purge_without_a_node_is_quiet(self): + self.assertEqual(sg.purge_command_intents(None, "DOC", bt.COMMAND_INTENT_SCHEMA), 0) def test_stop_server_purges_and_revokes(self): - with tempfile.TemporaryDirectory() as tmp: - commands, _ = self.make_debug_root(tmp) - target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) - stopped = [] - target._server = types.SimpleNamespace(stop=lambda: stopped.append(True)) - target._guard = sg.SessionGuard() - guard = target._guard - old = guard.token - target._node = FakeNode(["c1"]) - target._documents = {"command_intent": "DOC"} - target._debug_mirror_root = tmp - target.stop_server() - self.assertEqual(stopped, [True]) - self.assertEqual(target._node.database.keys, []) - self.assertEqual(sorted(p.name for p in commands.iterdir()), ["note.txt"]) - self.assertFalse(guard.admits({sg.TOKEN_FIELD: old})) - self.assertEqual(target.session_token, "") + target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) + stopped = [] + target._server = types.SimpleNamespace(stop=lambda: stopped.append(True)) + target._guard = sg.SessionGuard() + guard = target._guard + old = guard.token + target._node = FakeNode(["c1"]) + target._documents = {"command_intent": "DOC"} + target.stop_server() + self.assertEqual(stopped, [True]) + self.assertEqual(target._node.database.keys, []) + self.assertFalse(guard.admits({sg.TOKEN_FIELD: old})) + self.assertEqual(target.session_token, "") def test_stop_server_revokes_and_purges_even_when_the_socket_stop_raises(self): target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) @@ -229,24 +210,19 @@ class RealServerTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) - self.debug = str(Path(self.tmp.name) / "debug") - commands = Path(self.debug) / "blender" / "commands" - commands.mkdir(parents=True) - (commands / "stale.json").write_text("{}") self.cache = str(Path(self.tmp.name) / "node.ccmp") self.target = bt.BrokkrBlenderTarget(types.SimpleNamespace( path=types.SimpleNamespace(abspath=lambda p: p))) self.addCleanup(self.target.stop_server) def start(self, **kwargs): - return self.target.start_server(self.cache, PACKAGES, "127.0.0.1", 0, 100, 1 << 20, self.debug, **kwargs) + return self.target.start_server(self.cache, PACKAGES, "127.0.0.1", 0, 100, 1 << 20, **kwargs) - def test_default_start_has_no_token_and_purges_stale_debug_commands(self): + def test_default_start_has_no_token(self): status = self.start() self.assertTrue(status["running"]) self.assertFalse(status["tokenRequired"]) self.assertEqual(self.target.session_token, "") - self.assertEqual(list((Path(self.debug) / "blender" / "commands").glob("*.json")), []) self.assertTrue(status["cultmeshModule"].endswith("__init__.py")) self.assertIn("cultmesh_py", status["cultmeshModule"]) self.assertTrue(status["loopback"]) @@ -311,17 +287,17 @@ class RealServerTests(unittest.TestCase): self.assertEqual(self.queued(self.cache), []) def test_allow_true_goes_through_start_server_and_unticking_stops_it(self): - status = self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug, + status = self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, allow_non_loopback=True) self.assertTrue(status["running"]) self.assertFalse(status["loopback"]) with self.assertRaises(sg.BindRefused): - self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug, + self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, allow_non_loopback=False) self.assertFalse(self.target.server_status()["running"]) def test_unticking_the_allow_stops_a_running_non_loopback_server(self): - self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug, + self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, allow_non_loopback=True) self.target.enforce_bind_policy(False) self.assertFalse(self.target.server_status()["running"]) @@ -378,7 +354,7 @@ class RealServerTests(unittest.TestCase): def test_non_loopback_bind_is_refused_before_anything_starts(self): with self.assertRaises(sg.BindRefused): - self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug) + self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20) self.assertFalse(self.target.server_status()["running"]) From 8f5a660964d92fe9d4611ff0af8dae539db5d7e9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:30:27 +0100 Subject: [PATCH 028/223] Blender: removeNode and removeModifier on an absent target push no undo step NodeActions.changed says whether the last action wrote; run_intent pushes the labelled step only when it did (the run_intent half rode in the previous commit's blender_target.py). Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_bridge/node_actions.py | 4 ++++ surfaces/blender/tests/test_node_actions.py | 9 ++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/brokkr_bridge/node_actions.py b/surfaces/blender/brokkr_bridge/node_actions.py index 5210b86..aba236d 100644 --- a/surfaces/blender/brokkr_bridge/node_actions.py +++ b/surfaces/blender/brokkr_bridge/node_actions.py @@ -121,8 +121,10 @@ class NodeActions: def __init__(self, bpy_module: Any): self.bpy = bpy_module + self.changed = False # whether the last execute wrote anything: an absent-target removal does not def execute(self, action: str, command: dict[str, Any]) -> tuple[str, str]: + self.changed = True return getattr(self, "_" + action)(command) # tree and node lookup @@ -236,6 +238,7 @@ class NodeActions: raise ActionRefused(f"{node_id!r} is the group's own input/output node and stays.") node = next((n for n in tree.nodes if n.get("brokkr_id") == node_id), None) if node is None: + self.changed = False return f"Node {node_id!r} was already absent.", node_id tree.nodes.remove(node) # Blender drops the node's links with it return "Node removed.", node_id @@ -305,6 +308,7 @@ class NodeActions: raise ActionRefused("modifierName must be a string of at most 255 characters.") modifier = obj.modifiers.get(name) if modifier is None: + self.changed = False return f"Modifier {name!r} was already absent.", obj.name if modifier.type != "NODES": raise ActionRefused(f"{name!r} is not a Geometry Nodes modifier; only those are removed here.") diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index eac602f..6aeee39 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -544,8 +544,11 @@ class NodeActionTests(unittest.TestCase): tree = self.chain() self.accepted(action="removeNode", treeKey="G", id="b") self.assertEqual([n.get("brokkr_id") for n in tree.nodes], ["gin", "gout", "a", "c"]) + pushes = len(self.bpy.undo.pushes) again = self.accepted(action="removeNode", treeKey="G", id="b") self.assertIn("already absent", again["message"]) + self.assertEqual(len(self.bpy.undo.pushes), pushes) # nothing changed: no undo step + self.assertEqual(again["undoLabel"], "") for keep in ("gin", "gout"): self.refused(action="removeNode", treeKey="G", id=keep) self.refused(action="removeNode", treeKey="Nope", id="a") @@ -575,7 +578,11 @@ class NodeActionTests(unittest.TestCase): self.accepted(action="removeModifier", objectName="Host", modifierName="GN") self.assertEqual([m.name for m in host.modifiers], ["Sub"]) self.assertEqual(host.tagged, tags + 1) - self.assertIn("already absent", self.accepted(action="removeModifier", objectName="Host", modifierName="GN")["message"]) + pushes = len(self.bpy.undo.pushes) + again = self.accepted(action="removeModifier", objectName="Host", modifierName="GN") + self.assertIn("already absent", again["message"]) + self.assertEqual(len(self.bpy.undo.pushes), pushes) + self.assertEqual(again["undoLabel"], "") self.refused(action="removeModifier", objectName="Nope", modifierName="GN") for bad in (["x"], "x" * 256, "a\0b", 5): self.refused(action="removeModifier", objectName="Host", modifierName=bad) From 4510dcc45be5fbee8a27883b5237cd4270c88812 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:30:28 +0100 Subject: [PATCH 029/223] brokkr-ctl: delete ChangeGate, refuse hard-linked stores, pin the survivors The store lock removed the failure the stat gate compensated, so wait reads each poll. A store with more than one hard link is refused (unix nlink; windows via GetFileInformationByHandle, windows-sys already in the lock). Tests pin the 86400 s cap, the receipt-key prefix and -h as a flag; the help test finds the dispatch table by its own line after live-2 added other *ACTIONS tuples. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + brokkr-ctl/Cargo.toml | 3 ++ brokkr-ctl/src/blender.rs | 79 +++++++++++++-------------------------- brokkr-ctl/tests/cli.rs | 40 +++++++++++++++++++- 4 files changed, 69 insertions(+), 54 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f01e20a..cedd285 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -57,6 +57,7 @@ dependencies = [ "serde_json", "tempfile", "uuid", + "windows-sys 0.61.2", ] [[package]] diff --git a/brokkr-ctl/Cargo.toml b/brokkr-ctl/Cargo.toml index 4470cd6..b74147e 100644 --- a/brokkr-ctl/Cargo.toml +++ b/brokkr-ctl/Cargo.toml @@ -11,5 +11,8 @@ rmp-serde = "1.3" serde_json = "1" uuid = { version = "1", features = ["v7"] } +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] } + [dev-dependencies] tempfile = "3" diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index c342e91..e2a7a40 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -18,8 +18,6 @@ const RESERVED: [&str; 5] = ["schema", "commandId", "action", "requestedBy", "no const DEFAULT_TIMEOUT_SECS: u64 = 60; const POLL: Duration = Duration::from_millis(200); const MAX_TIMEOUT: Duration = Duration::from_secs(24 * 3600); -/// Even when the file looks unchanged, read it again this often. -const RECHECK: Duration = Duration::from_secs(5); /// What a receipt (or its absence) says; the exit code derives from it and from nothing else. pub enum Outcome { @@ -162,9 +160,35 @@ fn open_store(options: &Options) -> Result { if meta.file_type().is_symlink() || !meta.is_file() { bail!("store {} must be the add-on's regular file, not a link", path.display()); } + // The same swap would leave a second name on the old bytes. + if link_count(&path)? > 1 { + bail!("store {} has more than one hard link; it must be the add-on's only name for the file", path.display()); + } Ok(SingleFileMessagePackBackingStore::new(path)) } +#[cfg(unix)] +fn link_count(path: &std::path::Path) -> Result { + use std::os::unix::fs::MetadataExt; + Ok(std::fs::metadata(path)?.nlink()) +} + +/// std's `number_of_links` is unstable, so ask the handle. +#[cfg(windows)] +fn link_count(path: &std::path::Path) -> Result { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Storage::FileSystem::{BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle}; + let file = std::fs::File::open(path)?; + let mut info = std::mem::MaybeUninit::::zeroed(); + // SAFETY: the handle is live for the call and `info` is a writable BY_HANDLE_FILE_INFORMATION. + let ok = unsafe { GetFileInformationByHandle(file.as_raw_handle() as _, info.as_mut_ptr()) }; + if ok == 0 { + return Err(std::io::Error::last_os_error().into()); + } + // SAFETY: the call succeeded, so it filled the struct. + Ok(u64::from(unsafe { info.assume_init() }.nNumberOfLinks)) +} + fn requested_by(options: &Options) -> Result { let instance = std::env::var("EUREKA_INSTANCE").unwrap_or_default(); let agent = options @@ -244,16 +268,7 @@ fn wait_for_receipt( limit: Duration, ) -> Result { let started = Instant::now(); - let mut gate = ChangeGate::new(store.path()); loop { - if !gate.should_read() { - if started.elapsed() >= limit { - println!("status: timeout"); - return Ok(Outcome::Timeout.code()); - } - thread::sleep(POLL); - continue; - } if let Some(receipt) = read_receipt(store, id)? { print_fields(&receipt); let status = receipt.get("status").and_then(Value::as_str).unwrap_or(""); @@ -267,32 +282,6 @@ fn wait_for_receipt( } } -/// Polling must not hold the store: a read takes the shared lock and an open handle, and on -/// Windows that can make the add-on's replace fail. So the file's stat is polled and the store -/// is read only after it changed (and every RECHECK as a backstop). -pub struct ChangeGate { - path: PathBuf, - seen: Option<(u64, Option)>, - last_read: Option, -} - -impl ChangeGate { - pub fn new(path: &std::path::Path) -> Self { - Self { path: path.to_path_buf(), seen: None, last_read: None } - } - - pub fn should_read(&mut self) -> bool { - let stamp = std::fs::metadata(&self.path).ok().map(|m| (m.len(), m.modified().ok())); - let stale = self.last_read.is_none_or(|at| at.elapsed() >= RECHECK); - if self.seen.is_none() || stamp != self.seen || stale { - self.seen = stamp; - self.last_read = Some(Instant::now()); - return true; - } - false - } -} - fn receipts(store: &SingleFileMessagePackBackingStore, last: Option) -> Result { let mut found = Vec::new(); for envelope in store.pull_all()? { @@ -628,22 +617,6 @@ mod tests { assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err()); } - #[test] - fn the_gate_reads_first_then_only_after_the_file_changes() { - let dir = std::env::temp_dir().join(format!("brokkr-gate-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("s.ccmp"); - std::fs::write(&file, b"one").unwrap(); - let mut gate = ChangeGate::new(&file); - assert!(gate.should_read()); - assert!(!gate.should_read()); - assert!(!gate.should_read()); - std::fs::write(&file, b"three").unwrap(); - assert!(gate.should_read()); - assert!(!gate.should_read()); - std::fs::remove_dir_all(&dir).unwrap(); - } - #[test] fn statuses_map_to_exit_codes() { for (status, code) in [("accepted", 0), ("denied", 2), ("failed", 2), ("stopped", 3), ("weird", 2)] { diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 072ae2a..c3df5a6 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -240,6 +240,43 @@ fn a_symlinked_store_is_refused() { assert_eq!(ctl(&link, &["receipts"], None).status.code(), Some(1)); } +#[test] +fn a_hard_linked_store_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let link = dir.path().join("second-name.ccmp"); + std::fs::hard_link(&path, &link).unwrap(); + let before = std::fs::read(&path).unwrap(); + for name in [&path, &link] { + let output = ctl(name, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(1), "{}", name.display()); + assert!(String::from_utf8_lossy(&output.stderr).contains("hard link")); + } + assert_eq!(std::fs::read(&path).unwrap(), before); +} + +#[test] +fn the_timeout_cap_is_one_day_inclusive() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + // --help returns after parsing, so a legal timeout does not wait + let at_cap = ctl(&path, &["send", "createObject", "--help", "--timeout", "86400"], None); + assert_eq!(at_cap.status.code(), Some(0)); + let over = ctl(&path, &["send", "createObject", "--help", "--timeout", "86400.5"], None); + assert_eq!(over.status.code(), Some(1)); +} + +#[test] +fn short_help_is_a_flag() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + let output = ctl(&path, &["send", "createObject", "-h"], Some("nibu")); + assert_eq!(output.status.code(), Some(0)); + assert!(stdout(&output).contains("actions:")); + let group = ctl(&path, &["receipts", "-h"], None); + assert!(stdout(&group).contains("brokkr-ctl blender:")); +} + #[test] fn receipts_only_come_from_the_receipt_keys_and_type() { let dir = tempfile::tempdir().unwrap(); @@ -250,6 +287,7 @@ fn receipts_only_come_from_the_receipt_keys_and_type() { &[ envelope_at(RECEIPT, "elsewhere/fake", &fake), envelope_at(INTENT, "blender/receipts/wrongtype", &fake), + envelope_at(RECEIPT, "nested/blender/receipts/fake2", &fake), ], ); let listed = stdout(&ctl(&path, &["receipts"], None)); @@ -306,7 +344,7 @@ fn help_names_every_dispatched_action_and_only_fields_the_addon_mentions() { .filter_map(|rest| rest.split('"').next()) .map(String::from) .collect(); - let actions_line = source.lines().find(|l| l.contains("ACTIONS = (\"")).unwrap(); + let actions_line = source.lines().find(|l| l.trim_start().starts_with("ACTIONS = (\"")).unwrap(); dispatched.extend(actions_line.split('"').skip(1).step_by(2).map(String::from)); assert!(dispatched.len() >= 20, "{dispatched:?}"); let listed: Vec<&str> = help.lines().filter_map(|l| l.strip_prefix(" ")).filter(|l| !l.starts_with(' ')).collect(); From c723754ea6a9fe7b79f74cb766f088c179346e96 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:36:58 +0100 Subject: [PATCH 030/223] Blender live harness results rerun on the extension build (stock Blender 5.3, no PYLIBS) agent_turn_queue now also drops a command JSON under the debug root and checks it stays inert. Co-Authored-By: Claude Sonnet 5.5 --- .../tests/live/agent_turn_queue.result.json | 42 ++++++++++++------- .../tests/live/agent_turn_undo.result.json | 4 +- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json index 9d8a289..e76bb3f 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.result.json +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -16,9 +16,19 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:01:35.205337+00:00" + "observedAt": "2026-11-27T19:32:00.583673+00:00" } }, + { + "name": "queue: a command JSON under the debug root is inert (kept, never run, never receipted); the receipt export still lands", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "QCube" + ] + }, { "name": "queue: intent removed from the queue after the drain", "ok": true, @@ -37,7 +47,7 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:01:35.205337+00:00" + "observedAt": "2026-11-27T19:32:00.583673+00:00" } }, { @@ -53,7 +63,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:37.202231+00:00" + "observedAt": "2026-11-27T19:32:02.587784+00:00" } }, { @@ -69,7 +79,7 @@ "requestedBy": "", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:39.207926+00:00" + "observedAt": "2026-11-27T19:32:04.590532+00:00" } }, { @@ -125,7 +135,7 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:01:35.205337+00:00" + "observedAt": "2026-11-27T19:32:00.583673+00:00" }, "q2_original": { "schema": "brokkr.blender.command_receipt.v0", @@ -137,7 +147,7 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:01:35.205337+00:00" + "observedAt": "2026-11-27T19:32:00.583673+00:00" }, "q2_denial": { "schema": "brokkr.blender.command_receipt.v0", @@ -149,7 +159,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:37.202231+00:00" + "observedAt": "2026-11-27T19:32:02.587784+00:00" }, "q3": { "schema": "brokkr.blender.command_receipt.v0", @@ -161,12 +171,12 @@ "requestedBy": "", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:39.207926+00:00" + "observedAt": "2026-11-27T19:32:04.590532+00:00" }, "q6": [ { "schema": "brokkr.blender.command_receipt.v0", - "commandId": "ae0a53d8d0584e54b1ce518cf7e8cf9d", + "commandId": "8fe2e26fece047bcaca1b9938f1a030c", "action": "createObject", "status": "denied", "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", @@ -174,11 +184,11 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:43.220315+00:00" + "observedAt": "2026-11-27T19:32:08.599229+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", - "commandId": "f5ce147da5e0466ab0771ac13135f4be", + "commandId": "b1a5c7e22158468bb06f6b500c4fa2a7", "action": "createObject", "status": "denied", "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", @@ -186,7 +196,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:43.242934+00:00" + "observedAt": "2026-11-27T19:32:08.621069+00:00" } ], "q5": [ @@ -200,7 +210,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:45.227825+00:00" + "observedAt": "2026-11-27T19:32:10.606424+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", @@ -212,7 +222,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:45.250025+00:00" + "observedAt": "2026-11-27T19:32:10.629698+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", @@ -224,10 +234,10 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:01:45.281467+00:00" + "observedAt": "2026-11-27T19:32:10.665150+00:00" } ] }, - "msgpack": "F:\\aeth-wt\\brokkr-live-2.res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", + "msgpack": "F:\\aeth-wt\\brokkr-live-1.e2e\\res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json index 5468ce0..0437128 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.result.json +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -197,7 +197,7 @@ "name": "exportGltf and renderStill accepted with no undoLabel", "ok": true, "detail": [ - "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-a4ak7h0p\\object.glb (3484 bytes).", + "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-_y_dg6ko\\object.glb (3484 bytes).", "Rendered still to object.png." ] }, @@ -270,7 +270,7 @@ "intent": "exportGltf", "status": "accepted", "undoLabel": "", - "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-a4ak7h0p\\object.glb (3484 bytes)." + "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-_y_dg6ko\\object.glb (3484 bytes)." }, { "intent": "renderStill", From 1f469c47218b8207a6160eda0c3a46011dbcbad9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:04:46 +0100 Subject: [PATCH 031/223] CultLib pins to 9fc4bdda; one pure-Python msgpack wheel, no platform restriction cultcache-rs moves to 9fc4bdda (PR #180: cultcache-py decodes under msgpack's pure-Python fallback). The Windows-only C wheel is replaced by msgpack 1.2.2 repacked deterministically from the installed package; source, version and sha256 are in install.md. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 4 +- Cargo.toml | 2 +- .../brokkr_bridge/blender_manifest.toml | 10 ++-- .../msgpack-1.2.2-cp313-cp313-win_amd64.whl | Bin 72206 -> 0 bytes .../wheels/msgpack-1.2.2-py3-none-any.whl | Bin 0 -> 15448 bytes surfaces/blender/docs/install.md | 23 +++++++--- .../tests/live/agent_turn_undo.result.json | 14 +++--- .../blender/tests/test_extension_wheel.py | 43 ++++++++++++++++++ tools/build-msgpack-wheel.py | 27 +++++++++++ 9 files changed, 100 insertions(+), 23 deletions(-) delete mode 100644 surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl create mode 100644 surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-py3-none-any.whl create mode 100644 surfaces/blender/tests/test_extension_wheel.py create mode 100644 tools/build-msgpack-wheel.py diff --git a/Cargo.lock b/Cargo.lock index cedd285..1c9d7f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -136,7 +136,7 @@ dependencies = [ [[package]] name = "cultcache-rs" version = "0.3.1" -source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb" +source = "git+https://github.com/GameCult/CultLib.git?rev=9fc4bdda6a8620f846b58e89ddf476f4676d3e89#9fc4bdda6a8620f846b58e89ddf476f4676d3e89" dependencies = [ "anyhow", "chrono", @@ -157,7 +157,7 @@ dependencies = [ [[package]] name = "cultcache-rs-derive" version = "0.2.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=baf4ecf78fae634fafef956d3b85420162c074bb#baf4ecf78fae634fafef956d3b85420162c074bb" +source = "git+https://github.com/GameCult/CultLib.git?rev=9fc4bdda6a8620f846b58e89ddf476f4676d3e89#9fc4bdda6a8620f846b58e89ddf476f4676d3e89" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index c469605..5645f78 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,5 +6,5 @@ members = [ ] [workspace.dependencies] -cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "baf4ecf78fae634fafef956d3b85420162c074bb", package = "cultcache-rs" } +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "9fc4bdda6a8620f846b58e89ddf476f4676d3e89", package = "cultcache-rs" } diff --git a/surfaces/blender/brokkr_bridge/blender_manifest.toml b/surfaces/blender/brokkr_bridge/blender_manifest.toml index ec5feed..cbdf1d8 100644 --- a/surfaces/blender/brokkr_bridge/blender_manifest.toml +++ b/surfaces/blender/brokkr_bridge/blender_manifest.toml @@ -6,10 +6,8 @@ tagline = "Brokkr command intents, receipts and snapshots over CultMesh" maintainer = "GameCult " type = "add-on" blender_version_min = "5.3.0" -platforms = ["windows-x64"] license = ["SPDX:GPL-3.0-or-later"] -# CultLib's cultnet-py and cultcache-py import msgpack; Blender's Python does not ship it. The wheel is -# the installed msgpack 1.2.2 CPython 3.13 Windows build (Blender 5.3 runs Python 3.13). The C extension -# matters: CultLib at baf4ecf7 fails on msgpack's pure-Python fallback (object_pairs_hook gets a generator). -# Linux and macOS wheels are not bundled yet. -wheels = ["./wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl"] +# CultLib's cultnet-py and cultcache-py import msgpack; Blender's Python does not ship it. The wheel is one +# pure-Python msgpack 1.2.2 (no C extension), so the extension is platform-independent; CultLib 9fc4bdda +# (PR #180) decodes under msgpack's pure-Python fallback. Source and hash: docs/install.md. +wheels = ["./wheels/msgpack-1.2.2-py3-none-any.whl"] diff --git a/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl b/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl deleted file mode 100644 index 83a8682553e2b936e0c3cb72ecf267cd6ec8b371..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 72206 zcmY&;Q;aT58{|8-ZCht->x^yNwmoykwr$(CZQHi?+hi~Hzvxb<(|OWKRq~)pUJ3*h z6#xK0{k-&0blszJo zLxj-!IE-womWg+OYMwKHl6azUFXfs1yV%AHB%T_PGBCc;yraN@8< zK~4VkOyFTt@?>Xl%%8t;5r?*^LGa0m$&g`U zX#ZoLXWtugLeO>$hHG2L4V15#eLV1OaE5dg&)do|Jx(CA60`ekarMt@+2LXAhr_5I z;^!oKYt~ zAn(#=vy(yjH5`js%?BX=KjaufT=r=Fj~o{Nkpu1jBZrB*k%_&tg`KU_fAm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2_m?rP5WIStpfBrM63lQ&@Ut4$_uF`|iIOYiOpw1^TfU>4dZt!PC9Nq#5Nzy$>|a z3+PlY1zzjs5ccO2{XEglwj@$E zStwL#_sR=bvQGb4?Awzmw3FWaAsjW;Bbk-s{K8yS2Vbo6JxCq=w>kG9-FM|pRMe25 zIEY?pSNcB*xJ!c$hoxUPyPj0Z{KdlLl9Ck-Rclie4Sq_OJyrVt+m>4vA!Whc0QoyA zF9Q)?b{u!-lr>0sN5o=kRe?9KvjYPfg=?2%E>9|G zsY|LW%haZ5icya|L;%HA3gm4`Jn%4;rtu$x3Ta43Hm2^|6%j{8}YYe?B588 zKW@Q)BmU(d`+Mx)i_-r+b_eF)WB~GrNmEhmBSJwYb z`$t{)8~JxV_%~9V?LQ;`t`2`w|ISJOrebmYXX^jXP=BNTP9Oh9wf`5?|4AnDQefc! Rx*zJ#7W+ppja>ga`(GeE=H37R literal 0 HcmV?d00001 diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index f29c195..6452905 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -33,7 +33,7 @@ The command prints the record count and leaves the source unwritten. Records a n CultLib's `cultnet-py` and `cultcache-py` import `msgpack`, and Blender's Python does not ship it. Install Brokkr as an extension so Blender installs it for you: `surfaces/blender/brokkr_bridge/blender_manifest.toml` lists the bundled wheel -`wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl`, which Blender unpacks into the extension's own +`wheels/msgpack-1.2.2-py3-none-any.whl`, which Blender unpacks into the extension's own site-packages when the extension is enabled. Build and install it: ```text @@ -41,12 +41,21 @@ blender --command extension build --source-dir surfaces/blender/brokkr_bridge -- blender --command extension install-file --repo user_default --enable /brokkr_bridge-0.2.0.zip ``` -The bundled wheel is msgpack 1.2.2 for CPython 3.13 on Windows x64 (Blender 5.3's Python), -repacked from the installed package with its Apache-2.0 licence; the extension is therefore -declared `windows-x64`, Blender 5.3 or newer. The C extension matters: CultLib at `baf4ecf7` -fails on msgpack's pure-Python fallback. Linux and macOS wheels are not bundled yet: there, -or in a plain add-on directory install, put `msgpack` into Blender's Python yourself. A -CultLib package missing a module is reported by that module's name, not as a missing +The wheel is one pure-Python msgpack, so the extension carries no platform restriction (Blender 5.3 or +newer, any OS). msgpack then runs its pure-Python fallback, which CultLib `9fc4bdda` (PR #180) decodes. + +Wheel provenance: msgpack 1.2.2 as installed on the build host (CPython 3.13, the PyPI release; nothing +was downloaded), repacked by `tools/build-msgpack-wheel.py` from its `msgpack/__init__.py`, `exceptions.py`, +`ext.py` and `fallback.py` (the `_cmsgpack` C extension is left out) with the package's METADATA and +Apache-2.0 `COPYING`. The repack is deterministic; rebuild and compare: + +```text +python tools/build-msgpack-wheel.py +sha256 0b53d2ea2e21782a670fc152bb104d97623cfa337940518016a6b7ded369af42 msgpack-1.2.2-py3-none-any.whl +``` + +In a plain add-on directory install the wheel is not unpacked: put `msgpack` into Blender's Python +yourself. A CultLib package missing a module is reported by that module's name, not as a missing CultLib package. The default node cache is: diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json index 0437128..248b79b 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.result.json +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -5,7 +5,7 @@ { "name": "createObject accepted with undoLabel", "ok": true, - "detail": "Brokkr nibu/hands: createObject 00000001" + "detail": "Brokkr nibu/hands: createObject ent-turn" }, { "name": "transform applied", @@ -197,7 +197,7 @@ "name": "exportGltf and renderStill accepted with no undoLabel", "ok": true, "detail": [ - "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-_y_dg6ko\\object.glb (3484 bytes).", + "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-0ge72kvx\\object.glb (3484 bytes).", "Rendered still to object.png." ] }, @@ -215,19 +215,19 @@ { "intent": "createObject", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: createObject 00000001", + "undoLabel": "Brokkr nibu/hands: createObject ent-turn", "message": "Blender object created." }, { "intent": "setObjectTransform", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000002", + "undoLabel": "Brokkr nibu/hands: setObjectTransform ent-turn", "message": "Blender object transform updated." }, { "intent": "createObject", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: createObject 00000003", + "undoLabel": "Brokkr nibu/hands: createObject ent-turn", "message": "Blender object created." }, { @@ -263,14 +263,14 @@ { "intent": "createObject", "status": "accepted", - "undoLabel": "Brokkr nibu/hands: createObject 00000009", + "undoLabel": "Brokkr nibu/hands: createObject ent-turn", "message": "Blender object created." }, { "intent": "exportGltf", "status": "accepted", "undoLabel": "", - "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-_y_dg6ko\\object.glb (3484 bytes)." + "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-0ge72kvx\\object.glb (3484 bytes)." }, { "intent": "renderStill", diff --git a/surfaces/blender/tests/test_extension_wheel.py b/surfaces/blender/tests/test_extension_wheel.py new file mode 100644 index 0000000..36c3b0d --- /dev/null +++ b/surfaces/blender/tests/test_extension_wheel.py @@ -0,0 +1,43 @@ +"""The extension's one bundled wheel is pure Python, matches its recorded hash, and the manifest does not pin a platform.""" +from __future__ import annotations + +import base64 +import hashlib +import re +import tomllib +import unittest +import zipfile +from pathlib import Path + +ADDON = Path(__file__).resolve().parents[1] / "brokkr_bridge" +INSTALL = Path(__file__).resolve().parents[1] / "docs" / "install.md" + + +class ExtensionWheelTests(unittest.TestCase): + def setUp(self): + self.manifest = tomllib.loads((ADDON / "blender_manifest.toml").read_text(encoding="utf-8")) + + def test_one_pure_python_wheel_and_no_platform_restriction(self): + self.assertEqual(len(self.manifest["wheels"]), 1) + wheel = ADDON / self.manifest["wheels"][0] + self.assertTrue(wheel.name.endswith("-py3-none-any.whl"), wheel.name) + self.assertNotIn("platforms", self.manifest) + with zipfile.ZipFile(wheel) as z: + names = z.namelist() + self.assertEqual([n for n in names if n.endswith((".pyd", ".so", ".dylib"))], []) + self.assertIn("Root-Is-Purelib: true", z.read("msgpack-1.2.2.dist-info/WHEEL").decode()) + for line in z.read("msgpack-1.2.2.dist-info/RECORD").decode().splitlines(): + name, digest, size = line.split(",") + if digest: + data = z.read(name) + self.assertEqual(digest, "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode(), name) + self.assertEqual(int(size), len(data), name) + + def test_install_doc_records_the_wheel_hash(self): + wheel = ADDON / self.manifest["wheels"][0] + recorded = re.findall(r"\b[0-9a-f]{64}\b", INSTALL.read_text(encoding="utf-8")) + self.assertIn(hashlib.sha256(wheel.read_bytes()).hexdigest(), recorded) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/build-msgpack-wheel.py b/tools/build-msgpack-wheel.py new file mode 100644 index 0000000..a6d67af --- /dev/null +++ b/tools/build-msgpack-wheel.py @@ -0,0 +1,27 @@ +"""Repack the installed msgpack's pure-Python modules as one py3-none-any wheel (no download, no C extension). + +usage: python tools/build-msgpack-wheel.py +Deterministic: the same installed msgpack gives the same bytes, so the sha256 in install.md is checkable. +""" +import base64, hashlib, importlib.metadata as md, pathlib, sys, zipfile + +PURE = ("__init__.py", "exceptions.py", "ext.py", "fallback.py") # _cmsgpack is the C extension: left out +dist = md.distribution("msgpack") +version = dist.version +site = pathlib.Path(dist.locate_file("")) +files = {f"msgpack/{name}": (site / "msgpack" / name).read_bytes() for name in PURE} +info = f"msgpack-{version}.dist-info" +files[f"{info}/METADATA"] = dist.read_text("METADATA").encode() +files[f"{info}/top_level.txt"] = b"msgpack\n" +files[f"{info}/licenses/COPYING"] = (site / info / "licenses" / "COPYING").read_bytes() +files[f"{info}/WHEEL"] = b"Wheel-Version: 1.0\nGenerator: brokkr tools/build-msgpack-wheel.py\nRoot-Is-Purelib: true\nTag: py3-none-any\n" +digest = lambda data: "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() +files[f"{info}/RECORD"] = ("".join(f"{n},{digest(d)},{len(d)}\n" for n, d in files.items()) + f"{info}/RECORD,,\n").encode() + +out = pathlib.Path(sys.argv[1]) / f"msgpack-{version}-py3-none-any.whl" +with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z: + for name, data in files.items(): + entry = zipfile.ZipInfo(name, (1980, 1, 1, 0, 0, 0)) + entry.compress_type, entry.external_attr = zipfile.ZIP_DEFLATED, 0o644 << 16 + z.writestr(entry, data) +print(out, hashlib.sha256(out.read_bytes()).hexdigest()) From fe76ac45c470e195336b6485dd2e77dd514b0f3a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:04:47 +0100 Subject: [PATCH 032/223] live-1 Lows: undo label from the id tail, empty unlink pushes no step, wait pins exact key and poll sleep, architecture wording Each has a test that failed first; the ctl mutants (ends_with key, sleep removed) now fail. Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/src/blender.rs | 49 ++++++++++++++++--- brokkr-ctl/tests/cli.rs | 10 ++++ docs/architecture.md | 2 +- docs/live-collab-target.md | 4 +- .../blender/brokkr_bridge/blender_target.py | 2 +- .../blender/brokkr_bridge/node_actions.py | 1 + .../blender/tests/live/agent_turn_queue.py | 4 +- .../tests/live/agent_turn_queue.result.json | 42 ++++++++-------- surfaces/blender/tests/test_agent_turn.py | 16 +++++- surfaces/blender/tests/test_node_actions.py | 6 ++- 10 files changed, 101 insertions(+), 35 deletions(-) diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index e2a7a40..36e7245 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -267,18 +267,34 @@ fn wait_for_receipt( id: &str, limit: Duration, ) -> Result { - let started = Instant::now(); - loop { - if let Some(receipt) = read_receipt(store, id)? { + match poll_until(limit, POLL, || read_receipt(store, id))? { + Some(receipt) => { print_fields(&receipt); let status = receipt.get("status").and_then(Value::as_str).unwrap_or(""); - return Ok(Outcome::from_status(status).code()); + Ok(Outcome::from_status(status).code()) + } + None => { + println!("status: timeout"); + Ok(Outcome::Timeout.code()) + } + } +} + +/// Reads until `read` yields a value or `limit` passes, sleeping `poll` between reads. +fn poll_until( + limit: Duration, + poll: Duration, + mut read: impl FnMut() -> Result>, +) -> Result> { + let started = Instant::now(); + loop { + if let Some(found) = read()? { + return Ok(Some(found)); } if started.elapsed() >= limit { - println!("status: timeout"); - return Ok(Outcome::Timeout.code()); + return Ok(None); } - thread::sleep(POLL); + thread::sleep(poll); } } @@ -617,6 +633,25 @@ mod tests { assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err()); } + #[test] + fn polling_sleeps_between_reads_and_stops_at_the_limit() { + let mut reads = 0; + let found: Option = poll_until(Duration::from_millis(400), Duration::from_millis(100), || { + reads += 1; + Ok(None) + }) + .unwrap(); + assert_eq!(found, None); + assert!((2..=6).contains(&reads), "{reads} reads: the sleep paces them"); + let mut reads = 0; + let found = poll_until(Duration::from_secs(5), Duration::from_millis(100), || { + reads += 1; + Ok((reads == 3).then_some("receipt")) + }) + .unwrap(); + assert_eq!((found, reads), (Some("receipt"), 3)); + } + #[test] fn statuses_map_to_exit_codes() { for (status, code) in [("accepted", 0), ("denied", 2), ("failed", 2), ("stopped", 3), ("weird", 2)] { diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index c3df5a6..6161f6b 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -105,6 +105,16 @@ fn a_missing_store_is_not_created() { assert!(!path.exists()); } +#[test] +fn wait_matches_the_exact_receipt_key() { + let dir = tempfile::tempdir().unwrap(); + // receipts whose keys merely end with, or start with, the waited id are other commands' receipts + let path = store_with_receipts(dir.path(), &[("xr1", "accepted"), ("r1x", "accepted")]); + let output = ctl(&path, &["wait", "r1", "--timeout", "0.3"], None); + assert_eq!(output.status.code(), Some(4), "{}", stdout(&output)); + assert!(stdout(&output).contains("status: timeout")); +} + #[test] fn exit_code_follows_the_receipt() { let dir = tempfile::tempdir().unwrap(); diff --git a/docs/architecture.md b/docs/architecture.md index 9b102a9..843dbeb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -100,7 +100,7 @@ Derived State: - Unity package settings are adapter configuration, not Verse authority. - Blender add-on preferences are adapter configuration, not Verse authority. -- Blender JSON debug exports are inspection/import probes, not mirror authority. +- Blender JSON debug exports are export-only inspection output, not mirror authority and never read back as intents. - Unity and Blender sync UI fields are command/edit affordances; the `brokkr.sync.*` documents are the shared sync policy surface. - Ad hoc syncvar editors write `brokkr.sync.var.v0` policy records only; they diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index fcfedaa..2853e5a 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -99,7 +99,7 @@ resident service on that number); reading a record's stored version through Aeth **One agent turn primitive.** Every agent mutation in Blender goes through one function in the add-on: admit (sink enabled, `requestedBy` present, id unused, action typed and valid), run the action with every operator called `undo=False`, push exactly one undo -step labelled `Brokkr : `, write the receipt. A +step labelled `Brokkr : `, write the receipt. A refusal caught before any write pushes nothing and leaves the scene unchanged; an action that fails after writing pushes one step labelled `(failed)`, so the partial write is one undoable step. There is no second @@ -254,7 +254,7 @@ are the primitive for the push. | Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (`brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | | Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, stopped, failed, `undoLabel`, `lookPath`) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. | The primitive alone. Callers and the panel read. | | Agent identity `requestedBy` | `/` stated by the caller | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | -| Agent undo step | Blender undo entry `Brokkr : ` | One per accepted mutating intent; lives as Blender's stack does; never persisted by Brokkr. | Blender owns the stack; the primitive pushes; only the human undoes or redoes. | +| Agent undo step | Blender undo entry `Brokkr : ` | One per accepted mutating intent; lives as Blender's stack does; never persisted by Brokkr. | Blender owns the stack; the primitive pushes; only the human undoes or redoes. | | Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads. | The add-on alone. | | Human-edit sequences (snapshot: `humanEditSeq`, per-object `lastHumanEditSeq`) | Integers within a session id | Monotonic within a session; reset with it. Information for the agent; they gate nothing. | The add-on's depsgraph and undo handlers alone. | | Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, sequences, sink state, authoring binding summary) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 8684e8e..8302a69 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -542,7 +542,7 @@ class BrokkrBlenderTarget: self._receipted.add(command_id) return self._receipt(command, "denied", denial, "") - label = f"Brokkr {requested_by}: {action} {command_id[:8]}" + label = f"Brokkr {requested_by}: {action} {command_id[-8:]}" # the tail: uuid v7 ids lead with a timestamp, one value per minute push = action not in READ_ACTIONS and action not in NO_SCENE_CHANGE_ACTIONS self.agent_turn = True self._wrote = True diff --git a/surfaces/blender/brokkr_bridge/node_actions.py b/surfaces/blender/brokkr_bridge/node_actions.py index aba236d..389a536 100644 --- a/surfaces/blender/brokkr_bridge/node_actions.py +++ b/surfaces/blender/brokkr_bridge/node_actions.py @@ -254,6 +254,7 @@ class NodeActions: doomed = [l for l in tree.links if l.to_socket == into and (out is None or l.from_socket == out)] for link in doomed: tree.links.remove(link) + self.changed = bool(doomed) # no link matched: no undo step return f"Removed {len(doomed)} link(s).", tree.name def _linkSockets(self, command: dict[str, Any]) -> tuple[str, str]: diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py index f2b2d3c..1521ba0 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.py +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -39,6 +39,8 @@ bt = importlib.import_module(MODULE + ".blender_target") try: import msgpack R["msgpack"] = msgpack.__file__ + R["msgpack_packer"] = msgpack.Packer.__module__ # msgpack.fallback: the pure-Python codec, no C extension + R["msgpack_purepython_env"] = os.environ.get("MSGPACK_PUREPYTHON", "") except ImportError: R["msgpack"] = None prefs = bpy.context.preferences.addons[MODULE].preferences @@ -144,7 +146,7 @@ def q1_check(): R["receipts"]["q1"] = r S["q1_label"] = r and r.get("undoLabel") check("queue: createObject drained by the add-on timer, accepted, labelled, attributed", - r and r["status"] == "accepted" and r["undoLabel"] == "Brokkr nibu/hands: createObject aaaaaaaa" + r and r["status"] == "accepted" and r["undoLabel"] == "Brokkr nibu/hands: createObject aaa-0001" # the id's last 8 characters and r["requestedBy"] == "nibu/hands" and r["note"] == "queue test" and "QCube" in names(), r) check("queue: a command JSON under the debug root is inert (kept, never run, never receipted); the receipt export still lands", (SCRATCH / "debug" / "blender" / "commands" / "door-0001.json").exists() and "QDoor" not in names() diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json index e76bb3f..e1c803e 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.result.json +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -15,8 +15,8 @@ "objectName": "QCube", "requestedBy": "nibu/hands", "note": "queue test", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:32:00.583673+00:00" + "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", + "observedAt": "2026-11-27T20:02:43.826604+00:00" } }, { @@ -46,8 +46,8 @@ "objectName": "QCube", "requestedBy": "nibu/hands", "note": "queue test", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:32:00.583673+00:00" + "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", + "observedAt": "2026-11-27T20:02:43.826604+00:00" } }, { @@ -63,7 +63,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:02.587784+00:00" + "observedAt": "2026-11-27T20:02:45.831074+00:00" } }, { @@ -79,7 +79,7 @@ "requestedBy": "", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:04.590532+00:00" + "observedAt": "2026-11-27T20:02:47.837505+00:00" } }, { @@ -134,8 +134,8 @@ "objectName": "QCube", "requestedBy": "nibu/hands", "note": "queue test", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:32:00.583673+00:00" + "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", + "observedAt": "2026-11-27T20:02:43.826604+00:00" }, "q2_original": { "schema": "brokkr.blender.command_receipt.v0", @@ -146,8 +146,8 @@ "objectName": "QCube", "requestedBy": "nibu/hands", "note": "queue test", - "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", - "observedAt": "2026-11-27T19:32:00.583673+00:00" + "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", + "observedAt": "2026-11-27T20:02:43.826604+00:00" }, "q2_denial": { "schema": "brokkr.blender.command_receipt.v0", @@ -159,7 +159,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:02.587784+00:00" + "observedAt": "2026-11-27T20:02:45.831074+00:00" }, "q3": { "schema": "brokkr.blender.command_receipt.v0", @@ -171,12 +171,12 @@ "requestedBy": "", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:04.590532+00:00" + "observedAt": "2026-11-27T20:02:47.837505+00:00" }, "q6": [ { "schema": "brokkr.blender.command_receipt.v0", - "commandId": "8fe2e26fece047bcaca1b9938f1a030c", + "commandId": "3414cf427aa549ea9e9a52c4cfc61908", "action": "createObject", "status": "denied", "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", @@ -184,11 +184,11 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:08.599229+00:00" + "observedAt": "2026-11-27T20:02:51.875508+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", - "commandId": "b1a5c7e22158468bb06f6b500c4fa2a7", + "commandId": "3c53313e68aa4d07ab6e3e330396567d", "action": "createObject", "status": "denied", "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", @@ -196,7 +196,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:08.621069+00:00" + "observedAt": "2026-11-27T20:02:51.901697+00:00" } ], "q5": [ @@ -210,7 +210,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:10.606424+00:00" + "observedAt": "2026-11-27T20:02:53.881094+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", @@ -222,7 +222,7 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:10.629698+00:00" + "observedAt": "2026-11-27T20:02:53.905589+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", @@ -234,10 +234,12 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T19:32:10.665150+00:00" + "observedAt": "2026-11-27T20:02:53.944684+00:00" } ] }, - "msgpack": "F:\\aeth-wt\\brokkr-live-1.e2e\\res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", + "msgpack": "F:\\aeth-wt\\brokkr-live-pins.e2e\\res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", + "msgpack_packer": "msgpack.fallback", + "msgpack_purepython_env": "", "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 02706de..cf78e9b 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -56,12 +56,24 @@ class AgentTurnTests(unittest.TestCase): def test_accepted_receipt_carries_undo_label(self): receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="abcdef0123456789", requestedBy="nibu/hands", note="x" * 300) - label = "Brokkr nibu/hands: createObject abcdef01" + label = "Brokkr nibu/hands: createObject 23456789" # the id's tail: uuid v7 ids lead with a timestamp self.assertEqual(self.bpy.undo.pushes, [label]) self.assertEqual(receipt["undoLabel"], label) self.assertEqual(receipt["requestedBy"], "nibu/hands") self.assertEqual(len(receipt["note"]), 200) + def test_two_sends_a_minute_apart_get_distinct_labels(self): + # brokkr-ctl ids are uuid v7: the first 8 hex are one value per 65 seconds, the tail is random + self.run_action(action="createObject", objectType="EMPTY", commandId="01a21e88" + "0" * 16 + "aaaa1111") + self.run_action(action="createObject", objectType="EMPTY", commandId="01a21e88" + "0" * 16 + "bbbb2222") + self.assertEqual(len(set(self.bpy.undo.pushes)), 2, self.bpy.undo.pushes) + + def test_architecture_page_does_not_call_the_debug_json_an_import_path(self): + page = (SOURCE.parents[3] / "docs" / "architecture.md").read_text(encoding="utf-8") + for line in page.splitlines(): + if "debug" in line.lower() and "json" in line.lower(): + self.assertNotRegex(line.lower(), r"import", line) + def test_refusal_pushes_nothing(self): receipt = self.run_action(action="createObject", objectType="BOGUS") self.assertEqual(receipt["status"], "failed") @@ -79,7 +91,7 @@ class AgentTurnTests(unittest.TestCase): self.bpy.ops.object.empty_add = boom receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="deadbeef99") self.assertEqual(receipt["status"], "failed") - self.assertEqual(self.bpy.undo.pushes, ["Brokkr nibu/hands: createObject deadbeef (failed)"]) + self.assertEqual(self.bpy.undo.pushes, ["Brokkr nibu/hands: createObject adbeef99 (failed)"]) def test_agent_turn_flag_is_scoped(self): seen = [] diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index 6aeee39..f69cc07 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -559,7 +559,11 @@ class NodeActionTests(unittest.TestCase): self.accepted(action="linkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A") self.accepted(action="linkSockets", treeKey="G", fromNode="b", fromSocket="Out", toNode="c", toSocket="Size") self.refused(action="unlinkSockets", treeKey="G", fromNode="zzz", fromSocket="Out", toNode="c", toSocket="A") - self.assertIn("Removed 0", self.accepted(action="unlinkSockets", treeKey="G", fromNode="b", fromSocket="Out", toNode="c", toSocket="A")["message"]) + pushes = len(self.bpy.undo.pushes) + empty = self.accepted(action="unlinkSockets", treeKey="G", fromNode="b", fromSocket="Out", toNode="c", toSocket="A") + self.assertIn("Removed 0", empty["message"]) + self.assertEqual(len(self.bpy.undo.pushes), pushes) # nothing changed: no undo step + self.assertEqual(empty["undoLabel"], "") self.assertEqual(len(tree.links), 2) self.assertIn("Removed 1", self.accepted(action="unlinkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A")["message"]) self.assertEqual(len(tree.links), 1) From 17584e40f967e0d489d63b2f56c45c4e5ead0677 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:31:22 +0100 Subject: [PATCH 033/223] Wheel METADATA is the published file's bytes (rebuild, new sha256); a real unlinkSockets removal pins one undo step build-msgpack-wheel.py read METADATA through read_text, which folded CRLF and changed the hash PyPI's RECORD lists. The test compares the wheel's METADATA hash with the installed distribution's RECORD and failed first; the unlink test fails against a mutant that never reports a change. Co-Authored-By: Claude Sonnet 5.5 --- .../wheels/msgpack-1.2.2-py3-none-any.whl | Bin 15448 -> 15493 bytes surfaces/blender/docs/install.md | 4 ++-- .../blender/tests/test_extension_wheel.py | 16 ++++++++++++++++ surfaces/blender/tests/test_node_actions.py | 6 +++++- tools/build-msgpack-wheel.py | 2 +- 5 files changed, 24 insertions(+), 4 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-py3-none-any.whl b/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-py3-none-any.whl index 832d5453b3cd50d71b8902c0428d829b228c0c84..641dbcd4defc52d93da2caa7c3dbd742c463e507 100644 GIT binary patch delta 3977 zcmV;44|ed_c!hbe!6y#jkEuF04FCXMApig%0F!|`8k6ZK5Pw}W`X5mDe3Cp8{YZMf z)1A_DoR_bO?TPJXGHFJHL`XtS5-dPkRyzIP?^`@5N_H~ow4Ej)3G8B@-|j+hM9C9g z^1)9+8>#XkJBl8+TW35ILzbC&!KXLvR=s!_9Ysg&)@7AtT(5@gjWCAK#RYaTBedkH z{3LX{bzGGTrGEz^<1!tx(;R28Gp=qV`;SriT+R5D=gI27bJ`G1RraLadM&3SH)8Po zuFzm>&pXEX3o$r~4%)2?t$q>Ha&Z0j^^m<%nJ92_pDoI=FvIt4hDq*(xoGf@g7pa>65l)j-P4;2$eE;Ot@!8Agug_mbS<-I(C{|0Q6I1)UpEphlNi`+HeJo5;u}OGd z2o1LRoPS-eOer!VJHJHWB%%=bD=#;k>yS;>|VBGLqmmY+FHn+J9k9M^C3&k%~Hq=*x*){PT=1Ru{12Tk&fp5%>eQ zb;zEK9z}nAU{iSSAW8z`X*7!e4RjK6NqDVK9>BN54Qi2kVE zIxSf$O2byFV&ZOUF@h1eGoAr-SyrW`MDVfH2c|(t+z9r+%kwjkKdm5O*)eR!k%Ag0 zC(L9#O@+ql735|l8U-{gcqG2LGLnzbh>3_`n z3?;EsvdRb?;60s4Q))S>T;ZZkxd5be(S452Z#7`gg=iun|~DEblovQ zVxX%t=Ph#5dYRw~Aq9hziIgoXrV*BxCDPZHuiE@p@@xAhbZkM1?U=27LhnQj2;|<( z8f={U#@R*Xh!980x;Wo{oU8zp!LuZ#R@Hm~EP|J32=|y}0^`ANq?ZA2_d_O2M4`jyTus8&WH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;nD@qb>R|}h@DpJc18l6yHW@mQl(dFV9RVU@H33rFS7=~-!rxuL*!zcv z)rDAk>p5X#FYLvQZ$aR;9X*MO+64U(9^lDp2&3ynvWg~NQKWSv@st9~|jd0tRx z2dfc>-n&xKVn0HWe^=|vD)F@xU$sVET+Ora+YsK9$t;Pjmutlw;t%|le{K3JOGXg# z9W6rTetAZ!X#zSXb;AfKZZr~6Xx-47k?cP+{$=i`HvhD53nb8#yJ zT8kd zmdX`5UuR2ge4YItvnVyq0tFxEjJm#)`ZqOyK4_r9U;_k1Rsq2l#Dvo3)gvH6JJ9_4 zHCU%itec$Zt5c_L)#c3@UuSVlYC_|9+Ayvw&Om~HHl$sJwxkX%{0o?4o{ap$w9-Q0 zX4Q6+ZC$HkR$9!BImh!*{Hp$2>44LQl3U%qX&}=m9$SL%UY;Pqp&`WRUY%+oRAtkD zqgAjLp7EoSt;~GOVx;rBz6SSO)lLI>RkURNWL5g@cd> zzf5*6%gZyoSuGng!CsxQBvWYlX=UvwG!+zE-9;4+&0aQ_O!GkAcbp(7qVmEf{1iMd zAswBNI=jtm1F5=-)R(NHd?>~M4S|<`UL`$pLU?e+W>{@nJa$JnKOcmC({IBcn^S-+ ze1z$(iOcjSEvIy#zf)3n-A8tF%rRz+QklY5PbGE!?j^- zU#K__f{Ex$3&YR706wCdagp{|HVe1z`JvZro~`5WWNAKsX%0W4zM;9k&T(J=0JGpZ z5djJt-4{s-4FCX9Ad~w#UIO|wlaVzVlU_9qlY%=c0!KBIku@rl*gGl$88?%WH5!v1 xJQW-t=Zw0(0RRBF0ssIW00000000000001_0l7Dmku@5VX*?DNvpE0&007=;mJ9#@ diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 6452905..d85ab16 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -46,12 +46,12 @@ newer, any OS). msgpack then runs its pure-Python fallback, which CultLib `9fc4b Wheel provenance: msgpack 1.2.2 as installed on the build host (CPython 3.13, the PyPI release; nothing was downloaded), repacked by `tools/build-msgpack-wheel.py` from its `msgpack/__init__.py`, `exceptions.py`, -`ext.py` and `fallback.py` (the `_cmsgpack` C extension is left out) with the package's METADATA and +`ext.py` and `fallback.py` (the `_cmsgpack` C extension is left out) with the package's METADATA (read as bytes, so its hash is the one PyPI's RECORD lists) and Apache-2.0 `COPYING`. The repack is deterministic; rebuild and compare: ```text python tools/build-msgpack-wheel.py -sha256 0b53d2ea2e21782a670fc152bb104d97623cfa337940518016a6b7ded369af42 msgpack-1.2.2-py3-none-any.whl +sha256 91d288892c9622ffe1b3f1430a66956f93ae5964b4dcacf00c4eb93f3f4f65af msgpack-1.2.2-py3-none-any.whl ``` In a plain add-on directory install the wheel is not unpacked: put `msgpack` into Blender's Python diff --git a/surfaces/blender/tests/test_extension_wheel.py b/surfaces/blender/tests/test_extension_wheel.py index 36c3b0d..362e32f 100644 --- a/surfaces/blender/tests/test_extension_wheel.py +++ b/surfaces/blender/tests/test_extension_wheel.py @@ -3,6 +3,7 @@ from __future__ import annotations import base64 import hashlib +import importlib.metadata import re import tomllib import unittest @@ -33,6 +34,21 @@ class ExtensionWheelTests(unittest.TestCase): self.assertEqual(digest, "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode(), name) self.assertEqual(int(size), len(data), name) + def test_wheel_metadata_is_the_published_files_bytes(self): + """RECORD in the installed (PyPI) msgpack hashes its METADATA byte for byte; the wheel must carry the same bytes.""" + try: + dist = importlib.metadata.distribution("msgpack") + except importlib.metadata.PackageNotFoundError: + self.skipTest("msgpack is not installed here") + wheel = ADDON / self.manifest["wheels"][0] + if dist.version != "1.2.2": + self.skipTest(f"installed msgpack is {dist.version}") + expected = next(f for f in dist.files if f.name == "METADATA" and f.parent.name.endswith(".dist-info")).hash + with zipfile.ZipFile(wheel) as z: + data = z.read("msgpack-1.2.2.dist-info/METADATA") + digest = "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() + self.assertEqual(digest, f"{expected.mode}={expected.value}") + def test_install_doc_records_the_wheel_hash(self): wheel = ADDON / self.manifest["wheels"][0] recorded = re.findall(r"\b[0-9a-f]{64}\b", INSTALL.read_text(encoding="utf-8")) diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index f69cc07..eff659b 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -565,7 +565,11 @@ class NodeActionTests(unittest.TestCase): self.assertEqual(len(self.bpy.undo.pushes), pushes) # nothing changed: no undo step self.assertEqual(empty["undoLabel"], "") self.assertEqual(len(tree.links), 2) - self.assertIn("Removed 1", self.accepted(action="unlinkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A")["message"]) + pushes = len(self.bpy.undo.pushes) + removal = self.accepted(action="unlinkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A") + self.assertIn("Removed 1", removal["message"]) + self.assertEqual(len(self.bpy.undo.pushes), pushes + 1) # a real removal is one undo step + self.assertEqual(removal["undoLabel"], self.bpy.undo.pushes[-1]) self.assertEqual(len(tree.links), 1) self.accepted(action="unlinkSockets", treeKey="G", toNode="c", toSocket="Size") self.assertEqual(len(tree.links), 0) diff --git a/tools/build-msgpack-wheel.py b/tools/build-msgpack-wheel.py index a6d67af..6dbf28e 100644 --- a/tools/build-msgpack-wheel.py +++ b/tools/build-msgpack-wheel.py @@ -11,7 +11,7 @@ version = dist.version site = pathlib.Path(dist.locate_file("")) files = {f"msgpack/{name}": (site / "msgpack" / name).read_bytes() for name in PURE} info = f"msgpack-{version}.dist-info" -files[f"{info}/METADATA"] = dist.read_text("METADATA").encode() +files[f"{info}/METADATA"] = (site / info / "METADATA").read_bytes() # bytes: read_text would fold CRLF and change the hash PyPI's RECORD lists files[f"{info}/top_level.txt"] = b"msgpack\n" files[f"{info}/licenses/COPYING"] = (site / info / "licenses" / "COPYING").read_bytes() files[f"{info}/WHEEL"] = b"Wheel-Version: 1.0\nGenerator: brokkr tools/build-msgpack-wheel.py\nRoot-Is-Purelib: true\nTag: py3-none-any\n" From 044ac094b5ca6c036c6dec7e5283bea60d4b557e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:38:17 +0100 Subject: [PATCH 034/223] Stop agents: one human control turns the sink off and receipts every pending intent as stopped; presence in the panel purge_command_intents becomes stop_pending: a stopped receipt per intent, written before the intent is deleted. Stop agents, server start and server stop share that path. The timer runs one intent per tick so Stop lands between two. The panel's Agents section (active agents, pending count, last eight receipts) reads a display cache filled where receipts are written; the host snapshot carries agentCommandsEnabled, which brokkr-ctl status prints. Live proof on stock Blender 5.3 with real brokkr-ctl sends: tests/live/stop_presence.py. Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/src/blender.rs | 4 +- brokkr-ctl/tests/cli.rs | 4 +- surfaces/blender/brokkr_bridge/__init__.py | 98 +++++- .../blender/brokkr_bridge/blender_target.py | 116 ++++++- .../blender/brokkr_bridge/server_guard.py | 21 +- surfaces/blender/docs/install.md | 20 +- surfaces/blender/tests/live/gn_actions.py | 4 +- surfaces/blender/tests/live/gn_recreation.py | 4 +- surfaces/blender/tests/live/stop_presence.py | 254 ++++++++++++++ .../tests/live/stop_presence.result.json | 280 ++++++++++++++++ surfaces/blender/tests/test_agent_turn.py | 4 + surfaces/blender/tests/test_server_guard.py | 55 ++- surfaces/blender/tests/test_stop_presence.py | 313 ++++++++++++++++++ 13 files changed, 1118 insertions(+), 59 deletions(-) create mode 100644 surfaces/blender/tests/live/stop_presence.py create mode 100644 surfaces/blender/tests/live/stop_presence.result.json create mode 100644 surfaces/blender/tests/test_stop_presence.py diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index 36e7245..be25999 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -335,7 +335,7 @@ fn status(store: &SingleFileMessagePackBackingStore) -> Result { "activeObjectName", "selectedObjectNames", "objectCount", - "sink", + "agentCommandsEnabled", ] { if let Some(value) = snapshot.get(key) { print_field(key, value); @@ -401,7 +401,7 @@ brokkr-ctl blender: send typed intents to the live Blender add-on and read what Write one intent, then wait for its receipt and print it. `send --help` lists actions. wait [--timeout secs] Wait for a receipt and print it. receipts [--last n] Print stored receipts, oldest first. - status Print the host snapshot summary. + status Print the host snapshot summary, agentCommandsEnabled included. Every command needs --store or $BROKKR_BLENDER_STORE (the add-on's .ccmp). send needs $EUREKA_INSTANCE and --agent or $BROKKR_AGENT; requestedBy is '/'. diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 6161f6b..4ea7f24 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -326,12 +326,12 @@ fn receipts_sort_by_observed_time_not_by_key() { fn status_prints_the_snapshot_summary() { let dir = tempfile::tempdir().unwrap(); let path = store_with_receipts(dir.path(), &[]); - let snapshot = json!({"mode": "OBJECT", "activeScene": "Scene", "objectCount": 3, "selectedObjectNames": ["Cube"], "sink": {"enabled": true}}); + let snapshot = json!({"mode": "OBJECT", "activeScene": "Scene", "objectCount": 3, "selectedObjectNames": ["Cube"], "agentCommandsEnabled": false}); push(&path, &[envelope_at("brokkr.blender.host_snapshot.v0", "blender/host/current", &snapshot)]); let output = ctl(&path, &["status"], None); assert_eq!(output.status.code(), Some(0)); let text = stdout(&output); - for line in ["mode: OBJECT", "activeScene: Scene", "objectCount: 3", "selectedObjectNames: [\"Cube\"]", "sink: {\"enabled\":true}"] { + for line in ["mode: OBJECT", "activeScene: Scene", "objectCount: 3", "selectedObjectNames: [\"Cube\"]", "agentCommandsEnabled: false"] { assert!(text.contains(line), "{line} in {text}"); } } diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index 8a81707..1a4b5d2 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -31,6 +31,22 @@ def target(): return _target +def _sink_changed(prefs): + """The sink toggle moved: the stored host snapshot says so, so brokkr-ctl status never reads a stale toggle. + A node nothing has opened yet holds no snapshot to correct.""" + adapter = target() + if adapter.node_open: + adapter.publish_snapshot(bpy.context, prefs.cultmesh_cache_path, prefs.cultlib_py_src, + prefs.debug_mirror_root, prefs.auto_drain_commands) + + +def _redraw(): + for window in bpy.context.window_manager.windows: + for area in window.screen.areas: + if area.type == "VIEW_3D": + area.tag_redraw() + + class BrokkrPreferences(bpy.types.AddonPreferences): bl_idname = __name__ @@ -84,7 +100,9 @@ class BrokkrPreferences(bpy.types.AddonPreferences): auto_drain_commands: bpy.props.BoolProperty( name="Auto Drain Commands", default=False, - description="Poll and execute pending Brokkr Blender command intents on a timer", + update=lambda self, context: _sink_changed(self), + description="The command sink: poll and run queued agent intents on a timer. Only the operator turns it on, " + "and Stop agents turns it off; no agent intent can write it", ) serve_host: bpy.props.StringProperty( @@ -333,6 +351,10 @@ class BROKKR_PT_status(bpy.types.Panel): prefs = context.preferences.addons[__name__].preferences adapter = target() + stop = layout.row() + stop.scale_y = 1.6 + stop.operator("brokkr.stop_agents", icon="CANCEL") + layout.label(text=f"Provider: {PROVIDER_ID}") layout.label(text=f"Tool: {TOOL_KIND}") layout.label(text=f"Broker: {prefs.broker_uri}") @@ -409,10 +431,20 @@ class BROKKR_PT_status(bpy.types.Panel): layout.label(text=f"Materials: {adapter.last_snapshot.get('materialCount', 0)}") layout.label(text=f"Selected: {len(adapter.last_snapshot.get('selectedObjectNames', []))}") - if adapter.last_receipt: - layout.separator() - layout.label(text=f"Last receipt: {adapter.last_receipt.get('status', '')}") - layout.label(text=adapter.last_receipt.get("message", "")) + if adapter.node_open and not adapter.receipts_loaded: + adapter.load_recent_receipts(prefs.cultmesh_cache_path, prefs.cultlib_py_src) + agents_box = layout.box() + agents_box.label(text="Agents") + agents_box.label(text=f"Agent commands: {'on' if prefs.auto_drain_commands else 'off'}") + active = adapter.active_agents() + agents_box.label(text=f"Active: {', '.join(active)}" if active else "Active: none in the last 5 minutes") + agents_box.label(text=f"Pending: {adapter.pending_count}") + for item in adapter.recent_receipts(): + agents_box.label(text=f"{item.get('requestedBy') or '?'} {item.get('action', '')} {item.get('status', '')}") + if item.get("note"): + agents_box.label(text=f" {item['note']}") + if item.get("undoLabel"): + agents_box.label(text=f" {item['undoLabel']}") if adapter.last_auto_drain_error: layout.separator() @@ -438,11 +470,31 @@ class BROKKR_OT_capture_snapshot(bpy.types.Operator): prefs.cultmesh_cache_path, prefs.cultlib_py_src, prefs.debug_mirror_root, + prefs.auto_drain_commands, ) self.report({"INFO"}, f"Brokkr mirrored Blender snapshot: {snapshot['observedAt']}") return {"FINISHED"} +class BROKKR_OT_stop_agents(bpy.types.Operator): + bl_idname = "brokkr.stop_agents" + bl_label = "Stop agents" + bl_description = ("Turn agent commands off and give every pending intent a 'stopped' receipt without running it. " + "An action already running finishes as one undo step; Ctrl+Z takes it back") + + def execute(self, context): + prefs = context.preferences.addons[__name__].preferences + prefs.auto_drain_commands = False + try: + stopped = target().stop_pending("stopped by the operator", prefs.cultmesh_cache_path, + prefs.cultlib_py_src, prefs.debug_mirror_root) + except Exception as exc: + self.report({"ERROR"}, f"Agent commands are off, but pending intents could not be stopped: {exc}") + return {"CANCELLED"} + self.report({"INFO"}, f"Agent commands off; {stopped} pending intent(s) stopped.") + return {"FINISHED"} + + class BROKKR_OT_drain_commands(bpy.types.Operator): bl_idname = "brokkr.drain_commands" bl_label = "Drain Commands" @@ -616,39 +668,49 @@ def _auto_capture(scene, depsgraph): prefs.preferences.cultmesh_cache_path, prefs.preferences.cultlib_py_src, prefs.preferences.debug_mirror_root, + prefs.preferences.auto_drain_commands, ) +BUSY_INTERVAL = 0.05 # one intent per tick: Stop is a UI event, and it lands between two intents +IDLE_INTERVAL = 1.0 + + def _auto_drain_commands(): context = bpy.context addon = context.preferences.addons.get(__name__) adapter = target() if not addon: - return 1.0 + return IDLE_INTERVAL prefs = addon.preferences - if not prefs.auto_drain_commands: - adapter.last_auto_drain_error = "" - return 1.0 - + ran = 0 + pending_before = adapter.pending_count try: - adapter.configure_action_dirs(prefs.import_dir, prefs.output_dir) - adapter.drain_commands( - context, - prefs.cultmesh_cache_path, - prefs.cultlib_py_src, - prefs.debug_mirror_root, - ) + if adapter.node_open: + adapter.count_pending(prefs.cultmesh_cache_path, prefs.cultlib_py_src) + if prefs.auto_drain_commands: + adapter.configure_action_dirs(prefs.import_dir, prefs.output_dir) + ran = len(adapter.drain_commands( + context, + prefs.cultmesh_cache_path, + prefs.cultlib_py_src, + prefs.debug_mirror_root, + limit=1, + )) adapter.last_auto_drain_error = "" except Exception as exc: adapter.last_auto_drain_error = str(exc) - return 1.0 + if ran or adapter.pending_count != pending_before: + _redraw() + return BUSY_INTERVAL if ran else IDLE_INTERVAL classes = ( BrokkrPreferences, BROKKR_PT_status, + BROKKR_OT_stop_agents, BROKKR_OT_capture_snapshot, BROKKR_OT_drain_commands, BROKKR_OT_start_server, diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 8302a69..33a332a 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -9,13 +9,14 @@ import re import sys import uuid from array import array -from datetime import datetime, timezone +from collections import deque +from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any, Iterable from . import node_actions as na from . import scene_actions as sa -from .server_guard import BindRefused, SessionGuard, check_bind, guarded_server_class, is_loopback_host, purge_command_intents +from .server_guard import BindRefused, SessionGuard, check_bind, guarded_server_class, is_loopback_host, stop_pending PROVIDER_ID = "brokkr.blender_editor" TOOL_KIND = "blender-editor" @@ -63,6 +64,9 @@ REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") # out: it separates the '.denied' suffix). COMMAND_ID_SHAPE = re.compile(r"^[A-Za-z0-9_-]{1,128}$") NOTE_LIMIT = 200 +ACTIVE_AGENT_WINDOW = timedelta(minutes=5) # an agent is active when a receipt of its own is this recent +RECEIPTS_SHOWN = 8 +RECEIPTS_KEPT = 64 # the display cache; the node holds the receipts EVALUATED_POSITION_CAP = 256 EVALUATED_VERTEX_LIMIT = 1_000_000 @@ -99,7 +103,6 @@ class BrokkrBlenderTarget: def __init__(self, bpy_module: Any): self.bpy = bpy_module self.last_snapshot: dict[str, Any] | None = None - self.last_receipt: dict[str, Any] | None = None self.last_sync_receipt: dict[str, Any] | None = None self.last_auto_drain_error: str = "" self._node_key: tuple[str, str, str] | None = None @@ -115,6 +118,9 @@ class BrokkrBlenderTarget: self.agent_turn = False # true only inside run_intent self._wrote = True # run_intent: false when an accepted action changed nothing self._receipted: set[str] = set() + self._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts + self._receipts_loaded = False + self.pending_count = 0 # display cache: intents queued in the node def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: """The directories importGltf and renderStill may touch; empty leaves that action disabled.""" @@ -133,8 +139,9 @@ class BrokkrBlenderTarget: cache_path: str, cultlib_py_src: str, debug_mirror_root: str = "", + agent_commands_enabled: bool = False, ) -> dict[str, Any]: - snapshot = self.capture_snapshot(context) + snapshot = self.capture_snapshot(context, agent_commands_enabled) node, documents = self._open_node(cache_path, cultlib_py_src) node.database.put(documents["host_snapshot"], "blender/host/current", snapshot) if debug_mirror_root: @@ -148,16 +155,16 @@ class BrokkrBlenderTarget: cache_path: str, cultlib_py_src: str, debug_mirror_root: str = "", + limit: int | None = None, ) -> list[dict[str, Any]]: + """Run queued intents, oldest key first: all of them, or at most `limit`, the rest staying queued.""" node, documents = self._open_node(cache_path, cultlib_py_src) snapshot = node.database.snapshot() commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] - self._receipted.update( - r["commandId"] for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values() - if isinstance(r.get("commandId"), str)) + self._seed_receipted(snapshot) - for command_key, command in sorted(commands.items()): + for command_key, command in sorted(commands.items())[:limit]: command_id = command.get("commandId") valid = _valid_command_id(command_id) reused = valid and command_id in self._receipted @@ -183,12 +190,86 @@ class BrokkrBlenderTarget: debug_mirror_root: str = "", key_suffix: str = "", ) -> None: - command_id = (receipt.get("commandId") or uuid.uuid4().hex) + key_suffix node, documents = self._open_node(cache_path, cultlib_py_src) + self._put_receipt(node, documents, receipt, debug_mirror_root, key_suffix) + + def _put_receipt(self, node: Any, documents: dict[str, Any], receipt: dict[str, Any], + debug_mirror_root: str = "", key_suffix: str = "") -> None: + """The one place a receipt is written: the node, the debug export, and the panel's display cache.""" + command_id = (receipt.get("commandId") or uuid.uuid4().hex) + key_suffix node.database.put(documents["command_receipt"], f"blender/receipts/{command_id}", receipt) if debug_mirror_root: self._write_debug_document(debug_mirror_root, f"blender/receipts/{command_id}.json", receipt) - self.last_receipt = receipt + self.note_receipt(receipt) + + def _seed_receipted(self, snapshot: dict[str, Any]) -> None: + self._receipted.update( + r["commandId"] for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values() + if isinstance(r.get("commandId"), str)) + + def stop_pending(self, reason: str, cache_path: str, cultlib_py_src: str, debug_mirror_root: str = "") -> int: + """The Stop button's path: every queued intent gets a 'stopped' receipt and leaves the queue unrun.""" + node, documents = self._open_node(cache_path, cultlib_py_src) + return self._stop_pending(node, documents, reason, debug_mirror_root) + + def _stop_pending(self, node: Any, documents: dict[str, Any], reason: str, debug_mirror_root: str = "") -> int: + """Stop, server start and server stop all take intents off the queue here and nowhere else.""" + if node is None: + return 0 + self._seed_receipted(node.database.snapshot()) + + def write(queue_key: str, intent: dict[str, Any], why: str) -> None: + valid = _valid_command_id(intent.get("commandId")) + reused = valid and intent["commandId"] in self._receipted + receipt = self._receipt(intent, "stopped", f"Stopped ({why}); the intent was not run and nothing was changed.", "") + if not valid: + receipt["message"] += f" (queue key {queue_key})" + self._put_receipt(node, documents, receipt, debug_mirror_root, ".stopped" if reused else "") + if valid: + self._receipted.add(intent["commandId"]) # the id is spent: the sender resends under a new one + + return stop_pending(node, documents["command_intent"], COMMAND_INTENT_SCHEMA, write, reason) + + def note_receipt(self, receipt: dict[str, Any]) -> None: + self._recent.append(receipt) + + def recent_receipts(self) -> list[dict[str, Any]]: + """The last few receipts, newest first.""" + return list(self._recent)[::-1][:RECEIPTS_SHOWN] + + def active_agents(self) -> list[str]: + """Distinct requestedBy among receipts from the last five minutes, in order of first appearance.""" + cutoff = datetime.now(timezone.utc) - ACTIVE_AGENT_WINDOW + agents: dict[str, None] = {} + for item in self._recent: + who, seen = item.get("requestedBy"), _parse_time(item.get("observedAt")) + if who and seen is not None and seen >= cutoff: + agents[who] = None + return list(agents) + + def load_recent_receipts(self, cache_path: str, cultlib_py_src: str) -> None: + """Rebuild the display cache from the node's receipts, once: it replaces what this session noted, since each of those was written to the node.""" + if self._receipts_loaded: + return + node, _documents = self._open_node(cache_path, cultlib_py_src) + stored = sorted(node.database.snapshot().get(COMMAND_RECEIPT_SCHEMA, {}).values(), + key=lambda r: str(r.get("observedAt", ""))) + self._recent = deque(stored, maxlen=RECEIPTS_KEPT) # the node holds every receipt this session noted + self._receipts_loaded = True + + def count_pending(self, cache_path: str, cultlib_py_src: str) -> int: + node, _documents = self._open_node(cache_path, cultlib_py_src) + node.database.pull() + self.pending_count = len(node.database.snapshot().get(COMMAND_INTENT_SCHEMA, {})) + return self.pending_count + + @property + def receipts_loaded(self) -> bool: + return self._receipts_loaded + + @property + def node_open(self) -> bool: + return self._node is not None def refresh_sync_receipt( self, @@ -387,7 +468,7 @@ class BrokkrBlenderTarget: self.stop_server() self._cultmesh_module = "" - purge_command_intents(node, documents["command_intent"], COMMAND_INTENT_SCHEMA) + self._stop_pending(node, documents, "server started") cultmesh, _cultcache = _load_cultmesh(cultlib_py_src) self._cultmesh_module = str(getattr(cultmesh, "__file__", "") or "") verse_catalog = cultmesh.CultMesh.create_verse_catalog() @@ -458,7 +539,7 @@ class BrokkrBlenderTarget: finally: try: if was_running and self._node is not None: - purge_command_intents(self._node, self._documents["command_intent"], COMMAND_INTENT_SCHEMA) + self._stop_pending(self._node, self._documents, "server stopped") finally: self._server = None self._server_key = None @@ -490,7 +571,7 @@ class BrokkrBlenderTarget: "cultmeshModule": self._cultmesh_module, } - def capture_snapshot(self, context: Any) -> dict[str, Any]: + def capture_snapshot(self, context: Any, agent_commands_enabled: bool) -> dict[str, Any]: bpy = self.bpy scan = self._instance_scan() if any(o.type == "MESH" and len(o.modifiers) for o in bpy.data.objects) else None selected = [item.name for item in context.selected_objects if item is not None] @@ -513,6 +594,7 @@ class BrokkrBlenderTarget: "collectionCount": len(bpy.data.collections), "materialCount": len(bpy.data.materials), "imageCount": len(bpy.data.images), + "agentCommandsEnabled": bool(agent_commands_enabled), "capabilities": list(CAPABILITIES), "scenes": [self._scene_snapshot(scene) for scene in bpy.data.scenes], "objects": [self._object_snapshot(obj, scan) for obj in bpy.data.objects], @@ -1249,6 +1331,14 @@ def missing_gl_library() -> str | None: return None +def _parse_time(value: Any) -> datetime | None: + try: + parsed = datetime.fromisoformat(value) + except (TypeError, ValueError): + return None + return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc) + + def _now() -> str: return datetime.now(timezone.utc).isoformat() diff --git a/surfaces/blender/brokkr_bridge/server_guard.py b/surfaces/blender/brokkr_bridge/server_guard.py index 0dbba80..ff91c12 100644 --- a/surfaces/blender/brokkr_bridge/server_guard.py +++ b/surfaces/blender/brokkr_bridge/server_guard.py @@ -3,7 +3,7 @@ Stdlib only, no bpy: everything here is unit-testable without Blender. Always on: a non-loopback bind needs an explicit allow (check_bind), and command -intents queued before a start or stop are purged (purge_command_intents). +intents queued before a start or stop are stopped with a receipt each (stop_pending). Opt-in: a per-session token, checked on every document put and delete when the user turns it on in the add-on preferences (SessionGuard, guarded_server_class). """ @@ -12,7 +12,7 @@ from __future__ import annotations import hmac import ipaddress import secrets -from typing import Any +from typing import Any, Callable PUT_SCHEMA_VERSIONS = ("cultnet.document_put_raw.v0", "cultnet.document_delete.v0") TOKEN_FIELD = "sessionToken" @@ -90,12 +90,17 @@ def guarded_server_class(base: type, guard: SessionGuard) -> type: return GuardedServer -def purge_command_intents(node: Any, command_document: Any, command_schema: str) -> int: - """Delete every queued command intent from the node. Returns how many were removed.""" - removed = 0 +def stop_pending(node: Any, command_document: Any, command_schema: str, + write_receipt: Callable[[str, dict[str, Any], str], None], reason: str) -> int: + """Take every queued command intent off the node without running it: write_receipt(queue key, intent, reason) + first, then delete the intent. An intent whose receipt cannot be written stays queued and the error + propagates, so nothing leaves the queue unreceipted. Returns how many were stopped. Stop, server start + and server stop all come through here; `reason` says why, for the receipt.""" + stopped = 0 if node is not None: node.database.pull() - for key in list(node.database.snapshot().get(command_schema, {})): + for key, intent in list(node.database.snapshot().get(command_schema, {}).items()): + write_receipt(key, intent, reason) node.database.delete(command_document, key) - removed += 1 - return removed + stopped += 1 + return stopped diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index d85ab16..c04ad92 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -69,13 +69,27 @@ at `0` to bind a free local port, or set a fixed port when another runtime needs a stable endpoint. The panel reports the active `cultnet://host:port` endpoint after `Start Server`. +## Stop and the Agents panel + +`Stop agents` sits at the top of the Brokkr panel. It turns `Auto Drain Commands` (the command sink) off, then gives +every pending intent a `stopped` receipt without running it: the same path as `Start Server` and `Stop Server`. +Only the operator turns the sink on; no intent writes add-on preferences. The timer runs one intent per tick, so +Stop lands between two intents; an action already running finishes as one undo step, and `Ctrl+Z` takes it back. +A stopped intent's id is spent: the agent resends under a new id once the operator turns the sink back on. + +The `Agents` section lists the agents active in the last five minutes (distinct `requestedBy` among receipts), +the number of pending intents, and the last eight receipts as ` ` with their note and +undo label. It is a display cache of the node's receipts, rebuilt from the node on first draw. The host snapshot +carries `agentCommandsEnabled`, which `brokkr-ctl blender status` prints. + ## Server Safety Always on: -- `Start Server` and `Stop Server` purge queued command intents: every - `brokkr.blender.command_intent.v0` record in the node. Intents queued before a - start never run under the new session. +- `Start Server` and `Stop Server` stop queued command intents: each + `brokkr.blender.command_intent.v0` record in the node gets a receipt with status `stopped` that names the + reason, then leaves the queue unrun. Intents queued before a start never run under the new session, and the + sender (`brokkr-ctl wait`, exit 3) learns they were stopped. - After `Start Server` the panel shows the bind address, port and the file `cultmesh_py` was actually loaded from (its `__file__`, not the preference). - A `Serve Host` that is not loopback (`0.0.0.0`, a LAN address, a hostname diff --git a/surfaces/blender/tests/live/gn_actions.py b/surfaces/blender/tests/live/gn_actions.py index 62df949..9d86395 100644 --- a/surfaces/blender/tests/live/gn_actions.py +++ b/surfaces/blender/tests/live/gn_actions.py @@ -37,7 +37,7 @@ def ok(t, **cmd): r = act(t, **cmd); check("%s %s" % (cmd["action"], cmd.get("id") or cmd.get("treeKey") or cmd.get("objectName") or ""), r["status"] == "accepted", r["message"]); return r def evaluated(t, name): - snap = t.capture_snapshot(bpy.context) + snap = t.capture_snapshot(bpy.context, False) return [o for o in snap["objects"] if o["name"] == name][0]["evaluated"] def native_tree(build): @@ -254,7 +254,7 @@ def heavy(n, instanced): else: links = [("grid", "Mesh", "gout", "Geometry")] graph(tt, "Heavy", GEO_OUT, nodes, links); host(tt, "HeavyHost", "Heavy") - t0 = time.time(); snap = tt.capture_snapshot(bpy.context); dt = time.time() - t0 + t0 = time.time(); snap = tt.capture_snapshot(bpy.context, False); dt = time.time() - t0 return dt, [o for o in snap["objects"] if o["name"] == "HeavyHost"][0]["evaluated"] dt, ev = heavy(2000, True) R["capture_2000_grid_instanced_seconds"] = round(dt, 3) diff --git a/surfaces/blender/tests/live/gn_recreation.py b/surfaces/blender/tests/live/gn_recreation.py index f8127d9..c7dc47d 100644 --- a/surfaces/blender/tests/live/gn_recreation.py +++ b/surfaces/blender/tests/live/gn_recreation.py @@ -104,7 +104,7 @@ getattr(hob.modifiers["GN"].properties.inputs, ident).__setattr__("value", 5) before = len(evaluated_verts(hob)) r = act(t, action="setObjectCustomProperty", targetObjectName="ParamHost", propertyName=ident, value=12) after = len(evaluated_verts(hob)) -snap = t.capture_snapshot(bpy.context) +snap = t.capture_snapshot(bpy.context, False) ho = [o for o in snap["objects"] if o["name"] == "ParamHost"][0] gap("custom_property_does_not_drive_modifier", receipt=r["status"], verts_before=before, verts_after=after, identifier=ident, snapshot_modifier=ho["modifiers"], snapshot_mesh=ho["mesh"], @@ -153,7 +153,7 @@ g.links.new(grid.outputs["Mesh"], dis.inputs["Mesh"]); g.links.new(dis.outputs[" g.links.new(cone.outputs["Mesh"], iop.inputs["Instance"]); g.links.new(iop.outputs["Instances"], gout.inputs["Geometry"]) ob = host("ScatterHost", g); native = sorted(evaluated_instances(ob)) # what Brokkr can see of that object -snap = t.capture_snapshot(bpy.context); so = [o for o in snap["objects"] if o["name"] == "ScatterHost"][0] +snap = t.capture_snapshot(bpy.context, False); so = [o for o in snap["objects"] if o["name"] == "ScatterHost"][0] gap("snapshot_not_evaluated", brokkr_sees=so["mesh"], modifiers=so["modifiers"], evaluated_instances=len(native), repro="host object with Distribute->InstanceOnPoints: snapshot mesh.vertexCount=0, no instance count, no positions") # (a) replay the native points through actions (needs a side channel that is not Brokkr) diff --git a/surfaces/blender/tests/live/stop_presence.py b/surfaces/blender/tests/live/stop_presence.py new file mode 100644 index 0000000..e23f990 --- /dev/null +++ b/surfaces/blender/tests/live/stop_presence.py @@ -0,0 +1,254 @@ +"""Live proof, in GUI Blender with the add-on enabled, of Stop and presence, with real brokkr-ctl sends. + + BROKKR_SCRATCH= + BROKKR_CTL= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + blender --factory-startup --python stop_presence.py -- + +The driver stands in for the operator's hands only: it ticks the sink preference on and runs the add-on's own +"Stop agents" operator. Every intent is sent by brokkr-ctl; the add-on's timer drains them. Undo is read only here. +Writes .result.json, then quits Blender. +""" +import importlib +import json +import os +import re +import subprocess +import sys +import traceback +from pathlib import Path + +import bpy + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +CTL = os.environ["BROKKR_CTL"] +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": [], "notes": {}} + +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") +prefs = bpy.context.preferences.addons[MODULE].preferences +CACHE = str(SCRATCH / "stop.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +prefs.auto_drain_commands = False +adapter = addon.target() +ENV = dict(os.environ, EUREKA_INSTANCE="nibu", BROKKR_BLENDER_STORE=CACHE, BROKKR_AGENT="hands") +S = {"ids": []} + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def ctl(*args): + done = subprocess.run([CTL, "blender", *args], env=ENV, capture_output=True, text=True, timeout=30) + return done.returncode, done.stdout + + +def send(name, note): + code, out = ctl("send", "createObject", "--set", 'objectType="EMPTY"', "--set", f'name="{name}"', + "--note", note, "--no-wait") + match = re.search(r"commandId:\s*(\S+)", out) + assert code == 0 and match, (code, out) + return match.group(1) + + +def receipts(): + node, _ = adapter._open_node(CACHE, prefs.cultlib_py_src) + return {r["commandId"]: r for r in node.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).values()} + + +def pending(): + node, _ = adapter._open_node(CACHE, prefs.cultlib_py_src) + return list(node.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {})) + + +def empties(prefix): + return sorted(o.name for o in bpy.data.objects if o.name.startswith(prefix)) + + +def win(): + return bpy.context.temp_override(window=bpy.context.window_manager.windows[0]) + + +class Recorder: + """A layout that records the panel's labels and operators; the real BROKKR_PT_status.draw runs against it.""" + def __init__(self): + self.labels, self.operators = [], [] + + def __getattr__(self, name): + if name == "label": + return lambda text="", **kw: self.labels.append(text) + if name == "operator": + return lambda idname, **kw: self.operators.append(idname) + return lambda *a, **kw: self + + +def panel(): + layout = Recorder() + addon.BROKKR_PT_status.draw(type("Drawn", (), {"layout": layout})(), bpy.context) + return layout + + +# ---- steps ------------------------------------------------------------------------------------------------- + +def s_setup(): + with win(): + bpy.ops.brokkr.start_server() + bpy.ops.brokkr.capture_snapshot() + code, out = ctl("status") + check("setup: server up, sink off, brokkr-ctl status shows agentCommandsEnabled: false", + adapter.server_status()["running"] and code == 0 and "agentCommandsEnabled: false" in out, out) + + +def s_burst(): + S["ids"] = [send(f"B{n:02d}", "burst") for n in range(12)] + adapter.count_pending(CACHE, prefs.cultlib_py_src) + check("burst: 12 brokkr-ctl sends queue while the sink is off; nothing ran", + len(pending()) == 12 and not empties("B") and adapter.pending_count == 12, [len(pending()), empties("B")]) + + +def s_sink_on(): + prefs.auto_drain_commands = True # the operator ticks the sink + code, out = ctl("status") + check("sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", "agentCommandsEnabled: true" in out, out) + + +def started(): + return len(receipts()) >= 2 + + +def s_stop(): + S["at_stop"] = sorted(receipts()) + S["panel_before"] = panel().labels # what she sees the moment before she presses Stop, mid-burst + with win(): + S["stop_result"] = bpy.ops.brokkr.stop_agents() + S["after_stop_pending"] = pending() + + +def s_after_stop(): + rs = receipts() + ours = {i: rs.get(i) for i in S["ids"]} + states = {i: (r or {}).get("status") for i, r in ours.items()} + accepted = [i for i, s in states.items() if s == "accepted"] + stopped = [i for i, s in states.items() if s == "stopped"] + R["notes"]["states"] = states + R["notes"]["at_stop_receipted"] = len(S["at_stop"]) + check("stop: every one of the 12 intents has a receipt, each accepted or stopped, none missing", + len(accepted) + len(stopped) == 12 and len(stopped) >= 1 and len(accepted) >= 2, states) + check("stop: the queue is empty and the sink is off", pending() == [] and prefs.auto_drain_commands is False + and S["stop_result"] == {"FINISHED"}, [pending(), S["stop_result"]]) + check("stop: exactly the accepted intents ran, in key order, and the stopped ones left no object", + len(empties("B")) == len(accepted), [empties("B"), len(accepted)]) + check("stop: each accepted intent is one labelled undo step the receipt names", + all(rs[i]["undoLabel"].startswith("Brokkr nibu/hands: createObject ") for i in accepted), + [rs[i]["undoLabel"] for i in accepted][:3]) + check("stop: stopped receipts say who, what and why, and were never given an undo label", + all(rs[i]["requestedBy"] == "nibu/hands" and rs[i]["action"] == "createObject" and rs[i]["undoLabel"] == "" + and "stopped by the operator" in rs[i]["message"] for i in stopped), [rs[i]["message"] for i in stopped][:1]) + exits = {} + for i in S["ids"]: + code, out = ctl("wait", i, "--timeout", "5") + exits[i] = (states[i], code) + R["notes"]["wait_exits"] = exits + check("stop: brokkr-ctl wait exits 0 for accepted and the distinct 3 for stopped", + all(code == (0 if st == "accepted" else 3) for st, code in exits.values()), sorted(set(exits.values()))) + code, out = ctl("status") + check("stop: brokkr-ctl status now reads agentCommandsEnabled: false", "agentCommandsEnabled: false" in out, out) + S["accepted"], S["stopped"] = accepted, stopped + + +def s_undo(): + before = len(empties("B")) + with win(): + bpy.ops.ed.undo() + after = len(empties("B")) + check("stop + Ctrl+Z: one undo takes back the last agent step, nothing else", before - after == 1, [before, after]) + + +def s_panel(): + before = "\n".join(S["panel_before"]) + R["notes"]["panel_before_stop"] = S["panel_before"] + check("panel mid-burst: the agent is active, intents are pending, accepted receipts show note and undo label", + "Active: nibu/hands" in before and "Agent commands: on" in before and re.search(r"Pending: [1-9]", before) + and "nibu/hands createObject accepted" in before and "burst" in before + and "Brokkr nibu/hands: createObject" in before + and before.count("createObject accepted") == len(S["at_stop"]), before) # each receipt listed once + layout = panel() + text = "\n".join(layout.labels) + R["notes"]["panel_labels"] = layout.labels + check("panel after Stop: Stop agents is the first operator drawn", layout.operators[:1] == ["brokkr.stop_agents"], layout.operators[:3]) + check("panel after Stop: commands off, pending 0, the stopped receipts listed with who and what", + "Agent commands: off" in text and "Pending: 0" in text and "nibu/hands createObject stopped" in text, text) + + +def s_server_stop(): + S["ids2"] = [send(f"S{n}", "server-stop") for n in range(3)] + check("server stop: three intents queued behind a running server, sink off", len(pending()) == 3) + with win(): + bpy.ops.brokkr.stop_server() + rs = receipts() + check("server stop: the same path gives each a stopped receipt naming 'server stopped'", + pending() == [] and all(rs[i]["status"] == "stopped" and "server stopped" in rs[i]["message"] for i in S["ids2"]) + and not empties("S"), [rs[i]["message"] for i in S["ids2"]][:1]) + + +def s_server_start(): + S["ids3"] = [send(f"T{n}", "server-start") for n in range(2)] + with win(): + bpy.ops.brokkr.start_server() + rs = receipts() + exits = [ctl("wait", i, "--timeout", "5")[0] for i in S["ids3"]] + check("server start: intents queued while stopped get stopped receipts naming 'server started', wait exits 3", + pending() == [] and all(rs[i]["status"] == "stopped" and "server started" in rs[i]["message"] for i in S["ids3"]) + and exits == [3, 3] and not empties("T"), [exits, [rs[i]["message"] for i in S["ids3"]][:1]]) + + +def s_final(): + check("no add-on drain error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + with win(): + bpy.ops.brokkr.stop_server() + + +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +# The add-on's own timer drains between our ticks. Stop is pressed as soon as two receipts exist, so the burst +# is cut in the middle. +def runner(): + global i + try: + if i >= len(steps): + write() + bpy.ops.wm.quit_blender() + return None + step = steps[i] + if step == "wait-two": + if started(): + s_stop() + i += 1 + return 0.005 + step() + i += 1 + write() + return 0.5 if step is not s_sink_on else 0.005 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + write() + bpy.ops.wm.quit_blender() + return None + + +steps = [s_setup, s_burst, s_sink_on, "wait-two", s_after_stop, s_undo, s_panel, s_server_stop, s_server_start, s_final] +bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/stop_presence.result.json b/surfaces/blender/tests/live/stop_presence.result.json new file mode 100644 index 0000000..6bbb5cb --- /dev/null +++ b/surfaces/blender/tests/live/stop_presence.result.json @@ -0,0 +1,280 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "setup: server up, sink off, brokkr-ctl status shows agentCommandsEnabled: false", + "ok": true, + "detail": "observedAt: 2026-11-27T20:37:49.797904+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: false\n" + }, + { + "name": "burst: 12 brokkr-ctl sends queue while the sink is off; nothing ran", + "ok": true, + "detail": [ + 12, + [] + ] + }, + { + "name": "sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", + "ok": true, + "detail": "observedAt: 2026-11-27T20:37:51.169335+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: true\n" + }, + { + "name": "stop: every one of the 12 intents has a receipt, each accepted or stopped, none missing", + "ok": true, + "detail": { + "01a21eba859d7b21aa7e23791e640a17": "accepted", + "01a21eba85d175a083c1e8e542bbed1d": "accepted", + "01a21eba860f74f1b73c707054d48792": "stopped", + "01a21eba864b7881ba64c540fc461d4d": "stopped", + "01a21eba86a97292a71e1ca6d8acb2d8": "stopped", + "01a21eba86f2722093b458840f45af3a": "stopped", + "01a21eba87577fc1b50a0de908986e13": "stopped", + "01a21eba87b87f919b2dfac978be3b57": "stopped", + "01a21eba881c7a9286a621369083ac7b": "stopped", + "01a21eba886a7833ae7ff3224cdc4e29": "stopped", + "01a21eba88d978f3b5db769bb462f99b": "stopped", + "01a21eba897772009d540695cd6453cc": "stopped" + } + }, + { + "name": "stop: the queue is empty and the sink is off", + "ok": true, + "detail": [ + [], + "{'FINISHED'}" + ] + }, + { + "name": "stop: exactly the accepted intents ran, in key order, and the stopped ones left no object", + "ok": true, + "detail": [ + [ + "B00", + "B01" + ], + 2 + ] + }, + { + "name": "stop: each accepted intent is one labelled undo step the receipt names", + "ok": true, + "detail": [ + "Brokkr nibu/hands: createObject 1e640a17", + "Brokkr nibu/hands: createObject 42bbed1d" + ] + }, + { + "name": "stop: stopped receipts say who, what and why, and were never given an undo label", + "ok": true, + "detail": [ + "Stopped (stopped by the operator); the intent was not run and nothing was changed." + ] + }, + { + "name": "stop: brokkr-ctl wait exits 0 for accepted and the distinct 3 for stopped", + "ok": true, + "detail": [ + [ + "accepted", + 0 + ], + [ + "stopped", + 3 + ] + ] + }, + { + "name": "stop: brokkr-ctl status now reads agentCommandsEnabled: false", + "ok": true, + "detail": "observedAt: 2026-11-27T20:37:52.309838+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: B01\nselectedObjectNames: [\"B01\"]\nobjectCount: 5\nagentCommandsEnabled: false\n" + }, + { + "name": "stop + Ctrl+Z: one undo takes back the last agent step, nothing else", + "ok": true, + "detail": [ + 2, + 1 + ] + }, + { + "name": "panel mid-burst: the agent is active, intents are pending, accepted receipts show note and undo label", + "ok": true, + "detail": "Provider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:53223\nBind: 127.0.0.1:53223\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 3\nMaterials: 2\nSelected: 1\nAgents\nAgent commands: on\nActive: nibu/hands\nPending: 11\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject 42bbed1d\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject 1e640a17" + }, + { + "name": "panel after Stop: Stop agents is the first operator drawn", + "ok": true, + "detail": [ + "brokkr.stop_agents", + "brokkr.capture_snapshot", + "brokkr.drain_commands" + ] + }, + { + "name": "panel after Stop: commands off, pending 0, the stopped receipts listed with who and what", + "ok": true, + "detail": "Provider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:53223\nBind: 127.0.0.1:53223\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 5\nMaterials: 2\nSelected: 1\nAgents\nAgent commands: off\nActive: nibu/hands\nPending: 0\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst" + }, + { + "name": "server stop: three intents queued behind a running server, sink off", + "ok": true, + "detail": null + }, + { + "name": "server stop: the same path gives each a stopped receipt naming 'server stopped'", + "ok": true, + "detail": [ + "Stopped (server stopped); the intent was not run and nothing was changed." + ] + }, + { + "name": "server start: intents queued while stopped get stopped receipts naming 'server started', wait exits 3", + "ok": true, + "detail": [ + [ + 3, + 3 + ], + [ + "Stopped (server started); the intent was not run and nothing was changed." + ] + ] + }, + { + "name": "no add-on drain error", + "ok": true, + "detail": "" + } + ], + "notes": { + "states": { + "01a21eba859d7b21aa7e23791e640a17": "accepted", + "01a21eba85d175a083c1e8e542bbed1d": "accepted", + "01a21eba860f74f1b73c707054d48792": "stopped", + "01a21eba864b7881ba64c540fc461d4d": "stopped", + "01a21eba86a97292a71e1ca6d8acb2d8": "stopped", + "01a21eba86f2722093b458840f45af3a": "stopped", + "01a21eba87577fc1b50a0de908986e13": "stopped", + "01a21eba87b87f919b2dfac978be3b57": "stopped", + "01a21eba881c7a9286a621369083ac7b": "stopped", + "01a21eba886a7833ae7ff3224cdc4e29": "stopped", + "01a21eba88d978f3b5db769bb462f99b": "stopped", + "01a21eba897772009d540695cd6453cc": "stopped" + }, + "at_stop_receipted": 2, + "wait_exits": { + "01a21eba859d7b21aa7e23791e640a17": [ + "accepted", + 0 + ], + "01a21eba85d175a083c1e8e542bbed1d": [ + "accepted", + 0 + ], + "01a21eba860f74f1b73c707054d48792": [ + "stopped", + 3 + ], + "01a21eba864b7881ba64c540fc461d4d": [ + "stopped", + 3 + ], + "01a21eba86a97292a71e1ca6d8acb2d8": [ + "stopped", + 3 + ], + "01a21eba86f2722093b458840f45af3a": [ + "stopped", + 3 + ], + "01a21eba87577fc1b50a0de908986e13": [ + "stopped", + 3 + ], + "01a21eba87b87f919b2dfac978be3b57": [ + "stopped", + 3 + ], + "01a21eba881c7a9286a621369083ac7b": [ + "stopped", + 3 + ], + "01a21eba886a7833ae7ff3224cdc4e29": [ + "stopped", + 3 + ], + "01a21eba88d978f3b5db769bb462f99b": [ + "stopped", + 3 + ], + "01a21eba897772009d540695cd6453cc": [ + "stopped", + 3 + ] + }, + "panel_before_stop": [ + "Provider: brokkr.blender_editor", + "Tool: blender-editor", + "Broker: cultmesh://brokkr", + "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", + "Server: cultnet://127.0.0.1:53223", + "Bind: 127.0.0.1:53223", + "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", + "Object Sync", + "Timeline / Cinemachine", + "Ad Hoc Sync Var", + "Objects: 3", + "Materials: 2", + "Selected: 1", + "Agents", + "Agent commands: on", + "Active: nibu/hands", + "Pending: 11", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject 42bbed1d", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject 1e640a17" + ], + "panel_labels": [ + "Provider: brokkr.blender_editor", + "Tool: blender-editor", + "Broker: cultmesh://brokkr", + "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", + "Server: cultnet://127.0.0.1:53223", + "Bind: 127.0.0.1:53223", + "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", + "Object Sync", + "Timeline / Cinemachine", + "Ad Hoc Sync Var", + "Objects: 5", + "Materials: 2", + "Selected: 1", + "Agents", + "Agent commands: off", + "Active: nibu/hands", + "Pending: 0", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst" + ] + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index cf78e9b..b052cc9 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -236,6 +236,10 @@ class FakeNode: self.puts = [] self.deleted = [] self.database = self + self.runtime_id = "fake" + + def pull(self): + pass def snapshot(self): return {k: dict(v) for k, v in self.docs.items()} diff --git a/surfaces/blender/tests/test_server_guard.py b/surfaces/blender/tests/test_server_guard.py index d726162..e4490fa 100644 --- a/surfaces/blender/tests/test_server_guard.py +++ b/surfaces/blender/tests/test_server_guard.py @@ -131,7 +131,10 @@ class FakeDatabase: self.pulls += 1 def snapshot(self): - return {self.schema: {k: {} for k in self.keys}, "other.v0": {"keep": {}}} + return {self.schema: {k: {"commandId": k} for k in self.keys}, "other.v0": {"keep": {}}} + + def put(self, document, key, value): + pass def delete(self, document, key): self.deleted.append((document, key)) @@ -143,16 +146,32 @@ class FakeNode: self.database = FakeDatabase(bt.COMMAND_INTENT_SCHEMA, keys) -class PurgeTests(unittest.TestCase): - def test_purge_removes_queued_intents(self): +class StopPendingTests(unittest.TestCase): + def test_stop_pending_receipts_each_intent_then_deletes_it(self): node = FakeNode(["c1", "c2"]) - removed = sg.purge_command_intents(node, "DOC", bt.COMMAND_INTENT_SCHEMA) + events = [] + removed = sg.stop_pending(node, "DOC", bt.COMMAND_INTENT_SCHEMA, + lambda key, intent, reason: events.append(("receipt", key, intent["commandId"], reason)), + "why") self.assertEqual(removed, 2) self.assertEqual(node.database.deleted, [("DOC", "c1"), ("DOC", "c2")]) + self.assertEqual(events, [("receipt", "c1", "c1", "why"), ("receipt", "c2", "c2", "why")]) - def test_purge_without_a_node_is_quiet(self): - self.assertEqual(sg.purge_command_intents(None, "DOC", bt.COMMAND_INTENT_SCHEMA), 0) + def test_an_intent_whose_receipt_cannot_be_written_is_not_deleted(self): + node = FakeNode(["c1", "c2"]) + def writer(key, intent, reason): + if key == "c2": + raise OSError("disk full") + with self.assertRaises(OSError): + sg.stop_pending(node, "DOC", bt.COMMAND_INTENT_SCHEMA, writer, "why") + self.assertEqual(node.database.deleted, [("DOC", "c1")]) + self.assertEqual(node.database.keys, ["c2"]) + + def test_stop_pending_without_a_node_is_quiet(self): + self.assertEqual(sg.stop_pending(None, "DOC", bt.COMMAND_INTENT_SCHEMA, lambda k, i, r: 1 / 0, "why"), 0) + +class StopServerTests(unittest.TestCase): def test_stop_server_purges_and_revokes(self): target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) stopped = [] @@ -161,7 +180,7 @@ class PurgeTests(unittest.TestCase): guard = target._guard old = guard.token target._node = FakeNode(["c1"]) - target._documents = {"command_intent": "DOC"} + target._documents = {"command_intent": "DOC", "command_receipt": "RDOC"} target.stop_server() self.assertEqual(stopped, [True]) self.assertEqual(target._node.database.keys, []) @@ -178,7 +197,7 @@ class PurgeTests(unittest.TestCase): guard = target._guard old = guard.token target._node = FakeNode(["c1"]) - target._documents = {"command_intent": "DOC"} + target._documents = {"command_intent": "DOC", "command_receipt": "RDOC"} with self.assertRaises(OSError): target.stop_server() self.assertFalse(guard.admits({sg.TOKEN_FIELD: old})) @@ -195,7 +214,7 @@ class PurgeTests(unittest.TestCase): def test_stop_server_with_no_server_running_purges_nothing(self): target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) target._node = FakeNode(["c1"]) - target._documents = {"command_intent": "DOC"} + target._documents = {"command_intent": "DOC", "command_receipt": "RDOC"} target.stop_server() self.assertEqual(target._node.database.keys, ["c1"]) @@ -272,6 +291,22 @@ class RealServerTests(unittest.TestCase): fresh.database.pull() return list(fresh.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {})) + def receipt_states(self): + """commandId -> (status, reason) of the receipts a fresh node reads from disk.""" + cultmesh, cultcache = bt._load_cultmesh(PACKAGES) + fresh = cultmesh.CultMesh.start_node(self.cache, runtime_id="receipt-reader") + fresh.database.register_document(cultcache.define_document_type(bt.COMMAND_RECEIPT_SCHEMA)) + fresh.database.pull() + found = fresh.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).values() + return {r["commandId"]: (r["status"], r["message"]) for r in found} + + def assertStopped(self, reason): + states = self.receipt_states() + self.assertEqual(list(states), ["q1"]) + status, message = states["q1"] + self.assertEqual(status, "stopped") + self.assertIn(reason, message) + def test_start_purges_intents_queued_in_the_node_and_they_stay_gone_after_reopening(self): self.queue_intent() self.assertEqual(len(self.queued(self.cache)), 1) @@ -279,12 +314,14 @@ class RealServerTests(unittest.TestCase): node, _ = self.target._open_node(self.cache, PACKAGES) self.assertEqual(list(node.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {})), []) self.assertEqual(self.queued(self.cache), []) + self.assertStopped("server started") def test_stop_purges_intents_queued_while_running_and_they_stay_gone_after_reopening(self): self.start() self.queue_intent() self.target.stop_server() self.assertEqual(self.queued(self.cache), []) + self.assertStopped("server stopped") def test_allow_true_goes_through_start_server_and_unticking_stops_it(self): status = self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py new file mode 100644 index 0000000..6e77f68 --- /dev/null +++ b/surfaces/blender/tests/test_stop_presence.py @@ -0,0 +1,313 @@ +"""Stop and presence: one human control turns the sink off and receipts every pending intent as stopped; +the panel's agent activity is derived from receipts. A fake bpy and a fake node database; no Blender. +""" +from __future__ import annotations + +import re +import types +import unittest +import unittest.mock +from collections import deque +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import test_agent_turn as tat +import test_scene_actions as ts +import test_addon_ui as ui + +bt = ts.bt +NS = types.SimpleNamespace +addon = ui.addon +BRIDGE = Path(bt.__file__).parent +DOCS = {"command_intent": "i", "command_receipt": "r"} + + +class StopFixture(unittest.TestCase): + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + intent = tat.DrainTests.intent + + def patched(self, node): + patch = unittest.mock.patch.object(self.target, "_open_node", return_value=(node, DOCS)) + patch.start() + self.addCleanup(patch.stop) + + +class StopPendingTests(StopFixture): + def queue(self): + return tat.FakeNode({f"blender/commands/{n}": self.intent(n, requestedBy=who) + for n, who in (("q-1", "nibu/hands"), ("q-2", "nibu/hands"), ("q-3", "nibu/soul"))}) + + def test_stop_receipts_every_pending_intent(self): + node = self.queue() + self.patched(node) + stopped = self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual(stopped, 3) + receipts = dict(node.puts) + self.assertEqual(sorted(receipts), [f"blender/receipts/q-{n}" for n in (1, 2, 3)]) + for key, receipt in receipts.items(): + self.assertEqual(receipt["status"], "stopped", key) + self.assertIn("stopped by the operator", receipt["message"]) + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(receipt["action"], "createObject") + self.assertEqual(receipts["blender/receipts/q-3"]["requestedBy"], "nibu/soul") + self.assertEqual(sorted(node.deleted), sorted(node.docs[bt.COMMAND_INTENT_SCHEMA])) + self.assertEqual(self.bpy.created, []) # none dispatched + self.assertEqual(self.bpy.undo.pushes, []) + + def test_every_intent_is_receipted_before_it_is_deleted(self): + node = self.queue() + events = [] + node.put = lambda document, key, value: events.append(("put", key)) + node.delete = lambda document, key: events.append(("delete", key)) + self.patched(node) + self.target.stop_pending("stopped by the operator", "cache", "src") + for n in (1, 2, 3): + self.assertLess(events.index(("put", f"blender/receipts/q-{n}")), + events.index(("delete", f"blender/commands/q-{n}"))) + + def test_a_failed_receipt_write_leaves_the_intent_queued(self): + node = self.queue() + + def put(document, key, value): + raise OSError("disk full") + node.put = put + self.patched(node) + with self.assertRaises(OSError): + self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual(node.deleted, []) # no silent delete + + def test_a_stopped_id_is_spent_and_a_reused_id_keeps_its_original_receipt(self): + old = {"blender/receipts/q-1": {"commandId": "q-1", "status": "accepted"}} + node = tat.FakeNode({"blender/commands/a": self.intent("q-1"), "blender/commands/b": self.intent("q-2")}, old) + self.patched(node) + self.target.stop_pending("stopped by the operator", "cache", "src") + keys = [k for k, _ in node.puts] + self.assertNotIn("blender/receipts/q-1", keys) # write-once: the accepted receipt stands + self.assertIn("blender/receipts/q-1.stopped", keys) + self.assertIn("blender/receipts/q-2", keys) + later = self.run_action(action="createObject", objectType="EMPTY", commandId="q-2") + self.assertEqual(later["status"], "denied") # the sender resends under a new id + self.assertEqual(self.bpy.created, []) + + def test_a_malformed_id_is_receipted_under_a_fresh_key_naming_the_queue_key(self): + node = tat.FakeNode({"blender/commands/odd": self.intent(["x"])}) + self.patched(node) + self.target.stop_pending("stopped by the operator", "cache", "src") + ((key, receipt),) = node.puts + self.assertNotIn("[", key) + self.assertEqual(receipt["status"], "stopped") + self.assertIn("blender/commands/odd", receipt["message"]) + self.assertEqual(node.deleted, ["blender/commands/odd"]) + + def test_stop_with_nothing_pending_writes_nothing(self): + node = tat.FakeNode({}) + self.patched(node) + self.assertEqual(self.target.stop_pending("stopped by the operator", "cache", "src"), 0) + self.assertEqual((node.puts, node.deleted), ([], [])) + + def test_server_stop_and_start_receipt_with_their_own_reasons(self): + node = self.queue() + self.target._node, self.target._documents = node, DOCS + self.target._server = NS(stop=lambda: None) + self.target.stop_server() + self.assertEqual({v["status"] for _, v in node.puts}, {"stopped"}) + self.assertTrue(all("server stopped" in v["message"] for _, v in node.puts)) + self.assertEqual(len(node.deleted), 3) + + def test_start_server_receipts_stale_intents(self): + node = self.queue() + self.patched(node) + with unittest.mock.patch.object(bt, "_load_cultmesh", side_effect=RuntimeError("stop here")): + with self.assertRaises(RuntimeError): + self.target.start_server("cache", "src", "127.0.0.1", 0, 10, 1 << 20) + self.assertEqual({v["status"] for _, v in node.puts}, {"stopped"}) + self.assertTrue(all("server started" in v["message"] for _, v in node.puts)) + self.assertEqual(len(node.deleted), 3) + + +class DrainLimitTests(StopFixture): + def test_a_limited_drain_runs_that_many_and_leaves_the_rest_queued_for_stop(self): + node = tat.FakeNode({f"blender/commands/{n}": self.intent(n) for n in ("b-1", "b-2", "b-3")}) + node.delete = lambda document, key: (node.deleted.append(key), node.docs[bt.COMMAND_INTENT_SCHEMA].pop(key)) + self.patched(node) + receipts = self.target.drain_commands(self.context, "cache", "src", limit=1) + self.assertEqual([r["commandId"] for r in receipts], ["b-1"]) + self.assertEqual(node.deleted, ["blender/commands/b-1"]) + self.target.stop_pending("stopped by the operator", "cache", "src") + stopped = {v["commandId"]: v["status"] for _, v in node.puts} + self.assertEqual(stopped, {"b-1": "accepted", "b-2": "stopped", "b-3": "stopped"}) + self.assertEqual(len(self.bpy.created), 1) + + +class SnapshotTests(StopFixture): + def test_the_snapshot_carries_the_sink_toggle(self): + self.bpy.data = NS(objects=[], scenes=[], materials=[], images=[], collections=[], filepath="") + self.bpy.app = NS(version=(5, 3, 0)) + context = NS(selected_objects=[], active_object=None, scene=self.bpy.scene, mode="OBJECT") + for enabled in (True, False): + self.assertIs(self.target.capture_snapshot(context, enabled)["agentCommandsEnabled"], enabled) + + +def receipt(agent, action, status, minutes_ago=0, note="", undo="", key="k"): + when = datetime.now(timezone.utc) - timedelta(minutes=minutes_ago) + return {"commandId": key, "requestedBy": agent, "action": action, "status": status, "note": note, + "undoLabel": undo, "observedAt": when.isoformat(), "message": ""} + + +class PresenceTests(StopFixture): + def test_active_agents_are_distinct_requesters_in_the_last_five_minutes(self): + self.target.note_receipt(receipt("nibu/hands", "createObject", "accepted", 1)) + self.target.note_receipt(receipt("nibu/hands", "addNode", "accepted", 2)) + self.target.note_receipt(receipt("nibu/soul", "selectObject", "stopped", 4)) + self.target.note_receipt(receipt("nibu/eyes", "selectObject", "accepted", 6)) + self.assertEqual(self.target.active_agents(), ["nibu/hands", "nibu/soul"]) + + def test_recent_receipts_are_the_last_eight_newest_first(self): + for n in range(12): + self.target.note_receipt(receipt("nibu/hands", f"a{n}", "accepted", key=f"k{n}")) + self.assertEqual([r["action"] for r in self.target.recent_receipts()], [f"a{n}" for n in range(11, 3, -1)]) + + def test_publish_receipt_and_stop_both_fill_the_display_cache(self): + node = tat.FakeNode({"blender/commands/s-1": self.intent("s-1")}) + self.patched(node) + self.target.publish_receipt("cache", "src", receipt("nibu/hands", "createObject", "accepted", key="p-1")) + self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual({r["commandId"]: r["status"] for r in self.target.recent_receipts()}, + {"p-1": "accepted", "s-1": "stopped"}) + + def test_first_load_rebuilds_the_cache_from_the_node_once(self): + stored = {f"blender/receipts/{n}": receipt("nibu/hands", "createObject", "accepted", n, key=f"n{n}") + for n in range(1, 4)} + node = tat.FakeNode({}, stored) + self.patched(node) + self.target.load_recent_receipts("cache", "src") + self.assertEqual([r["commandId"] for r in self.target.recent_receipts()], ["n1", "n2", "n3"]) + node.docs[bt.COMMAND_RECEIPT_SCHEMA]["blender/receipts/x"] = receipt("a/b", "x", "accepted", key="x") + self.target.load_recent_receipts("cache", "src") + self.assertEqual(len(self.target.recent_receipts()), 3) # loaded once + + def test_loading_after_receipts_were_noted_lists_each_receipt_once(self): + stored = {"blender/receipts/n1": receipt("nibu/hands", "createObject", "accepted", 1, key="n1")} + node = tat.FakeNode({}, stored) + self.patched(node) + self.target.note_receipt(stored["blender/receipts/n1"]) # written by this session before the first draw + self.target.load_recent_receipts("cache", "src") + self.assertEqual([r["commandId"] for r in self.target.recent_receipts()], ["n1"]) + + def test_pending_count_comes_from_the_node(self): + node = tat.FakeNode({"blender/commands/a": self.intent("a"), "blender/commands/b": self.intent("b")}) + self.patched(node) + self.assertEqual(self.target.count_pending("cache", "src"), 2) + + +class PanelAndOperatorTests(unittest.TestCase): + def setUp(self): + self.target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=lambda p: p))) + addon._target = self.target + self.addCleanup(lambda: setattr(addon, "_target", None)) + self.prefs = unittest.mock.MagicMock(auto_drain_commands=True, cultmesh_cache_path="cache", + cultlib_py_src="src", debug_mirror_root="", broker_uri="b") + self.context = NS(preferences=NS(addons={"brokkr_addon": NS(preferences=self.prefs)})) + + def test_stop_agents_turns_the_sink_off_and_receipts_the_queue(self): + node = tat.FakeNode({"blender/commands/a": {"commandId": "a-1", "requestedBy": "x/y", "action": "createObject"}}) + with unittest.mock.patch.object(self.target, "_open_node", return_value=(node, DOCS)): + operator = addon.BROKKR_OT_stop_agents() + result = operator.execute(self.context) + self.assertEqual(result, {"FINISHED"}) + self.assertFalse(self.prefs.auto_drain_commands) + self.assertEqual([v["status"] for _, v in node.puts], ["stopped"]) + self.assertIn("stopped by the operator", node.puts[0][1]["message"]) + + def test_stop_agents_is_registered_and_first_in_the_panel(self): + self.assertIn(addon.BROKKR_OT_stop_agents, addon.classes) + layout = unittest.mock.MagicMock() + panel = addon.BROKKR_PT_status() + panel.layout = layout + panel.draw(self.context) + first = [c for c in layout.mock_calls if c[0] == "operator" or c[0].endswith(".operator")][0] + self.assertEqual(first.args[0], "brokkr.stop_agents") + + def test_the_sink_preference_defaults_off_and_says_only_the_operator_turns_it_on(self): + prop = addon.BrokkrPreferences.__annotations__["auto_drain_commands"] + self.assertIs(prop.kwargs["default"], False) + self.assertIn("operator", prop.kwargs["description"].lower()) + self.assertTrue(callable(prop.kwargs.get("update"))) # the stored snapshot follows the toggle + + def test_toggling_the_sink_republishes_the_stored_snapshot_once_a_node_is_open(self): + update = addon.BrokkrPreferences.__annotations__["auto_drain_commands"].kwargs["update"] + addon.bpy.context = NS() + with unittest.mock.patch.object(self.target, "publish_snapshot") as publish: + update(self.prefs, None) + publish.assert_not_called() # nothing has opened a node: no snapshot to correct + self.target._node = object() + self.prefs.auto_drain_commands = False + update(self.prefs, None) + self.assertEqual(publish.call_args.args[-1], False) + + def test_the_agents_section_lists_agents_pending_and_receipts(self): + self.target.note_receipt(receipt("nibu/hands", "createObject", "accepted", 1, note="a cube", + undo="Brokkr nibu/hands: createObject abcd1234")) + self.target.note_receipt(receipt("nibu/soul", "setLight", "stopped", 2)) + self.target.pending_count = 3 + self.target._receipts_loaded = True + layout = unittest.mock.MagicMock() + panel = addon.BROKKR_PT_status() + panel.layout = layout + panel.draw(self.context) + texts = [str(c.kwargs.get("text", "")) for c in layout.mock_calls if c.kwargs] + joined = "\n".join(texts) + self.assertIn("Agents", joined) + self.assertIn("nibu/hands", joined) + self.assertIn("nibu/soul setLight stopped", joined) + self.assertIn("nibu/hands createObject accepted", joined) + self.assertIn("a cube", joined) + self.assertIn("Brokkr nibu/hands: createObject abcd1234", joined) + self.assertRegex(joined, r"Pending: 3") + self.assertNotIn("Last receipt", joined) + + +class TimerTests(unittest.TestCase): + def setUp(self): + self.target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=lambda p: p))) + addon._target = self.target + self.addCleanup(lambda: setattr(addon, "_target", None)) + self.prefs = NS(auto_drain_commands=True, cultmesh_cache_path="c", cultlib_py_src="s", debug_mirror_root="", + import_dir="", output_dir="") + patch = unittest.mock.patch.object(addon, "_redraw") + self.redraws = patch.start() + self.addCleanup(patch.stop) + addon.bpy.context = NS(preferences=NS(addons=NS(get=lambda name: NS(preferences=self.prefs)))) + self.drains = [] + self.target.drain_commands = lambda *a, **k: self.drains.append(k) or [1] * self.ran + self.target.count_pending = lambda *a: 0 + self.target.configure_action_dirs = lambda *a: None + + def test_the_timer_drains_one_intent_per_tick_so_stop_lands_between_them(self): + self.ran = 1 + interval = addon._auto_drain_commands() + self.assertEqual(self.drains[0].get("limit"), 1) + self.assertLess(interval, 0.22) # more may be queued: come back soon (bound: geometric mean of the 0.05 shipped and the 1.0 idle reading) + + def test_an_empty_tick_goes_back_to_the_idle_interval(self): + self.ran = 0 + self.assertEqual(addon._auto_drain_commands(), 1.0) + + def test_with_the_sink_off_the_timer_runs_nothing(self): + self.prefs.auto_drain_commands = False + self.ran = 1 + self.assertEqual(addon._auto_drain_commands(), 1.0) + self.assertEqual(self.drains, []) + + +class NoPreferenceWritesTests(unittest.TestCase): + def test_no_action_writes_preferences(self): + # the sink toggle is the human's: no intent or action code reaches add-on preferences + for name in ("scene_actions.py", "node_actions.py", "blender_target.py"): + source = (BRIDGE / name).read_text(encoding="utf-8") + self.assertEqual(re.findall(r"[.]preferences\b|\bprefs\b", source), [], name) + + +if __name__ == "__main__": + unittest.main() From 861edd3195a95ce68fa60d72320379570d0c2e75 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:53:10 +0100 Subject: [PATCH 035/223] Stop: a sink-off add-on answers arriving intents stopped; Agents under Stop; pending zero after Stop; survivors pinned Soul s1: post-stop-queue-runs (ruling sink-off-answers-stopped), agents-section-buried, pending-stale-after-stop, stop-survivors-unpinned. The live harness now sends a concurrent burst with the sink on, cuts it with Stop, and shows a later send answered stopped at once (wait exit 3) with nothing firing on re-enable. Co-Authored-By: Claude Sonnet 5.5 --- docs/live-collab-target.md | 4 +- surfaces/blender/brokkr_bridge/__init__.py | 53 ++-- .../blender/brokkr_bridge/blender_target.py | 4 +- surfaces/blender/docs/install.md | 7 +- surfaces/blender/tests/live/stop_presence.py | 125 ++++++--- .../tests/live/stop_presence.result.json | 249 +++++++++++------- surfaces/blender/tests/test_stop_presence.py | 43 ++- 7 files changed, 320 insertions(+), 165 deletions(-) diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index 2853e5a..545df3d 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -119,7 +119,9 @@ This is scene-level only; the `.cc` keeps its revision refusal (phase two). **Stop is one control, and only the human holds it.** Stop turns the command sink off and gives every pending intent a `stopped` receipt without running it. An action already running finishes as one undo step, so Stop plus Ctrl+Z always returns her -scene. No intent can turn the sink on; intents queued before Stop never run. +scene. No intent can turn the sink on; intents queued before Stop never run, and an intent that +arrives while the sink is off gets a `stopped` receipt at once (`brokkr-live:ruling:sink-off-answers-stopped`), +so nothing queues to fire on re-enable. **The agent sees her view and her edits.** `look` is a read intent: it captures her 3D view to a scratch PNG named by command id (`brush-tree:ruling:look-files-are-scratch`) diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index 1a4b5d2..5495956 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -355,6 +355,21 @@ class BROKKR_PT_status(bpy.types.Panel): stop.scale_y = 1.6 stop.operator("brokkr.stop_agents", icon="CANCEL") + if adapter.node_open and not adapter.receipts_loaded: + adapter.load_recent_receipts(prefs.cultmesh_cache_path, prefs.cultlib_py_src) + agents_box = layout.box() + agents_box.label(text="Agents") + agents_box.label(text=f"Agent commands: {'on' if prefs.auto_drain_commands else 'off'}") + active = adapter.active_agents() + agents_box.label(text=f"Active: {', '.join(active)}" if active else "Active: none in the last 5 minutes") + agents_box.label(text=f"Pending: {adapter.pending_count}") + for item in adapter.recent_receipts(): + agents_box.label(text=f"{item.get('requestedBy') or '?'} {item.get('action', '')} {item.get('status', '')}") + if item.get("note"): + agents_box.label(text=f" {item['note']}") + if item.get("undoLabel"): + agents_box.label(text=f" {item['undoLabel']}") + layout.label(text=f"Provider: {PROVIDER_ID}") layout.label(text=f"Tool: {TOOL_KIND}") layout.label(text=f"Broker: {prefs.broker_uri}") @@ -431,21 +446,6 @@ class BROKKR_PT_status(bpy.types.Panel): layout.label(text=f"Materials: {adapter.last_snapshot.get('materialCount', 0)}") layout.label(text=f"Selected: {len(adapter.last_snapshot.get('selectedObjectNames', []))}") - if adapter.node_open and not adapter.receipts_loaded: - adapter.load_recent_receipts(prefs.cultmesh_cache_path, prefs.cultlib_py_src) - agents_box = layout.box() - agents_box.label(text="Agents") - agents_box.label(text=f"Agent commands: {'on' if prefs.auto_drain_commands else 'off'}") - active = adapter.active_agents() - agents_box.label(text=f"Active: {', '.join(active)}" if active else "Active: none in the last 5 minutes") - agents_box.label(text=f"Pending: {adapter.pending_count}") - for item in adapter.recent_receipts(): - agents_box.label(text=f"{item.get('requestedBy') or '?'} {item.get('action', '')} {item.get('status', '')}") - if item.get("note"): - agents_box.label(text=f" {item['note']}") - if item.get("undoLabel"): - agents_box.label(text=f" {item['undoLabel']}") - if adapter.last_auto_drain_error: layout.separator() layout.label(text="Auto drain error:") @@ -688,16 +688,19 @@ def _auto_drain_commands(): pending_before = adapter.pending_count try: if adapter.node_open: - adapter.count_pending(prefs.cultmesh_cache_path, prefs.cultlib_py_src) - if prefs.auto_drain_commands: - adapter.configure_action_dirs(prefs.import_dir, prefs.output_dir) - ran = len(adapter.drain_commands( - context, - prefs.cultmesh_cache_path, - prefs.cultlib_py_src, - prefs.debug_mirror_root, - limit=1, - )) + if prefs.auto_drain_commands: + adapter.configure_action_dirs(prefs.import_dir, prefs.output_dir) + ran = len(adapter.drain_commands( + context, + prefs.cultmesh_cache_path, + prefs.cultlib_py_src, + prefs.debug_mirror_root, + limit=1, + )) + adapter.count_pending(prefs.cultmesh_cache_path, prefs.cultlib_py_src) + else: # the add-on owns the sink, so it answers: nothing queues to fire on re-enable + adapter.stop_pending("agent commands are off", prefs.cultmesh_cache_path, + prefs.cultlib_py_src, prefs.debug_mirror_root) adapter.last_auto_drain_error = "" except Exception as exc: adapter.last_auto_drain_error = str(exc) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 33a332a..82be6e2 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -228,7 +228,9 @@ class BrokkrBlenderTarget: if valid: self._receipted.add(intent["commandId"]) # the id is spent: the sender resends under a new one - return stop_pending(node, documents["command_intent"], COMMAND_INTENT_SCHEMA, write, reason) + stopped = stop_pending(node, documents["command_intent"], COMMAND_INTENT_SCHEMA, write, reason) + self.pending_count = 0 + return stopped def note_receipt(self, receipt: dict[str, Any]) -> None: self._recent.append(receipt) diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index c04ad92..0b5917c 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -75,9 +75,12 @@ after `Start Server`. every pending intent a `stopped` receipt without running it: the same path as `Start Server` and `Stop Server`. Only the operator turns the sink on; no intent writes add-on preferences. The timer runs one intent per tick, so Stop lands between two intents; an action already running finishes as one undo step, and `Ctrl+Z` takes it back. -A stopped intent's id is spent: the agent resends under a new id once the operator turns the sink back on. +A stopped intent's id is spent. While the sink is off the add-on answers every intent that arrives with a +`stopped` receipt ("agent commands are off") at once, so `brokkr-ctl wait` exits 3 and nothing queues to fire when +the operator turns the sink back on. The answer needs a node the add-on has opened (a running server or a published +snapshot). -The `Agents` section lists the agents active in the last five minutes (distinct `requestedBy` among receipts), +The `Agents` section sits directly under Stop agents and lists the agents active in the last five minutes (distinct `requestedBy` among receipts), the number of pending intents, and the last eight receipts as ` ` with their note and undo label. It is a display cache of the node's receipts, rebuilt from the node on first draw. The host snapshot carries `agentCommandsEnabled`, which `brokkr-ctl blender status` prints. diff --git a/surfaces/blender/tests/live/stop_presence.py b/surfaces/blender/tests/live/stop_presence.py index e23f990..a9b176d 100644 --- a/surfaces/blender/tests/live/stop_presence.py +++ b/surfaces/blender/tests/live/stop_presence.py @@ -16,6 +16,7 @@ import os import re import subprocess import sys +import time import traceback from pathlib import Path @@ -50,14 +51,22 @@ def ctl(*args): return done.returncode, done.stdout +SEND = ["send", "createObject", "--set", 'objectType="EMPTY"'] + + def send(name, note): - code, out = ctl("send", "createObject", "--set", 'objectType="EMPTY"', "--set", f'name="{name}"', - "--note", note, "--no-wait") + code, out = ctl(*SEND, "--set", f'name="{name}"', "--note", note, "--no-wait") match = re.search(r"commandId:\s*(\S+)", out) assert code == 0 and match, (code, out) return match.group(1) +def spawn(name, note): + """A brokkr-ctl send that runs beside Blender's timers: the sender is another process, as an agent is.""" + return subprocess.Popen([CTL, "blender", *SEND, "--set", f'name="{name}"', "--note", note, "--no-wait"], + env=ENV, stdout=subprocess.PIPE, text=True) + + def receipts(): node, _ = adapter._open_node(CACHE, prefs.cultlib_py_src) return {r["commandId"]: r for r in node.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).values()} @@ -96,6 +105,8 @@ def panel(): # ---- steps ------------------------------------------------------------------------------------------------- +BURST = 20 + def s_setup(): with win(): @@ -107,16 +118,10 @@ def s_setup(): def s_burst(): - S["ids"] = [send(f"B{n:02d}", "burst") for n in range(12)] - adapter.count_pending(CACHE, prefs.cultlib_py_src) - check("burst: 12 brokkr-ctl sends queue while the sink is off; nothing ran", - len(pending()) == 12 and not empties("B") and adapter.pending_count == 12, [len(pending()), empties("B")]) - - -def s_sink_on(): prefs.auto_drain_commands = True # the operator ticks the sink code, out = ctl("status") check("sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", "agentCommandsEnabled: true" in out, out) + S["procs"] = [spawn(f"B{n:02d}", "burst") for n in range(BURST)] def started(): @@ -128,68 +133,103 @@ def s_stop(): S["panel_before"] = panel().labels # what she sees the moment before she presses Stop, mid-burst with win(): S["stop_result"] = bpy.ops.brokkr.stop_agents() - S["after_stop_pending"] = pending() - + S["pending_after_stop"] = adapter.pending_count + + +def finished(): + return all(p.poll() is not None for p in S["procs"]) and pending() == [] + def s_after_stop(): + ids = [] + for proc in S["procs"]: + match = re.search(r"commandId:\s*(\S+)", proc.stdout.read()) + ids.append(match.group(1)) + S["ids"] = ids rs = receipts() - ours = {i: rs.get(i) for i in S["ids"]} - states = {i: (r or {}).get("status") for i, r in ours.items()} - accepted = [i for i, s in states.items() if s == "accepted"] - stopped = [i for i, s in states.items() if s == "stopped"] + states = {i: (rs.get(i) or {}).get("status") for i in ids} + accepted = [i for i, st in states.items() if st == "accepted"] + stopped = [i for i, st in states.items() if st == "stopped"] R["notes"]["states"] = states - R["notes"]["at_stop_receipted"] = len(S["at_stop"]) - check("stop: every one of the 12 intents has a receipt, each accepted or stopped, none missing", - len(accepted) + len(stopped) == 12 and len(stopped) >= 1 and len(accepted) >= 2, states) - check("stop: the queue is empty and the sink is off", pending() == [] and prefs.auto_drain_commands is False - and S["stop_result"] == {"FINISHED"}, [pending(), S["stop_result"]]) - check("stop: exactly the accepted intents ran, in key order, and the stopped ones left no object", - len(empties("B")) == len(accepted), [empties("B"), len(accepted)]) + check("stop: every one of the 20 intents has a receipt, each accepted or stopped, none missing", + len(accepted) + len(stopped) == BURST and len(stopped) >= 1 and len(accepted) >= 2, states) + check("stop: the queue is empty, the sink is off, Pending read 0 the moment Stop returned", + pending() == [] and prefs.auto_drain_commands is False and S["stop_result"] == {"FINISHED"} + and S["pending_after_stop"] == 0, [pending(), S["stop_result"], S["pending_after_stop"]]) + check("stop: exactly the accepted intents ran and the stopped ones left no object", + len(empties("B")) == len(accepted), [len(empties("B")), len(accepted)]) check("stop: each accepted intent is one labelled undo step the receipt names", all(rs[i]["undoLabel"].startswith("Brokkr nibu/hands: createObject ") for i in accepted), [rs[i]["undoLabel"] for i in accepted][:3]) - check("stop: stopped receipts say who, what and why, and were never given an undo label", + check("stop: stopped receipts say who, what and why, and never carry an undo label", all(rs[i]["requestedBy"] == "nibu/hands" and rs[i]["action"] == "createObject" and rs[i]["undoLabel"] == "" - and "stopped by the operator" in rs[i]["message"] for i in stopped), [rs[i]["message"] for i in stopped][:1]) - exits = {} - for i in S["ids"]: - code, out = ctl("wait", i, "--timeout", "5") - exits[i] = (states[i], code) + and ("stopped by the operator" in rs[i]["message"] or "agent commands are off" in rs[i]["message"]) + for i in stopped), sorted({rs[i]["message"][:50] for i in stopped})) + R["notes"]["stop_reasons"] = sorted({rs[i]["message"][:48] for i in stopped}) + exits = {i: (states[i], ctl("wait", i, "--timeout", "5")[0]) for i in ids} R["notes"]["wait_exits"] = exits check("stop: brokkr-ctl wait exits 0 for accepted and the distinct 3 for stopped", all(code == (0 if st == "accepted" else 3) for st, code in exits.values()), sorted(set(exits.values()))) code, out = ctl("status") check("stop: brokkr-ctl status now reads agentCommandsEnabled: false", "agentCommandsEnabled: false" in out, out) - S["accepted"], S["stopped"] = accepted, stopped -def s_undo(): +def s_late(): + """An agent that never saw Stop sends again and waits: the add-on's timer answers at once, nothing queues.""" + S["late_began"] = time.time() + S["late"] = subprocess.Popen([CTL, "blender", *SEND, "--set", 'name="Late"', "--note", "late", "--timeout", "10"], + env=ENV, stdout=subprocess.PIPE, text=True) + + +def late_done(): + return S["late"].poll() is not None + + +def s_late_check(): + took = time.time() - S["late_began"] + out = S["late"].stdout.read() + code = S["late"].returncode + R["notes"]["late"] = {"exit": code, "seconds": round(took, 2), "out": out} + check("sink off: a send after Stop is answered stopped at once (wait exit 3, 'agent commands are off'), nothing queued", + code == 3 and took < 5 and "agent commands are off" in out and pending() == [] and not empties("Late"), + [code, took, out]) + S["receipt_count"] = len(receipts()) + prefs.auto_drain_commands = True # she turns the sink back on + + +def s_reenabled(): + check("re-enable: nothing queued fires; the late intent never runs", + pending() == [] and not empties("Late") and len(receipts()) == S["receipt_count"], + [pending(), empties("Late"), len(receipts()) - S["receipt_count"]]) before = len(empties("B")) with win(): bpy.ops.ed.undo() - after = len(empties("B")) - check("stop + Ctrl+Z: one undo takes back the last agent step, nothing else", before - after == 1, [before, after]) + check("stop + Ctrl+Z: one undo takes back the last agent step, nothing else", before - len(empties("B")) == 1, + [before, len(empties("B"))]) def s_panel(): before = "\n".join(S["panel_before"]) R["notes"]["panel_before_stop"] = S["panel_before"] - check("panel mid-burst: the agent is active, intents are pending, accepted receipts show note and undo label", - "Active: nibu/hands" in before and "Agent commands: on" in before and re.search(r"Pending: [1-9]", before) + check("panel mid-burst: Agents is first under Stop, the agent is active, accepted receipts show note and undo label, each once", + S["panel_before"].index("Agents") < S["panel_before"].index("Provider: brokkr.blender_editor") + and "Active: nibu/hands" in before and "Agent commands: on" in before and "nibu/hands createObject accepted" in before and "burst" in before and "Brokkr nibu/hands: createObject" in before - and before.count("createObject accepted") == len(S["at_stop"]), before) # each receipt listed once + and before.count("createObject accepted") == len(S["at_stop"]), before) + prefs.auto_drain_commands = False layout = panel() text = "\n".join(layout.labels) R["notes"]["panel_labels"] = layout.labels check("panel after Stop: Stop agents is the first operator drawn", layout.operators[:1] == ["brokkr.stop_agents"], layout.operators[:3]) check("panel after Stop: commands off, pending 0, the stopped receipts listed with who and what", "Agent commands: off" in text and "Pending: 0" in text and "nibu/hands createObject stopped" in text, text) + prefs.auto_drain_commands = True def s_server_stop(): - S["ids2"] = [send(f"S{n}", "server-stop") for n in range(3)] - check("server stop: three intents queued behind a running server, sink off", len(pending()) == 3) + S["ids2"] = [send(f"S{n}", "server-stop") for n in range(3)] # the sender blocks Blender's thread: they cannot drain yet + check("server stop: three intents queued behind a running server, sink on", len(pending()) == 3, len(pending())) with win(): bpy.ops.brokkr.stop_server() rs = receipts() @@ -225,7 +265,7 @@ def write(): # The add-on's own timer drains between our ticks. Stop is pressed as soon as two receipts exist, so the burst -# is cut in the middle. +# is cut in the middle; sends that arrive after it meet a sink that is off. def runner(): global i try: @@ -239,10 +279,14 @@ def runner(): s_stop() i += 1 return 0.005 + if step in ("wait-done", "wait-late"): + if (finished if step == "wait-done" else late_done)(): + i += 1 + return 0.1 step() i += 1 write() - return 0.5 if step is not s_sink_on else 0.005 + return 0.005 if step is s_burst else 0.5 except Exception: R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) write() @@ -250,5 +294,6 @@ def runner(): return None -steps = [s_setup, s_burst, s_sink_on, "wait-two", s_after_stop, s_undo, s_panel, s_server_stop, s_server_start, s_final] +steps = [s_setup, s_burst, "wait-two", "wait-done", s_after_stop, s_late, "wait-late", s_late_check, s_reenabled, s_panel, + s_server_stop, s_server_start, s_final] bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/stop_presence.result.json b/surfaces/blender/tests/live/stop_presence.result.json index 6bbb5cb..bb6f00b 100644 --- a/surfaces/blender/tests/live/stop_presence.result.json +++ b/surfaces/blender/tests/live/stop_presence.result.json @@ -5,55 +5,53 @@ { "name": "setup: server up, sink off, brokkr-ctl status shows agentCommandsEnabled: false", "ok": true, - "detail": "observedAt: 2026-11-27T20:37:49.797904+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: false\n" - }, - { - "name": "burst: 12 brokkr-ctl sends queue while the sink is off; nothing ran", - "ok": true, - "detail": [ - 12, - [] - ] + "detail": "observedAt: 2026-11-27T20:52:54.171327+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: false\n" }, { "name": "sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", "ok": true, - "detail": "observedAt: 2026-11-27T20:37:51.169335+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: true\n" + "detail": "observedAt: 2026-11-27T20:52:54.505375+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: true\n" }, { - "name": "stop: every one of the 12 intents has a receipt, each accepted or stopped, none missing", + "name": "stop: every one of the 20 intents has a receipt, each accepted or stopped, none missing", "ok": true, "detail": { - "01a21eba859d7b21aa7e23791e640a17": "accepted", - "01a21eba85d175a083c1e8e542bbed1d": "accepted", - "01a21eba860f74f1b73c707054d48792": "stopped", - "01a21eba864b7881ba64c540fc461d4d": "stopped", - "01a21eba86a97292a71e1ca6d8acb2d8": "stopped", - "01a21eba86f2722093b458840f45af3a": "stopped", - "01a21eba87577fc1b50a0de908986e13": "stopped", - "01a21eba87b87f919b2dfac978be3b57": "stopped", - "01a21eba881c7a9286a621369083ac7b": "stopped", - "01a21eba886a7833ae7ff3224cdc4e29": "stopped", - "01a21eba88d978f3b5db769bb462f99b": "stopped", - "01a21eba897772009d540695cd6453cc": "stopped" + "01a21ec852a07e139e33eba7c8c21251": "accepted", + "01a21ec852b27442b17daac0eef61b81": "accepted", + "01a21ec852b47ae08561010021792ee2": "stopped", + "01a21ec852b77eb393c0f081d680b1d3": "stopped", + "01a21ec852ce78c0b66a2c2ce666f185": "stopped", + "01a21ec852cd7d30b8ec875ee4a9272e": "stopped", + "01a21ec852ce7582bff08d6a81921ee4": "stopped", + "01a21ec852e57a009ad0e186af6f0cfa": "stopped", + "01a21ec852e57cb3859bf2d738ef586a": "stopped", + "01a21ec852ec72c0bfd939a5bb39fde3": "stopped", + "01a21ec852ec78c28d7e16c9edc4cc07": "stopped", + "01a21ec8530772339db47b279044d6f5": "stopped", + "01a21ec853237550b1855dd0f0f27269": "stopped", + "01a21ec853347ac1b822f5d61ae8afcb": "stopped", + "01a21ec853457d418b3bd09272666916": "stopped", + "01a21ec853447c328eac215160e935d8": "stopped", + "01a21ec8535375309be1eec02df779f4": "stopped", + "01a21ec853577ba393761e10d99a14d5": "stopped", + "01a21ec853617913965abb873a2228b9": "stopped", + "01a21ec853617d41884613d8831720fe": "stopped" } }, { - "name": "stop: the queue is empty and the sink is off", + "name": "stop: the queue is empty, the sink is off, Pending read 0 the moment Stop returned", "ok": true, "detail": [ [], - "{'FINISHED'}" + "{'FINISHED'}", + 0 ] }, { - "name": "stop: exactly the accepted intents ran, in key order, and the stopped ones left no object", + "name": "stop: exactly the accepted intents ran and the stopped ones left no object", "ok": true, "detail": [ - [ - "B00", - "B01" - ], + 2, 2 ] }, @@ -61,15 +59,15 @@ "name": "stop: each accepted intent is one labelled undo step the receipt names", "ok": true, "detail": [ - "Brokkr nibu/hands: createObject 1e640a17", - "Brokkr nibu/hands: createObject 42bbed1d" + "Brokkr nibu/hands: createObject c8c21251", + "Brokkr nibu/hands: createObject eef61b81" ] }, { - "name": "stop: stopped receipts say who, what and why, and were never given an undo label", + "name": "stop: stopped receipts say who, what and why, and never carry an undo label", "ok": true, "detail": [ - "Stopped (stopped by the operator); the intent was not run and nothing was changed." + "Stopped (stopped by the operator); the intent was " ] }, { @@ -89,7 +87,25 @@ { "name": "stop: brokkr-ctl status now reads agentCommandsEnabled: false", "ok": true, - "detail": "observedAt: 2026-11-27T20:37:52.309838+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: B01\nselectedObjectNames: [\"B01\"]\nobjectCount: 5\nagentCommandsEnabled: false\n" + "detail": "observedAt: 2026-11-27T20:52:55.144050+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: B01\nselectedObjectNames: [\"B01\"]\nobjectCount: 5\nagentCommandsEnabled: false\n" + }, + { + "name": "sink off: a send after Stop is answered stopped at once (wait exit 3, 'agent commands are off'), nothing queued", + "ok": true, + "detail": [ + 3, + 0.6096086502075195, + "commandId: 01a21ec8598f754383d402238c3af85d\naction: createObject\ncommandId: 01a21ec8598f754383d402238c3af85d\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T20:52:56.732437+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + ] + }, + { + "name": "re-enable: nothing queued fires; the late intent never runs", + "ok": true, + "detail": [ + [], + [], + 0 + ] }, { "name": "stop + Ctrl+Z: one undo takes back the last agent step, nothing else", @@ -100,9 +116,9 @@ ] }, { - "name": "panel mid-burst: the agent is active, intents are pending, accepted receipts show note and undo label", + "name": "panel mid-burst: Agents is first under Stop, the agent is active, accepted receipts show note and undo label, each once", "ok": true, - "detail": "Provider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:53223\nBind: 127.0.0.1:53223\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 3\nMaterials: 2\nSelected: 1\nAgents\nAgent commands: on\nActive: nibu/hands\nPending: 11\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject 42bbed1d\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject 1e640a17" + "detail": "Agents\nAgent commands: on\nActive: nibu/hands\nPending: 18\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject eef61b81\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject c8c21251\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:55445\nBind: 127.0.0.1:55445\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 3\nMaterials: 2\nSelected: 1" }, { "name": "panel after Stop: Stop agents is the first operator drawn", @@ -116,12 +132,12 @@ { "name": "panel after Stop: commands off, pending 0, the stopped receipts listed with who and what", "ok": true, - "detail": "Provider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:53223\nBind: 127.0.0.1:53223\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 5\nMaterials: 2\nSelected: 1\nAgents\nAgent commands: off\nActive: nibu/hands\nPending: 0\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst" + "detail": "Agents\nAgent commands: off\nActive: nibu/hands\nPending: 0\nnibu/hands createObject stopped\n late\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:55445\nBind: 127.0.0.1:55445\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 4\nMaterials: 2\nSelected: 1" }, { - "name": "server stop: three intents queued behind a running server, sink off", + "name": "server stop: three intents queued behind a running server, sink on", "ok": true, - "detail": null + "detail": 3 }, { "name": "server stop: the same path gives each a stopped receipt naming 'server stopped'", @@ -151,115 +167,149 @@ ], "notes": { "states": { - "01a21eba859d7b21aa7e23791e640a17": "accepted", - "01a21eba85d175a083c1e8e542bbed1d": "accepted", - "01a21eba860f74f1b73c707054d48792": "stopped", - "01a21eba864b7881ba64c540fc461d4d": "stopped", - "01a21eba86a97292a71e1ca6d8acb2d8": "stopped", - "01a21eba86f2722093b458840f45af3a": "stopped", - "01a21eba87577fc1b50a0de908986e13": "stopped", - "01a21eba87b87f919b2dfac978be3b57": "stopped", - "01a21eba881c7a9286a621369083ac7b": "stopped", - "01a21eba886a7833ae7ff3224cdc4e29": "stopped", - "01a21eba88d978f3b5db769bb462f99b": "stopped", - "01a21eba897772009d540695cd6453cc": "stopped" + "01a21ec852a07e139e33eba7c8c21251": "accepted", + "01a21ec852b27442b17daac0eef61b81": "accepted", + "01a21ec852b47ae08561010021792ee2": "stopped", + "01a21ec852b77eb393c0f081d680b1d3": "stopped", + "01a21ec852ce78c0b66a2c2ce666f185": "stopped", + "01a21ec852cd7d30b8ec875ee4a9272e": "stopped", + "01a21ec852ce7582bff08d6a81921ee4": "stopped", + "01a21ec852e57a009ad0e186af6f0cfa": "stopped", + "01a21ec852e57cb3859bf2d738ef586a": "stopped", + "01a21ec852ec72c0bfd939a5bb39fde3": "stopped", + "01a21ec852ec78c28d7e16c9edc4cc07": "stopped", + "01a21ec8530772339db47b279044d6f5": "stopped", + "01a21ec853237550b1855dd0f0f27269": "stopped", + "01a21ec853347ac1b822f5d61ae8afcb": "stopped", + "01a21ec853457d418b3bd09272666916": "stopped", + "01a21ec853447c328eac215160e935d8": "stopped", + "01a21ec8535375309be1eec02df779f4": "stopped", + "01a21ec853577ba393761e10d99a14d5": "stopped", + "01a21ec853617913965abb873a2228b9": "stopped", + "01a21ec853617d41884613d8831720fe": "stopped" }, - "at_stop_receipted": 2, + "stop_reasons": [ + "Stopped (stopped by the operator); the intent wa" + ], "wait_exits": { - "01a21eba859d7b21aa7e23791e640a17": [ + "01a21ec852a07e139e33eba7c8c21251": [ "accepted", 0 ], - "01a21eba85d175a083c1e8e542bbed1d": [ + "01a21ec852b27442b17daac0eef61b81": [ "accepted", 0 ], - "01a21eba860f74f1b73c707054d48792": [ + "01a21ec852b47ae08561010021792ee2": [ "stopped", 3 ], - "01a21eba864b7881ba64c540fc461d4d": [ + "01a21ec852b77eb393c0f081d680b1d3": [ "stopped", 3 ], - "01a21eba86a97292a71e1ca6d8acb2d8": [ + "01a21ec852ce78c0b66a2c2ce666f185": [ "stopped", 3 ], - "01a21eba86f2722093b458840f45af3a": [ + "01a21ec852cd7d30b8ec875ee4a9272e": [ "stopped", 3 ], - "01a21eba87577fc1b50a0de908986e13": [ + "01a21ec852ce7582bff08d6a81921ee4": [ "stopped", 3 ], - "01a21eba87b87f919b2dfac978be3b57": [ + "01a21ec852e57a009ad0e186af6f0cfa": [ "stopped", 3 ], - "01a21eba881c7a9286a621369083ac7b": [ + "01a21ec852e57cb3859bf2d738ef586a": [ "stopped", 3 ], - "01a21eba886a7833ae7ff3224cdc4e29": [ + "01a21ec852ec72c0bfd939a5bb39fde3": [ "stopped", 3 ], - "01a21eba88d978f3b5db769bb462f99b": [ + "01a21ec852ec78c28d7e16c9edc4cc07": [ "stopped", 3 ], - "01a21eba897772009d540695cd6453cc": [ + "01a21ec8530772339db47b279044d6f5": [ + "stopped", + 3 + ], + "01a21ec853237550b1855dd0f0f27269": [ + "stopped", + 3 + ], + "01a21ec853347ac1b822f5d61ae8afcb": [ + "stopped", + 3 + ], + "01a21ec853457d418b3bd09272666916": [ + "stopped", + 3 + ], + "01a21ec853447c328eac215160e935d8": [ + "stopped", + 3 + ], + "01a21ec8535375309be1eec02df779f4": [ + "stopped", + 3 + ], + "01a21ec853577ba393761e10d99a14d5": [ + "stopped", + 3 + ], + "01a21ec853617913965abb873a2228b9": [ + "stopped", + 3 + ], + "01a21ec853617d41884613d8831720fe": [ "stopped", 3 ] }, + "late": { + "exit": 3, + "seconds": 0.61, + "out": "commandId: 01a21ec8598f754383d402238c3af85d\naction: createObject\ncommandId: 01a21ec8598f754383d402238c3af85d\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T20:52:56.732437+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + }, "panel_before_stop": [ + "Agents", + "Agent commands: on", + "Active: nibu/hands", + "Pending: 18", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject eef61b81", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject c8c21251", "Provider: brokkr.blender_editor", "Tool: blender-editor", "Broker: cultmesh://brokkr", "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", - "Server: cultnet://127.0.0.1:53223", - "Bind: 127.0.0.1:53223", + "Server: cultnet://127.0.0.1:55445", + "Bind: 127.0.0.1:55445", "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", "Object Sync", "Timeline / Cinemachine", "Ad Hoc Sync Var", "Objects: 3", "Materials: 2", - "Selected: 1", - "Agents", - "Agent commands: on", - "Active: nibu/hands", - "Pending: 11", - "nibu/hands createObject accepted", - " burst", - " Brokkr nibu/hands: createObject 42bbed1d", - "nibu/hands createObject accepted", - " burst", - " Brokkr nibu/hands: createObject 1e640a17" + "Selected: 1" ], "panel_labels": [ - "Provider: brokkr.blender_editor", - "Tool: blender-editor", - "Broker: cultmesh://brokkr", - "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", - "Server: cultnet://127.0.0.1:53223", - "Bind: 127.0.0.1:53223", - "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", - "Object Sync", - "Timeline / Cinemachine", - "Ad Hoc Sync Var", - "Objects: 5", - "Materials: 2", - "Selected: 1", "Agents", "Agent commands: off", "Active: nibu/hands", "Pending: 0", "nibu/hands createObject stopped", - " burst", + " late", "nibu/hands createObject stopped", " burst", "nibu/hands createObject stopped", @@ -273,7 +323,20 @@ "nibu/hands createObject stopped", " burst", "nibu/hands createObject stopped", - " burst" + " burst", + "Provider: brokkr.blender_editor", + "Tool: blender-editor", + "Broker: cultmesh://brokkr", + "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", + "Server: cultnet://127.0.0.1:55445", + "Bind: 127.0.0.1:55445", + "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", + "Object Sync", + "Timeline / Cinemachine", + "Ad Hoc Sync Var", + "Objects: 4", + "Materials: 2", + "Selected: 1" ] }, "ok": true diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py index 6e77f68..1126a2a 100644 --- a/surfaces/blender/tests/test_stop_presence.py +++ b/surfaces/blender/tests/test_stop_presence.py @@ -195,6 +195,24 @@ class PresenceTests(StopFixture): self.target.load_recent_receipts("cache", "src") self.assertEqual([r["commandId"] for r in self.target.recent_receipts()], ["n1"]) + def test_many_agents_inside_the_window_are_all_active_beyond_eight_receipts(self): + for n in range(20): + self.target.note_receipt(receipt(f"nibu/a{n}", "createObject", "accepted", 1, key=f"m{n}")) + self.assertEqual(len(self.target.active_agents()), 20) + + def test_a_receipt_time_without_a_zone_is_read_as_utc(self): + fresh = receipt("nibu/naive", "createObject", "accepted", 1) + fresh["observedAt"] = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + self.target.note_receipt(fresh) + self.assertEqual(self.target.active_agents(), ["nibu/naive"]) + + def test_pending_reads_zero_the_moment_stop_returns(self): + node = tat.FakeNode({"blender/commands/a": self.intent("a-1"), "blender/commands/b": self.intent("b-1")}) + self.patched(node) + self.assertEqual(self.target.count_pending("cache", "src"), 2) + self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual(self.target.pending_count, 0) + def test_pending_count_comes_from_the_node(self): node = tat.FakeNode({"blender/commands/a": self.intent("a"), "blender/commands/b": self.intent("b")}) self.patched(node) @@ -259,6 +277,11 @@ class PanelAndOperatorTests(unittest.TestCase): texts = [str(c.kwargs.get("text", "")) for c in layout.mock_calls if c.kwargs] joined = "\n".join(texts) self.assertIn("Agents", joined) + agents_at = [i for i, c in enumerate(layout.mock_calls) if c.kwargs.get("text") == "Agents"][0] + first_sync = [i for i, c in enumerate(layout.mock_calls) if c.args[:1] == ("brokkr.publish_object_sync",)][0] + first_other = [i for i, c in enumerate(layout.mock_calls) if str(c.kwargs.get("text", "")).startswith("Provider")][0] + self.assertLess(agents_at, first_other) # directly under Stop agents, above everything else + self.assertLess(agents_at, first_sync) self.assertIn("nibu/hands", joined) self.assertIn("nibu/soul setLight stopped", joined) self.assertIn("nibu/hands createObject accepted", joined) @@ -279,10 +302,13 @@ class TimerTests(unittest.TestCase): self.redraws = patch.start() self.addCleanup(patch.stop) addon.bpy.context = NS(preferences=NS(addons=NS(get=lambda name: NS(preferences=self.prefs)))) - self.drains = [] + self.drains, self.counts, self.stops = [], [], [] + self.ran = 0 self.target.drain_commands = lambda *a, **k: self.drains.append(k) or [1] * self.ran - self.target.count_pending = lambda *a: 0 + self.target.count_pending = lambda *a: self.counts.append(a) or 0 + self.target.stop_pending = lambda *a: self.stops.append(a) or 0 self.target.configure_action_dirs = lambda *a: None + self.target._node = object() def test_the_timer_drains_one_intent_per_tick_so_stop_lands_between_them(self): self.ran = 1 @@ -294,11 +320,22 @@ class TimerTests(unittest.TestCase): self.ran = 0 self.assertEqual(addon._auto_drain_commands(), 1.0) - def test_with_the_sink_off_the_timer_runs_nothing(self): + def test_with_the_sink_on_the_timer_keeps_the_pending_count_moving(self): + addon._auto_drain_commands() + self.assertEqual(len(self.counts), 1) + + def test_with_the_sink_off_every_arriving_intent_is_answered_stopped_not_queued(self): self.prefs.auto_drain_commands = False self.ran = 1 self.assertEqual(addon._auto_drain_commands(), 1.0) self.assertEqual(self.drains, []) + self.assertEqual([call[0] for call in self.stops], ["agent commands are off"]) + + def test_with_the_sink_off_and_no_node_open_the_timer_opens_nothing(self): + self.prefs.auto_drain_commands = False + self.target._node = None + addon._auto_drain_commands() + self.assertEqual((self.stops, self.drains, self.counts), ([], [], [])) class NoPreferenceWritesTests(unittest.TestCase): From 6c2da2f5343c9af4fc279880efdf4a1c5af0f71e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:04:33 +0100 Subject: [PATCH 036/223] Stop: the timer opens the node when the sink is on or a store already exists; an idle session makes no store Soul s2 node-gate-unpinned-sink-on: in a default install nothing opened the node, so the sink-on drain never started and a sink-off send got no answer. Live harness now starts from a default install with no snapshot published, and a second Blender on the same store proves the sink-off, node-closed answer. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_bridge/__init__.py | 4 +- .../blender/brokkr_bridge/blender_target.py | 3 + .../live/stop_presence.closed.result.json | 28 +++ surfaces/blender/tests/live/stop_presence.py | 60 ++++-- .../tests/live/stop_presence.result.json | 172 ++++++++++-------- surfaces/blender/tests/test_stop_presence.py | 25 ++- 6 files changed, 198 insertions(+), 94 deletions(-) create mode 100644 surfaces/blender/tests/live/stop_presence.closed.result.json diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index 5495956..4926385 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -687,7 +687,9 @@ def _auto_drain_commands(): ran = 0 pending_before = adapter.pending_count try: - if adapter.node_open: + # The sink on, a node open, or a store already on disk: any running Blender answers within a tick, and + # an idle session never creates a store. + if prefs.auto_drain_commands or adapter.node_open or adapter.store_exists(prefs.cultmesh_cache_path): if prefs.auto_drain_commands: adapter.configure_action_dirs(prefs.import_dir, prefs.output_dir) ran = len(adapter.drain_commands( diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 82be6e2..363e017 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -265,6 +265,9 @@ class BrokkrBlenderTarget: self.pending_count = len(node.database.snapshot().get(COMMAND_INTENT_SCHEMA, {})) return self.pending_count + def store_exists(self, cache_path: str) -> bool: + return Path(self.resolve_cache_path(cache_path)).is_file() + @property def receipts_loaded(self) -> bool: return self._receipts_loaded diff --git a/surfaces/blender/tests/live/stop_presence.closed.result.json b/surfaces/blender/tests/live/stop_presence.closed.result.json new file mode 100644 index 0000000..2fa8684 --- /dev/null +++ b/surfaces/blender/tests/live/stop_presence.closed.result.json @@ -0,0 +1,28 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "phase two: a store on disk from phase one, sink off, no snapshot published this session", + "ok": true, + "detail": null + }, + { + "name": "phase two: a send to a sink-off Blender with a closed node is answered stopped at once (exit 3)", + "ok": true, + "detail": [ + 3, + 1.2883892059326172, + "commandId: 01a21ed2b9747d53bc380f32f2057a09\naction: createObject\ncommandId: 01a21ed2b9747d53bc380f32f2057a09\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: closed\nobjectName: \nobservedAt: 2026-11-27T21:04:17.259806+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + ] + } + ], + "notes": { + "closed": { + "exit": 3, + "seconds": 1.29, + "out": "commandId: 01a21ed2b9747d53bc380f32f2057a09\naction: createObject\ncommandId: 01a21ed2b9747d53bc380f32f2057a09\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: closed\nobjectName: \nobservedAt: 2026-11-27T21:04:17.259806+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + } + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/stop_presence.py b/surfaces/blender/tests/live/stop_presence.py index a9b176d..b1889f8 100644 --- a/surfaces/blender/tests/live/stop_presence.py +++ b/surfaces/blender/tests/live/stop_presence.py @@ -5,6 +5,7 @@ BROKKR_ADDON_MODULE= BROKKR_CULTLIB= blender --factory-startup --python stop_presence.py -- + Run a second Blender on the same store with BROKKR_PHASE=closed for the sink-off, node-closed answer. The driver stands in for the operator's hands only: it ticks the sink preference on and runs the add-on's own "Stop agents" operator. Every intent is sent by brokkr-ctl; the add-on's timer drains them. Undo is read only here. @@ -109,18 +110,30 @@ BURST = 20 def s_setup(): + """A default install: no server, no snapshot, Auto Capture off, sink off. An idle session makes no store.""" + check("setup: default install, no node open and no store file", not adapter.node_open and not Path(CACHE).exists(), + [adapter.node_open, Path(CACHE).exists()]) + + +def s_idle_check(): + check("idle: with the sink off and no store, the timer has still opened no node and made no store", + not adapter.node_open and not Path(CACHE).exists(), [adapter.node_open, Path(CACHE).exists()]) + prefs.auto_drain_commands = True # the operator ticks the sink + + +def node_opened(): + return adapter.node_open + + +def s_open(): + check("sink on with the node closed: the timer opened the node itself (an empty node writes no file until something is put)", adapter.node_open, None) with win(): - bpy.ops.brokkr.start_server() - bpy.ops.brokkr.capture_snapshot() + bpy.ops.brokkr.capture_snapshot() # she presses Capture, so brokkr-ctl status has a snapshot to read code, out = ctl("status") - check("setup: server up, sink off, brokkr-ctl status shows agentCommandsEnabled: false", - adapter.server_status()["running"] and code == 0 and "agentCommandsEnabled: false" in out, out) + check("the stored snapshot says agentCommandsEnabled: true", code == 0 and "agentCommandsEnabled: true" in out, out) def s_burst(): - prefs.auto_drain_commands = True # the operator ticks the sink - code, out = ctl("status") - check("sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", "agentCommandsEnabled: true" in out, out) S["procs"] = [spawn(f"B{n:02d}", "burst") for n in range(BURST)] @@ -227,6 +240,11 @@ def s_panel(): prefs.auto_drain_commands = True +def s_server_up(): + with win(): + bpy.ops.brokkr.start_server() + + def s_server_stop(): S["ids2"] = [send(f"S{n}", "server-stop") for n in range(3)] # the sender blocks Blender's thread: they cannot drain yet check("server stop: three intents queued behind a running server, sink on", len(pending()) == 3, len(pending())) @@ -279,8 +297,11 @@ def runner(): s_stop() i += 1 return 0.005 - if step in ("wait-done", "wait-late"): - if (finished if step == "wait-done" else late_done)(): + if step in ("wait-done", "wait-late", "wait-store", "wait-idle"): + if step == "wait-idle": + S["idle"] = S.get("idle", 0) + 1 + if {"wait-done": finished, "wait-late": late_done, "wait-store": node_opened, + "wait-idle": lambda: S.get("idle", 0) >= 15}[step](): i += 1 return 0.1 step() @@ -294,6 +315,23 @@ def runner(): return None -steps = [s_setup, s_burst, "wait-two", "wait-done", s_after_stop, s_late, "wait-late", s_late_check, s_reenabled, s_panel, - s_server_stop, s_server_start, s_final] +if os.environ.get("BROKKR_PHASE") == "closed": + # Phase two, a fresh Blender on the phase-one store: sink off, no node opened, a store on disk. A send must + # be answered stopped within a tick. + def s_closed(): + check("phase two: a store on disk from phase one, sink off, no snapshot published this session", + Path(CACHE).exists() and not prefs.auto_drain_commands and adapter.last_snapshot is None, None) + S["late_began"] = time.time() + S["late"] = subprocess.Popen([CTL, "blender", *SEND, "--set", 'name="Closed"', "--note", "closed", "--timeout", "10"], + env=ENV, stdout=subprocess.PIPE, text=True) + + def s_closed_check(): + out, code, took = S["late"].stdout.read(), S["late"].returncode, time.time() - S["late_began"] + R["notes"]["closed"] = {"exit": code, "seconds": round(took, 2), "out": out} + check("phase two: a send to a sink-off Blender with a closed node is answered stopped at once (exit 3)", + code == 3 and took < 5 and "agent commands are off" in out and not empties("Closed"), [code, took, out]) + steps = [s_closed, "wait-late", s_closed_check] +else: + steps = [s_setup, "wait-idle", s_idle_check, "wait-store", s_open, s_burst, "wait-two", "wait-done", s_after_stop, s_late, "wait-late", s_late_check, s_reenabled, s_panel, + s_server_up, s_server_stop, s_server_start, s_final] bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/stop_presence.result.json b/surfaces/blender/tests/live/stop_presence.result.json index bb6f00b..ab9f8ee 100644 --- a/surfaces/blender/tests/live/stop_presence.result.json +++ b/surfaces/blender/tests/live/stop_presence.result.json @@ -3,39 +3,55 @@ "module": "bl_ext.user_default.brokkr_bridge", "checks": [ { - "name": "setup: server up, sink off, brokkr-ctl status shows agentCommandsEnabled: false", + "name": "setup: default install, no node open and no store file", "ok": true, - "detail": "observedAt: 2026-11-27T20:52:54.171327+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: false\n" + "detail": [ + false, + false + ] }, { - "name": "sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", + "name": "idle: with the sink off and no store, the timer has still opened no node and made no store", "ok": true, - "detail": "observedAt: 2026-11-27T20:52:54.505375+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: true\n" + "detail": [ + false, + false + ] + }, + { + "name": "sink on with the node closed: the timer opened the node itself (an empty node writes no file until something is put)", + "ok": true, + "detail": null + }, + { + "name": "the stored snapshot says agentCommandsEnabled: true", + "ok": true, + "detail": "observedAt: 2026-11-27T21:04:00.546944+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: true\n" }, { "name": "stop: every one of the 20 intents has a receipt, each accepted or stopped, none missing", "ok": true, "detail": { - "01a21ec852a07e139e33eba7c8c21251": "accepted", - "01a21ec852b27442b17daac0eef61b81": "accepted", - "01a21ec852b47ae08561010021792ee2": "stopped", - "01a21ec852b77eb393c0f081d680b1d3": "stopped", - "01a21ec852ce78c0b66a2c2ce666f185": "stopped", - "01a21ec852cd7d30b8ec875ee4a9272e": "stopped", - "01a21ec852ce7582bff08d6a81921ee4": "stopped", - "01a21ec852e57a009ad0e186af6f0cfa": "stopped", - "01a21ec852e57cb3859bf2d738ef586a": "stopped", - "01a21ec852ec72c0bfd939a5bb39fde3": "stopped", - "01a21ec852ec78c28d7e16c9edc4cc07": "stopped", - "01a21ec8530772339db47b279044d6f5": "stopped", - "01a21ec853237550b1855dd0f0f27269": "stopped", - "01a21ec853347ac1b822f5d61ae8afcb": "stopped", - "01a21ec853457d418b3bd09272666916": "stopped", - "01a21ec853447c328eac215160e935d8": "stopped", - "01a21ec8535375309be1eec02df779f4": "stopped", - "01a21ec853577ba393761e10d99a14d5": "stopped", - "01a21ec853617913965abb873a2228b9": "stopped", - "01a21ec853617d41884613d8831720fe": "stopped" + "01a21ed27e2e74e1b8e725800116e4e8": "accepted", + "01a21ed27e347fc1a9335eece58a845e": "accepted", + "01a21ed27e51773392985e0e1859abec": "stopped", + "01a21ed27e6d7b53a39ad7e8d7316c8b": "stopped", + "01a21ed27e6f78c1a05ed37723e2b309": "stopped", + "01a21ed27e6d76f1bb533bed0a748a13": "stopped", + "01a21ed27e6d7c1092c429ea773c8fc1": "stopped", + "01a21ed27e6f7d33a2055b67edc92f18": "stopped", + "01a21ed27e8272e195d68ac7f7fdf699": "stopped", + "01a21ed27e897ba19eba4c3b3093126d": "stopped", + "01a21ed27e9379e3831640c51caf5f7a": "stopped", + "01a21ed27ea270008ef42324ca91b333": "stopped", + "01a21ed27e9472d3930a123edde8b2fd": "stopped", + "01a21ed27ed57222bce4b3537264e29c": "stopped", + "01a21ed27ea674d1bb4f93ccf3f84df2": "stopped", + "01a21ed27ed07ea180078e4a1d81fc24": "stopped", + "01a21ed27eb37ea3ac2277d337e6fad9": "stopped", + "01a21ed27ed07f63aa4a193a340243bd": "stopped", + "01a21ed27ed070408f8bd458009ab441": "stopped", + "01a21ed27ed27ba1ae1e97b2320d6264": "stopped" } }, { @@ -59,8 +75,8 @@ "name": "stop: each accepted intent is one labelled undo step the receipt names", "ok": true, "detail": [ - "Brokkr nibu/hands: createObject c8c21251", - "Brokkr nibu/hands: createObject eef61b81" + "Brokkr nibu/hands: createObject 0116e4e8", + "Brokkr nibu/hands: createObject e58a845e" ] }, { @@ -87,15 +103,15 @@ { "name": "stop: brokkr-ctl status now reads agentCommandsEnabled: false", "ok": true, - "detail": "observedAt: 2026-11-27T20:52:55.144050+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: B01\nselectedObjectNames: [\"B01\"]\nobjectCount: 5\nagentCommandsEnabled: false\n" + "detail": "observedAt: 2026-11-27T21:04:01.582528+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: B01\nselectedObjectNames: [\"B01\"]\nobjectCount: 5\nagentCommandsEnabled: false\n" }, { "name": "sink off: a send after Stop is answered stopped at once (wait exit 3, 'agent commands are off'), nothing queued", "ok": true, "detail": [ 3, - 0.6096086502075195, - "commandId: 01a21ec8598f754383d402238c3af85d\naction: createObject\ncommandId: 01a21ec8598f754383d402238c3af85d\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T20:52:56.732437+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + 0.6054728031158447, + "commandId: 01a21ed2867e7733982b0eaf93547dcc\naction: createObject\ncommandId: 01a21ed2867e7733982b0eaf93547dcc\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T21:04:03.327292+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" ] }, { @@ -118,7 +134,7 @@ { "name": "panel mid-burst: Agents is first under Stop, the agent is active, accepted receipts show note and undo label, each once", "ok": true, - "detail": "Agents\nAgent commands: on\nActive: nibu/hands\nPending: 18\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject eef61b81\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject c8c21251\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:55445\nBind: 127.0.0.1:55445\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 3\nMaterials: 2\nSelected: 1" + "detail": "Agents\nAgent commands: on\nActive: nibu/hands\nPending: 18\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject e58a845e\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject 0116e4e8\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: stopped\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 3\nMaterials: 2\nSelected: 1" }, { "name": "panel after Stop: Stop agents is the first operator drawn", @@ -132,7 +148,7 @@ { "name": "panel after Stop: commands off, pending 0, the stopped receipts listed with who and what", "ok": true, - "detail": "Agents\nAgent commands: off\nActive: nibu/hands\nPending: 0\nnibu/hands createObject stopped\n late\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:55445\nBind: 127.0.0.1:55445\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 4\nMaterials: 2\nSelected: 1" + "detail": "Agents\nAgent commands: off\nActive: nibu/hands\nPending: 0\nnibu/hands createObject stopped\n late\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: stopped\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 4\nMaterials: 2\nSelected: 1" }, { "name": "server stop: three intents queued behind a running server, sink on", @@ -167,108 +183,108 @@ ], "notes": { "states": { - "01a21ec852a07e139e33eba7c8c21251": "accepted", - "01a21ec852b27442b17daac0eef61b81": "accepted", - "01a21ec852b47ae08561010021792ee2": "stopped", - "01a21ec852b77eb393c0f081d680b1d3": "stopped", - "01a21ec852ce78c0b66a2c2ce666f185": "stopped", - "01a21ec852cd7d30b8ec875ee4a9272e": "stopped", - "01a21ec852ce7582bff08d6a81921ee4": "stopped", - "01a21ec852e57a009ad0e186af6f0cfa": "stopped", - "01a21ec852e57cb3859bf2d738ef586a": "stopped", - "01a21ec852ec72c0bfd939a5bb39fde3": "stopped", - "01a21ec852ec78c28d7e16c9edc4cc07": "stopped", - "01a21ec8530772339db47b279044d6f5": "stopped", - "01a21ec853237550b1855dd0f0f27269": "stopped", - "01a21ec853347ac1b822f5d61ae8afcb": "stopped", - "01a21ec853457d418b3bd09272666916": "stopped", - "01a21ec853447c328eac215160e935d8": "stopped", - "01a21ec8535375309be1eec02df779f4": "stopped", - "01a21ec853577ba393761e10d99a14d5": "stopped", - "01a21ec853617913965abb873a2228b9": "stopped", - "01a21ec853617d41884613d8831720fe": "stopped" + "01a21ed27e2e74e1b8e725800116e4e8": "accepted", + "01a21ed27e347fc1a9335eece58a845e": "accepted", + "01a21ed27e51773392985e0e1859abec": "stopped", + "01a21ed27e6d7b53a39ad7e8d7316c8b": "stopped", + "01a21ed27e6f78c1a05ed37723e2b309": "stopped", + "01a21ed27e6d76f1bb533bed0a748a13": "stopped", + "01a21ed27e6d7c1092c429ea773c8fc1": "stopped", + "01a21ed27e6f7d33a2055b67edc92f18": "stopped", + "01a21ed27e8272e195d68ac7f7fdf699": "stopped", + "01a21ed27e897ba19eba4c3b3093126d": "stopped", + "01a21ed27e9379e3831640c51caf5f7a": "stopped", + "01a21ed27ea270008ef42324ca91b333": "stopped", + "01a21ed27e9472d3930a123edde8b2fd": "stopped", + "01a21ed27ed57222bce4b3537264e29c": "stopped", + "01a21ed27ea674d1bb4f93ccf3f84df2": "stopped", + "01a21ed27ed07ea180078e4a1d81fc24": "stopped", + "01a21ed27eb37ea3ac2277d337e6fad9": "stopped", + "01a21ed27ed07f63aa4a193a340243bd": "stopped", + "01a21ed27ed070408f8bd458009ab441": "stopped", + "01a21ed27ed27ba1ae1e97b2320d6264": "stopped" }, "stop_reasons": [ "Stopped (stopped by the operator); the intent wa" ], "wait_exits": { - "01a21ec852a07e139e33eba7c8c21251": [ + "01a21ed27e2e74e1b8e725800116e4e8": [ "accepted", 0 ], - "01a21ec852b27442b17daac0eef61b81": [ + "01a21ed27e347fc1a9335eece58a845e": [ "accepted", 0 ], - "01a21ec852b47ae08561010021792ee2": [ + "01a21ed27e51773392985e0e1859abec": [ "stopped", 3 ], - "01a21ec852b77eb393c0f081d680b1d3": [ + "01a21ed27e6d7b53a39ad7e8d7316c8b": [ "stopped", 3 ], - "01a21ec852ce78c0b66a2c2ce666f185": [ + "01a21ed27e6f78c1a05ed37723e2b309": [ "stopped", 3 ], - "01a21ec852cd7d30b8ec875ee4a9272e": [ + "01a21ed27e6d76f1bb533bed0a748a13": [ "stopped", 3 ], - "01a21ec852ce7582bff08d6a81921ee4": [ + "01a21ed27e6d7c1092c429ea773c8fc1": [ "stopped", 3 ], - "01a21ec852e57a009ad0e186af6f0cfa": [ + "01a21ed27e6f7d33a2055b67edc92f18": [ "stopped", 3 ], - "01a21ec852e57cb3859bf2d738ef586a": [ + "01a21ed27e8272e195d68ac7f7fdf699": [ "stopped", 3 ], - "01a21ec852ec72c0bfd939a5bb39fde3": [ + "01a21ed27e897ba19eba4c3b3093126d": [ "stopped", 3 ], - "01a21ec852ec78c28d7e16c9edc4cc07": [ + "01a21ed27e9379e3831640c51caf5f7a": [ "stopped", 3 ], - "01a21ec8530772339db47b279044d6f5": [ + "01a21ed27ea270008ef42324ca91b333": [ "stopped", 3 ], - "01a21ec853237550b1855dd0f0f27269": [ + "01a21ed27e9472d3930a123edde8b2fd": [ "stopped", 3 ], - "01a21ec853347ac1b822f5d61ae8afcb": [ + "01a21ed27ed57222bce4b3537264e29c": [ "stopped", 3 ], - "01a21ec853457d418b3bd09272666916": [ + "01a21ed27ea674d1bb4f93ccf3f84df2": [ "stopped", 3 ], - "01a21ec853447c328eac215160e935d8": [ + "01a21ed27ed07ea180078e4a1d81fc24": [ "stopped", 3 ], - "01a21ec8535375309be1eec02df779f4": [ + "01a21ed27eb37ea3ac2277d337e6fad9": [ "stopped", 3 ], - "01a21ec853577ba393761e10d99a14d5": [ + "01a21ed27ed07f63aa4a193a340243bd": [ "stopped", 3 ], - "01a21ec853617913965abb873a2228b9": [ + "01a21ed27ed070408f8bd458009ab441": [ "stopped", 3 ], - "01a21ec853617d41884613d8831720fe": [ + "01a21ed27ed27ba1ae1e97b2320d6264": [ "stopped", 3 ] @@ -276,7 +292,7 @@ "late": { "exit": 3, "seconds": 0.61, - "out": "commandId: 01a21ec8598f754383d402238c3af85d\naction: createObject\ncommandId: 01a21ec8598f754383d402238c3af85d\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T20:52:56.732437+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + "out": "commandId: 01a21ed2867e7733982b0eaf93547dcc\naction: createObject\ncommandId: 01a21ed2867e7733982b0eaf93547dcc\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T21:04:03.327292+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" }, "panel_before_stop": [ "Agents", @@ -285,17 +301,15 @@ "Pending: 18", "nibu/hands createObject accepted", " burst", - " Brokkr nibu/hands: createObject eef61b81", + " Brokkr nibu/hands: createObject e58a845e", "nibu/hands createObject accepted", " burst", - " Brokkr nibu/hands: createObject c8c21251", + " Brokkr nibu/hands: createObject 0116e4e8", "Provider: brokkr.blender_editor", "Tool: blender-editor", "Broker: cultmesh://brokkr", "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", - "Server: cultnet://127.0.0.1:55445", - "Bind: 127.0.0.1:55445", - "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", + "Server: stopped", "Object Sync", "Timeline / Cinemachine", "Ad Hoc Sync Var", @@ -328,9 +342,7 @@ "Tool: blender-editor", "Broker: cultmesh://brokkr", "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", - "Server: cultnet://127.0.0.1:55445", - "Bind: 127.0.0.1:55445", - "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", + "Server: stopped", "Object Sync", "Timeline / Cinemachine", "Ad Hoc Sync Var", diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py index 1126a2a..4583ce0 100644 --- a/surfaces/blender/tests/test_stop_presence.py +++ b/surfaces/blender/tests/test_stop_presence.py @@ -4,6 +4,7 @@ the panel's agent activity is derived from receipts. A fake bpy and a fake node from __future__ import annotations import re +import tempfile import types import unittest import unittest.mock @@ -331,10 +332,30 @@ class TimerTests(unittest.TestCase): self.assertEqual(self.drains, []) self.assertEqual([call[0] for call in self.stops], ["agent commands are off"]) - def test_with_the_sink_off_and_no_node_open_the_timer_opens_nothing(self): + def test_with_the_sink_on_and_no_node_open_the_timer_still_drains(self): + self.target._node = None + self.ran = 1 + addon._auto_drain_commands() + self.assertEqual(len(self.drains), 1) + + def test_with_the_sink_off_and_an_existing_store_a_closed_node_still_answers_stopped(self): self.prefs.auto_drain_commands = False self.target._node = None - addon._auto_drain_commands() + with tempfile.TemporaryDirectory() as tmp: + store = Path(tmp) / "node.ccmp" + store.write_bytes(b"") + self.prefs.cultmesh_cache_path = str(store) + addon._auto_drain_commands() + self.assertEqual([call[0] for call in self.stops], ["agent commands are off"]) + + def test_an_idle_session_creates_no_store_and_answers_nothing(self): + self.prefs.auto_drain_commands = False + self.target._node = None + with tempfile.TemporaryDirectory() as tmp: + store = Path(tmp) / "node.ccmp" + self.prefs.cultmesh_cache_path = str(store) + addon._auto_drain_commands() + self.assertFalse(store.exists()) self.assertEqual((self.stops, self.drains, self.counts), ([], [], [])) From 54478cd0ad1715c056fa2be9b52b49c00cdd0095 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:19:53 +0100 Subject: [PATCH 037/223] Perception: look captures her 3D view to a scratch PNG; the snapshot carries Edit Mode selection, a session id and human-edit sequences look is a read action under run_intent (no undo step, allowed in Edit Mode). It overrides screenshot_area to the largest VIEW_3D area's WINDOW region, writes /look/.png and prunes to the newest 20. Human-edit tracking is always on and separate from auto_capture; nothing admits or refuses an intent on it. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_bridge/__init__.py | 30 ++ .../blender/brokkr_bridge/blender_target.py | 125 ++++- surfaces/blender/tests/test_addon_ui.py | 2 +- surfaces/blender/tests/test_perception.py | 483 ++++++++++++++++++ surfaces/blender/tests/test_scene_actions.py | 5 +- 5 files changed, 639 insertions(+), 6 deletions(-) create mode 100644 surfaces/blender/tests/test_perception.py diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index 4926385..58fd75b 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -672,6 +672,30 @@ def _auto_capture(scene, depsgraph): ) +# Human-edit tracking is always on and reads no preference: it must not depend on auto_capture. Persistent, so +# opening another file does not drop them. +@bpy.app.handlers.persistent +def _track_human_edits(scene, depsgraph): + target().track_human_edits(depsgraph) + + +@bpy.app.handlers.persistent +def _track_undo_redo(scene, *_): + target().note_undo_redo() + + +@bpy.app.handlers.persistent +def _new_session(*_): + target().renew_session() + + +_PERCEPTION_HANDLERS = ( + ("depsgraph_update_post", _track_human_edits), + ("undo_post", _track_undo_redo), + ("redo_post", _track_undo_redo), + ("load_post", _new_session), +) + BUSY_INTERVAL = 0.05 # one intent per tick: Stop is a UI event, and it lands between two intents IDLE_INTERVAL = 1.0 @@ -733,6 +757,9 @@ def register(): bpy.utils.register_class(cls) if _auto_capture not in bpy.app.handlers.depsgraph_update_post: bpy.app.handlers.depsgraph_update_post.append(_auto_capture) + for name, handler in _PERCEPTION_HANDLERS: + if handler not in getattr(bpy.app.handlers, name): + getattr(bpy.app.handlers, name).append(handler) if not bpy.app.timers.is_registered(_auto_drain_commands): bpy.app.timers.register(_auto_drain_commands, first_interval=1.0, persistent=True) @@ -740,6 +767,9 @@ def register(): def unregister(): if _auto_capture in bpy.app.handlers.depsgraph_update_post: bpy.app.handlers.depsgraph_update_post.remove(_auto_capture) + for name, handler in _PERCEPTION_HANDLERS: + if handler in getattr(bpy.app.handlers, name): + getattr(bpy.app.handlers, name).remove(handler) if bpy.app.timers.is_registered(_auto_drain_commands): bpy.app.timers.unregister(_auto_drain_commands) global _target diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 363e017..c69a493 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -45,8 +45,8 @@ CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY") GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT") GL_RUNTIME_LIBRARY = "libEGL.so.1" -# Actions that only read the scene and so push no undo step (live-5 adds look). -READ_ACTIONS: tuple[str, ...] = () +# Actions that only read the scene and so push no undo step. +READ_ACTIONS = ("look",) MUTATING_ACTIONS = ( "createObject", "deleteObject", "setObjectTransform", "setObjectVisibility", "setObjectParent", "setObjectCustomProperty", "selectObject", "assignMaterial", "importGltf", "exportGltf", @@ -57,8 +57,11 @@ MUTATING_ACTIONS = ( NO_SCENE_CHANGE_ACTIONS = ("exportGltf", "renderStill") # While an object is in Edit Mode, undo steps are edit-mesh steps, so a scene write is not reverted by # one undo, and some operators leave Edit Mode (brokkr-live:ruling:object-intents-refused-in-edit-mode). -# Anything that writes scene state or changes her mode is refused; renderStill does neither. -EDIT_MODE_SAFE_ACTIONS = ("renderStill",) +# Anything that writes scene state or changes her mode is refused; renderStill and look do neither. +EDIT_MODE_SAFE_ACTIONS = ("renderStill", "look") +LOOK_DIR = "look" # under the output directory: scratch captures named by command id (brush-tree:ruling:look-files-are-scratch) +LOOK_KEPT = 20 # the newest captures that stay after each look +EDIT_SELECTION_CAP = 4096 # indices listed per element kind and object; the total stays true beside the list REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") # A commandId becomes part of a receipt key, so it is a short string of key-safe characters ('.' is left # out: it separates the '.denied' suffix). @@ -121,6 +124,11 @@ class BrokkrBlenderTarget: self._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts self._receipts_loaded = False self.pending_count = 0 # display cache: intents queued in the node + # What she did, as observed: nothing reads these back to admit or refuse an intent (scene-last-writer-wins). + self.session_id = uuid.uuid4().hex + self.human_edit_seq = 0 + self._last_human_edit: dict[str, int] = {} # object name -> human_edit_seq when she last changed it + self._looked: dict[str, int] = {} # requestedBy -> human_edit_seq at that agent's last look def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: """The directories importGltf and renderStill may touch; empty leaves that action disabled.""" @@ -593,6 +601,9 @@ class BrokkrBlenderTarget: "activeScene": active_scene, "activeObjectName": active_object, "mode": context.mode, + "sessionId": self.session_id, + "humanEditSeq": self.human_edit_seq, + "editSelection": self.edit_selection(), "selectedObjectNames": selected, "sceneCount": len(bpy.data.scenes), "objectCount": len(bpy.data.objects), @@ -702,6 +713,8 @@ class BrokkrBlenderTarget: return self._set_world(context, command) if action == "renderStill": return self._render_still(context, command) + if action == "look": + return self._look(context, command) if action in na.NodeActions.ACTIONS: message, name = self.nodes.execute(action, command) self._wrote = self.nodes.changed @@ -1034,6 +1047,108 @@ class BrokkrBlenderTarget: render.image_settings.file_format, scene.camera) = saved return self._receipt(command, "accepted", f"Rendered still to {path.name}.", scene.name) + # ---- perception: what she sees and what she did ---------------------------------------------------------- + + def renew_session(self) -> None: + """A new session id and zeroed counters: names mean something else in a freshly loaded file.""" + self.session_id = uuid.uuid4().hex + self.human_edit_seq = 0 + self._last_human_edit.clear() + self._looked.clear() + + def track_human_edits(self, depsgraph: Any) -> None: + """A depsgraph update outside an agent turn is hers. What changed is read from each update's flags, never + from presence in the list: an update also names what only depends on the change.""" + if self.agent_turn: + return + changed = [u.id.name for u in depsgraph.updates + if u.id.id_type == "OBJECT" and (u.is_updated_transform or u.is_updated_geometry or u.is_updated_shading)] + if not changed: + return + self.human_edit_seq += 1 + for name in changed: + self._last_human_edit[name] = self.human_edit_seq + + def note_undo_redo(self) -> None: + """An undo or redo cannot be narrowed to objects from its updates, so it moves the session counter only.""" + self.human_edit_seq += 1 + + def last_human_edit_seq(self, name: str) -> int: + return self._last_human_edit.get(name, 0) + + def edit_selection(self) -> list[dict[str, Any]]: + """Her selection in every object in Edit Mode, read live from the edit mesh without leaving the mode.""" + editing = [obj for obj in self.bpy.data.objects if getattr(obj, "mode", "OBJECT") == "EDIT"] + entries: list[dict[str, Any]] = [] + if not editing: + return entries + import bmesh # exists only inside Blender; nothing is imported when no object is being edited + for obj in editing: + if obj.type != "MESH": + entries.append({"name": obj.name, "type": obj.type, "unsupported": True}) + continue + mesh = bmesh.from_edit_mesh(obj.data) + entry: dict[str, Any] = {"name": obj.name, "type": obj.type} + for key, elements in (("vertices", mesh.verts), ("edges", mesh.edges), ("faces", mesh.faces)): + chosen = [index for index, element in enumerate(elements) if element.select] + entry[key] = chosen[:EDIT_SELECTION_CAP] + entry[key + "Total"] = len(chosen) + entries.append(entry) + return entries + + def _viewport(self) -> tuple[Any, Any, Any]: + """The window, area and WINDOW region of the largest 3D view: the only pixels look may read.""" + best = None + for window in self.bpy.context.window_manager.windows: + for area in window.screen.areas: + if area.type == "VIEW_3D" and (best is None or area.width * area.height > best[1].width * best[1].height): + best = (window, area) + region = next((r for r in best[1].regions if r.type == "WINDOW"), None) if best else None + if region is None: + raise sa.ActionRefused("No 3D viewport is open to look at.") + return best[0], best[1], region + + def _look(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + """Capture her 3D view to /look/.png. screenshot_area reads Blender's own framebuffer + for the area it is overridden to, so the desktop and other applications are never in the picture; a menu or + popup Blender draws over the view is, as she sees it.""" + name = f"{LOOK_DIR}/{command['commandId']}.png" + path = sa.resolve_inside(self.output_dir, name, "output", new_file=True) + window, area, region = self._viewport() + path.parent.mkdir(parents=True, exist_ok=True) + if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: + raise sa.ActionRefused("Output path changed while it was being checked.") + with self.bpy.context.temp_override(window=window, area=area, region=region): + result = self.bpy.ops.screen.screenshot_area("EXEC_DEFAULT", False, filepath=str(path)) + if "FINISHED" not in result or not path.is_file(): + raise sa.ActionRefused("Blender did not write the capture.") + self._prune_looks(path.parent) + requested_by = command["requestedBy"] + since = self._looked.get(requested_by, 0) + self._looked[requested_by] = self.human_edit_seq + receipt = self._receipt(command, "accepted", f"Captured the 3D view to {LOOK_DIR}/{path.name}.", "") + receipt.update({ + "lookPath": str(path), + "sessionId": self.session_id, + "humanEditSeq": self.human_edit_seq, + "humanEditsSinceLook": self.human_edit_seq - since, + "editedSinceLook": sorted(n for n, seq in self._last_human_edit.items() if seq > since), + "editSelection": self.edit_selection(), + }) + self._wrote = False + return receipt + + @staticmethod + def _prune_looks(directory: Path) -> None: + """Keep the newest LOOK_KEPT captures: plain .png files directly in the look directory, nothing else.""" + found = [] + with os.scandir(directory) as entries: + for entry in entries: + if entry.name.lower().endswith(".png") and entry.is_file(follow_symlinks=False): + found.append((entry.stat(follow_symlinks=False).st_mtime_ns, entry.name, entry.path)) + for _mtime, _name, old in sorted(found)[:-LOOK_KEPT]: + os.unlink(old) + def _resolve_object(self, command: dict[str, Any]) -> Any: name = command.get("targetObjectName") or command.get("objectName") return self.bpy.data.objects.get(name) if name else None @@ -1061,6 +1176,7 @@ class BrokkrBlenderTarget: "scale": _to_list(obj.scale), "visible": bool(obj.visible_get()), "selected": bool(obj.select_get()), + "lastHumanEditSeq": self.last_human_edit_seq(obj.name), "parentName": obj.parent.name if obj.parent else "", "collections": [collection.name for collection in obj.users_collection], "materials": [slot.material.name for slot in obj.material_slots if slot.material], @@ -1196,6 +1312,7 @@ class BrokkrBlenderTarget: "requestedBy": command["requestedBy"] if isinstance(command.get("requestedBy"), str) else "", "note": command["note"][:NOTE_LIMIT] if isinstance(command.get("note"), str) else "", "undoLabel": "", + "lookPath": "", "observedAt": _now(), } diff --git a/surfaces/blender/tests/test_addon_ui.py b/surfaces/blender/tests/test_addon_ui.py index 04e97d3..74c8a24 100644 --- a/surfaces/blender/tests/test_addon_ui.py +++ b/surfaces/blender/tests/test_addon_ui.py @@ -32,7 +32,7 @@ def load_addon(): fake = types.ModuleType("bpy") fake.types = NS(AddonPreferences=Base, Panel=Base, Operator=Base) fake.props = props - fake.app = NS(handlers=NS(depsgraph_update_post=[]), timers=NS(is_registered=lambda f: False)) + fake.app = NS(handlers=NS(depsgraph_update_post=[], persistent=lambda f: setattr(f, "persistent", True) or f), timers=NS(is_registered=lambda f: False)) fake.utils = NS() previous = sys.modules.get("bpy") sys.modules["bpy"] = fake diff --git a/surfaces/blender/tests/test_perception.py b/surfaces/blender/tests/test_perception.py new file mode 100644 index 0000000..ee793e8 --- /dev/null +++ b/surfaces/blender/tests/test_perception.py @@ -0,0 +1,483 @@ +"""Perception: look captures her 3D view, the snapshot carries her Edit Mode selection, a session id and +human-edit sequences. A fake bpy, a fake bmesh and fake depsgraphs; no Blender. +""" +from __future__ import annotations + +import contextlib +import inspect +import os +import re +import sys +import types +import unittest +import unittest.mock +from pathlib import Path + +import test_scene_actions as ts +import test_addon_ui as ui + +bt = ts.bt +NS = types.SimpleNamespace +addon = ui.addon +BRIDGE = Path(bt.__file__).parent +PNG = b"\x89PNG\r\n\x1a\n" + b"x" * 32 + + +def area(kind, width, height, name=None): + return NS(type=kind, width=width, height=height, name=name or kind, + regions=[NS(type="HEADER"), NS(type="WINDOW", width=width, height=height)]) + + +def window(*areas): + return NS(screen=NS(areas=list(areas))) + + +class Element: + def __init__(self, selected): + self.select = selected + + +class FakeBmesh: + """bmesh.from_edit_mesh(mesh) -> a mesh with verts, edges and faces that carry .select.""" + def __init__(self, meshes): + self.meshes = meshes + self.reads = 0 + + def from_edit_mesh(self, mesh): + self.reads += 1 + verts, edges, faces = self.meshes[id(mesh)] + return NS(verts=[Element(s) for s in verts], edges=[Element(s) for s in edges], + faces=[Element(s) for s in faces]) + + +class PerceptionFixture(unittest.TestCase): + """The scene fixture plus a window with a 3D view, a screenshot operator and a bmesh.""" + run_action = ts.ActionTests.run_action + + def setUp(self): + ts.ActionTests.setUp(self) + self.view = area("VIEW_3D", 1574, 888) + self.windows = [window(area("PROPERTIES", 300, 900), self.view, area("TIMELINE", 1600, 100))] + self.stack, self.shots, self.shot_result, self.shot_writes = [], [], {"FINISHED"}, True + bpy = self.bpy + bpy.context.window_manager.windows = self.windows + bpy.context.temp_override = self.override + bpy.ops.screen = NS(screenshot_area=self.screenshot) + bpy.mesh_data = NS(name="CubeMesh", vertices=[], edges=[], polygons=[], uv_layers=[], shape_keys=None) + bpy.mesh.data = bpy.mesh_data + bpy.mesh.mode = "OBJECT" + self.bmesh = FakeBmesh({id(bpy.mesh_data): ([True, False, True], [False, True], [False])}) + patch = unittest.mock.patch.dict(sys.modules, {"bmesh": self.bmesh}) + patch.start() + self.addCleanup(patch.stop) + bpy.data.scenes = [bpy.scene] + + @contextlib.contextmanager + def override(self, **kw): + self.stack.append(kw) + try: + yield + finally: + self.stack.pop() + + def screenshot(self, mode, undo, filepath): + assert (mode, undo) == ("EXEC_DEFAULT", False) # operators run with undo off + self.shots.append((dict(self.stack[-1]) if self.stack else None, filepath)) + if self.shot_writes: + Path(filepath).write_bytes(PNG) + return self.shot_result + + def look(self, **command): + return self.run_action(action="look", **command) + + def look_dir(self): + return self.root / "out" / "look" + + +class LookTests(PerceptionFixture): + def test_look_is_a_read_action(self): + receipt = self.look(commandId="look-0001") + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(self.bpy.undo.pushes, []) # reads push no undo step + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(Path(receipt["lookPath"]), self.look_dir() / "look-0001.png") + self.assertEqual((self.look_dir() / "look-0001.png").read_bytes(), PNG) + self.assertEqual(self.bpy.created, []) + + def test_other_receipts_carry_an_empty_look_path(self): + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["lookPath"], "") + + def test_look_captures_only_the_largest_3d_view_and_its_window_region(self): + # the capture is scoped to one area's WINDOW region: that is what keeps the desktop and every + # other Blender area out of the picture + small = area("VIEW_3D", 400, 300) + big = area("VIEW_3D", 1600, 900) + second = window(area("OUTLINER", 3000, 3000), small) + self.windows.append(second) + self.windows[0].screen.areas.append(big) + self.look() + override, path = self.shots[0] + self.assertIs(override["area"], big) + self.assertIs(override["window"], self.windows[0]) + self.assertEqual((override["region"].type, override["region"].width), ("WINDOW", 1600)) + self.assertEqual(len(self.shots), 1) + + def test_look_in_a_second_window_uses_that_window(self): + only = area("VIEW_3D", 800, 600) + self.windows[0].screen.areas.remove(self.view) + self.windows.append(window(only)) + self.look() + self.assertIs(self.shots[0][0]["window"], self.windows[1]) + self.assertIs(self.shots[0][0]["area"], only) + + def test_look_without_a_3d_view_is_refused_and_captures_nothing(self): + self.windows[0].screen.areas.remove(self.view) + receipt = self.look() + self.assertEqual(receipt["status"], "failed") + self.assertIn("3D", receipt["message"]) + self.assertEqual((self.shots, receipt["lookPath"]), ([], "")) + self.assertFalse(self.look_dir().exists()) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_look_without_an_output_directory_is_refused(self): + self.target.configure_action_dirs(str(self.root / "in"), "") + receipt = self.look() + self.assertEqual(receipt["status"], "failed") + self.assertIn("output", receipt["message"]) + self.assertEqual(self.shots, []) + + def test_a_cancelled_or_unwritten_capture_is_a_failed_receipt_with_no_path(self): + self.shot_result = {"CANCELLED"} + receipt = self.look(commandId="look-c1") + self.assertEqual((receipt["status"], receipt["lookPath"]), ("failed", "")) + self.shot_result, self.shot_writes = {"FINISHED"}, False + receipt = self.look(commandId="look-c2") + self.assertEqual((receipt["status"], receipt["lookPath"]), ("failed", "")) + + def test_look_works_in_edit_mode_and_leaves_her_mode_alone(self): + self.bpy.mesh.mode = "EDIT" + receipt = self.look() + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(self.bpy.mesh.mode, "EDIT") + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "denied") + + def test_look_prunes_to_twenty(self): + # look-files-are-scratch: the newest twenty files stay, the capture just taken among them + self.look_dir().mkdir(parents=True) + for n in range(30): + old = self.look_dir() / f"old-{n:02d}.png" + old.write_bytes(PNG) + os.utime(old, (1_000_000 + n, 1_000_000 + n)) + receipt = self.look(commandId="look-new") + kept = sorted(p.name for p in self.look_dir().iterdir()) + self.assertEqual(len(kept), 20, kept) + self.assertIn("look-new.png", kept) + self.assertEqual([k for k in kept if k != "look-new.png"], [f"old-{n:02d}.png" for n in range(11, 30)]) # the newest 19 of the old + self.assertTrue(Path(receipt["lookPath"]).is_file()) + + def test_the_pruning_below_the_cap_removes_nothing(self): + for n in range(19): + self.look(commandId=f"look-{n:03d}") + self.assertEqual(len(list(self.look_dir().iterdir())), 19) + self.look(commandId="look-last") + self.assertEqual(len(list(self.look_dir().iterdir())), 20) + + def test_pruning_touches_only_png_files_directly_inside_look(self): + self.look_dir().mkdir(parents=True) + (self.root / "out" / "keep.png").write_bytes(PNG) + (self.look_dir() / "notes.txt").write_text("x") + (self.look_dir() / "dir.png").mkdir() + for n in range(25): + f = self.look_dir() / f"old-{n:02d}.png" + f.write_bytes(PNG) + os.utime(f, (1_000_000 + n, 1_000_000 + n)) + self.look() + self.assertTrue((self.root / "out" / "keep.png").exists()) + self.assertTrue((self.look_dir() / "notes.txt").exists()) + self.assertTrue((self.look_dir() / "dir.png").is_dir()) + self.assertEqual(len([p for p in self.look_dir().iterdir() if p.suffix == ".png" and p.is_file()]), 20) + + def test_a_refused_look_prunes_nothing(self): + self.look_dir().mkdir(parents=True) + for n in range(30): + (self.look_dir() / f"old-{n:02d}.png").write_bytes(PNG) + self.windows[0].screen.areas.remove(self.view) + self.look() + self.assertEqual(len(list(self.look_dir().iterdir())), 30) + + def test_a_refusal_does_not_echo_the_output_path(self): + self.windows[0].screen.areas.remove(self.view) + self.assertNotIn(str(self.root), self.look()["message"]) + + +def rich(obj): + """What the real _object_snapshot reads of an object.""" + for key, value in dict(library=None, location=(0.0, 0.0, 0.0), rotation_euler=(0.0, 0.0, 0.0), scale=(1.0, 1.0, 1.0), + parent=None, users_collection=[], material_slots=[], modifiers=[], constraints=[]).items(): + setattr(obj, key, value) + obj.visible_get = lambda: True + obj.items = lambda: [] + obj.mode = getattr(obj, "mode", "OBJECT") + return obj + + +class EditSelectionTests(PerceptionFixture): + def snapshot(self): + for obj in self.bpy.data.objects: + rich(obj) + self.bpy.camera_data.name, self.bpy.light_data.name, self.bpy.camera_data.angle = "CamData", "LightData", 0.6 + self.bpy.app.version = (5, 3, 0) + self.bpy.data.filepath = "" + for name in ("collections", "materials", "images"): + setattr(self.bpy.data, name, []) + self.bpy.scene.frame_current = self.bpy.scene.frame_start = self.bpy.scene.frame_end = 1 + self.bpy.scene.collection = None + context = NS(selected_objects=[], active_object=None, scene=self.bpy.scene, mode="EDIT_MESH") + with unittest.mock.patch.object(self.target, "_evaluated_snapshot", return_value=None): + return self.target.capture_snapshot(context, False) + + def test_selection_is_read_from_the_edit_mesh_without_leaving_edit_mode(self): + self.bpy.mesh.mode = "EDIT" + selection = self.target.edit_selection() + self.assertEqual(selection, [{"name": "Cube", "type": "MESH", + "vertices": [0, 2], "verticesTotal": 2, + "edges": [1], "edgesTotal": 1, + "faces": [], "facesTotal": 0}]) + self.assertEqual(self.bpy.mesh.mode, "EDIT") + self.assertEqual(self.bmesh.reads, 1) + + def test_nothing_in_edit_mode_is_an_empty_list_and_reads_no_mesh(self): + self.assertEqual(self.target.edit_selection(), []) + self.assertEqual(self.bmesh.reads, 0) + + def test_each_list_is_capped_at_4096_with_the_true_total_beside_it(self): + self.bpy.mesh.mode = "EDIT" + self.bmesh.meshes[id(self.bpy.mesh_data)] = ([True] * 5000, [False] * 5000 + [True], [True] * 4096) + entry = self.target.edit_selection()[0] + self.assertEqual((len(entry["vertices"]), entry["verticesTotal"]), (4096, 5000)) + self.assertEqual(entry["vertices"][:3], [0, 1, 2]) + self.assertEqual((entry["edges"], entry["edgesTotal"]), ([5000], 1)) + self.assertEqual((len(entry["faces"]), entry["facesTotal"]), (4096, 4096)) + + def test_every_object_in_edit_mode_is_listed_and_a_non_mesh_says_unsupported(self): + self.bpy.mesh.mode = "EDIT" + self.bpy.cam.mode = "EDIT" + names = {e["name"]: e for e in self.target.edit_selection()} + self.assertEqual(sorted(names), ["Cam", "Cube"]) + self.assertEqual(names["Cam"], {"name": "Cam", "type": "CAMERA", "unsupported": True}) + + def test_the_snapshot_carries_selection_session_and_sequences(self): + self.bpy.mesh.mode = "EDIT" + snap = self.snapshot() + self.assertEqual(snap["editSelection"][0]["vertices"], [0, 2]) + self.assertEqual(snap["sessionId"], self.target.session_id) + self.assertEqual(snap["humanEditSeq"], 0) + self.assertTrue(all(o["lastHumanEditSeq"] == 0 for o in snap["objects"])) + self.assertEqual(self.snapshot()["sessionId"], snap["sessionId"]) + + def test_the_object_snapshot_carries_the_last_human_edit_sequence(self): + self.target._last_human_edit["Cube"] = 7 + objects = {o["name"]: o["lastHumanEditSeq"] for o in self.snapshot()["objects"]} + self.assertEqual(objects, {"Cam": 0, "Lamp": 0, "Cube": 7}) + + +def update(name, *, kind="OBJECT", transform=False, geometry=False, shading=False): + return NS(id=NS(name=name, id_type=kind), is_updated_transform=transform, is_updated_geometry=geometry, + is_updated_shading=shading) + + +def depsgraph(*updates): + return NS(updates=list(updates)) + + +class HumanEditTests(PerceptionFixture): + def test_an_update_outside_an_agent_turn_bumps_the_sequence_and_stamps_the_object(self): + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.target.human_edit_seq, 1) + self.assertEqual(self.target.last_human_edit_seq("Cube"), 1) + self.target.track_human_edits(depsgraph(update("Lamp", geometry=True))) + self.assertEqual((self.target.human_edit_seq, self.target.last_human_edit_seq("Lamp")), (2, 2)) + self.assertEqual(self.target.last_human_edit_seq("Cube"), 1) + + def test_a_constrained_follower_moves_with_its_target(self): + # the update names both objects, the follower's carrying the transform flag only because of its constraint + self.target.track_human_edits(depsgraph(update("Cube", transform=True), update("Follower", transform=True))) + self.assertEqual(self.target.last_human_edit_seq("Follower"), self.target.last_human_edit_seq("Cube")) + self.assertEqual(self.target.human_edit_seq, 1) + + def test_geometry_and_shading_count_and_an_unflagged_presence_does_not(self): + self.target.track_human_edits(depsgraph(update("Cube", shading=True))) + self.assertEqual(self.target.last_human_edit_seq("Cube"), 1) + self.target.track_human_edits(depsgraph(update("Lamp"), update("Cam"))) # named, not changed + self.assertEqual((self.target.human_edit_seq, self.target.last_human_edit_seq("Lamp")), (1, 0)) + + def test_only_objects_are_stamped(self): + self.target.track_human_edits(depsgraph(update("Mesh", kind="MESH", geometry=True))) + self.assertEqual(self.target.human_edit_seq, 0) + + def test_agent_turn_updates_do_not_count_as_human(self): + # the update arrives inside the turn (probe depsgraph-timing), so the in-turn flag attributes it + original = self.bpy.ops.object.empty_add + + def add_and_update(*a, **kw): + original(*a, **kw) + self.target.track_human_edits(depsgraph(update("Empty", transform=True, geometry=True))) + + self.bpy.ops.object.empty_add = add_and_update + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted") + self.assertEqual(self.target.human_edit_seq, 0) + self.assertEqual(self.target.last_human_edit_seq("Empty"), 0) + self.target.track_human_edits(depsgraph(update("Empty", transform=True))) # after the turn: hers + self.assertEqual(self.target.human_edit_seq, 1) + + def test_a_failed_turn_still_ends_the_turn_for_attribution(self): + def boom(*a, **kw): + raise RuntimeError("half done") + self.bpy.ops.object.empty_add = boom + self.run_action(action="createObject", objectType="EMPTY") + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.target.human_edit_seq, 1) + + def test_undo_and_redo_bump_the_sequence_without_naming_an_object(self): + self.target.note_undo_redo() + self.target.note_undo_redo() + self.assertEqual(self.target.human_edit_seq, 2) + self.assertEqual(self.target._last_human_edit, {}) + + def test_human_edit_seq_never_refuses(self): + # scene-last-writer-wins: an intent after her edit is accepted, and so is one that targets what she edited + rich(self.bpy.mesh) + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + receipt = self.run_action(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted") + self.assertEqual(len(self.bpy.undo.pushes), 2) + + def test_the_admission_code_never_reads_the_sequences(self): + source = inspect.getsource(bt.BrokkrBlenderTarget.run_intent) + self.assertEqual(re.findall(r"humanEditSeq|lastHumanEditSeq|human_edit", source), []) + self.assertEqual(re.findall(r"human_edit|session_id", inspect.getsource(bt.BrokkrBlenderTarget._dispatch)), []) + + def test_a_new_session_resets_the_counters_and_mints_a_new_id(self): + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + before = self.target.session_id + self.target.renew_session() + self.assertNotEqual(self.target.session_id, before) + self.assertEqual((self.target.human_edit_seq, self.target.last_human_edit_seq("Cube")), (0, 0)) + + def test_two_targets_mint_different_session_ids(self): + self.assertNotEqual(bt.BrokkrBlenderTarget(self.bpy).session_id, self.target.session_id) + + +class LookReportsHerEditsTests(PerceptionFixture): + def test_the_receipt_carries_the_session_the_selection_and_the_edits_since_the_last_look(self): + self.bpy.mesh.mode = "EDIT" + first = self.look(requestedBy="nibu/hands") + self.assertEqual(first["sessionId"], self.target.session_id) + self.assertEqual((first["humanEditSeq"], first["humanEditsSinceLook"], first["editedSinceLook"]), (0, 0, [])) + self.assertEqual(first["editSelection"][0]["vertices"], [0, 2]) + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.target.track_human_edits(depsgraph(update("Lamp", geometry=True))) + second = self.look(requestedBy="nibu/hands") + self.assertEqual((second["humanEditSeq"], second["humanEditsSinceLook"]), (2, 2)) + self.assertEqual(second["editedSinceLook"], ["Cube", "Lamp"]) + third = self.look(requestedBy="nibu/hands") + self.assertEqual((third["humanEditsSinceLook"], third["editedSinceLook"]), (0, [])) + + def test_each_agent_has_its_own_last_look(self): + self.look(requestedBy="nibu/hands") + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.look(requestedBy="nibu/hands")["humanEditsSinceLook"], 1) + self.assertEqual(self.look(requestedBy="nibu/soul")["humanEditsSinceLook"], 1) # soul's first look: all of it + + def test_a_new_session_forgets_the_last_look(self): + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.look(requestedBy="nibu/hands") # her edit number 1 is now seen + self.target.renew_session() + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) # number 1 again, in the new session + receipt = self.look(requestedBy="nibu/hands") + self.assertEqual((receipt["humanEditSeq"], receipt["humanEditsSinceLook"], receipt["editedSinceLook"]), (1, 1, ["Cube"])) + + def test_a_refused_look_does_not_move_the_last_look(self): + self.look(requestedBy="nibu/hands") + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.windows[0].screen.areas.remove(self.view) + self.look(requestedBy="nibu/hands") + self.windows[0].screen.areas.append(self.view) + self.assertEqual(self.look(requestedBy="nibu/hands")["humanEditsSinceLook"], 1) + + +class StorePathTests(unittest.TestCase): + def test_the_default_blend_relative_store_is_found_where_the_blend_file_is(self): + # live-3 Low: store_exists must resolve the default '//.brokkr/...' against the blend file, as the add-on does + import tempfile + with tempfile.TemporaryDirectory() as tmp: + blend = Path(tmp).resolve() + (blend / ".brokkr").mkdir() + (blend / ".brokkr" / "blender-editor.ccmp").write_bytes(b"") + + def abspath(p): + return str(blend / p[2:]) if p.startswith("//") else p + + target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=abspath))) + self.assertTrue(target.store_exists(bt.DEFAULT_CULTMESH_CACHE_PATH)) + self.assertTrue(target.store_exists("")) # an empty preference means the default + self.assertEqual(Path(target.resolve_cache_path(bt.DEFAULT_CULTMESH_CACHE_PATH)), + blend / ".brokkr" / "blender-editor.ccmp") + (blend / ".brokkr" / "blender-editor.ccmp").unlink() + self.assertFalse(target.store_exists(bt.DEFAULT_CULTMESH_CACHE_PATH)) + + def test_the_preference_default_is_the_blend_relative_path_the_target_resolves(self): + prop = addon.BrokkrPreferences.__annotations__["cultmesh_cache_path"] + self.assertEqual(prop.kwargs["default"], "//.brokkr/blender-editor.ccmp") + self.assertEqual(bt.DEFAULT_CULTMESH_CACHE_PATH, prop.kwargs["default"]) + + +class HandlerWiringTests(unittest.TestCase): + def setUp(self): + self.lists = {name: [] for name in ("depsgraph_update_post", "undo_post", "redo_post", "load_post")} + handlers = NS(persistent=lambda f: setattr(f, "persistent", True) or f, **self.lists) + self.fake = NS(app=NS(handlers=handlers, timers=NS(is_registered=lambda f: False, register=lambda *a, **k: None, + unregister=lambda f: None)), + utils=NS(register_class=lambda c: None, unregister_class=lambda c: None)) + patch = unittest.mock.patch.multiple(addon.bpy, app=self.fake.app, utils=self.fake.utils) + patch.start() + self.addCleanup(patch.stop) + self.target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=lambda p: p))) + addon._target = self.target + self.addCleanup(lambda: setattr(addon, "_target", None)) + + def test_register_adds_persistent_human_edit_handlers_and_unregister_removes_them(self): + addon.register() + for name in ("depsgraph_update_post", "undo_post", "redo_post", "load_post"): + ours = [h for h in self.lists[name] if getattr(h, "persistent", False)] + self.assertEqual(len(ours), 1, name) + self.assertIn(addon._auto_capture, self.lists["depsgraph_update_post"]) # the snapshot handler stays + self.assertEqual(len(self.lists["depsgraph_update_post"]), 2) + addon.register() # twice adds nothing + self.assertEqual(len(self.lists["depsgraph_update_post"]), 2) + addon.unregister() + self.assertEqual([len(v) for v in self.lists.values()], [0, 0, 0, 0]) + + def test_the_handlers_feed_the_target(self): + addon.register() + addon._target = self.target + track = next(h for h in self.lists["depsgraph_update_post"] if getattr(h, "persistent", False)) + track(None, depsgraph(update("Cube", transform=True))) + self.assertEqual(self.target.human_edit_seq, 1) + self.lists["undo_post"][0](None) + self.lists["redo_post"][0](None) + self.assertEqual(self.target.human_edit_seq, 3) + before = self.target.session_id + self.lists["load_post"][0](None) + self.assertNotEqual(self.target.session_id, before) + self.assertEqual(self.target.human_edit_seq, 0) + + def test_the_human_edit_tracker_does_not_depend_on_auto_capture(self): + # always on: it reads no preference at all + source = inspect.getsource(addon._track_human_edits) + self.assertNotRegex(source, r"auto_capture|preferences") + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index 6c73c67..fcc2b64 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -67,7 +67,10 @@ def fake_render(): class Objects(dict): - """bpy.data.objects: a mapping with keys() and get().""" + """bpy.data.objects: a mapping with keys() and get(); like bpy_prop_collection, iterating it yields the objects.""" + + def __iter__(self): + return iter(self.values()) class FakeUndo: From 5fcc8900215625ca44af58a7eb075775f9e3fdbc Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:19:53 +0100 Subject: [PATCH 038/223] brokkr-ctl blender look: send look, print the receipt's lookPath, selection and edits since the last look Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/src/blender.rs | 15 ++++++++++--- brokkr-ctl/tests/cli.rs | 47 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index be25999..9bb89d1 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -119,7 +119,13 @@ pub fn run(args: &[String]) -> Result { return Ok(0); } match sub.as_str() { - "send" => send(&options), + "send" => send(&options, one_positional(&options, "send [--set key=json]...")?), + "look" => { + if !options.positional.is_empty() || !options.sets.is_empty() { + bail!("usage: brokkr-ctl blender look [--note text] [--agent name] [--no-wait] [--timeout secs]"); + } + send(&options, "look") + } "wait" => { let id = one_positional(&options, "wait ")?; let store = open_store(&options)?; @@ -232,8 +238,7 @@ fn build_intent( Ok(Value::Object(map)) } -fn send(options: &Options) -> Result { - let action = one_positional(options, "send [--set key=json]...")?; +fn send(options: &Options, action: &str) -> Result { let requested_by = requested_by(options)?; let mut store = open_store(options)?; let command_id = uuid::Uuid::now_v7().simple().to_string(); @@ -399,6 +404,9 @@ brokkr-ctl blender: send typed intents to the live Blender add-on and read what send [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs] Write one intent, then wait for its receipt and print it. `send --help` lists actions. + look [--note text] [--agent name] [--no-wait] [--timeout secs] + `send look`: capture the 3D view she is looking at. The receipt prints lookPath (a PNG), her + Edit Mode selection, and how many edits she made since this agent last looked. wait [--timeout secs] Wait for a receipt and print it. receipts [--last n] Print stored receipts, oldest first. status Print the host snapshot summary, agentCommandsEnabled included. @@ -544,6 +552,7 @@ const ACTIONS: &[(&str, &[Field])] = &[ ("cameraName", "string", ""), ], ), + ("look", &[]), ( "createNodeGroup", &[ diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 4ea7f24..a7293e1 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -80,6 +80,53 @@ fn send_writes_a_pullable_intent() { assert!(envelopes.iter().any(|e| e.key == "blender/receipts/seed"), "other records survive the write"); } +/// `look` is `send look`: one intent, no fields, the same receipt wait. +#[test] +fn look_sends_the_look_action_and_prints_the_receipts_look_path() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let output = ctl(&path, &["look", "--agent", "hands", "--note", "checking the view", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr)); + let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string(); + let envelopes = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + let intent = envelopes.iter().find(|e| e.key == format!("blender/commands/{id}")).expect("intent key"); + let payload: Value = cultcache_rs::decode_payload(&intent.payload).unwrap(); + assert_eq!( + payload, + json!({"schema": INTENT, "commandId": id, "action": "look", "requestedBy": "nibu/hands", + "note": "checking the view"}) + ); + // the add-on's receipt for it prints like any other: lookPath and the perception fields are plain lines + let mut store = SingleFileMessagePackBackingStore::new(&path); + let receipt = json!({"schema": RECEIPT, "commandId": id, "status": "accepted", "lookPath": "C:/out/look/x.png", + "humanEditSeq": 3, "editSelection": [{"name": "Cube", "vertices": [0, 2]}]}); + store.push(&envelope(RECEIPT, &format!("blender/receipts/{id}"), &receipt)).unwrap(); + let waited = ctl(&path, &["wait", &id, "--timeout", "5"], None); + assert_eq!(waited.status.code(), Some(0)); + let text = stdout(&waited); + assert!(text.contains("lookPath: C:/out/look/x.png"), "{text}"); + assert!(text.contains("humanEditSeq: 3") && text.contains("\"vertices\":[0,2]"), "{text}"); +} + +#[test] +fn look_takes_no_fields_and_no_second_action() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + for extra in [vec!["--set", "x=1"], vec!["createObject"]] { + let mut args = vec!["look", "--agent", "hands", "--no-wait"]; + args.extend(extra.iter()); + assert_eq!(ctl(&path, &args, Some("nibu")).status.code(), Some(1), "{extra:?}"); + } + let store = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + assert!(!store.iter().any(|e| e.key.starts_with("blender/commands/")), "a refused look writes nothing"); +} + +#[test] +fn the_group_help_names_look() { + let output = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")).args(["blender", "--help"]).output().unwrap(); + assert!(stdout(&output).contains("look")); +} + #[test] fn an_intent_without_instance_or_agent_is_refused_and_writes_nothing() { let dir = tempfile::tempdir().unwrap(); From bbe5176ca248d5847d0f450751c7510266c55a8b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:25:50 +0100 Subject: [PATCH 039/223] Perception: live proof in a stock Blender 5.3 through brokkr-ctl, and the look contract in the docs Co-Authored-By: Claude Sonnet 5.5 --- docs/provider-contract.md | 1 + surfaces/blender/docs/install.md | 18 + surfaces/blender/tests/live/perception.py | 275 +++++++++++ .../blender/tests/live/perception.result.json | 437 ++++++++++++++++++ 4 files changed, 731 insertions(+) create mode 100644 surfaces/blender/tests/live/perception.py create mode 100644 surfaces/blender/tests/live/perception.result.json diff --git a/docs/provider-contract.md b/docs/provider-contract.md index 8c1132f..cda8707 100644 --- a/docs/provider-contract.md +++ b/docs/provider-contract.md @@ -220,6 +220,7 @@ All Blender writes use `brokkr.blender.command_intent.v0` and receive - `setLight` - `setWorld` - `renderStill` +- `look` (a read: a PNG of her 3D view under the output directory's `look/`, her Edit Mode selection and her edit counters in the receipt) - `createNodeGroup`, `addNode`, `removeNode`, `linkSockets`, `unlinkSockets`, `addModifier`, `removeModifier`, `setModifierInput` (Geometry Nodes graphs; fields in `surfaces/blender/docs/node-actions.md`) diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 0b5917c..0eb7d40 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -175,6 +175,7 @@ Admitted command actions: - `setLight` - `setWorld` - `renderStill` +- `look` Scene action fields (all other keys are ignored; a refused intent changes nothing and gets a `failed` receipt whose message names the rule): @@ -227,6 +228,23 @@ gets a `failed` receipt whose message names the rule): CPU. The check applies to the scene's engine when `engine` is omitted. No such check runs on Windows or macOS. +- `look`: no fields. Captures the 3D view she is looking at (the largest 3D view across the windows, its + main region) to `/look/.png` and puts the absolute path in the receipt's + `lookPath`; refused when the output directory is unset or no 3D view is open. It reads Blender's own + framebuffer for that one region, so her desktop and other applications are never in the picture; a menu, + popup or the splash Blender draws over the view is, as she sees it. It is a read: no undo step, and it runs in + Edit Mode. The capture blocks her UI for about 70 ms. The look directory keeps the newest 20 PNGs (scratch, + never read back). The receipt also carries `sessionId`, `humanEditSeq`, `humanEditsSinceLook` and + `editedSinceLook` (object names), counted for the sending `requestedBy` since its previous look in this + session, and `editSelection`: for each object in Edit Mode its selected vertex, edge and face indices (each + list capped at 4096, the true count beside it as `verticesTotal` and so on; non-mesh objects say + `unsupported`). The host snapshot carries the same `sessionId`, `humanEditSeq`, `editSelection` and each + object's `lastHumanEditSeq`. The sequences come from depsgraph updates outside an agent turn, counted per + flagged object (transform, geometry or shading) and from undo and redo; opening a file starts a new session. An + update also flags objects that only depend on what she changed (a constrained follower), and adding or + linking an object flags all of them, so `editedSinceLook` can name more than she touched. They are + observations: no intent is refused because of them. + The scene actions were run against Blender 5.2.3 LTS headless with `surfaces/blender/tests/live/headless_smoke.py` (usage in its docstring). One real failure it found: Blender's `engine` enum is dynamic, so `bl_rna` lists only diff --git a/surfaces/blender/tests/live/perception.py b/surfaces/blender/tests/live/perception.py new file mode 100644 index 0000000..a62aeb8 --- /dev/null +++ b/surfaces/blender/tests/live/perception.py @@ -0,0 +1,275 @@ +"""Live proof, in GUI Blender with the add-on installed as an extension, of perception, with real brokkr-ctl sends. + + BROKKR_SCRATCH= + BROKKR_CTL= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + blender --python perception.py -- + +Run it in a Blender whose resource path is fresh (BLENDER_USER_RESOURCE_PATH) so the add-on's preferences are the +defaults. The driver stands in for the operator's hands only: it saves the blend, ticks the sink and sets the render +output directory (the two preferences an operator sets), enters Edit Mode, selects, moves objects and presses undo. +Every intent is sent by brokkr-ctl and answered by the add-on's own timer. Writes .result.json, then quits. +""" +import importlib +import json +import os +import shutil +import struct +import subprocess +import sys +import time +import traceback +from pathlib import Path + +import bmesh +import bpy + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +CTL = os.environ["BROKKR_CTL"] +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": [], "notes": {}} + +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +prefs = bpy.context.preferences.addons[MODULE].preferences +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +adapter = addon.target() +STORE = SCRATCH / ".brokkr" / "blender-editor.ccmp" # what the default blend-relative preference resolves to +ENV = dict(os.environ, EUREKA_INSTANCE="nibu", BROKKR_BLENDER_STORE=str(STORE), BROKKR_AGENT="hands") + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def fields(text): + out = {} + for line in text.splitlines(): + key, _, value = line.partition(": ") + try: + out[key] = json.loads(value) if value[:1] in "[{0123456789" else value + except ValueError: + out[key] = value + return out + + +def ctl(*args): + """A brokkr-ctl run beside Blender's timers (it blocks until the receipt, and the add-on's timer answers it).""" + proc = subprocess.Popen([CTL, "blender", *args], env=ENV, stdout=subprocess.PIPE, text=True) + began = time.perf_counter() + while proc.poll() is None: + yield + out = proc.stdout.read() + return proc.returncode, fields(out), round((time.perf_counter() - began) * 1000) + + +def png_size(path): + data = Path(path).read_bytes() + assert data[:8] == b"\x89PNG\r\n\x1a\n", "not a PNG" + return struct.unpack(">II", data[16:24]) + + +def view3d(): + for window in bpy.context.window_manager.windows: + for area in window.screen.areas: + if area.type == "VIEW_3D": + return window, area, next(r for r in area.regions if r.type == "WINDOW") + + +def snapshot(): + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.brokkr.capture_snapshot() + return adapter.last_snapshot + + +def objects_named(prefix): + return sorted(o.name for o in bpy.data.objects if o.name.startswith(prefix)) + + +def mode_edit(on): + window, area, region = view3d() + cube = bpy.data.objects["Cube"] + bpy.context.view_layer.objects.active = cube # she clicks it first + cube.select_set(True) + with bpy.context.temp_override(window=window, area=area, region=region, active_object=cube, object=cube): + bpy.ops.object.mode_set(mode="EDIT" if on else "OBJECT") + + +def flow(): + cube = bpy.data.objects["Cube"] + window, area, region = view3d() + R["notes"]["window_px"] = [window.width, window.height] + R["notes"]["region_px"] = [region.width, region.height] + R["notes"]["area_px"] = [area.width, area.height] + + # ---- a default install: the preferences are untouched except what the operator sets ---- + check("default install: the store preference is the blend-relative default", + prefs.cultmesh_cache_path == "//.brokkr/blender-editor.ccmp", prefs.cultmesh_cache_path) + bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "perception.blend")) + prefs.output_dir = str(SCRATCH / "out") + prefs.auto_drain_commands = True # the operator ticks the sink + yield 1.0 + snap = snapshot() + check("the default blend-relative store was created beside the saved blend", STORE.is_file(), str(STORE)) + check("the snapshot carries sessionId, humanEditSeq 0, editSelection [] and per-object lastHumanEditSeq", + snap["sessionId"] == adapter.session_id and snap["humanEditSeq"] == 0 and snap["editSelection"] == [] + and all(o["lastHumanEditSeq"] == 0 for o in snap["objects"]), [snap["sessionId"], snap["humanEditSeq"]]) + session = snap["sessionId"] + + # ---- look: her 3D view, scoped to the viewport ---- + code, r, ms = yield from ctl("look", "--note", "first look") + R["notes"]["first_look"] = r + R["notes"]["first_look_round_trip_ms"] = ms + path = r.get("lookPath", "") + size = png_size(path) if path and Path(path).is_file() else None + check("look: exit 0, accepted, a lookPath PNG under /look/.png", + code == 0 and r.get("status") == "accepted" and size is not None + and Path(path).parent == (SCRATCH / "out" / "look") and Path(path).name == r["commandId"] + ".png", [code, r]) + check("look: the PNG is the 3D view's WINDOW region, not the Blender window and not the desktop", + list(size) == R["notes"]["region_px"] and list(size) != R["notes"]["window_px"], [size, R["notes"]]) + check("look: no undo step, receipt names the session, edits so far 0, none edited since", + r.get("undoLabel", "") == "" and r.get("sessionId") == session and r.get("humanEditSeq") == 0 + and r.get("humanEditsSinceLook") == 0 and r.get("editedSinceLook") == [], r) + + # ---- the agent's own edits are not hers ---- + seq_before = adapter.human_edit_seq + code, r, _ = yield from ctl("send", "createObject", "--set", 'objectType="EMPTY"', "--set", 'name="AgentEmpty"') + code2, r2, _ = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[0,0,0.5]") + for _ in range(12): # a deferred depsgraph update, if the turn left one behind, arrives within a few ticks + yield 0.1 + check("agent turns (createObject, setObjectTransform) leave humanEditSeq unmoved, also after idle ticks", + code == 0 and code2 == 0 and adapter.human_edit_seq == seq_before == 0 + and adapter.last_human_edit_seq("AgentEmpty") == 0 and adapter.last_human_edit_seq("Cube") == 0, + [code, code2, adapter.human_edit_seq, adapter._last_human_edit]) + + # ---- Edit Mode selection, read live, without leaving Edit Mode ---- + mode_edit(True) + yield 0.3 + bm = bmesh.from_edit_mesh(cube.data) + for v in bm.verts: + v.select = False + bm.verts.ensure_lookup_table() + bm.verts[0].select = True + bm.verts[3].select = True + bm.select_flush_mode() + bmesh.update_edit_mesh(cube.data) + yield 0.3 + code, r, _ = yield from ctl("look") + if r.get("lookPath"): + shutil.copy(r["lookPath"], SCRATCH / "edit-look.png") + sel = (r.get("editSelection") or [{}])[0] + check("edit selection: look reads her two selected vertices live; the mode stays Edit Mode", + code == 0 and sel.get("name") == "Cube" and sel.get("vertices") == [0, 3] and sel.get("verticesTotal") == 2 + and bpy.context.mode == "EDIT_MESH", [r.get("editSelection"), bpy.context.mode]) + code, r2, _ = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[0,0,3]") + check("an object intent is refused while she is in Edit Mode (ruling in force); look was not", code == 2 and r2.get("status") == "denied", + r2.get("message")) + snap = snapshot() + check("the snapshot's editSelection matches", snap["editSelection"][0]["vertices"] == [0, 3], snap["editSelection"]) + mode_edit(False) + yield 0.3 + + # ---- her edits: counters, and a follower that moves with its target ---- + follower = bpy.data.objects.new("Follower", bpy.data.meshes.new("FollowerMesh")) + bpy.context.scene.collection.objects.link(follower) + constraint = follower.constraints.new("COPY_LOCATION") + constraint.target = cube + constraint.use_y = False + yield 0.5 + # Linking an object rebuilds the depsgraph relations and Blender flags other objects in that update: collateral + # of her adding an object, recorded, not attributed to a move. + R["notes"]["after_adding_follower"] = dict(adapter._last_human_edit) + code, r, _ = yield from ctl("look") # the marker: what she does next is "since this look" + marker = r["humanEditSeq"] + cube.location.x = 2.0 # her move + yield 0.5 + cube.location.x = 4.0 + yield 0.5 + snap = snapshot() + by = {o["name"]: o["lastHumanEditSeq"] for o in snap["objects"]} + R["notes"]["after_moving_cube"] = {"marker": marker, "humanEditSeq": snap["humanEditSeq"], "last": by} + check("her moves bump humanEditSeq; Cube and its constrained Follower carry the same last sequence, the untouched Light and Camera do not", + snap["humanEditSeq"] > marker and by["Cube"] == by["Follower"] == snap["humanEditSeq"] + and by["Light"] <= marker and by["Camera"] <= marker, [marker, snap["humanEditSeq"], by]) + code, r, _ = yield from ctl("look") + check("the next look says what changed since the last one: exactly the moved Cube and its Follower", + r["humanEditsSinceLook"] >= 2 and r["editedSinceLook"] == ["Cube", "Follower"], r) + code, r, _ = yield from ctl("look") + check("and a look right after it says nothing changed since", r["humanEditsSinceLook"] == 0 and r["editedSinceLook"] == [], r) + + # ---- scene-last-writer-wins and act-then-undo ---- + seq = adapter.human_edit_seq + code, r, _ = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[9,9,9]") + check("after her edit, the agent's action on the same object is accepted (last writer wins)", code == 0 and r.get("status") == "accepted" + and tuple(round(c, 3) for c in bpy.data.objects["Cube"].location) == (9.0, 9.0, 9.0), r) + check("and still did not count as hers", adapter.human_edit_seq == seq, [seq, adapter.human_edit_seq]) + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.ed.undo() # her Ctrl+Z + yield 0.5 + check("her Ctrl+Z takes the agent's step back and counts as hers", + bpy.data.objects["Cube"].location.x != 9.0 and adapter.human_edit_seq > seq, + [bpy.data.objects["Cube"].location.x, seq, adapter.human_edit_seq]) + + # ---- a popup open over the view is in the picture, as she sees it ---- + window, area, region = view3d() + with bpy.context.temp_override(window=window, area=area, region=region): + bpy.ops.wm.call_menu("INVOKE_DEFAULT", name="VIEW3D_MT_add") + yield 0.8 + code, r, _ = yield from ctl("look", "--note", "with the Add menu open") + R["notes"]["popup_look"] = r.get("lookPath") + if r.get("lookPath"): + shutil.copy(r["lookPath"], SCRATCH / "popup-look.png") # the look directory is pruned; this copy is for a human to see + check("look with a popup open: accepted, a PNG of the same region size", code == 0 and r.get("lookPath") + and list(png_size(r["lookPath"])) == R["notes"]["region_px"], r) + + # ---- prune to twenty ---- + for _ in range(24): + yield from ctl("look") + kept = sorted((SCRATCH / "out" / "look").glob("*.png")) + check("after 30 looks the look directory holds exactly the newest 20 PNGs", len(kept) == 20, len(kept)) + + # ---- refusals ---- + area.type = "OUTLINER" + yield 0.3 + code, r, _ = yield from ctl("look") + area.type = "VIEW_3D" + check("no 3D view open: look is refused naming why, with no path", code == 2 and "3D" in r.get("message", "") and r.get("lookPath", "") == "", r) + prefs.output_dir = "" + code, r, _ = yield from ctl("look") + prefs.output_dir = str(SCRATCH / "out") + check("no output directory set: look is refused naming why", code == 2 and "output" in r.get("message", ""), r) + code, r, _ = yield from ctl("look") + check("the next look works again", code == 0, r) + check("no add-on drain error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + + +gen = flow() +wait_until = 0.0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def runner(): + global wait_until + try: + delay = next(gen) + return delay if isinstance(delay, (int, float)) and delay else 0.05 + except StopIteration: + write() + bpy.ops.wm.quit_blender() + return None + except Exception: + R.setdefault("errors", []).append(traceback.format_exc()) + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/perception.result.json b/surfaces/blender/tests/live/perception.result.json new file mode 100644 index 0000000..ac8afdb --- /dev/null +++ b/surfaces/blender/tests/live/perception.result.json @@ -0,0 +1,437 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "default install: the store preference is the blend-relative default", + "ok": true, + "detail": "//.brokkr/blender-editor.ccmp" + }, + { + "name": "the default blend-relative store was created beside the saved blend", + "ok": true, + "detail": "F:\\aeth-wt\\brokkr-live-5.scratch\\.brokkr\\blender-editor.ccmp" + }, + { + "name": "the snapshot carries sessionId, humanEditSeq 0, editSelection [] and per-object lastHumanEditSeq", + "ok": true, + "detail": [ + "3e3712b94e944cb9ad4a74aafdc699bd", + 0 + ] + }, + { + "name": "look: exit 0, accepted, a lookPath PNG under /look/.png", + "ok": true, + "detail": [ + 0, + { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + ] + }, + { + "name": "look: the PNG is the 3D view's WINDOW region, not the Blender window and not the desktop", + "ok": true, + "detail": [ + [ + 1574, + 888 + ], + { + "window_px": [ + 1920, + 1009 + ], + "region_px": [ + 1574, + 888 + ], + "area_px": [ + 1574, + 888 + ], + "first_look": { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + }, + "first_look_round_trip_ms": 456, + "after_adding_follower": { + "Cube": 4, + "Light": 4, + "Camera": 4, + "AgentEmpty": 4, + "Follower": 4 + }, + "after_moving_cube": { + "marker": 4, + "humanEditSeq": 6, + "last": { + "AgentEmpty": 4, + "Camera": 4, + "Cube": 6, + "Follower": 6, + "Light": 4 + } + }, + "popup_look": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee581c771d2b3b688dfce3996f3.png" + } + ] + }, + { + "name": "look: no undo step, receipt names the session, edits so far 0, none edited since", + "ok": true, + "detail": { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "agent turns (createObject, setObjectTransform) leave humanEditSeq unmoved, also after idle ticks", + "ok": true, + "detail": [ + 0, + 0, + 0, + { + "Cube": 8, + "Light": 8, + "Camera": 8, + "AgentEmpty": 8, + "Follower": 6 + } + ] + }, + { + "name": "edit selection: look reads her two selected vertices live; the mode stays Edit Mode", + "ok": true, + "detail": [ + [ + { + "edges": [], + "edgesTotal": 0, + "faces": [], + "facesTotal": 0, + "name": "Cube", + "type": "MESH", + "vertices": [ + 0, + 3 + ], + "verticesTotal": 2 + } + ], + "EDIT_MESH" + ] + }, + { + "name": "an object intent is refused while she is in Edit Mode (ruling in force); look was not", + "ok": true, + "detail": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "name": "the snapshot's editSelection matches", + "ok": true, + "detail": [ + { + "name": "Cube", + "type": "MESH", + "vertices": [ + 0, + 3 + ], + "verticesTotal": 2, + "edges": [], + "edgesTotal": 0, + "faces": [], + "facesTotal": 0 + } + ] + }, + { + "name": "her moves bump humanEditSeq; Cube and its constrained Follower carry the same last sequence, the untouched Light and Camera do not", + "ok": true, + "detail": [ + 4, + 6, + { + "AgentEmpty": 4, + "Camera": 4, + "Cube": 6, + "Follower": 6, + "Light": 4 + } + ] + }, + { + "name": "the next look says what changed since the last one: exactly the moved Cube and its Follower", + "ok": true, + "detail": { + "commandId": "01a21ee56f787012b0f2312b77c478b4", + "action": "look", + "editSelection": [], + "editedSinceLook": [ + "Cube", + "Follower" + ], + "humanEditSeq": 6, + "humanEditsSinceLook": 2, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee56f787012b0f2312b77c478b4.png", + "message": "Captured the 3D view to look/01a21ee56f787012b0f2312b77c478b4.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:24:43.509761+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "and a look right after it says nothing changed since", + "ok": true, + "detail": { + "commandId": "01a21ee574627220a1ed3e104667b73c", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 6, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee574627220a1ed3e104667b73c.png", + "message": "Captured the 3D view to look/01a21ee574627220a1ed3e104667b73c.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:24:44.677117+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after her edit, the agent's action on the same object is accepted (last writer wins)", + "ok": true, + "detail": { + "commandId": "01a21ee5788978c1b7f353ca2e2147be", + "action": "setObjectTransform", + "lookPath": "", + "message": "Blender object transform updated.", + "note": "", + "objectName": "Cube", + "observedAt": "2026-11-27T21:24:45.745214+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 2e2147be" + } + }, + { + "name": "and still did not count as hers", + "ok": true, + "detail": [ + 6, + 6 + ] + }, + { + "name": "her Ctrl+Z takes the agent's step back and counts as hers", + "ok": true, + "detail": [ + 0.0, + 6, + 8 + ] + }, + { + "name": "look with a popup open: accepted, a PNG of the same region size", + "ok": true, + "detail": { + "commandId": "01a21ee581c771d2b3b688dfce3996f3", + "action": "look", + "editSelection": [], + "editedSinceLook": [ + "AgentEmpty", + "Camera", + "Cube", + "Light" + ], + "humanEditSeq": 8, + "humanEditsSinceLook": 2, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee581c771d2b3b688dfce3996f3.png", + "message": "Captured the 3D view to look/01a21ee581c771d2b3b688dfce3996f3.png.", + "note": "with the Add menu open", + "objectName": "", + "observedAt": "2026-11-27T21:24:47.877250+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after 30 looks the look directory holds exactly the newest 20 PNGs", + "ok": true, + "detail": 20 + }, + { + "name": "no 3D view open: look is refused naming why, with no path", + "ok": true, + "detail": { + "commandId": "01a21ee5f6b27cc2ae9dd61ee3a5bdef", + "action": "look", + "lookPath": "", + "message": "No 3D viewport is open to look at.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:25:17.807716+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "failed", + "undoLabel": "" + } + }, + { + "name": "no output directory set: look is refused naming why", + "ok": true, + "detail": { + "commandId": "01a21ee5fa117271abc6c3536e2194d3", + "action": "look", + "lookPath": "", + "message": "output directory is not configured in the add-on preferences.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:25:18.920883+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "failed", + "undoLabel": "" + } + }, + { + "name": "the next look works again", + "ok": true, + "detail": { + "commandId": "01a21ee5fe627fc3ad7ae77850c6e812", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 8, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5fe627fc3ad7ae77850c6e812.png", + "message": "Captured the 3D view to look/01a21ee5fe627fc3ad7ae77850c6e812.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:25:20.088455+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "no add-on drain error", + "ok": true, + "detail": "" + } + ], + "notes": { + "window_px": [ + 1920, + 1009 + ], + "region_px": [ + 1574, + 888 + ], + "area_px": [ + 1574, + 888 + ], + "first_look": { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + }, + "first_look_round_trip_ms": 456, + "after_adding_follower": { + "Cube": 4, + "Light": 4, + "Camera": 4, + "AgentEmpty": 4, + "Follower": 4 + }, + "after_moving_cube": { + "marker": 4, + "humanEditSeq": 6, + "last": { + "AgentEmpty": 4, + "Camera": 4, + "Cube": 6, + "Follower": 6, + "Light": 4 + } + }, + "popup_look": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee581c771d2b3b688dfce3996f3.png" + }, + "ok": true +} \ No newline at end of file From 1286ad8fc4fffa27b7f53ce691b9936c0690389d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:54:35 +0100 Subject: [PATCH 040/223] Perception fixes: offscreen look when Blender is not drawing, scene update sequence and capture source in the receipt, selection totals from the mesh and a capped scan, coarse attribution flagged, path re-check and prune pinned Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/blender_target.py | 103 ++++++- surfaces/blender/tests/test_perception.py | 255 +++++++++++++++++- 2 files changed, 345 insertions(+), 13 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index c69a493..93a9fb5 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -6,8 +6,10 @@ import json import math import os import re +import struct import sys import uuid +import zlib from array import array from collections import deque from datetime import datetime, timedelta, timezone @@ -129,6 +131,8 @@ class BrokkrBlenderTarget: self.human_edit_seq = 0 self._last_human_edit: dict[str, int] = {} # object name -> human_edit_seq when she last changed it self._looked: dict[str, int] = {} # requestedBy -> human_edit_seq at that agent's last look + self.scene_update_seq = 0 # every depsgraph update, hers or the agent's: what a capture reflects + self._coarse = {"seq": 0, "why": ""} # the latest human edit whose per-object stamps are not precise def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: """The directories importGltf and renderStill may touch; empty leaves that action disabled.""" @@ -1055,10 +1059,13 @@ class BrokkrBlenderTarget: self.human_edit_seq = 0 self._last_human_edit.clear() self._looked.clear() + self.scene_update_seq = 0 + self._coarse = {"seq": 0, "why": ""} def track_human_edits(self, depsgraph: Any) -> None: """A depsgraph update outside an agent turn is hers. What changed is read from each update's flags, never from presence in the list: an update also names what only depends on the change.""" + self.scene_update_seq += 1 if self.agent_turn: return changed = [u.id.name for u in depsgraph.updates @@ -1068,10 +1075,13 @@ class BrokkrBlenderTarget: self.human_edit_seq += 1 for name in changed: self._last_human_edit[name] = self.human_edit_seq + if len(changed) >= 2 and len(changed) == len(self.bpy.data.objects): + self._coarse = {"seq": self.human_edit_seq, "why": "all objects flagged"} # an add or a link does this def note_undo_redo(self) -> None: """An undo or redo cannot be narrowed to objects from its updates, so it moves the session counter only.""" self.human_edit_seq += 1 + self._coarse = {"seq": self.human_edit_seq, "why": "undo or redo flags all objects"} def last_human_edit_seq(self, name: str) -> int: return self._last_human_edit.get(name, 0) @@ -1089,10 +1099,20 @@ class BrokkrBlenderTarget: continue mesh = bmesh.from_edit_mesh(obj.data) entry: dict[str, Any] = {"name": obj.name, "type": obj.type} - for key, elements in (("vertices", mesh.verts), ("edges", mesh.edges), ("faces", mesh.faces)): - chosen = [index for index, element in enumerate(elements) if element.select] - entry[key] = chosen[:EDIT_SELECTION_CAP] - entry[key + "Total"] = len(chosen) + # The totals are the mesh's own counts; the scan stops at the cap or when every selected one is found. + for key, elements, total in (("vertices", mesh.verts, obj.data.total_vert_sel), + ("edges", mesh.edges, obj.data.total_edge_sel), + ("faces", mesh.faces, obj.data.total_face_sel)): + chosen: list[int] = [] + want = min(total, EDIT_SELECTION_CAP) + if want: + for index, element in enumerate(elements): + if element.select: + chosen.append(index) + if len(chosen) == want: + break + entry[key] = chosen + entry[key + "Total"] = total entries.append(entry) return entries @@ -1118,26 +1138,81 @@ class BrokkrBlenderTarget: path.parent.mkdir(parents=True, exist_ok=True) if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: raise sa.ActionRefused("Output path changed while it was being checked.") - with self.bpy.context.temp_override(window=window, area=area, region=region): - result = self.bpy.ops.screen.screenshot_area("EXEC_DEFAULT", False, filepath=str(path)) - if "FINISHED" not in result or not path.is_file(): - raise sa.ActionRefused("Blender did not write the capture.") + source = "region" if self._windows_drawn() else "offscreen" + if source == "region": + with self.bpy.context.temp_override(window=window, area=area, region=region): + result = self.bpy.ops.screen.screenshot_area("EXEC_DEFAULT", False, filepath=str(path)) + if "FINISHED" not in result or not path.is_file(): + raise sa.ActionRefused("Blender did not write the capture.") + else: # a minimised window stops redrawing, so its framebuffer is a stale frame: draw the view itself + try: + width, height, rgba = self._render_view_offscreen(window, area, region) + path.write_bytes(_png_bytes(width, height, rgba)) + except Exception: + path.unlink(missing_ok=True) + raise sa.ActionRefused("Blender is not drawing its window and the view could not be rendered offscreen.") from None self._prune_looks(path.parent) requested_by = command["requestedBy"] since = self._looked.get(requested_by, 0) self._looked[requested_by] = self.human_edit_seq + coarse = self._coarse["seq"] > since receipt = self._receipt(command, "accepted", f"Captured the 3D view to {LOOK_DIR}/{path.name}.", "") receipt.update({ "lookPath": str(path), + "captureSource": source, + "sceneUpdateSeq": self.scene_update_seq, "sessionId": self.session_id, "humanEditSeq": self.human_edit_seq, "humanEditsSinceLook": self.human_edit_seq - since, "editedSinceLook": sorted(n for n, seq in self._last_human_edit.items() if seq > since), + "editedSinceLookCoarse": coarse, + "editedSinceLookNote": (f"Coarse: {self._coarse['why']}; editedSinceLook may name objects she did not touch." + if coarse else ""), "editSelection": self.edit_selection(), }) self._wrote = False return receipt + def _windows_drawn(self) -> bool: + """False when every Blender window of this process is minimised, so none is redrawing. Only Windows can + say; elsewhere a window is taken as drawn.""" + if sys.platform != "win32": + return True + from ctypes import wintypes + user32 = ctypes.windll.user32 + iconic: list[bool] = [] + + @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) + def visit(hwnd, _lparam): + owner = wintypes.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + name = ctypes.create_unicode_buffer(64) + user32.GetClassNameW(hwnd, name, 64) + if owner.value == os.getpid() and name.value == "GHOST_WindowClass" and user32.IsWindowVisible(hwnd): + iconic.append(bool(user32.IsIconic(hwnd))) + return True + + user32.EnumWindows(visit, 0) + return not iconic or not all(iconic) + + def _render_view_offscreen(self, window: Any, area: Any, region: Any) -> tuple[int, int, bytes]: + """The 3D view's own viewpoint drawn into an offscreen buffer of the region's size: RGBA bytes, bottom row + first. Overlays and popups are not drawn.""" + import gpu # only inside Blender + space = area.spaces.active + rv3d = space.region_3d + width, height = region.width, region.height + context = self.bpy.context + offscreen = gpu.types.GPUOffScreen(width, height) + try: + offscreen.draw_view3d(context.scene, context.view_layer, space, region, rv3d.view_matrix, + rv3d.window_matrix, do_color_management=True) + with offscreen.bind(): + buffer = gpu.state.active_framebuffer_get().read_color(0, 0, width, height, 4, 0, "UBYTE") + return width, height, bytes(buffer) + finally: + offscreen.free() + @staticmethod def _prune_looks(directory: Path) -> None: """Keep the newest LOOK_KEPT captures: plain .png files directly in the look directory, nothing else.""" @@ -1461,6 +1536,18 @@ def _parse_time(value: Any) -> datetime | None: return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc) +def _png_bytes(width: int, height: int, rgba: bytes) -> bytes: + """An 8-bit RGBA PNG of bottom-row-first pixels, written top row first.""" + stride = width * 4 + rows = b"".join(b"\x00" + rgba[y * stride:(y + 1) * stride] for y in range(height - 1, -1, -1)) + + def chunk(kind: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(rows, 1)) + chunk(b"IEND", b"")) + + def _now() -> str: return datetime.now(timezone.utc).isoformat() diff --git a/surfaces/blender/tests/test_perception.py b/surfaces/blender/tests/test_perception.py index ee793e8..48ba6fb 100644 --- a/surfaces/blender/tests/test_perception.py +++ b/surfaces/blender/tests/test_perception.py @@ -33,21 +33,40 @@ def window(*areas): class Element: - def __init__(self, selected): - self.select = selected + def __init__(self, selected, fake): + self._select, self._fake = selected, fake + + @property + def select(self): + self._fake.touched += 1 # every look at an element's flag costs a Python call in the real thing + return self._select + + +class Elements: + """A lazy sequence: a million of them without a million objects.""" + def __init__(self, fake, flags): + self.fake, self.flags = fake, flags + + def __iter__(self): + for flag in self.flags: + yield Element(flag, self.fake) class FakeBmesh: - """bmesh.from_edit_mesh(mesh) -> a mesh with verts, edges and faces that carry .select.""" + """bmesh.from_edit_mesh(mesh) -> verts, edges, faces that carry .select. The mesh carries + total_vert_sel and friends, as Mesh does in Edit Mode; a test may set them apart from the flags.""" def __init__(self, meshes): self.meshes = meshes self.reads = 0 + self.touched = 0 + self.totals = None # override: (verts, edges, faces) the mesh claims def from_edit_mesh(self, mesh): self.reads += 1 verts, edges, faces = self.meshes[id(mesh)] - return NS(verts=[Element(s) for s in verts], edges=[Element(s) for s in edges], - faces=[Element(s) for s in faces]) + counts = self.totals or tuple(sum(1 for f in kind if f) for kind in (verts, edges, faces)) + mesh.total_vert_sel, mesh.total_edge_sel, mesh.total_face_sel = counts + return NS(verts=Elements(self, verts), edges=Elements(self, edges), faces=Elements(self, faces)) class PerceptionFixture(unittest.TestCase): @@ -221,6 +240,215 @@ def rich(obj): return obj +class _All: + """Endless selected flags: a scan that does not stop at the cap would never return.""" + def __iter__(self): + return iter([True] * 5_000_000) + + +class _First: + """A huge mesh whose first n elements are selected: reading past them would show in the touches.""" + def __init__(self, n): + self.n = n + + def __iter__(self): + for i in range(10_000_000): + yield i < self.n + + +class LookFreshnessTests(PerceptionFixture): + """A minimised Blender stops redrawing, so a region capture is a stale frame. Then the view is drawn offscreen.""" + + def setUp(self): + super().setUp() + self.drawn = True + self.target._windows_drawn = lambda: self.drawn + self.offscreen_calls = [] + self.pixels = bytes([10, 20, 30, 255, 40, 50, 60, 255, # bottom row first, as GL reads it + 70, 80, 90, 255, 100, 110, 120, 255]) + + def render(window, area, region): + self.offscreen_calls.append((window, area, region)) + return 2, 2, self.pixels + + self.target._render_view_offscreen = render + + def test_a_drawn_window_is_captured_from_the_region_and_says_so(self): + receipt = self.look() + self.assertEqual((receipt["captureSource"], len(self.shots), self.offscreen_calls), ("region", 1, [])) + + def test_a_window_that_is_not_drawn_is_rendered_offscreen_and_says_so(self): + self.drawn = False + receipt = self.look(commandId="look-off") + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(receipt["captureSource"], "offscreen") + self.assertEqual(self.shots, []) # the stale framebuffer is never read + window, area, region = self.offscreen_calls[0] + self.assertIs(window, self.windows[0]) + self.assertIs(area, self.view) + self.assertEqual(region.type, "WINDOW") + self.assertEqual(Path(receipt["lookPath"]), self.look_dir() / "look-off.png") + + def test_the_offscreen_file_is_a_png_of_the_pixels_top_row_first(self): + import struct + import zlib + self.drawn = False + data = Path(self.look()["lookPath"]).read_bytes() + self.assertEqual(data[:8], b"\x89PNG\r\n\x1a\n") + chunks, at = {}, 8 + while at < len(data): + size, kind = struct.unpack(">I4s", data[at:at + 8]) + chunks[kind] = data[at + 8:at + 8 + size] + at += 12 + size + self.assertEqual(struct.unpack(">IIBBBBB", chunks[b"IHDR"]), (2, 2, 8, 6, 0, 0, 0)) + raw = zlib.decompress(chunks[b"IDAT"]) + rows = [raw[i:i + 9] for i in range(0, len(raw), 9)] # a filter byte, then 2 RGBA pixels + self.assertEqual([r[0] for r in rows], [0, 0]) + self.assertEqual(rows[0][1:], self.pixels[8:]) # the top of the picture is the last row GL read + self.assertEqual(rows[1][1:], self.pixels[:8]) + + def test_an_offscreen_failure_is_a_refusal_never_a_stale_picture(self): + self.drawn = False + + def boom(*a): + raise RuntimeError("no gpu") + + self.target._render_view_offscreen = boom + receipt = self.look() + self.assertEqual((receipt["status"], receipt["lookPath"]), ("failed", "")) + self.assertEqual(self.shots, []) + self.assertEqual(list(self.look_dir().glob("*.png")) if self.look_dir().exists() else [], []) + + def test_the_receipt_names_the_scene_update_the_picture_reflects(self): + first = self.look()["sceneUpdateSeq"] + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.look()["sceneUpdateSeq"], first + 1) + + def test_agent_turn_updates_move_the_scene_update_sequence_too(self): + # it counts every update, hers or the agent's: what the capture reflects is the whole scene + before = self.target.scene_update_seq + self.target.agent_turn = True + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.target.agent_turn = False + self.assertEqual((self.target.scene_update_seq, self.target.human_edit_seq), (before + 1, 0)) + + def test_an_update_without_flags_still_counts_as_a_scene_update(self): + before = self.target.scene_update_seq + self.target.track_human_edits(depsgraph(update("Cube"))) + self.assertEqual(self.target.scene_update_seq, before + 1) + + def test_a_new_session_restarts_the_scene_update_sequence(self): + self.target.track_human_edits(depsgraph(update("Cube"))) + self.target.renew_session() + self.assertEqual(self.target.scene_update_seq, 0) + + def test_the_default_window_check_assumes_drawn_off_windows(self): + target = bt.BrokkrBlenderTarget(self.bpy) + with unittest.mock.patch.object(bt.sys, "platform", "linux"): + self.assertTrue(target._windows_drawn()) + + +class LookPathTests(PerceptionFixture): + def test_a_path_that_changes_after_the_directory_is_made_is_refused_and_nothing_is_captured(self): + # the second check is the guard for the gap between the first check and the capture + real = bt.sa.resolve_inside + calls = [] + + def swapped(root, candidate, label, **kw): + path = real(root, candidate, label, **kw) + calls.append(path) + return path if len(calls) == 1 else path.with_name("elsewhere.png") + + with unittest.mock.patch.object(bt.sa, "resolve_inside", swapped): + receipt = self.look() + self.assertEqual((receipt["status"], len(calls)), ("failed", 2)) + self.assertIn("changed", receipt["message"]) + self.assertEqual((self.shots, receipt["lookPath"]), ([], "")) + + def test_the_prune_does_not_follow_a_link_to_a_file(self): + # a link named *.png is not a plain file: it is never counted or removed through + removed = [] + + class Entry: + def __init__(self, name, mtime, link): + self.name, self.path, self._mtime, self._link = name, "dir/" + name, mtime, link + + def is_file(self, follow_symlinks=True): + return follow_symlinks or not self._link # a link is a file only when followed + + def stat(self, follow_symlinks=True): + return NS(st_mtime_ns=self._mtime) + + entries = [Entry(f"f{n:02d}.png", n, False) for n in range(21)] + [Entry("link.png", 0, True)] + + class Scan: + def __enter__(self): + return iter(entries) + + def __exit__(self, *a): + return False + + with unittest.mock.patch.object(bt.os, "scandir", lambda d: Scan()), \ + unittest.mock.patch.object(bt.os, "unlink", removed.append): + bt.BrokkrBlenderTarget._prune_looks(Path("dir")) + self.assertEqual(removed, ["dir/f00.png"]) + + +class CoarseAttributionTests(PerceptionFixture): + NOTE_WORDS = ("all objects flagged",) + + def edits(self, since_look="nibu/hands"): + return self.look(requestedBy=since_look) + + def test_a_precise_edit_is_not_marked_coarse(self): + self.edits() + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + receipt = self.edits() + self.assertEqual((receipt["editedSinceLookCoarse"], receipt["editedSinceLookNote"]), (False, "")) + + def test_an_update_that_flags_every_object_is_marked_coarse_and_says_why(self): + self.edits() + self.target.track_human_edits(depsgraph(*[update(n, transform=True, geometry=True) for n in ("Cube", "Lamp", "Cam")])) + receipt = self.edits() + self.assertTrue(receipt["editedSinceLookCoarse"]) + self.assertIn("all objects flagged", receipt["editedSinceLookNote"]) + self.assertEqual(receipt["editedSinceLook"], ["Cam", "Cube", "Lamp"]) # the semantics are unchanged + + def test_an_undo_or_redo_is_coarse(self): + self.edits() + self.target.note_undo_redo() + receipt = self.edits() + self.assertTrue(receipt["editedSinceLookCoarse"]) + self.assertIn("undo", receipt["editedSinceLookNote"]) + + def test_coarse_clears_with_the_next_look_and_comes_back_only_for_a_new_coarse_edit(self): + self.edits() + self.target.note_undo_redo() + self.assertTrue(self.edits()["editedSinceLookCoarse"]) + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + + def test_each_agent_has_its_own_coarse_since_its_last_look(self): + self.edits("nibu/hands") + self.target.note_undo_redo() + self.edits("nibu/hands") + self.assertTrue(self.edits("nibu/soul")["editedSinceLookCoarse"]) # soul has not looked since + + def test_a_new_session_forgets_coarse(self): + self.target.note_undo_redo() + self.target.renew_session() + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + + def test_one_object_in_a_scene_of_one_is_not_coarse(self): + # nothing to over-attribute when there is only one object to name + for name in ("Cam", "Lamp"): + del self.bpy.data.objects[name] + self.edits() + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + + class EditSelectionTests(PerceptionFixture): def snapshot(self): for obj in self.bpy.data.objects: @@ -259,6 +487,23 @@ class EditSelectionTests(PerceptionFixture): self.assertEqual((entry["edges"], entry["edgesTotal"]), ([5000], 1)) self.assertEqual((len(entry["faces"]), entry["facesTotal"]), (4096, 4096)) + def test_totals_come_from_the_mesh_and_the_scan_stops_at_the_cap(self): + # a million selected of each kind: the totals are the mesh's own counts, and each kind is read only up to the cap + self.bpy.mesh.mode = "EDIT" + self.bmesh.meshes[id(self.bpy.mesh_data)] = (_All(), _All(), _All()) + self.bmesh.totals = (1_000_000, 2_000_000, 3_000_000) + entry = self.target.edit_selection()[0] + self.assertEqual((entry["verticesTotal"], entry["edgesTotal"], entry["facesTotal"]), (1_000_000, 2_000_000, 3_000_000)) + self.assertEqual([len(entry[k]) for k in ("vertices", "edges", "faces")], [4096] * 3) + self.assertEqual(self.bmesh.touched, 3 * 4096) + + def test_a_small_selection_in_a_big_mesh_stops_when_every_selected_element_is_found(self): + self.bpy.mesh.mode = "EDIT" + self.bmesh.meshes[id(self.bpy.mesh_data)] = (_First(3), _First(2), _First(0)) + entry = self.target.edit_selection()[0] + self.assertEqual((entry["vertices"], entry["edges"], entry["faces"]), ([0, 1, 2], [0, 1], [])) + self.assertEqual(self.bmesh.touched, 3 + 2) # no scan past the last selected one, none at all when the total is zero + def test_every_object_in_edit_mode_is_listed_and_a_non_mesh_says_unsupported(self): self.bpy.mesh.mode = "EDIT" self.bpy.cam.mode = "EDIT" From 270b596f050354bcd7a7a7114969bed1582ce0e0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:57:02 +0100 Subject: [PATCH 041/223] Perception fixes: live proof (minimised look, coarse flags, 1M-vertex read) and the contract in the docs Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/docs/install.md | 10 +- .../blender/tests/live/perception_fixes.py | 243 ++++++++++++++ .../tests/live/perception_fixes.result.json | 298 ++++++++++++++++++ 3 files changed, 549 insertions(+), 2 deletions(-) create mode 100644 surfaces/blender/tests/live/perception_fixes.py create mode 100644 surfaces/blender/tests/live/perception_fixes.result.json diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 0eb7d40..d3dec32 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -233,7 +233,11 @@ gets a `failed` receipt whose message names the rule): `lookPath`; refused when the output directory is unset or no 3D view is open. It reads Blender's own framebuffer for that one region, so her desktop and other applications are never in the picture; a menu, popup or the splash Blender draws over the view is, as she sees it. It is a read: no undo step, and it runs in - Edit Mode. The capture blocks her UI for about 70 ms. The look directory keeps the newest 20 PNGs (scratch, + Edit Mode. The capture blocks her UI for about 70 ms. `captureSource` says how it was taken: `region`, or + `offscreen` when every Blender window is minimised (Windows only; a minimised window stops redrawing, so its + framebuffer is a stale frame) and the view's own viewpoint is drawn offscreen at the region's size instead, with + her popups and menus not drawn; an offscreen failure is a refusal, never a stale picture. `sceneUpdateSeq` is the + count of depsgraph updates, hers and the agent's, that the picture reflects. The look directory keeps the newest 20 PNGs (scratch, never read back). The receipt also carries `sessionId`, `humanEditSeq`, `humanEditsSinceLook` and `editedSinceLook` (object names), counted for the sending `requestedBy` since its previous look in this session, and `editSelection`: for each object in Edit Mode its selected vertex, edge and face indices (each @@ -242,7 +246,9 @@ gets a `failed` receipt whose message names the rule): object's `lastHumanEditSeq`. The sequences come from depsgraph updates outside an agent turn, counted per flagged object (transform, geometry or shading) and from undo and redo; opening a file starts a new session. An update also flags objects that only depend on what she changed (a constrained follower), and adding or - linking an object flags all of them, so `editedSinceLook` can name more than she touched. They are + linking an object flags all of them, so `editedSinceLook` can name more than she touched; the receipt then + says so: `editedSinceLookCoarse` is true, with the reason in `editedSinceLookNote` (an update that flagged every + object, or an undo or redo). Selection totals are the mesh's own counts and the index scan stops at the cap. They are observations: no intent is refused because of them. The scene actions were run against Blender 5.2.3 LTS headless with diff --git a/surfaces/blender/tests/live/perception_fixes.py b/surfaces/blender/tests/live/perception_fixes.py new file mode 100644 index 0000000..7facba2 --- /dev/null +++ b/surfaces/blender/tests/live/perception_fixes.py @@ -0,0 +1,243 @@ +"""Live proof of the live-5 fix batch, in GUI Blender with the add-on installed as an extension, real brokkr-ctl looks. + +Same environment as perception.py (BROKKR_SCRATCH, BROKKR_CTL, BROKKR_CULTLIB; a fresh BLENDER_USER_RESOURCE_PATH). + blender --python perception_fixes.py -- +The driver stands in for the operator: it saves the blend, ticks the sink, sets the output directory, minimises and +restores the Blender window (Windows ShowWindow on this process's own window), moves objects, enters Edit Mode. +""" +import ctypes +import importlib +import json +import os +import statistics +import subprocess +import sys +import time +import traceback +from ctypes import wintypes +from pathlib import Path + +import bmesh +import bpy +import numpy + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +CTL = os.environ["BROKKR_CTL"] +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +R = {"blender": bpy.app.version_string, "checks": [], "notes": {}} +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +prefs = bpy.context.preferences.addons[MODULE].preferences +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +adapter = addon.target() +STORE = SCRATCH / ".brokkr" / "blender-editor.ccmp" +ENV = dict(os.environ, EUREKA_INSTANCE="nibu", BROKKR_BLENDER_STORE=str(STORE), BROKKR_AGENT="hands") +user32 = ctypes.windll.user32 + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def fields(text): + out = {} + for line in text.splitlines(): + key, _, value = line.partition(": ") + try: + out[key] = json.loads(value) if value[:1] in "[{0123456789tf" else value + except ValueError: + out[key] = value + return out + + +def ctl(*args): + proc = subprocess.Popen([CTL, "blender", *args], env=ENV, stdout=subprocess.PIPE, text=True) + while proc.poll() is None: + yield + return proc.returncode, fields(proc.stdout.read()) + + +def blender_windows(): + found = [] + + @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) + def visit(hwnd, _): + owner = wintypes.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + name = ctypes.create_unicode_buffer(64) + user32.GetClassNameW(hwnd, name, 64) + if owner.value == os.getpid() and name.value == "GHOST_WindowClass" and user32.IsWindowVisible(hwnd): + found.append(hwnd) + return True + + user32.EnumWindows(visit, 0) + return found + + +def show(cmd): # 6 minimise, 9 restore + for hwnd in blender_windows(): + user32.ShowWindow(hwnd, cmd) + + +def pixels(path): + image = bpy.data.images.load(str(path)) + try: + return numpy.array(image.pixels[:], dtype=numpy.float32).reshape(image.size[1], image.size[0], 4) + finally: + bpy.data.images.remove(image) + + +def diff_box(a, b): + mask = numpy.abs(a - b).max(axis=2) > 0.02 + if not mask.any(): + return None + ys, xs = numpy.where(mask) + return [int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())] + + +def old_scan(obj): + """The scan this fix replaces: every vertex, edge and face walked in Python.""" + mesh = bmesh.from_edit_mesh(obj.data) + out = [] + for elements in (mesh.verts, mesh.edges, mesh.faces): + chosen = [i for i, e in enumerate(elements) if e.select] + out.append((chosen[:4096], len(chosen))) + return out + + +def flow(): + bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "fixes.blend")) + prefs.output_dir = str(SCRATCH / "out") + prefs.auto_drain_commands = True + yield 1.0 + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.brokkr.capture_snapshot() + cube = bpy.data.objects["Cube"] + # ---- minimised window: look must show the current scene ---- + code, a0 = yield from ctl("look") + check("window up: the region capture, source named", code == 0 and a0["captureSource"] == "region", a0) + show(6) + yield 1.0 + iconic = [bool(user32.IsIconic(h)) for h in blender_windows()] + R["notes"]["iconic_after_minimise"] = iconic + check("the Blender window is minimised (IsIconic)", iconic and all(iconic), iconic) + code, a = yield from ctl("look") + cube.location.x = 3.0 # her edit, while minimised + yield 0.5 + code, b = yield from ctl("look") + pa = pixels(a["lookPath"]) if a.get("lookPath") else None + pb = pixels(b["lookPath"]) if b.get("lookPath") else None + box = diff_box(pa, pb) if pa is not None and pb is not None else None + R["notes"]["minimised"] = {"a": a, "b": b, "diff_box": box} + check("minimised: both looks are accepted and say they were rendered offscreen", + code == 0 and a.get("captureSource") == "offscreen" and b.get("captureSource") == "offscreen", [a.get("captureSource"), b.get("captureSource")]) + check("minimised: the Cube moved by her shows in the next look (the pictures differ, in a box)", box is not None, box) + check("minimised: sceneUpdateSeq advanced between the two looks", b["sceneUpdateSeq"] > a["sceneUpdateSeq"], [a["sceneUpdateSeq"], b["sceneUpdateSeq"]]) + check("minimised: size equals the 3D region", [pb.shape[1], pb.shape[0]] == [1574, 888] if pb is not None else False, + None if pb is None else [pb.shape[1], pb.shape[0]]) + # the agent's own move while minimised, then look + code, m = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[-3,0,0]") + code, c = yield from ctl("look") + pc = pixels(c["lookPath"]) + check("minimised: the agent's own move is in its next look", diff_box(pb, pc) is not None and c["sceneUpdateSeq"] > b["sceneUpdateSeq"], diff_box(pb, pc)) + show(9) + yield 1.5 + code, d = yield from ctl("look") + check("restored: back to the region capture", code == 0 and d.get("captureSource") == "region", d.get("captureSource")) + + # ---- coarse attribution ---- + code, e0 = yield from ctl("look") + follower = bpy.data.objects.new("Follower", bpy.data.meshes.new("FM")) + bpy.context.scene.collection.objects.link(follower) + yield 0.5 + code, e1 = yield from ctl("look") + check("after her link of an object: the receipt says the attribution is coarse", + e1.get("editedSinceLookCoarse") is True and "all objects flagged" in e1.get("editedSinceLookNote", ""), e1) + code, e2 = yield from ctl("look") + cube.location.y = 1.0 + yield 0.5 + code, e3 = yield from ctl("look") + check("after a plain move: not coarse, only the Cube named", e3.get("editedSinceLookCoarse") is False and e3.get("editedSinceLook") == ["Cube"], e3) + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.ed.undo() + yield 0.5 + code, e4 = yield from ctl("look") + check("after her undo: coarse", e4.get("editedSinceLookCoarse") is True, e4) + + # ---- one million vertices in Edit Mode ---- + mesh = bpy.data.meshes.new("Big") + bm = bmesh.new() + bmesh.ops.create_grid(bm, x_segments=1000, y_segments=1000, size=1.0) + bm.to_mesh(mesh) + bm.free() + big = bpy.data.objects.new("Big", mesh) + bpy.context.scene.collection.objects.link(big) + bpy.context.view_layer.objects.active = big + for o in bpy.context.view_layer.objects: + o.select_set(o is big) + yield 0.5 + window = bpy.context.window_manager.windows[0] + area = next(a for a in window.screen.areas if a.type == "VIEW_3D") + region = next(r for r in area.regions if r.type == "WINDOW") + with bpy.context.temp_override(window=window, area=area, region=region, active_object=big, object=big): + bpy.ops.object.mode_set(mode="EDIT") + bpy.ops.mesh.select_all(action="SELECT") + yield 0.5 + R["notes"]["verts"] = len(mesh.vertices) + new_ms, old_ms = [], [] + for _ in range(5): # paired, interleaved + t = time.perf_counter() + new = adapter.edit_selection() + new_ms.append((time.perf_counter() - t) * 1000) + t = time.perf_counter() + old = old_scan(big) + old_ms.append((time.perf_counter() - t) * 1000) + entry = new[0] + parts = {} + t = time.perf_counter(); bm2 = bmesh.from_edit_mesh(big.data); parts["from_edit_mesh"] = (time.perf_counter() - t) * 1000 + t = time.perf_counter(); totals = (big.data.total_vert_sel, big.data.total_edge_sel, big.data.total_face_sel); parts["totals"] = (time.perf_counter() - t) * 1000 + for name, seq in (("verts", bm2.verts), ("edges", bm2.edges), ("faces", bm2.faces)): + t = time.perf_counter(); n = 0 + for i, e in enumerate(seq): + if e.select: + n += 1 + if n == 4096: + break + parts[name] = (time.perf_counter() - t) * 1000 + R["notes"]["edit_selection_parts_ms"] = {k: round(v, 1) for k, v in parts.items()} + R["notes"]["edit_selection_ms"] = {"new": [round(x) for x in new_ms], "old": [round(x) for x in old_ms], + "new_median": round(statistics.median(new_ms)), "old_median": round(statistics.median(old_ms))} + check("1M vertices: the totals are the mesh's own and the lists are capped at 4096", + entry["verticesTotal"] == 1_002_001 and len(entry["vertices"]) == 4096 and entry["vertices"] == old[0][0] + and entry["edgesTotal"] == old[1][1] and entry["facesTotal"] == old[2][1], [entry["verticesTotal"], entry["edgesTotal"], entry["facesTotal"]]) + check("1M vertices: the read is several times faster than the full scan (medians in notes)", + statistics.median(old_ms) > 3 * statistics.median(new_ms), R["notes"]["edit_selection_ms"]) + with bpy.context.temp_override(window=window, area=area, region=region, active_object=big, object=big): + bpy.ops.object.mode_set(mode="OBJECT") + check("no add-on drain error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + + +gen = flow() + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def runner(): + try: + delay = next(gen) + return delay if isinstance(delay, (int, float)) and delay else 0.05 + except StopIteration: + write() + bpy.ops.wm.quit_blender() + except Exception: + R.setdefault("errors", []).append(traceback.format_exc()) + write() + bpy.ops.wm.quit_blender() + + +bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/perception_fixes.result.json b/surfaces/blender/tests/live/perception_fixes.result.json new file mode 100644 index 0000000..af2638c --- /dev/null +++ b/surfaces/blender/tests/live/perception_fixes.result.json @@ -0,0 +1,298 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "window up: the region capture, source named", + "ok": true, + "detail": { + "commandId": "01a21f023e60712180b8b5afee5b2621", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f023e60712180b8b5afee5b2621.png", + "message": "Captured the 3D view to look/01a21f023e60712180b8b5afee5b2621.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:11.107854+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 0, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "the Blender window is minimised (IsIconic)", + "ok": true, + "detail": [ + true + ] + }, + { + "name": "minimised: both looks are accepted and say they were rendered offscreen", + "ok": true, + "detail": [ + "offscreen", + "offscreen" + ] + }, + { + "name": "minimised: the Cube moved by her shows in the next look (the pictures differ, in a box)", + "ok": true, + "detail": [ + 711, + 248, + 975, + 529 + ] + }, + { + "name": "minimised: sceneUpdateSeq advanced between the two looks", + "ok": true, + "detail": [ + 0, + 1 + ] + }, + { + "name": "minimised: size equals the 3D region", + "ok": true, + "detail": [ + 1574, + 888 + ] + }, + { + "name": "minimised: the agent's own move is in its next look", + "ok": true, + "detail": [ + 656, + 248, + 975, + 581 + ] + }, + { + "name": "restored: back to the region capture", + "ok": true, + "detail": "region" + }, + { + "name": "after her link of an object: the receipt says the attribution is coarse", + "ok": true, + "detail": { + "commandId": "01a21f02711f7571991decbd06059938", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [ + "Camera", + "Cube", + "Follower", + "Light" + ], + "editedSinceLookCoarse": true, + "editedSinceLookNote": "Coarse: all objects flagged; editedSinceLook may name objects she did not touch.", + "humanEditSeq": 4, + "humanEditsSinceLook": 1, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f02711f7571991decbd06059938.png", + "message": "Captured the 3D view to look/01a21f02711f7571991decbd06059938.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:23.908406+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 5, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after a plain move: not coarse, only the Cube named", + "ok": true, + "detail": { + "commandId": "01a21f027a1873a1a21df913136a4d49", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [ + "Cube" + ], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 5, + "humanEditsSinceLook": 1, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f027a1873a1a21df913136a4d49.png", + "message": "Captured the 3D view to look/01a21f027a1873a1a21df913136a4d49.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:26.306053+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 6, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after her undo: coarse", + "ok": true, + "detail": { + "commandId": "01a21f027ec27dd0bda5c62b0974531a", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [ + "Camera", + "Cube", + "Light" + ], + "editedSinceLookCoarse": true, + "editedSinceLookNote": "Coarse: all objects flagged; editedSinceLook may name objects she did not touch.", + "humanEditSeq": 7, + "humanEditsSinceLook": 2, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f027ec27dd0bda5c62b0974531a.png", + "message": "Captured the 3D view to look/01a21f027ec27dd0bda5c62b0974531a.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:27.505456+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 7, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "1M vertices: the totals are the mesh's own and the lists are capped at 4096", + "ok": true, + "detail": [ + 1002001, + 2002000, + 1000000 + ] + }, + { + "name": "1M vertices: the read is several times faster than the full scan (medians in notes)", + "ok": true, + "detail": { + "new": [ + 221, + 191, + 185, + 197, + 193 + ], + "old": [ + 977, + 950, + 974, + 1059, + 956 + ], + "new_median": 193, + "old_median": 974 + } + }, + { + "name": "no add-on drain error", + "ok": true, + "detail": "" + } + ], + "notes": { + "iconic_after_minimise": [ + true + ], + "minimised": { + "a": { + "commandId": "01a21f02458877a186fe6a31fe3b32d6", + "action": "look", + "captureSource": "offscreen", + "editSelection": [], + "editedSinceLook": [], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f02458877a186fe6a31fe3b32d6.png", + "message": "Captured the 3D view to look/01a21f02458877a186fe6a31fe3b32d6.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:13.275722+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 0, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + }, + "b": { + "commandId": "01a21f024b1876d0a4ec6281a49404a2", + "action": "look", + "captureSource": "offscreen", + "editSelection": [], + "editedSinceLook": [ + "Cube" + ], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 1, + "humanEditsSinceLook": 1, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f024b1876d0a4ec6281a49404a2.png", + "message": "Captured the 3D view to look/01a21f024b1876d0a4ec6281a49404a2.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:56:14.485857+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 1, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "status": "accepted", + "undoLabel": "" + }, + "diff_box": [ + 711, + 248, + 975, + 529 + ] + }, + "verts": 1002001, + "edit_selection_parts_ms": { + "from_edit_mesh": 0.0, + "totals": 0.0, + "verts": 24.7, + "edges": 79.6, + "faces": 33.2 + }, + "edit_selection_ms": { + "new": [ + 221, + 191, + 185, + 197, + 193 + ], + "old": [ + 977, + 950, + 974, + 1059, + 956 + ], + "new_median": 193, + "old_median": 974 + } + }, + "ok": true +} \ No newline at end of file From 282d9eff7a2901d1672c4bcb61106f22d8b791b4 Mon Sep 17 00:00:00 2001 From: Eureka Date: Sat, 28 Nov 2026 01:13:22 +0000 Subject: [PATCH 042/223] Blender add-on: glTF export checked against real Blender, atomic export, a render refusal that holds (#17) --- brokkr-daemon/src/main.rs | 36 +++ docs/provider-contract.md | 1 + surfaces/blender/brokkr_bridge/__init__.py | 2 +- .../blender/brokkr_bridge/blender_target.py | 264 +++++++++++++--- surfaces/blender/brokkr_bridge/gl_probe.py | 15 + surfaces/blender/docs/install.md | 27 +- surfaces/blender/tests/live/export_gltf.py | 102 ++++++ .../tests/live/export_gltf.result.json | 114 +++++++ surfaces/blender/tests/live/refusals.py | 74 +++++ .../blender/tests/live/refusals.result.json | 57 ++++ surfaces/blender/tests/test_scene_actions.py | 293 ++++++++++++++++-- 11 files changed, 904 insertions(+), 81 deletions(-) create mode 100644 surfaces/blender/brokkr_bridge/gl_probe.py create mode 100644 surfaces/blender/tests/live/export_gltf.py create mode 100644 surfaces/blender/tests/live/export_gltf.result.json create mode 100644 surfaces/blender/tests/live/refusals.py create mode 100644 surfaces/blender/tests/live/refusals.result.json diff --git a/brokkr-daemon/src/main.rs b/brokkr-daemon/src/main.rs index f83e29b..643cae9 100644 --- a/brokkr-daemon/src/main.rs +++ b/brokkr-daemon/src/main.rs @@ -3379,6 +3379,42 @@ mod tests { Ok(()) } + #[test] + fn sync_once_writes_an_inactive_unity_object_as_hidden_in_blender() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_component_property_stores(&unity_path, &blender_path, "active-state")?; + MirrorStore::open(&unity_path)?.put_messagepack_document( + "brokkr.unity.host_snapshot.v0", + "unity/host/current", + &json!({ + "sceneObjects": [{ + "objectId": "unity-cube", + "name": "Cube", + "path": "/Cube", + "activeSelf": false + }] + }), + )?; + + let report = run_sync_once(&SyncArgs { + unity_cache: unity_path, + blender_cache: blender_path.clone(), + dry_run: false, + })?; + + assert_eq!(report.blender_commands_written, 1, "{report:#?}"); + let command = MirrorStore::open(&blender_path)? + .documents()? + .into_iter() + .find(|document| document.key.starts_with("blender/commands/")) + .expect("Brokkr should emit a Blender visibility command"); + assert_eq!(command.value["action"], "setObjectVisibility"); + assert_eq!(command.value["visible"], false); + Ok(()) + } + #[test] fn dry_run_counts_active_state_command_but_writes_none() -> Result<()> { let temp = tempfile::tempdir()?; diff --git a/docs/provider-contract.md b/docs/provider-contract.md index cda8707..6ccbb10 100644 --- a/docs/provider-contract.md +++ b/docs/provider-contract.md @@ -216,6 +216,7 @@ All Blender writes use `brokkr.blender.command_intent.v0` and receive - `selectObject` - `assignMaterial` - `importGltf` +- `exportGltf` (writes under the add-on preference Render Output Directory, never overwriting) - `setCamera` - `setLight` - `setWorld` diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index 58fd75b..c9db1ec 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -88,7 +88,7 @@ class BrokkrPreferences(bpy.types.AddonPreferences): name="Render Output Directory", subtype="DIR_PATH", default="", - description="renderStill may only write files inside this directory; empty disables renderStill", + description="renderStill and exportGltf may only write files inside this directory; empty disables both", ) auto_capture: bpy.props.BoolProperty( diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 93a9fb5..0bc72b3 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -6,8 +6,12 @@ import json import math import os import re +import shutil +import signal import struct +import subprocess import sys +import tempfile import uuid import zlib from array import array @@ -16,6 +20,11 @@ from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any, Iterable +if os.name == "nt": + import msvcrt +else: + import fcntl + from . import node_actions as na from . import scene_actions as sa from .server_guard import BindRefused, SessionGuard, check_bind, guarded_server_class, is_loopback_host, stop_pending @@ -42,10 +51,14 @@ SYNC_RECEIPT_SCHEMA = "brokkr.sync.receipt.v0" CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY") -# Engines that draw through the GL stack. A headless Linux Blender without libEGL aborts the whole -# process inside bpy.ops.render.render for these (no receipt); CYCLES renders on the CPU. +# Engines that draw through the GL stack. A headless Blender with no usable GL device aborts the whole +# process inside bpy.ops.render.render for these (no receipt); CYCLES renders on the CPU. Whether it +# will is found by rendering one pixel in a child Blender (gl_render_failure), not by guessing at libraries. GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT") -GL_RUNTIME_LIBRARY = "libEGL.so.1" +GL_PROBE_TIMEOUT_SECONDS = 120 +EXPORT_STAGE_PREFIX = ".brokkr-export-" +STAGE_LOCK = ".brokkr-lock" +STAGE_JOURNAL = ".brokkr-journal" # Actions that only read the scene and so push no undo step. READ_ACTIONS = ("look",) @@ -732,8 +745,9 @@ class BrokkrBlenderTarget: raise sa.ActionRefused( f"objectType {shown!r} cannot be created; allowed: {', '.join(CREATABLE_OBJECT_TYPES)}.") mesh_type = command.get("meshType") - if object_type == "MESH" and mesh_type is not None and ( - not isinstance(mesh_type, str) or mesh_type.upper() != "CUBE"): + if mesh_type is not None and object_type != "MESH": + raise sa.ActionRefused(f"meshType applies only to objectType MESH, not {object_type}.") + if mesh_type is not None and (not isinstance(mesh_type, str) or mesh_type.upper() != "CUBE"): raise sa.ActionRefused(f"meshType {mesh_type!r} is not available; a MESH is a CUBE.") name = command.get("name") or f"Brokkr {object_type.title()}" location = _vector(command.get("location"), 3, (0.0, 0.0, 0.0)) @@ -868,6 +882,8 @@ class BrokkrBlenderTarget: name = command.get("filepath") if not isinstance(name, str): raise sa.ActionRefused("filepath must be a string.") + if self.output_dir: + _sweep_stale_stages(Path(self.output_dir).resolve()) path = sa.resolve_inside(self.output_dir, name, "output", new_file=True) suffix = path.suffix.lower() if suffix not in sa.GLTF_EXTENSIONS: @@ -892,30 +908,90 @@ class BrokkrBlenderTarget: off_layer = [o.name for o in chosen if o.name not in context.view_layer.objects] if off_layer: raise sa.ActionRefused(f"Selection object is not in the active view layer: {off_layer[0]}") - binary = path.with_suffix(".bin") - if suffix == ".gltf" and os.path.lexists(binary): - raise sa.ActionRefused("output path already exists; output actions never overwrite: " + binary.name) - path.parent.mkdir(parents=True, exist_ok=True) - # Re-check after the folders exist and just before use (residual TOCTOU as in renderStill). - if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: - raise sa.ActionRefused("Output path changed while it was being checked.") - # The selection is touched only when one was asked for, and only on view-layer objects. - objects = list(context.view_layer.objects.values()) if chosen else [] - saved = [(obj, obj.select_get()) for obj in objects] + # The exporter writes into a fresh staging folder beside the target, never onto the output + # directory: it may also write a .bin and texture files whose names Brokkr does not choose. Only + # after it finishes does every file move into place, each refused if its name is taken, so no + # existing file is overwritten and a failed export leaves nothing behind (not even new folders). + made = [] + for folder in (path.parent, *path.parent.parents): + if folder.exists() or folder == Path(self.output_dir).resolve(): + break + made.append(folder) + stage = None + lock_fd = None + moved: list[tuple[Path, Path]] = [] + new_dirs: list[Path] = [] try: - for obj in objects: - obj.select_set(obj in chosen) - result = self.bpy.ops.export_scene.gltf("EXEC_DEFAULT", False, - filepath=str(path), export_format="GLB" if suffix == ".glb" else "GLTF_SEPARATE", - use_selection=bool(chosen), **options) - finally: - for obj, state in saved: - if obj.name in self.bpy.data.objects: - obj.select_set(state) - if "FINISHED" not in result: - raise sa.ActionRefused(f"glTF export did not finish: {sorted(result)}") - if not path.is_file(): - raise sa.ActionRefused("glTF export wrote no file.") + path.parent.mkdir(parents=True, exist_ok=True) + # Re-check after the folders exist and just before use (residual TOCTOU as in renderStill). + if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: + raise sa.ActionRefused("Output path changed while it was being checked.") + stage, lock_fd = _open_stage(path.parent) + staged = stage / path.name + # The selection is touched only when one was asked for, and only on view-layer objects. + objects = list(context.view_layer.objects.values()) if chosen else [] + saved = [(obj, obj.select_get()) for obj in objects] + try: + for obj in objects: + obj.select_set(obj in chosen) + result = self.bpy.ops.export_scene.gltf("EXEC_DEFAULT", False, + filepath=str(staged), export_format="GLB" if suffix == ".glb" else "GLTF_SEPARATE", + use_selection=bool(chosen), **options) + finally: + for obj, state in saved: + if obj.name in self.bpy.data.objects: + obj.select_set(state) + if "FINISHED" not in result: + raise sa.ActionRefused(f"glTF export did not finish: {sorted(result)}") + if not staged.is_file(): + raise sa.ActionRefused("glTF export wrote no file.") + written = sorted(f.relative_to(stage) for f in stage.rglob("*") if f.is_file() and f != stage / STAGE_LOCK) + taken = [str(f) for f in written if os.path.lexists(path.parent / f)] + if taken: + raise sa.ActionRefused("output path already exists; output actions never overwrite: " + taken[0]) + for relative in written: + target = path.parent / relative + for folder in (target.parent, *target.parent.parents): + if folder.exists() or folder == path.parent: + break + new_dirs.append(folder) + target.parent.mkdir(parents=True, exist_ok=True) + os.rename(stage / relative, target) + moved.append((stage / relative, target)) + except BaseException as failure: + # A move that fails partway is rolled back: the target is the whole new export or untouched. + stuck = [] + for source, target in reversed(moved): + try: + os.rename(target, source) + except OSError: + stuck.append(target) + if lock_fd is not None: + os.close(lock_fd) + if stage is not None and stuck: + # The rollback itself failed: keep the stage with a journal of the files left in the + # target. Its lock is released, so the next export's sweep removes them and the retry works. + (stage / STAGE_JOURNAL).write_text( + "\n".join(t.relative_to(path.parent).as_posix() for t in stuck), encoding="utf-8") + raise sa.ActionRefused( + "glTF export failed and could not be rolled back; files left in the output directory: " + + ", ".join(t.relative_to(Path(self.output_dir).resolve()).as_posix() for t in stuck) + + ". The next export removes them.") from failure + if stage is not None: + shutil.rmtree(stage, ignore_errors=True) + for folder in sorted(set(new_dirs), key=lambda f: -len(f.parts)): + try: + folder.rmdir() + except OSError: + pass + for folder in made: # deepest first: only the folders this call made, only if still empty + try: + folder.rmdir() + except OSError: + pass + raise + os.close(lock_fd) + shutil.rmtree(stage, ignore_errors=True) return self._receipt(command, "accepted", f"Exported glTF to {path} ({path.stat().st_size} bytes).", "") def _resolve_typed(self, command: dict[str, Any], object_type: str) -> Any: @@ -1024,11 +1100,11 @@ class BrokkrBlenderTarget: except TypeError: raise sa.ActionRefused(f"engine {engine} is not available in this Blender.") from None if render.engine in GL_RENDER_ENGINES and getattr(getattr(self.bpy, "app", None), "background", False): - missing = missing_gl_library() - if missing: + failure = gl_render_failure(getattr(self.bpy.app, "binary_path", ""), render.engine) + if failure: raise sa.ActionRefused( - f"engine {render.engine} needs {missing}, which this headless Blender cannot load " - "(rendering would abort the process); use engine CYCLES.") + f"engine {render.engine} cannot render in this headless Blender ({failure}); " + "rendering would abort the process; use engine CYCLES.") if width is not None: render.resolution_x = width if height is not None: @@ -1515,17 +1591,123 @@ def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: return cultmesh_py, cultcache_py -@functools.lru_cache(maxsize=None) -def missing_gl_library() -> str | None: - """The GL runtime library this host cannot load, or None. Probed once, on Linux only: on - Windows and macOS a failed GPU render is not a headless-EGL abort.""" - if not sys.platform.startswith("linux"): - return None +GL_PROBE_SCRIPT = Path(__file__).with_name("gl_probe.py") # runs inside the child Blender + + +def _try_lock(fd: int) -> bool: + """Take an exclusive lock on the file, without waiting; the OS drops it when the holder dies.""" try: - ctypes.CDLL(GL_RUNTIME_LIBRARY) + if os.name == "nt": + os.lseek(fd, 0, os.SEEK_SET) + msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) + else: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: - return GL_RUNTIME_LIBRARY - return None + return False + return True + + +def _open_stage(parent: Path) -> tuple[Path, int]: + """A fresh staging folder in parent whose lock file this export holds, locked, until it closes the + descriptor or dies: a held lock is how a sweep knows the stage is live.""" + stage = Path(tempfile.mkdtemp(prefix=EXPORT_STAGE_PREFIX, dir=parent)) + fd = os.open(stage / STAGE_LOCK, os.O_RDWR | os.O_CREAT) + if not _try_lock(fd): + os.close(fd) + raise OSError(f"could not lock staging folder {stage}") + return stage, fd + + +def _sweep_stale_stages(top: Path) -> None: + """Remove every staging folder under top whose lock can be taken: its export is over or its Blender + died. A held lock (an export running now, in any process) leaves the folder alone, and so does a + folder with no lock file yet (an export between creating it and locking it).""" + for root, dirs, _ in os.walk(top): + for name in [d for d in dirs if d.startswith(EXPORT_STAGE_PREFIX)]: + dirs.remove(name) + _sweep_stage(Path(root) / name) + + +def _sweep_stage(stage: Path) -> None: + try: + fd = os.open(stage / STAGE_LOCK, os.O_RDWR) + except OSError: + return + try: + if not _try_lock(fd): + return + journal = stage / STAGE_JOURNAL + if journal.is_file(): # a failed rollback's leftovers in the target + for line in journal.read_text(encoding="utf-8").splitlines(): + relative = Path(line) + if not line or relative.is_absolute() or ".." in relative.parts: + continue + target = stage.parent / relative + if target.is_file() and not target.is_symlink(): + target.unlink(missing_ok=True) + for folder in target.parents: + if folder == stage.parent: + break + try: + folder.rmdir() + except OSError: + break + finally: + os.close(fd) + shutil.rmtree(stage, ignore_errors=True) + + +def _kill_tree(process: "subprocess.Popen[str]") -> None: + """Kill process and everything it started, so none keeps its output pipe open.""" + if os.name == "nt": + subprocess.run(["taskkill", "/F", "/T", "/PID", str(process.pid)], capture_output=True, check=False) + else: + try: + os.killpg(process.pid, signal.SIGKILL) + except OSError: + pass + process.kill() + + +_GL_PROBES: dict[tuple[str, str], str | None] = {} + + +def gl_render_failure(binary: str, engine: str) -> str | None: + """Why a headless render with this engine would not survive on this host, or None when it does. + + Renders one pixel in a child process of the same Blender binary: the render aborts the process + it runs in, so only a child can find out. A definite outcome (it rendered, or it exited without + finishing) is cached per binary and engine for the life of the process; a hang, an unstartable + binary or an unknown binary is reported but not cached, so the next render probes again.""" + if not binary or not os.path.isfile(binary): + return "the Blender binary is unknown, so rendering could not be probed" + if (binary, engine) in _GL_PROBES: + return _GL_PROBES[(binary, engine)] + command = [binary, "--background", "--factory-startup", "--python-exit-code", "1", + "--python", str(GL_PROBE_SCRIPT), "--", engine] + group = {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == "nt" else {"start_new_session": True} + try: + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, **group) + except OSError as exc: + return f"the one-pixel test render could not start: {exc}" + try: + stdout, _ = process.communicate(timeout=GL_PROBE_TIMEOUT_SECONDS) + except subprocess.TimeoutExpired: + _kill_tree(process) + try: + process.communicate(timeout=10) + except subprocess.TimeoutExpired: + pass + return f"a one-pixel test render did not finish in {GL_PROBE_TIMEOUT_SECONDS} s" + if process.returncode == 0 and "BROKKR_GL_PROBE_OK" in stdout: + outcome = None + else: + outcome = f"a one-pixel test render exited with status {process.returncode}" + _GL_PROBES[(binary, engine)] = outcome + return outcome + + +gl_render_failure.cache_clear = _GL_PROBES.clear def _parse_time(value: Any) -> datetime | None: diff --git a/surfaces/blender/brokkr_bridge/gl_probe.py b/surfaces/blender/brokkr_bridge/gl_probe.py new file mode 100644 index 0000000..6331daa --- /dev/null +++ b/surfaces/blender/brokkr_bridge/gl_probe.py @@ -0,0 +1,15 @@ +"""Run inside a child Blender by blender_target.gl_render_failure: render one pixel with the engine named +after `--`, and print the completion marker only if the render returned.""" +import sys + +import bpy + +bpy.ops.wm.read_factory_settings(use_empty=True) +scene = bpy.context.scene +scene.render.engine = sys.argv[-1] +scene.render.resolution_x = scene.render.resolution_y = 1 +camera = bpy.data.objects.new("probe", bpy.data.cameras.new("probe")) +scene.collection.objects.link(camera) +scene.camera = camera +bpy.ops.render.render(write_still=False) +print("BROKKR_GL_PROBE_OK") diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index d3dec32..cf2c3c2 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -184,19 +184,22 @@ gets a `failed` receipt whose message names the rule): `name`, `location`. Any other `objectType` (for example `TEXT` or `CURVE`) is refused with the allowed set named. A `MESH` is a cube (`size`); a `meshType` other than `CUBE` (case-insensitive, no surrounding whitespace) is refused rather than ignored. - `meshType` is checked only when `objectType` is `MESH`; an explicit `objectType: null` is refused. + `meshType` on any other `objectType` is refused too; an explicit `objectType: null` is refused. - `importGltf`: `filepath`, `.gltf` or `.glb`, relative to the add-on preference `Import Directory` (absolute paths, `..` and symlinks that resolve outside it are refused). Empty `Import Directory` disables the action. Needs Blender's glTF add-on. - `exportGltf`: `filepath`, `.glb` (binary) or `.gltf` (separate `.bin`), relative to the add-on preference `Render Output Directory` (the renderStill rules: no `..`, no links, and an - existing name, or an existing `.bin` beside a `.gltf`, is refused; there is no overwrite). + existing name is refused; there is no overwrite). Optional `extras` (custom properties become node `extras`), `yUp`, `applyModifiers` (each true by default, must be a boolean) and `selection` (a non-empty list of object names; any name not found, or not in the active view layer, refuses the export; the - selection is touched only when one is given, and restored afterwards). Not checked: texture - files a `.gltf` export writes beside it (only the `.bin` is), and a link or swap made between the - check and the write (the same residual as renderStill). + selection is touched only when one is given, and restored afterwards). The exporter writes into a + staging folder beside the target and Brokkr then moves each file into place (the `.glb`, or the `.gltf` + with its `.bin` and texture files), refusing the whole export, naming the file, if any of those names is + taken: nothing existing is overwritten. A refused or failed export leaves no file and no new folder, so + the same name can be retried. Each export holds an OS lock on its staging folder; the next export removes any `.brokkr-export-*` folder under the output directory whose lock is free (its Blender died), and a rollback that itself fails is refused naming the files left, which that same sweep removes. Not checked: a link or swap made between the check and the move (the + same residual as renderStill). The receipt message carries the written path and byte size. Needs Blender's glTF add-on. - `setCamera`: `targetObjectName` (a camera object); optional `lens` (mm), `cameraType` (`PERSP`, `ORTHO`, `PANO`), `panoramaType` (for example @@ -223,10 +226,12 @@ gets a `failed` receipt whose message names the rule): camera, file path and format are restored after the render. The render blocks Blender's UI until it finishes. In a background (`-b`) Blender on Linux, the GL engines `BLENDER_WORKBENCH`, `BLENDER_EEVEE` and `BLENDER_EEVEE_NEXT` are refused - with a `failed` receipt when `libEGL.so.1` cannot be loaded (probed once and cached for the life of the process), because - rendering would abort the whole process with no receipt; `CYCLES` renders on the - CPU. The check applies to the scene's engine when `engine` is omitted. No such - check runs on Windows or macOS. + with a `failed` receipt when a one-pixel test render of that engine does not finish in a child + process of the same Blender binary (it aborts, hangs past 120 s, or the binary is unknown). The + probe runs once per engine and is cached for the life of the process, so the first GL render + after startup waits for it. Rendering would otherwise abort the whole process with no receipt; + `CYCLES` renders on the CPU. The check applies to the scene's engine when `engine` is omitted. + A foreground Blender is not probed. - `look`: no fields. Captures the 3D view she is looking at (the largest 3D view across the windows, its main region) to `/look/.png` and puts the absolute path in the receipt's @@ -254,7 +259,9 @@ gets a `failed` receipt whose message names the rule): The scene actions were run against Blender 5.2.3 LTS headless with `surfaces/blender/tests/live/headless_smoke.py` (usage in its docstring). One real failure it found: Blender's `engine` enum is dynamic, so `bl_rna` lists only -`BLENDER_EEVEE`; `renderStill` now asks Blender by assignment instead. +`BLENDER_EEVEE`; `renderStill` now asks Blender by assignment instead. `tests/live/export_gltf.py` and +`tests/live/refusals.py` (Blender 5.3.0 headless, usage in their docstrings) run `exportGltf` against the +real exporter and the render probe and `meshType` refusal against real bpy. ### Path rules and the residual race diff --git a/surfaces/blender/tests/live/export_gltf.py b/surfaces/blender/tests/live/export_gltf.py new file mode 100644 index 0000000..ff9e0bc --- /dev/null +++ b/surfaces/blender/tests/live/export_gltf.py @@ -0,0 +1,102 @@ +"""Live proof of exportGltf on real bpy: the option names exist on the real exporter, extras reach the +file, selection filters, .gltf writes its .bin and textures without overwriting, a refused or failed +export leaves nothing behind. + + BROKKR_ADDON= \ + blender -b --factory-startup --python export_gltf.py -- result.json + +Exit status is non-zero if any check fails. +""" +import bpy, sys, os, json, types, tempfile +from pathlib import Path + +ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() +pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)] +sys.modules["brokkr_bridge"] = pkg +from brokkr_bridge import blender_target as bt + +out = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else "export_gltf_result.json" +R = {"blender": bpy.app.version_string, "checks": []} + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + print("CHECK", "ok " if ok else "FAIL", name, detail if not ok else "", flush=True) + + +# Every exporter keyword the add-on passes must be a property of the real operator. +props = {p.identifier for p in bpy.ops.export_scene.gltf.get_rna_type().properties} +passed = {"filepath", "export_format", "use_selection", "export_extras", "export_yup", "export_apply"} +check("exporter has every option the add-on passes", passed <= props, sorted(passed - props)) +work = Path(tempfile.mkdtemp(prefix="brokkr-export-live-")) +bpy.ops.wm.read_factory_settings(use_empty=True) +t = bt.BrokkrBlenderTarget(bpy) +t.configure_action_dirs("", str(work)) +bpy.ops.mesh.primitive_cube_add(); cube = bpy.context.active_object; cube.name = "Cube"; cube["brokkr_tag"] = "hello" +bpy.ops.mesh.primitive_uv_sphere_add(location=(3, 0, 0)); sphere = bpy.context.active_object; sphere.name = "Sphere" +image = bpy.data.images.new("brokkr_tex", 4, 4) +scratch = Path(tempfile.mkdtemp(prefix="brokkr-export-src-")) +image.filepath_raw = str(scratch / "brokkr_tex_src.png"); image.file_format = "PNG"; image.save() +mat = bpy.data.materials.new("Textured"); mat.use_nodes = True +node = mat.node_tree.nodes.new("ShaderNodeTexImage"); node.image = image +mat.node_tree.links.new(node.outputs["Color"], mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"]) +cube.data.materials.append(mat) +N = [0] + + +def act(**cmd): + N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]); cmd["action"] = "exportGltf" + return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) + + +def listing(): + return sorted(str(p.relative_to(work)).replace("\\", "/") for p in work.rglob("*")) + + +r = act(filepath="all.glb") +check("glb accepted", r["status"] == "accepted", r["message"]) +check("glb written, no staging folder", listing() == ["all.glb"], listing()) +glb = (work / "all.glb").read_bytes() +check("glb carries extras", b"brokkr_tag" in glb and b"hello" in glb) +r = act(filepath="noextras.glb", extras=False) +check("extras=false leaves them out", b"brokkr_tag" not in (work / "noextras.glb").read_bytes(), r["message"]) +cube.select_set(True); sphere.select_set(False) +r = act(filepath="only.glb", selection=["Sphere"]) +data = (work / "only.glb").read_bytes() +check("selection exports only the sphere", b"Sphere" in data and b"Cube" not in data, r["message"]) +check("selection restored", cube.select_get() and not sphere.select_get(), (cube.select_get(), sphere.select_get())) + +r = act(filepath="sep/s.gltf") +check("gltf accepted", r["status"] == "accepted", r["message"]) +files = listing() +check("gltf writes its bin and the texture beside it", "sep/s.gltf" in files and "sep/s.bin" in files and any(f.startswith("sep/brokkr_tex") for f in files), files) +before = {f: (work / f).read_bytes() for f in listing() if (work / f).is_file()} +texture = next(f for f in files if f.startswith("sep/brokkr_tex")) +(work / texture).write_bytes(b"precious") +r = act(filepath="sep/s2.gltf") +check("a taken texture name refuses", r["status"] == "failed" and Path(texture).name in r["message"], r["message"]) +check("the taken texture is untouched", (work / texture).read_bytes() == b"precious") +check("the refused export leaves nothing", not any(f.startswith("sep/s2") for f in listing()) and not any(".brokkr-export" in f for f in listing()), listing()) + +r = act(filepath="fresh/deep/x.glb", selection=["Nope"]) +check("refused selection makes no folder", r["status"] == "failed" and not (work / "fresh").exists(), r["message"]) +orig = bpy.ops.export_scene.gltf +bt_target = t +class Boom: + def __call__(self, *a, **k): + Path(k["filepath"]).write_bytes(b"partial"); raise RuntimeError("died midway") + def get_rna_type(self): return orig.get_rna_type() +import types as _t +t.bpy = _t.SimpleNamespace(**{k: getattr(bpy, k) for k in ("data", "app", "path", "context")}) +t.bpy.ops = _t.SimpleNamespace(export_scene=_t.SimpleNamespace(gltf=Boom()), import_scene=bpy.ops.import_scene, render=bpy.ops.render) +r = act(filepath="fresh/deep/x.glb") +check("a failing exporter is a failed receipt", r["status"] == "failed", r["message"]) +check("and leaves no partial file or new folder", not (work / "fresh").exists(), listing()) +t.bpy = bpy +r = act(filepath="fresh/deep/x.glb") +check("the same name then exports", r["status"] == "accepted" and (work / "fresh" / "deep" / "x.glb").is_file(), r["message"]) + +import shutil +shutil.rmtree(work, ignore_errors=True); shutil.rmtree(scratch, ignore_errors=True) +json.dump(R, open(out, "w"), indent=1) +sys.exit(0 if all(c["ok"] for c in R["checks"]) else 1) diff --git a/surfaces/blender/tests/live/export_gltf.result.json b/surfaces/blender/tests/live/export_gltf.result.json new file mode 100644 index 0000000..ff10cae --- /dev/null +++ b/surfaces/blender/tests/live/export_gltf.result.json @@ -0,0 +1,114 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "exporter has every option the add-on passes", + "ok": true, + "detail": [] + }, + { + "name": "glb accepted", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\all.glb (72752 bytes)." + }, + { + "name": "glb written, no staging folder", + "ok": true, + "detail": [ + "all.glb" + ] + }, + { + "name": "glb carries extras", + "ok": true, + "detail": null + }, + { + "name": "extras=false leaves them out", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\noextras.glb (72720 bytes)." + }, + { + "name": "selection exports only the sphere", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\only.glb (70240 bytes)." + }, + { + "name": "selection restored", + "ok": true, + "detail": [ + true, + false + ] + }, + { + "name": "gltf accepted", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\sep\\s.gltf (2840 bytes)." + }, + { + "name": "gltf writes its bin and the texture beside it", + "ok": true, + "detail": [ + "all.glb", + "noextras.glb", + "only.glb", + "sep", + "sep/brokkr_tex_src.png", + "sep/s.bin", + "sep/s.gltf" + ] + }, + { + "name": "a taken texture name refuses", + "ok": true, + "detail": "output path already exists; output actions never overwrite: brokkr_tex_src.png" + }, + { + "name": "the taken texture is untouched", + "ok": true, + "detail": null + }, + { + "name": "the refused export leaves nothing", + "ok": true, + "detail": [ + "all.glb", + "noextras.glb", + "only.glb", + "sep", + "sep/brokkr_tex_src.png", + "sep/s.bin", + "sep/s.gltf" + ] + }, + { + "name": "refused selection makes no folder", + "ok": true, + "detail": "Selection object was not found: Nope" + }, + { + "name": "a failing exporter is a failed receipt", + "ok": true, + "detail": "died midway" + }, + { + "name": "and leaves no partial file or new folder", + "ok": true, + "detail": [ + "all.glb", + "noextras.glb", + "only.glb", + "sep", + "sep/brokkr_tex_src.png", + "sep/s.bin", + "sep/s.gltf" + ] + }, + { + "name": "the same name then exports", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\fresh\\deep\\x.glb (72752 bytes)." + } + ] +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/refusals.py b/surfaces/blender/tests/live/refusals.py new file mode 100644 index 0000000..3abd794 --- /dev/null +++ b/surfaces/blender/tests/live/refusals.py @@ -0,0 +1,74 @@ +"""Live proof of the renderStill GL refusal and the createObject meshType refusal on real bpy. + + BROKKR_ADDON= \ + blender -b --factory-startup --python refusals.py -- result.json + +The pass outcome runs a real child Blender (a one-pixel Workbench and EEVEE render) and then a real +renderStill. The abort outcome needs a host whose headless GL fails (a container with libEGL and no +GPU), which this script cannot make: it runs the real probe against a stand-in binary that aborts, and +on such a host the first two checks fail instead of passing. Exit status is non-zero if any check fails. +""" +import bpy, sys, os, json, types, tempfile, stat, shutil +from pathlib import Path + +ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() +pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)] +sys.modules["brokkr_bridge"] = pkg +from brokkr_bridge import blender_target as bt + +out = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else "refusals_result.json" +R = {"blender": bpy.app.version_string, "background": bpy.app.background, "platform": sys.platform, "checks": []} + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + print("CHECK", "ok " if ok else "FAIL", name, detail if not ok else "", flush=True) + + +work = Path(tempfile.mkdtemp(prefix="brokkr-refusals-live-")) +bpy.ops.wm.read_factory_settings(use_empty=True) +t = bt.BrokkrBlenderTarget(bpy) +t.configure_action_dirs("", str(work)) +N = [0] + + +def act(action, **cmd): + N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]); cmd["action"] = action + return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) + + +for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE_NEXT", "BLENDER_EEVEE"): + try: # the engine enum is dynamic: ask by assignment + bpy.context.scene.render.engine = engine + except TypeError: + continue + if True: + failure = bt.gl_render_failure(bpy.app.binary_path, engine) + check("real one-pixel %s render survives in a child Blender" % engine, failure is None, failure) + +bpy.ops.object.camera_add(); bpy.context.scene.camera = bpy.context.active_object +r = act("renderStill", outputPath="shot.png", engine="BLENDER_WORKBENCH", resolutionX=8, resolutionY=8) +check("renderStill Workbench headless renders after the probe", r["status"] == "accepted" and (work / "shot.png").is_file(), r["message"]) + +stand_in = work / ("abort.cmd" if os.name == "nt" else "abort.sh") +stand_in.write_text("@echo off\r\nexit /b 3\r\n" if os.name == "nt" else "#!/bin/sh\nkill -ABRT $$\n") +stand_in.chmod(stand_in.stat().st_mode | stat.S_IEXEC) +failure = bt.gl_render_failure(str(stand_in), "BLENDER_WORKBENCH") +check("a child that aborts is a refusal reason", failure is not None and "exited with status" in failure, failure) +t.bpy = types.SimpleNamespace(data=bpy.data, path=bpy.path, context=bpy.context, ops=bpy.ops, + app=types.SimpleNamespace(background=True, binary_path=str(stand_in))) +bpy.context.scene.render.engine = "BLENDER_WORKBENCH" +r = act("renderStill", outputPath="no.png", engine="BLENDER_WORKBENCH") +check("renderStill refuses and renders nothing", r["status"] == "failed" and "cannot render" in r["message"] and not (work / "no.png").exists(), r["message"]) +t.bpy = bpy + +for kind in ("LIGHT", "EMPTY", "CAMERA"): + r = act("createObject", objectType=kind, meshType="CYLINDER") + check("meshType on %s is refused" % kind, r["status"] == "failed" and "MESH" in r["message"], r["message"]) +check("and nothing was created for them", len([o for o in bpy.data.objects if o.type in ("LIGHT", "EMPTY")]) == 0) +r = act("createObject", objectType="MESH", meshType="cube") +check("meshType CUBE on a MESH still works", r["status"] == "accepted", r["message"]) + +shutil.rmtree(work, ignore_errors=True) +json.dump(R, open(out, "w"), indent=1) +sys.exit(0 if all(c["ok"] for c in R["checks"]) else 1) diff --git a/surfaces/blender/tests/live/refusals.result.json b/surfaces/blender/tests/live/refusals.result.json new file mode 100644 index 0000000..0047130 --- /dev/null +++ b/surfaces/blender/tests/live/refusals.result.json @@ -0,0 +1,57 @@ +{ + "blender": "5.3.0", + "background": true, + "platform": "win32", + "checks": [ + { + "name": "real one-pixel BLENDER_WORKBENCH render survives in a child Blender", + "ok": true, + "detail": null + }, + { + "name": "real one-pixel BLENDER_EEVEE render survives in a child Blender", + "ok": true, + "detail": null + }, + { + "name": "renderStill Workbench headless renders after the probe", + "ok": true, + "detail": "Rendered still to shot.png." + }, + { + "name": "a child that aborts is a refusal reason", + "ok": true, + "detail": "a one-pixel test render exited with status 3" + }, + { + "name": "renderStill refuses and renders nothing", + "ok": true, + "detail": "engine BLENDER_WORKBENCH cannot render in this headless Blender (a one-pixel test render exited with status 3); rendering would abort the process; use engine CYCLES." + }, + { + "name": "meshType on LIGHT is refused", + "ok": true, + "detail": "meshType applies only to objectType MESH, not LIGHT." + }, + { + "name": "meshType on EMPTY is refused", + "ok": true, + "detail": "meshType applies only to objectType MESH, not EMPTY." + }, + { + "name": "meshType on CAMERA is refused", + "ok": true, + "detail": "meshType applies only to objectType MESH, not CAMERA." + }, + { + "name": "and nothing was created for them", + "ok": true, + "detail": null + }, + { + "name": "meshType CUBE on a MESH still works", + "ok": true, + "detail": "Blender object created." + } + ] +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index fcc2b64..a36df4a 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -108,6 +108,8 @@ class FakeBpy: self.exported = [] self.export_result = {"FINISHED"} self.export_writes = True + self.export_siblings = [] # extra files the exporter writes beside the target (textures) + self.export_raises_after_writing = None for o in self.data.objects.values(): o.selected = o is self.mesh o.select_get = (lambda o=o: o.selected) @@ -143,8 +145,15 @@ class FakeBpy: assert (mode, undo) == ("EXEC_DEFAULT", False) kwargs["selected_at_call"] = sorted(o.name for o in self.data.objects.values() if o.selected) self.exported.append(kwargs) + target = Path(kwargs["filepath"]) if self.export_writes: - Path(kwargs["filepath"]).write_bytes(b"x" * 10) + target.write_bytes(b"x" * 10) + if target.suffix == ".gltf": + target.with_suffix(".bin").write_bytes(b"b" * 4) + for name in self.export_siblings: + (target.parent / name).write_bytes(b"t" * 3) + if self.export_raises_after_writing: + raise RuntimeError(self.export_raises_after_writing) return self.export_result def render_still(self, mode, undo, write_still): @@ -267,8 +276,11 @@ class ActionTests(unittest.TestCase): self.assertIn(path, receipt["message"]) self.assertIn("10 bytes", receipt["message"]) call = self.bpy.exported[0] - self.assertEqual({k: v for k, v in call.items() if k != "selected_at_call"}, - {"filepath": path, "export_format": "GLB", "export_extras": True, + staged = Path(call["filepath"]) # the exporter writes into a staging folder, then Brokkr moves the file + self.assertEqual((staged.name, staged.parent.parent, staged.parent.name.startswith(".brokkr-export-")), + ("a.glb", self.root / "out" / "ship", True)) + self.assertEqual({k: v for k, v in call.items() if k not in ("selected_at_call", "filepath")}, + {"export_format": "GLB", "export_extras": True, "export_yup": True, "export_apply": True, "use_selection": False}) def test_export_gltf_suffix_is_separate_and_options_pass_through(self): @@ -343,13 +355,155 @@ class ActionTests(unittest.TestCase): self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["taken.glb"]) self.assertIn("already exists", self.run_action(action="exportGltf", filepath="taken.glb")["message"]) - def test_export_gltf_refuses_an_existing_bin_sibling(self): + def test_export_gltf_writes_its_bin_and_textures_beside_it_and_nothing_else(self): + self.bpy.export_siblings = ["tex.png"] + receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(receipt["status"], "accepted", receipt) + self.assertEqual(sorted(p.name for p in (self.root / "out" / "sub").iterdir()), ["a.bin", "a.gltf", "tex.png"]) + self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["sub"]) # no staging folder left + + def test_export_gltf_refuses_an_existing_bin_sibling_and_keeps_it(self): (self.root / "out" / "a.bin").write_bytes(b"old") - self.assertEqual(self.run_action(action="exportGltf", filepath="a.gltf")["status"], "failed") - self.assertEqual(self.bpy.exported, []) + receipt = self.run_action(action="exportGltf", filepath="a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertIn("a.bin", receipt["message"]) + self.assertEqual((self.root / "out" / "a.bin").read_bytes(), b"old") + self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["a.bin"]) + + def test_export_gltf_never_overwrites_a_texture_the_exporter_writes(self): + (self.root / "out" / "tex.png").write_bytes(b"old") + self.bpy.export_siblings = ["tex.png"] + receipt = self.run_action(action="exportGltf", filepath="a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertIn("tex.png", receipt["message"]) + self.assertEqual((self.root / "out" / "tex.png").read_bytes(), b"old") + self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["tex.png"]) # no a.gltf, no a.bin + + def test_a_failed_export_leaves_no_file_no_folder_and_the_name_can_be_retried(self): + self.bpy.export_raises_after_writing = "exporter died midway" + receipt = self.run_action(action="exportGltf", filepath="new/deep/a.glb") + self.assertEqual(receipt["status"], "failed") + self.assertEqual(list((self.root / "out").iterdir()), []) + self.bpy.export_raises_after_writing = None + retry = self.run_action(action="exportGltf", filepath="new/deep/a.glb") + self.assertEqual(retry["status"], "accepted", retry) + self.assertTrue((self.root / "out" / "new" / "deep" / "a.glb").is_file()) + + def test_a_move_that_fails_partway_rolls_back_so_the_target_is_untouched_and_retry_works(self): + self.bpy.export_siblings = ["tex1.png", "tex2.png"] + real_rename = os.rename + calls = [] + + def fail_on_third(src, dst): + calls.append(dst) + if len(calls) == 3: + raise OSError("disk full") + return real_rename(src, dst) + + with mock.patch.object(bt.os, "rename", fail_on_third): + receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertGreaterEqual(len(calls), 3) + self.assertEqual(list((self.root / "out").iterdir()), []) # nothing moved stays; no staging, no new folder + retry = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(retry["status"], "accepted", retry) + self.assertEqual(sorted(p.name for p in (self.root / "out" / "sub").iterdir()), + ["a.bin", "a.gltf", "tex1.png", "tex2.png"]) + + HOLD_STAGE = ( + "import sys\n" + "sys.path.insert(0, sys.argv[1])\n" + "import types\n" + "pkg = types.ModuleType('brokkr_bridge'); pkg.__path__ = [sys.argv[1] + '/brokkr_bridge']\n" + "sys.modules['brokkr_bridge'] = pkg\n" + "from brokkr_bridge import blender_target as bt\n" + "from pathlib import Path\n" + "stage, fd = bt._open_stage(Path(sys.argv[2]))\n" + "print(stage, flush=True)\n" + "sys.stdin.read()\n") + + def start_export_holding_a_stage(self): + import subprocess + child = subprocess.Popen([sys.executable, "-c", self.HOLD_STAGE, str(ADDON.parent), str(self.root / "out")], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + self.addCleanup(child.kill) + self.addCleanup(child.wait) + self.addCleanup(child.stdout.close) + self.addCleanup(child.stdin.close) + return child, Path(child.stdout.readline().strip()) + + def test_a_sweep_spares_another_processs_live_stage_and_removes_a_killed_ones(self): + child, stage = self.start_export_holding_a_stage() + (stage / "a.glb").write_bytes(b"in flight") + os.utime(stage, (0, 0)) # old by any clock: only the lock decides + bt._sweep_stale_stages(self.root / "out") + self.assertTrue((stage / "a.glb").exists()) + self.assertEqual(self.run_action(action="exportGltf", filepath="b.glb")["status"], "accepted") + self.assertTrue((stage / "a.glb").exists()) # an export in this process swept too + child.kill() + child.wait() + bt._sweep_stale_stages(self.root / "out") + self.assertFalse(stage.exists()) + + def test_a_sweep_leaves_a_folder_whose_lock_is_not_made_yet(self): + early = self.root / "out" / ".brokkr-export-early" + early.mkdir() + bt._sweep_stale_stages(self.root / "out") + self.assertTrue(early.exists()) + + def test_a_failed_rollback_is_refused_loudly_naming_the_files_and_the_next_export_recovers(self): + self.bpy.export_siblings = ["tex1.png"] + real_rename = os.rename + calls = [] + + def fail_forever_from_third(src, dst): + calls.append(dst) + if len(calls) >= 3: + raise OSError("disk gone") + return real_rename(src, dst) + + with mock.patch.object(bt.os, "rename", fail_forever_from_third): + receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertIn("could not be rolled back", receipt["message"]) + self.assertIn("sub/a.bin", receipt["message"]) + self.assertIn("sub/a.gltf", receipt["message"]) + self.assertTrue((self.root / "out" / "sub" / "a.bin").exists()) + retry = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(retry["status"], "accepted", retry) + self.assertEqual(sorted(p.name for p in (self.root / "out").rglob("*") if p.is_file()), + ["a.bin", "a.gltf", "tex1.png"]) + self.assertEqual([p.name for p in (self.root / "out").iterdir()], ["sub"]) # no stage left + + def test_a_failed_texture_subfolder_move_leaves_no_empty_folder(self): + self.bpy.export_siblings = [] + real_rename = os.rename + + def fail_the_texture(src, dst): + if "textures" in str(dst): + raise OSError("no") + return real_rename(src, dst) + + orig = self.bpy.export_gltf + + def with_subfolder(mode, undo, **kw): + result = orig(mode, undo, **kw) + target = Path(kw["filepath"]) + (target.parent / "textures").mkdir() + (target.parent / "textures" / "t.png").write_bytes(b"t") + return result + + self.bpy.ops.export_scene.gltf = with_subfolder + with mock.patch.object(bt.os, "rename", fail_the_texture): + receipt = self.run_action(action="exportGltf", filepath="a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertEqual(list((self.root / "out").iterdir()), []) def test_export_refuses_a_symlinked_folder(self): - os.symlink(self.root, self.root / "out" / "link") + try: + os.symlink(self.root, self.root / "out" / "link") + except OSError: + self.skipTest("the OS denies symlink creation to this user") self.assertEqual(self.run_action(action="exportGltf", filepath="link/a.glb")["status"], "failed") self.assertEqual(self.bpy.exported, []) @@ -427,29 +581,36 @@ class ActionTests(unittest.TestCase): self.assertIn("CUBE", receipt["message"]) self.assertEqual(self.bpy.created, []) - # renderStill: GPU engines without a GL runtime - def test_render_still_refuses_gpu_engines_headless_when_the_gl_library_is_missing(self): + def test_mesh_type_on_a_non_mesh_object_is_refused_not_ignored(self): + for object_type in ("LIGHT", "EMPTY", "CAMERA"): + receipt = self.run_action(action="createObject", objectType=object_type, meshType="CYLINDER") + self.assertEqual(receipt["status"], "failed", object_type) + self.assertIn("MESH", receipt["message"]) + self.assertEqual(self.bpy.created, []) + + # renderStill: GPU engines that would abort a headless Blender + def test_render_still_refuses_gpu_engines_headless_when_a_test_render_fails(self): self.bpy.app.background = True for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT", "blender_workbench"): self.bpy.scene.render.ENGINES = FakeRender.ENGINES + ("BLENDER_EEVEE_NEXT",) - with mock.patch.object(bt, "missing_gl_library", return_value="libEGL.so.1"): + with mock.patch.object(bt, "gl_render_failure", return_value="a one-pixel test render exited with status 134"): receipt = self.run_action(action="renderStill", outputPath="a.png", engine=engine) self.assertEqual(receipt["status"], "failed", engine) - self.assertIn("libEGL.so.1", receipt["message"]) + self.assertIn("one-pixel test render", receipt["message"]) self.assertIn("CYCLES", receipt["message"]) self.assertEqual(self.bpy.rendered, []) self.assertEqual(self.bpy.scene.render.engine, "BLENDER_EEVEE") def test_render_still_refuses_the_scene_engine_too_and_leaves_no_folder(self): self.bpy.app.background = True # scene engine is BLENDER_EEVEE - with mock.patch.object(bt, "missing_gl_library", return_value="libEGL.so.1"): + with mock.patch.object(bt, "gl_render_failure", return_value="a one-pixel test render exited with status 134"): receipt = self.run_action(action="renderStill", outputPath="shots/a.png") self.assertEqual(receipt["status"], "failed") self.assertFalse((self.root / "out" / "shots").exists()) - def test_render_still_gl_check_spares_cycles_foreground_and_a_present_library(self): - probe = mock.Mock(return_value="libEGL.so.1") - with mock.patch.object(bt, "missing_gl_library", probe): + def test_render_still_gl_check_spares_cycles_foreground_and_a_working_test_render(self): + probe = mock.Mock(return_value="a one-pixel test render exited with status 134") + with mock.patch.object(bt, "gl_render_failure", probe): self.bpy.app.background = True self.assertEqual(self.run_action(action="renderStill", outputPath="a.png", engine="CYCLES")["status"], "accepted") probe.assert_not_called() @@ -460,20 +621,94 @@ class ActionTests(unittest.TestCase): probe.return_value = None self.assertEqual(self.run_action(action="renderStill", outputPath="c.png", engine="BLENDER_WORKBENCH")["status"], "accepted") - def test_missing_gl_library_probes_only_on_linux_and_only_once(self): - bt.missing_gl_library.cache_clear() - with mock.patch.object(bt.sys, "platform", "win32"), mock.patch.object(bt.ctypes, "CDLL", side_effect=OSError) as cdll: - self.assertIsNone(bt.missing_gl_library()) - cdll.assert_not_called() - bt.missing_gl_library.cache_clear() - with mock.patch.object(bt.sys, "platform", "linux"), mock.patch.object(bt.ctypes, "CDLL", side_effect=OSError) as cdll: - self.assertEqual(bt.missing_gl_library(), "libEGL.so.1") - self.assertEqual(bt.missing_gl_library(), "libEGL.so.1") - cdll.assert_called_once_with("libEGL.so.1") - bt.missing_gl_library.cache_clear() - with mock.patch.object(bt.sys, "platform", "linux"), mock.patch.object(bt.ctypes, "CDLL"): - self.assertIsNone(bt.missing_gl_library()) - bt.missing_gl_library.cache_clear() + def fake_blender(self, status, marker=True): + """A stand-in Blender binary: a script that ignores its arguments, prints the probe's completion + marker (or not) and exits with status.""" + if os.name == "nt": + path = self.root / "fake_blender.cmd" + path.write_text("@echo off\r\n" + ("echo BROKKR_GL_PROBE_OK\r\n" if marker else "") + f"exit /b {status}\r\n") + else: + path = self.root / "fake_blender.sh" + path.write_text("#!/bin/sh\n" + ("echo BROKKR_GL_PROBE_OK\n" if marker else "") + f"exit {status}\n") + path.chmod(0o755) + return str(path) + + def test_gl_probe_passes_when_the_test_render_finishes_and_says_so(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + self.assertIsNone(bt.gl_render_failure(self.fake_blender(0), "BLENDER_EEVEE")) + + def test_gl_probe_fails_on_an_abort_a_missing_marker_a_hang_and_an_unknown_binary(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + self.assertIn("status 3", bt.gl_render_failure(self.fake_blender(3), "BLENDER_EEVEE")) + self.assertIn("status 0", bt.gl_render_failure(self.fake_blender(0, marker=False), "BLENDER_WORKBENCH")) + with mock.patch.object(bt, "GL_PROBE_TIMEOUT_SECONDS", 0.001): + self.assertIn("did not finish", bt.gl_render_failure(self.fake_blender(0), "BLENDER_EEVEE_NEXT")) + self.assertIn("unknown", bt.gl_render_failure("", "BLENDER_EEVEE")) + self.assertIn("unknown", bt.gl_render_failure(str(self.root / "missing"), "BLENDER_EEVEE")) + + def slow_blender(self): + """A stand-in that starts a child which holds the output pipe for 30 s.""" + if os.name == "nt": + path = self.root / "slow_blender.cmd" + path.write_text("@echo off\r\nping -n 30 127.0.0.1 >nul\r\n") + else: + path = self.root / "slow_blender.sh" + path.write_text("#!/bin/sh\nsleep 30\necho BROKKR_GL_PROBE_OK\n") + path.chmod(0o755) + return path + + def test_gl_probe_timeout_returns_on_time_killing_the_childs_children_and_is_not_cached(self): + import time + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + slow = self.slow_blender() + with mock.patch.object(bt, "GL_PROBE_TIMEOUT_SECONDS", 1): + started = time.monotonic() + failure = bt.gl_render_failure(str(slow), "BLENDER_EEVEE") + took = time.monotonic() - started + self.assertIn("did not finish", failure) + self.assertLess(took, 10) + # the same binary and engine, now fast: a timeout was not remembered + slow.unlink() + fast = self.fake_blender(0) + os.replace(fast, str(slow.with_suffix(Path(fast).suffix))) + self.assertIsNone(bt.gl_render_failure(str(slow.with_suffix(Path(fast).suffix)), "BLENDER_EEVEE")) + + def test_gl_probe_caches_a_definite_abort_and_forgets_an_unstartable_binary(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + binary = self.fake_blender(3) + self.assertIn("status 3", bt.gl_render_failure(binary, "BLENDER_EEVEE")) + self.fake_blender(0) # same path, now a working binary: the abort is still the answer + self.assertIn("status 3", bt.gl_render_failure(binary, "BLENDER_EEVEE")) + with mock.patch.object(bt.subprocess, "Popen", side_effect=OSError("denied")): + self.assertIn("could not start", bt.gl_render_failure(binary, "BLENDER_WORKBENCH")) + self.assertIsNone(bt.gl_render_failure(binary, "BLENDER_WORKBENCH")) + + def test_gl_probe_runs_once_per_binary_and_engine(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + binary = self.fake_blender(0) + with mock.patch.object(bt.subprocess, "Popen", wraps=bt.subprocess.Popen) as run: + bt.gl_render_failure(binary, "BLENDER_EEVEE") + bt.gl_render_failure(binary, "BLENDER_EEVEE") + bt.gl_render_failure(binary, "BLENDER_WORKBENCH") + self.assertEqual(run.call_count, 2) + + def test_render_still_end_to_end_with_a_binary_that_aborts_and_one_that_renders(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + self.bpy.app.background = True + self.bpy.app.binary_path = self.fake_blender(134) + refused = self.run_action(action="renderStill", outputPath="a.png") + self.assertEqual(refused["status"], "failed") + self.assertIn("status 134", refused["message"]) + self.assertEqual(self.bpy.rendered, []) + bt.gl_render_failure.cache_clear() + self.bpy.app.binary_path = self.fake_blender(0) + self.assertEqual(self.run_action(action="renderStill", outputPath="a.png")["status"], "accepted") # importGltf: names def test_import_refuses_drive_unc_extended_stream_and_device_names(self): From 00b38e8e09e79abb9f7b0db3de1459fef6a82186 Mon Sep 17 00:00:00 2001 From: Eureka Date: Sat, 28 Nov 2026 01:31:36 +0000 Subject: [PATCH 043/223] Brokkr C#: snapshot lists as whole values; C# pin to CultLib 9fc4bdda; snapshots reach disk again (#18) --- Directory.Build.props | 4 +- Directory.Build.targets | 4 +- brokkr-command/Program.cs | 8 ++- .../BrokkrHostSnapshotTests.cs | 60 +++++++++++++++++++ brokkr-contracts.Tests/EditorProbe.cs | 4 +- .../Editor/BrokkrCultMeshMirror.cs | 15 ++--- .../Editor/BrokkrUnitySnapshotBuilder.cs | 17 +++--- .../Runtime/BrokkrHostSnapshot.cs | 25 ++++++-- 8 files changed, 110 insertions(+), 27 deletions(-) create mode 100644 brokkr-contracts.Tests/BrokkrHostSnapshotTests.cs diff --git a/Directory.Build.props b/Directory.Build.props index c8a3c67..0b65fe5 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,8 +2,8 @@ $(CULTLIB_ROOT) $(MSBuildThisFileDirectory)..\CultLib - - 42dce3611a81adc5c5fac54cadbaa5637d6022d3 + + 9fc4bdda6a8620f846b58e89ddf476f4676d3e89 C:\Program Files\Git\cmd\git.exe git diff --git a/Directory.Build.targets b/Directory.Build.targets index 46d436a..624e78a 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,6 +1,6 @@ + worktree of that revision: git worktree add , detached (in CultLib). --> @@ -17,7 +17,7 @@ + Text="CultLib must be revision $(CultLibRevision); found $([System.String]::Copy($(ActualCultLibRevision)).Trim()). Set CultLibRoot to a clean worktree of that revision." /> - cache.TryGet(new CultRecordKey("unity/host/current"), out BrokkrHostSnapshot? host) ? host : null; + private static BrokkrHostSnapshot? ReadHostSnapshot(CultCache cache) + { + if (!cache.TryGet(new CultRecordKey("unity/host/current"), out BrokkrHostSnapshot? host)) return null; + host.RefuseDefaultLists(); + return host; + } private static Dictionary Parse(string[] args) { diff --git a/brokkr-contracts.Tests/BrokkrHostSnapshotTests.cs b/brokkr-contracts.Tests/BrokkrHostSnapshotTests.cs new file mode 100644 index 0000000..4a7fc06 --- /dev/null +++ b/brokkr-contracts.Tests/BrokkrHostSnapshotTests.cs @@ -0,0 +1,60 @@ +using System.Collections.Immutable; +using GameCult.Brokkr; +using MessagePack; + +namespace Brokkr.Contracts.Tests; + +public sealed class BrokkrHostSnapshotTests +{ + // Captured before the lists became ImmutableArray holders: the record payload must not change. + private const string PayloadHex = + "DC0013D92567616D6563756C742E62726F6B6B722E746F6F6C5F686F73745F736E617073686F742E7630B362726F6B6B722E756E6974795F656469746F72AC756E6974792D656469746F72A170A174A0A0A000900090919EA16FA0A0A0C2A00000A09195A163A0A0C29195A178A0A0A131C2A0A0A0909196A161A0A0C2C2A0C2C2C2C2C2"; + + private static BrokkrHostSnapshot Populated() => new() + { + projectPath = "p", + observedAt = "t", + sceneObjects = ImmutableArray.Create(new BrokkrGameObjectSnapshot + { + objectId = "o", + components = ImmutableArray.Create(new BrokkrComponentSnapshot + { + componentId = "c", + properties = ImmutableArray.Create(new BrokkrSerializedPropertySnapshot { path = "x", value = "1" }) + }) + }), + assets = ImmutableArray.Create(new BrokkrAssetSnapshot { path = "a" }) + }; + + [Fact] + public void ListsAreWholeValuesWithTheSameBytesAsArrays() => + Assert.Equal(PayloadHex, Convert.ToHexString(MessagePackSerializer.Serialize(Populated()))); + + [Fact] + public void PopulatedSnapshotIsAccepted() => Populated().RefuseDefaultLists(); + + [Theory] + [InlineData(12)] + [InlineData(13)] + public void NilListsDecodeToDefaultAndAreRefused(int key) + { + var fields = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(Populated())); + fields[key] = null; + var snapshot = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(fields)); + + var error = Assert.Throws(snapshot.RefuseDefaultLists); + Assert.Contains("default", error.Message); + } + + [Fact] + public void DefaultNestedListsAreRefused() + { + var snapshot = Populated(); + snapshot.sceneObjects[0].components = default; + Assert.Throws(snapshot.RefuseDefaultLists); + + snapshot = Populated(); + snapshot.sceneObjects[0].components[0].properties = default; + Assert.Throws(snapshot.RefuseDefaultLists); + } +} diff --git a/brokkr-contracts.Tests/EditorProbe.cs b/brokkr-contracts.Tests/EditorProbe.cs index 1445697..45fb41e 100644 --- a/brokkr-contracts.Tests/EditorProbe.cs +++ b/brokkr-contracts.Tests/EditorProbe.cs @@ -9,7 +9,7 @@ namespace Brokkr.Contracts.Tests; // The scenario harness: an editor without Unity. It opens the store exactly as BrokkrCultMeshMirror does (a CultMesh // node with StartServer=false over a directory store, no shard log) and runs one service tick in the // service order: pull, drain pending intents through BrokkrCommandDrain (the same class the service uses), host -// snapshot, soft flush. "Executing" an intent only records it, so the scenarios measure delivery and once-only +// snapshot, flush. "Executing" an intent only records it, so the scenarios measure delivery and once-only // execution, not Unity. It is also a thin IBrokkrCommandStore in front of the real BrokkrCommandStore, with knobs to // make writes fail and to land a writer between the enable's pull and its commit. internal sealed class EditorProbe : IDisposable, IBrokkrCommandStore @@ -132,7 +132,7 @@ internal sealed class EditorProbe : IDisposable, IBrokkrCommandStore projectPath = "probe", agentCommandsEnabled = AgentCommandsEnabled }); - await node.FlushAsync(soft: true); + await node.FlushAsync(); return handled; } diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs index fccfe07..1c46ed7 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs @@ -77,8 +77,9 @@ namespace GameCult.Brokkr.Editor internal async Task PublishSnapshotAsync(BrokkrHostSnapshot snapshot) { RequireRunning(); + snapshot.RefuseDefaultLists(); await node.Database.PutAsync(new CultRecordKey("unity/host/current"), snapshot); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } // Command ids are single-use: a caller with no id gets a fresh one, and reusing an answered id is a defect. @@ -91,42 +92,42 @@ namespace GameCult.Brokkr.Editor } await node.Database.PutAsync(BrokkrCommandLedger.CommandKey(command.commandId), command); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishQuestRouteAsync(BrokkrQuestRoute route) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"unity/quest-routes/{route.id}"), route); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishSyncSessionAsync(BrokkrSyncSession session) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"sync/sessions/{session.sessionId}"), session); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishSyncObjectBindingAsync(BrokkrSyncObjectBinding binding) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"sync/bindings/objects/{binding.bindingId}"), binding); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishSyncVarAsync(BrokkrSyncVar syncVar) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"sync/vars/{syncVar.syncVarId}"), syncVar); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishTimelineBindingAsync(BrokkrSyncTimelineBinding binding) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"sync/bindings/timelines/{binding.bindingId}"), binding); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal bool TryDequeueSyncReceipt(out BrokkrSyncReceipt receipt) diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs index 45ae610..3536a50 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Globalization; using System.Linq; using System.Reflection; @@ -55,7 +56,7 @@ namespace GameCult.Brokkr.Editor }; } - private static BrokkrGameObjectSnapshot[] CaptureSceneObjects() + private static ImmutableArray CaptureSceneObjects() { var objects = new List(); @@ -73,7 +74,7 @@ namespace GameCult.Brokkr.Editor } } - return objects.ToArray(); + return objects.ToImmutableArray(); } private static void CaptureGameObject( @@ -109,7 +110,7 @@ namespace GameCult.Brokkr.Editor } } - private static BrokkrComponentSnapshot[] CaptureComponents(GameObject gameObject) + private static ImmutableArray CaptureComponents(GameObject gameObject) { return gameObject.GetComponents() .Where(component => component != null) @@ -121,7 +122,7 @@ namespace GameCult.Brokkr.Editor enabled = ReadEnabled(component), properties = CaptureProperties(component) }) - .ToArray(); + .ToImmutableArray(); } private static string[] CaptureMaterialNames(GameObject gameObject) @@ -135,7 +136,7 @@ namespace GameCult.Brokkr.Editor .ToArray(); } - private static BrokkrSerializedPropertySnapshot[] CaptureProperties(UnityEngine.Object target) + private static ImmutableArray CaptureProperties(UnityEngine.Object target) { var properties = new List(); using var serializedObject = new SerializedObject(target); @@ -165,10 +166,10 @@ namespace GameCult.Brokkr.Editor } } - return properties.ToArray(); + return properties.ToImmutableArray(); } - private static BrokkrAssetSnapshot[] CaptureAssets() + private static ImmutableArray CaptureAssets() { return AssetDatabase.GetAllAssetPaths() .Where(path => path.StartsWith("Assets/", StringComparison.Ordinal)) @@ -185,7 +186,7 @@ namespace GameCult.Brokkr.Editor name = System.IO.Path.GetFileNameWithoutExtension(path) }; }) - .ToArray(); + .ToImmutableArray(); } internal static string GetObjectId(UnityEngine.Object target) diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs index a33b9d2..f30466e 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Immutable; using GameCult.Caching; using MessagePack; @@ -21,14 +22,30 @@ namespace GameCult.Brokkr [Key(9)] public string[] selectedObjectNames = Array.Empty(); [Key(10)] public int assetCount; [Key(11)] public string[] capabilities = Array.Empty(); - [Key(12)] public BrokkrGameObjectSnapshot[] sceneObjects = Array.Empty(); - [Key(13)] public BrokkrAssetSnapshot[] assets = Array.Empty(); + [Key(12)] public ImmutableArray sceneObjects = ImmutableArray.Empty; + [Key(13)] public ImmutableArray assets = ImmutableArray.Empty; [Key(14)] public bool isPlaying; [Key(15)] public bool isPaused; [Key(16)] public bool isCompiling; [Key(17)] public bool isUpdating; // False means the editor executes no agent commands: the operator has not enabled the sink. [Key(18)] public bool agentCommandsEnabled; + + // The snapshot lists are whole values (ImmutableArray, no element ids): a store row from a writer that left + // one nil decodes to a default array, which this refuses instead of letting a reader throw later. + public void RefuseDefaultLists() + { + if (sceneObjects.IsDefault) throw new InvalidOperationException("Brokkr host snapshot sceneObjects is default, not a list."); + if (assets.IsDefault) throw new InvalidOperationException("Brokkr host snapshot assets is default, not a list."); + foreach (var sceneObject in sceneObjects) + { + if (sceneObject.components.IsDefault) + throw new InvalidOperationException($"Brokkr host snapshot object '{sceneObject.path}' components is default, not a list."); + foreach (var component in sceneObject.components) + if (component.properties.IsDefault) + throw new InvalidOperationException($"Brokkr host snapshot component '{component.typeName}' properties is default, not a list."); + } + } } // Written by the editor, into the store, when the operator enables the command sink. The token is also kept in @@ -73,7 +90,7 @@ namespace GameCult.Brokkr [Key(6)] public int layer; [Key(7)] public int childCount; [Key(8)] public string parentId = ""; - [Key(9)] public BrokkrComponentSnapshot[] components = Array.Empty(); + [Key(9)] public ImmutableArray components = ImmutableArray.Empty; [Key(10)] public string localPosition = ""; [Key(11)] public string localEulerAngles = ""; [Key(12)] public string localScale = ""; @@ -88,7 +105,7 @@ namespace GameCult.Brokkr [Key(1)] public string typeName = ""; [Key(2)] public string assemblyQualifiedName = ""; [Key(3)] public bool enabled; - [Key(4)] public BrokkrSerializedPropertySnapshot[] properties = Array.Empty(); + [Key(4)] public ImmutableArray properties = ImmutableArray.Empty; } [MessagePackObject] From 7c6092bc0a13a71d7586d3e14b3a5eea8a09bf53 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 02:47:07 +0100 Subject: [PATCH 044/223] Blender add-on: one action table (actions.json) decides every intent's fields and undo class run_intent admits through action_table.validate: unknown field, wrong type, enum miss, bound miss, missing required field are 'denied' (admission: nothing ran, no undo step). The entry's changesScene and editModeSafe replace READ_ACTIONS, MUTATING_ACTIONS, NO_SCENE_CHANGE_ACTIONS and EDIT_MODE_SAFE_ACTIONS; the handler is '_' + the action's name, so _dispatch's if-chain, the scene field helpers (number, integer, choice, color), node_actions' text/tree_key/check_idname and the cross-aliases (objectName on scene actions, targetObjectName on node actions, parentName) are gone. New bounds only where nothing was checked: createObject size, lightType/emptyDisplayType enums, resolution minimum 4 (Blender clamps 1..3 silently), the probed panoramaType items, node label 63. Handlers keep scene-dependent refusals (ActionRefused, 'failed'). Parity fixture surfaces/blender/tests/action_cases.json is for brokkr-ctl's validator, which follows. Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/action_table.py | 213 +++++++++++++++ surfaces/blender/brokkr_bridge/actions.json | 144 ++++++++++ .../blender/brokkr_bridge/blender_target.py | 250 ++++++------------ .../blender/brokkr_bridge/node_actions.py | 135 +++------- .../blender/brokkr_bridge/scene_actions.py | 79 +----- surfaces/blender/tests/action_cases.json | 233 ++++++++++++++++ .../blender/tests/live/agent_turn_queue.py | 2 +- .../blender/tests/live/agent_turn_undo.py | 4 +- surfaces/blender/tests/test_action_table.py | 181 +++++++++++++ surfaces/blender/tests/test_agent_turn.py | 15 +- .../blender/tests/test_material_actions.py | 4 +- surfaces/blender/tests/test_node_actions.py | 3 +- surfaces/blender/tests/test_perception.py | 2 +- surfaces/blender/tests/test_scene_actions.py | 76 +++--- 14 files changed, 955 insertions(+), 386 deletions(-) create mode 100644 surfaces/blender/brokkr_bridge/action_table.py create mode 100644 surfaces/blender/brokkr_bridge/actions.json create mode 100644 surfaces/blender/tests/action_cases.json create mode 100644 surfaces/blender/tests/test_action_table.py diff --git a/surfaces/blender/brokkr_bridge/action_table.py b/surfaces/blender/brokkr_bridge/action_table.py new file mode 100644 index 0000000..dafbe9e --- /dev/null +++ b/surfaces/blender/brokkr_bridge/action_table.py @@ -0,0 +1,213 @@ +"""The action table: which Blender intents exist, what fields each may carry, and each action's undo class. + +actions.json (schema brokkr.blender.actions.v0) is the one owner. run_intent admits every intent through +validate(); brokkr-ctl embeds the same file for `send --help` and early refusal, with the same rules and +message text (surfaces/blender/tests/action_cases.json pins the two). Stdlib only, no bpy. + +Vocabulary: null means absent; a required field absent is refused; a field neither declared nor in the +envelope is refused; enums match exactly; number and integer are never bool and always within the declared +minimum and maximum, integer is whole; string may declare minLength, maxLength, chars (a named charset), +prefixes (starts with one and has at least one more character) and forbid (substrings); array declares +items, minItems, maxItems; object with properties is closed and recursive, without is a free map; any is +any non-null value; only {field, in} refuses a field present unless the sibling's value is in the list; +defaults fill absent top-level fields after validation. Scene-dependent rules stay in the handlers. +""" +from __future__ import annotations + +import functools +import json +import math +from pathlib import Path +from typing import Any + +TABLE_PATH = Path(__file__).with_name("actions.json") +SCHEMA = "brokkr.blender.actions.v0" +TYPES = ("string", "number", "integer", "boolean", "array", "object", "any") +TYPE_WORDS = {"string": "a string", "number": "a finite number", "integer": "a whole number", + "boolean": "true or false", "array": "an array", "object": "an object"} + + +class IntentInvalid(ValueError): + """The intent breaks a rule of the table; the message names the field path and the rule.""" + + +class TableInvalid(ValueError): + """actions.json itself is malformed.""" + + +def number_text(value: float) -> str: + """A bound as it is printed in messages: whole values without a fraction, others as the shortest digits.""" + return str(int(value)) if value == int(value) else repr(float(value)) + + +def _list(items: list) -> str: + return ", ".join(items) + + +@functools.lru_cache(maxsize=1) +def _raw() -> dict[str, Any]: + return json.loads(TABLE_PATH.read_text(encoding="utf-8")) + + +@functools.lru_cache(maxsize=1) +def table() -> dict[str, Any]: + """actions.json, loaded and checked once.""" + document = _raw() + check_table(document) + return document + + +def entry(action: Any) -> dict[str, Any] | None: + """The table row for an action name, or None.""" + return _by_name().get(action) if isinstance(action, str) else None + + +@functools.lru_cache(maxsize=1) +def _by_name() -> dict[str, dict[str, Any]]: + return {a["name"]: a for a in table()["actions"]} + + +def check_table(document: dict[str, Any]) -> None: + """Refuse a table with an unbounded number field, an 'only' naming a missing field, an unknown charset, + a default that breaks its own field's rules, or a bound that prints differently in Python and Rust.""" + if document.get("schema") != SCHEMA: + raise TableInvalid(f"table schema must be {SCHEMA}") + charsets = document.get("charsets", {}) + names = set() + for action in document["actions"]: + if action["name"] in names: + raise TableInvalid(f"action {action['name']} is listed twice") + names.add(action["name"]) + fields = {f["name"]: f for f in action["fields"]} + if len(fields) != len(action["fields"]): + raise TableInvalid(f"{action['name']} repeats a field") + for field in action["fields"]: + _check_spec(field, f"{action['name']}.{field['name']}", charsets, fields, top=True) + if "default" in field: + try: + _value(field, field["default"], field["name"]) + except IntentInvalid as error: + raise TableInvalid(f"{action['name']}.{field['name']} default: {error}") from None + + +def _check_spec(spec: dict[str, Any], where: str, charsets: dict, siblings: dict, top: bool) -> None: + kind = spec.get("type") + if kind not in TYPES: + raise TableInvalid(f"{where}: unknown type {kind!r}") + if kind in ("number", "integer"): + for bound in ("minimum", "maximum"): + value = spec.get(bound) + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise TableInvalid(f"{where}: a {kind} field declares {bound}") + if "e" in number_text(value): + raise TableInvalid(f"{where}: {bound} {value} does not print as plain digits") + if "chars" in spec and spec["chars"] not in charsets: + raise TableInvalid(f"{where}: charset {spec['chars']!r} is not defined") + if "only" in spec: + if not top or spec["only"]["field"] not in siblings: + raise TableInvalid(f"{where}: 'only' must name a field of the same action") + if "default" in spec and not top: + raise TableInvalid(f"{where}: only top-level fields have defaults") + if kind == "array": + _check_spec(spec["items"], where + "[]", charsets, siblings, top=False) + if kind == "object" and "properties" in spec: + inner = {p["name"]: p for p in spec["properties"]} + for prop in spec["properties"]: + _check_spec(prop, f"{where}.{prop['name']}", charsets, inner, top=False) + + +def validate(command: dict[str, Any]) -> dict[str, Any]: + """The normalized copy of an intent (nulls dropped, defaults filled), or IntentInvalid naming the rule.""" + action = command.get("action", "") + row = entry(action) + if row is None: + raise IntentInvalid(f"Unsupported Blender command action: {action}") + present = {k: v for k, v in command.items() if v is not None} + _fields(row["fields"], present, None, action, set(table()["envelope"])) + result = dict(present) + for field in row["fields"]: + if field["name"] not in result and "default" in field: + result[field["name"]] = field["default"] + return result + + +def _fields(specs: list[dict[str, Any]], values: dict[str, Any], parent: str | None, where: str, skip: set) -> None: + """The fields of an action (parent None) or of a closed object: unknown names first, sorted, then each + declared field in table order.""" + declared = [s["name"] for s in specs] + for key in sorted(k for k in values if k not in skip and k not in declared): + raise IntentInvalid(f"{where} has no field '{key}'; its fields: {_list(declared) or 'none'}.") + for spec in specs: + path = spec["name"] if parent is None else f"{parent}.{spec['name']}" + value = values.get(spec["name"]) + if value is None: + if spec.get("required"): + raise IntentInvalid(f"{path} is required.") + continue + only = spec.get("only") + if only is not None and values.get(only["field"]) not in only["in"]: + raise IntentInvalid(f"{path} applies only when {only['field']} is one of {_list(only['in'])}.") + _value(spec, value, path) + + +def _value(spec: dict[str, Any], value: Any, path: str) -> None: + kind = spec["type"] + if kind == "any": + return + if kind in ("number", "integer"): + _number(spec, value, path) + elif kind == "string": + if not isinstance(value, str): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if "enum" in spec: + if value not in spec["enum"]: + raise IntentInvalid(f"{path} must be one of {_list(spec['enum'])}.") + else: + _string(spec, value, path) + elif kind == "boolean": + if not isinstance(value, bool): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + elif kind == "array": + if not isinstance(value, list): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if "minItems" in spec and len(value) < spec["minItems"]: + raise IntentInvalid(f"{path} must have at least {spec['minItems']} items.") + if "maxItems" in spec and len(value) > spec["maxItems"]: + raise IntentInvalid(f"{path} must have at most {spec['maxItems']} items.") + for index, item in enumerate(value): + if item is None: + raise IntentInvalid(f"{path}[{index}] must be {TYPE_WORDS.get(spec['items']['type'], 'a value')}.") + _value(spec["items"], item, f"{path}[{index}]") + elif kind == "object": + if not isinstance(value, dict): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if "properties" in spec: + _fields(spec["properties"], {k: v for k, v in value.items() if v is not None}, path, path, frozenset()) + + +def _string(spec: dict[str, Any], value: str, path: str) -> None: + if "minLength" in spec and len(value) < spec["minLength"]: + raise IntentInvalid(f"{path} must have at least {spec['minLength']} characters.") + if "maxLength" in spec and len(value) > spec["maxLength"]: + raise IntentInvalid(f"{path} must have at most {spec['maxLength']} characters.") + if "chars" in spec: + charset = _raw()["charsets"][spec["chars"]] + if any(c not in charset["allowed"] for c in value): + raise IntentInvalid(f"{path} may contain only {charset['text']}.") + if "prefixes" in spec and not any(value.startswith(p) and len(value) > len(p) for p in spec["prefixes"]): + raise IntentInvalid(f"{path} must start with one of {_list(spec['prefixes'])} and have at least one more character.") + for part in spec.get("forbid", ()): + if part in value: + raise IntentInvalid(f"{path} may not contain '{part}'.") + + +def _number(spec: dict[str, Any], value: Any, path: str) -> None: + kind = spec["type"] + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if isinstance(value, float) and not math.isfinite(value): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if kind == "integer" and isinstance(value, float) and value != int(value): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if not spec["minimum"] <= value <= spec["maximum"]: + raise IntentInvalid(f"{path} must be between {number_text(spec['minimum'])} and {number_text(spec['maximum'])}.") diff --git a/surfaces/blender/brokkr_bridge/actions.json b/surfaces/blender/brokkr_bridge/actions.json new file mode 100644 index 0000000..a605e01 --- /dev/null +++ b/surfaces/blender/brokkr_bridge/actions.json @@ -0,0 +1,144 @@ +{ + "schema": "brokkr.blender.actions.v0", + "envelope": ["schema", "commandId", "action", "requestedBy", "note"], + "charsets": { + "id": {"allowed": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-", "text": "letters, digits, '.', '_' or '-'"}, + "key": {"allowed": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ._-", "text": "letters, digits, space, '.', '_' or '-'"}, + "alnum": {"allowed": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "text": "letters and digits"} + }, + "actions": [ + {"name": "createObject", "doc": "Add an object at a location; a MESH is a cube.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "objectType", "type": "string", "enum": ["MESH", "LIGHT", "CAMERA", "EMPTY"], "default": "EMPTY"}, + {"name": "name", "type": "string"}, + {"name": "location", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z]"}, + {"name": "size", "type": "number", "minimum": 0.001, "maximum": 1000000, "default": 1, "doc": "cube size, used by MESH"}, + {"name": "meshType", "type": "string", "enum": ["CUBE"], "only": {"field": "objectType", "in": ["MESH"]}}, + {"name": "lightType", "type": "string", "enum": ["POINT", "SUN", "SPOT", "AREA"], "default": "POINT", "only": {"field": "objectType", "in": ["LIGHT"]}}, + {"name": "emptyDisplayType", "type": "string", "enum": ["PLAIN_AXES", "ARROWS", "SINGLE_ARROW", "CIRCLE", "CUBE", "SPHERE", "CONE", "IMAGE"], "default": "PLAIN_AXES", "only": {"field": "objectType", "in": ["EMPTY"]}} + ]}, + {"name": "deleteObject", "doc": "Delete an object.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"} + ]}, + {"name": "setObjectTransform", "doc": "Set any of an object's location, rotation and scale.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "location", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z]"}, + {"name": "rotationEuler", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z] radians"}, + {"name": "scale", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z]"} + ]}, + {"name": "setObjectVisibility", "doc": "Show or hide an object in the viewport and in renders.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "visible", "type": "boolean", "default": true} + ]}, + {"name": "setObjectParent", "doc": "Parent an object to another.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "parentObjectName", "type": "string", "doc": "empty or absent clears the parent"} + ]}, + {"name": "setObjectCustomProperty", "doc": "Set one custom property on an object.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "propertyName", "type": "string", "default": "brokkrValue"}, + {"name": "value", "type": "any", "required": true, "doc": "any JSON value Blender accepts as a property"} + ]}, + {"name": "selectObject", "doc": "Select an object and make it active.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "clearSelection", "type": "boolean", "default": true} + ]}, + {"name": "assignMaterial", "doc": "Assign a material (created when new) to an object's slots.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "materialName", "type": "string", "default": "Brokkr Material"}, + {"name": "color", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}, "minItems": 3, "maxItems": 4, "doc": "[r,g,b] or [r,g,b,a], linear; alpha defaults to 1"} + ]}, + {"name": "importGltf", "doc": "Import a .gltf or .glb from the add-on's import directory.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "filepath", "type": "string", "required": true, "doc": "relative to the add-on's import directory"} + ]}, + {"name": "exportGltf", "doc": "Write the scene, or the named objects, as .glb or .gltf into the output directory.", "changesScene": false, "editModeSafe": false, "fields": [ + {"name": "filepath", "type": "string", "required": true, "doc": ".glb or .gltf relative to the add-on's output directory"}, + {"name": "extras", "type": "boolean", "default": true}, + {"name": "yUp", "type": "boolean", "default": true}, + {"name": "applyModifiers", "type": "boolean", "default": true}, + {"name": "selection", "type": "array", "items": {"type": "string", "minLength": 1}, "minItems": 1, "doc": "object names; the whole scene when absent"} + ]}, + {"name": "setCamera", "doc": "Change a camera's lens, projection and clipping.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "lens", "type": "number", "minimum": 1, "maximum": 5000, "doc": "mm"}, + {"name": "cameraType", "type": "string", "enum": ["PERSP", "ORTHO", "PANO"]}, + {"name": "orthoScale", "type": "number", "minimum": 0.001, "maximum": 100000}, + {"name": "clipStart", "type": "number", "minimum": 0.0001, "maximum": 1000000}, + {"name": "clipEnd", "type": "number", "minimum": 0.001, "maximum": 10000000}, + {"name": "panoramaType", "type": "string", "enum": ["EQUIRECTANGULAR", "EQUIANGULAR_CUBEMAP_FACE", "MIRRORBALL", "FISHEYE_EQUIDISTANT", "FISHEYE_EQUISOLID", "FISHEYE_LENS_POLYNOMIAL", "CENTRAL_CYLINDRICAL"]}, + {"name": "active", "type": "boolean", "doc": "true makes it the scene camera"} + ]}, + {"name": "setLight", "doc": "Change a light's energy, colour and type.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "energy", "type": "number", "minimum": 0, "maximum": 10000000}, + {"name": "color", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}, "minItems": 3, "maxItems": 3, "doc": "[r,g,b] linear"}, + {"name": "lightType", "type": "string", "enum": ["POINT", "SUN", "SPOT", "AREA"]} + ]}, + {"name": "setWorld", "doc": "Edit the world's Background node; a world is created when there is none.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "worldName", "type": "string", "doc": "default: the scene's world"}, + {"name": "color", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}, "minItems": 3, "maxItems": 3, "doc": "[r,g,b] linear"}, + {"name": "strength", "type": "number", "minimum": 0, "maximum": 1000000} + ]}, + {"name": "renderStill", "doc": "Render the scene to a still in the output directory; settings are restored afterwards.", "changesScene": false, "editModeSafe": true, "fields": [ + {"name": "outputPath", "type": "string", "required": true, "doc": ".png, .jpg or .exr relative to the add-on's output directory"}, + {"name": "engine", "type": "string", "minLength": 1, "doc": "a render engine identifier of the running Blender"}, + {"name": "resolutionX", "type": "integer", "minimum": 4, "maximum": 16384}, + {"name": "resolutionY", "type": "integer", "minimum": 4, "maximum": 16384}, + {"name": "cameraName", "type": "string"} + ]}, + {"name": "look", "doc": "Capture the 3D view she is looking at; the receipt carries lookPath.", "changesScene": false, "editModeSafe": true, "fields": [ + ]}, + {"name": "createNodeGroup", "doc": "Create a geometry node group with an interface.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "interface", "type": "array", "required": true, "minItems": 1, "maxItems": 64, "items": {"type": "object", "properties": [{"name": "inOut", "type": "string", "required": true, "enum": ["INPUT", "OUTPUT"]}, {"name": "name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, {"name": "type", "type": "string", "required": true, "enum": ["Geometry", "Float", "Int", "Bool", "Vector"]}, {"name": "default", "type": "any", "doc": "a value of the socket's type"}]}, "doc": "sockets: {inOut, name, type, default?}"} + ]}, + {"name": "addNode", "doc": "Add a node to a geometry node group.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "id", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true, "doc": "brokkr's key for the node"}, + {"name": "blIdname", "type": "string", "required": true, "chars": "alnum", "prefixes": ["GeometryNode", "FunctionNode", "ShaderNode"], "forbid": ["Import", "Export", "Script", "Bake", "Group", "Simulation", "Repeat", "Foreach", "Viewer", "TexImage", "TexEnvironment", "ImageTexture", "InputImage", "TexIES"], "doc": "Blender's node type; file, script, cache, group and image nodes are refused"}, + {"name": "location", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 2, "maxItems": 2, "default": [0, 0], "doc": "[x,y]"}, + {"name": "label", "type": "string", "maxLength": 63}, + {"name": "properties", "type": "object", "doc": "enum, bool, int or float node settings"}, + {"name": "inputs", "type": "object", "doc": "unlinked input defaults"} + ]}, + {"name": "removeNode", "doc": "Remove a node and its links.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "id", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true} + ]}, + {"name": "linkSockets", "doc": "Link one node's output socket to another's input.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "fromNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true}, + {"name": "fromSocket", "type": "string", "required": true, "doc": "identifier or unique name"}, + {"name": "toNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true}, + {"name": "toSocket", "type": "string", "required": true, "doc": "identifier or unique name"} + ]}, + {"name": "unlinkSockets", "doc": "Remove the links into an input socket, or only the one from a named output.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "toNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true}, + {"name": "toSocket", "type": "string", "required": true}, + {"name": "fromNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "doc": "with fromSocket: remove only that link"}, + {"name": "fromSocket", "type": "string"} + ]}, + {"name": "addModifier", "doc": "Add or retarget a Geometry Nodes modifier on an object.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "objectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "modifierType", "type": "string", "enum": ["NODES"], "default": "NODES"}, + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "modifierName", "type": "string", "chars": "key", "minLength": 1, "maxLength": 63, "default": "Brokkr GeoNodes"} + ]}, + {"name": "removeModifier", "doc": "Remove a Geometry Nodes modifier from an object.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "objectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "modifierName", "type": "string", "minLength": 1, "maxLength": 255, "forbid": ["\u0000"], "default": "Brokkr GeoNodes"} + ]}, + {"name": "setModifierInput", "doc": "Set one exposed input of a Geometry Nodes modifier.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "objectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "modifierName", "type": "string", "default": "Brokkr GeoNodes"}, + {"name": "socket", "type": "string", "required": true, "doc": "identifier or unique interface name"}, + {"name": "value", "type": "any", "required": true, "doc": "Float, Int, Bool or Vector"} + ]} + ] +} diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 0bc72b3..fab5357 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -25,6 +25,7 @@ if os.name == "nt": else: import fcntl +from . import action_table as at from . import node_actions as na from . import scene_actions as sa from .server_guard import BindRefused, SessionGuard, check_bind, guarded_server_class, is_loopback_host, stop_pending @@ -49,8 +50,6 @@ SYNC_VAR_SCHEMA = "brokkr.sync.var.v0" SYNC_TIMELINE_BINDING_SCHEMA = "brokkr.sync.timeline_binding.v0" SYNC_RECEIPT_SCHEMA = "brokkr.sync.receipt.v0" -CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY") - # Engines that draw through the GL stack. A headless Blender with no usable GL device aborts the whole # process inside bpy.ops.render.render for these (no receipt); CYCLES renders on the CPU. Whether it # will is found by rendering one pixel in a child Blender (gl_render_failure), not by guessing at libraries. @@ -60,20 +59,6 @@ EXPORT_STAGE_PREFIX = ".brokkr-export-" STAGE_LOCK = ".brokkr-lock" STAGE_JOURNAL = ".brokkr-journal" -# Actions that only read the scene and so push no undo step. -READ_ACTIONS = ("look",) -MUTATING_ACTIONS = ( - "createObject", "deleteObject", "setObjectTransform", "setObjectVisibility", "setObjectParent", - "setObjectCustomProperty", "selectObject", "assignMaterial", "importGltf", "exportGltf", - "setCamera", "setLight", "setWorld", "renderStill", -) -# Actions that change no scene state: they push no undo step (exportGltf restores its selection; -# renderStill restores its settings). -NO_SCENE_CHANGE_ACTIONS = ("exportGltf", "renderStill") -# While an object is in Edit Mode, undo steps are edit-mesh steps, so a scene write is not reverted by -# one undo, and some operators leave Edit Mode (brokkr-live:ruling:object-intents-refused-in-edit-mode). -# Anything that writes scene state or changes her mode is refused; renderStill and look do neither. -EDIT_MODE_SAFE_ACTIONS = ("renderStill", "look") LOOK_DIR = "look" # under the output directory: scratch captures named by command id (brush-tree:ruling:look-files-are-scratch) LOOK_KEPT = 20 # the newest captures that stay after each look EDIT_SELECTION_CAP = 4096 # indices listed per element kind and object; the total stays true beside the list @@ -636,29 +621,40 @@ class BrokkrBlenderTarget: } def run_intent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - """The one agent turn: admit, run with operator undo off, push one labelled undo step, receipt.""" + """The one agent turn: admit, run with operator undo off, push one labelled undo step, receipt. + + Admission order: commandId shape, id unused, requestedBy, then the action table (action known, fields + valid), then Edit Mode. While an object is in Edit Mode undo steps are edit-mesh steps, so a scene write + is not reverted by one undo and some operators leave Edit Mode + (brokkr-live:ruling:object-intents-refused-in-edit-mode); the table's editModeSafe actions write nothing + and change no mode. A refusal at admission is 'denied': nothing ran, no undo step.""" command_id = command.get("commandId") requested_by = command.get("requestedBy") action = command.get("action", "") denial = "" + row = None if not _valid_command_id(command_id): denial = "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'." elif command_id in self._receipted: denial = f"commandId {command_id!r} was already receipted; ids are single-use." elif not isinstance(requested_by, str) or not REQUESTED_BY_SHAPE.fullmatch(requested_by): denial = "Intent has no requestedBy of the form '/'." - elif action not in MUTATING_ACTIONS and action not in READ_ACTIONS and action not in na.NodeActions.ACTIONS: - denial = f"Unsupported Blender command action: {action}" - elif action not in EDIT_MODE_SAFE_ACTIONS and self._edit_mode_object() is not None: - denial = (f"Object {self._edit_mode_object()!r} is in Edit Mode: object-level intents are refused " - "until she leaves it; nothing was changed.") + else: + try: + command = at.validate(command) + row = at.entry(action) + except at.IntentInvalid as error: + denial = str(error) + if not denial and not row["editModeSafe"] and self._edit_mode_object() is not None: + denial = (f"Object {self._edit_mode_object()!r} is in Edit Mode: object-level intents are refused " + "until she leaves it; nothing was changed.") if denial: if _valid_command_id(command_id): self._receipted.add(command_id) return self._receipt(command, "denied", denial, "") label = f"Brokkr {requested_by}: {action} {command_id[-8:]}" # the tail: uuid v7 ids lead with a timestamp, one value per minute - push = action not in READ_ACTIONS and action not in NO_SCENE_CHANGE_ACTIONS + push = row["changesScene"] self.agent_turn = True self._wrote = True try: @@ -700,108 +696,70 @@ class BrokkrBlenderTarget: self.bpy.ops.ed.undo_push(message=label) def _dispatch(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - """The action table. Only run_intent calls it; it owns refusal, failure and the undo step.""" - action = command.get("action", "") - if action == "createObject": - return self._create_object(context, command) - if action == "deleteObject": - return self._delete_object(context, command) - if action == "setObjectTransform": - return self._set_object_transform(context, command) - if action == "setObjectVisibility": - return self._set_object_visibility(context, command) - if action == "setObjectParent": - return self._set_object_parent(context, command) - if action == "setObjectCustomProperty": - return self._set_object_custom_property(context, command) - if action == "selectObject": - return self._select_object(context, command) - if action == "assignMaterial": - return self._assign_material(context, command) - if action == "importGltf": - return self._import_gltf(context, command) - if action == "exportGltf": - return self._export_gltf(context, command) - if action == "setCamera": - return self._set_camera(context, command) - if action == "setLight": - return self._set_light(context, command) - if action == "setWorld": - return self._set_world(context, command) - if action == "renderStill": - return self._render_still(context, command) - if action == "look": - return self._look(context, command) - if action in na.NodeActions.ACTIONS: + """Only run_intent calls it, with an intent the table admitted: the handler is '_' + the action's name, + on NodeActions for the node actions and on this target for the rest. It owns refusal, failure and the undo step.""" + action = command["action"] + if hasattr(self.nodes, "_" + action): message, name = self.nodes.execute(action, command) self._wrote = self.nodes.changed return self._receipt(command, "accepted", message, name) - return self._receipt(command, "failed", f"Unsupported Blender command action: {action}", "") + return getattr(self, "_" + action)(context, command) - def _create_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - object_type = command.get("objectType", "EMPTY") - if not isinstance(object_type, str) or object_type not in CREATABLE_OBJECT_TYPES: - shown = object_type if isinstance(object_type, str) else repr(object_type) - raise sa.ActionRefused( - f"objectType {shown!r} cannot be created; allowed: {', '.join(CREATABLE_OBJECT_TYPES)}.") - mesh_type = command.get("meshType") - if mesh_type is not None and object_type != "MESH": - raise sa.ActionRefused(f"meshType applies only to objectType MESH, not {object_type}.") - if mesh_type is not None and (not isinstance(mesh_type, str) or mesh_type.upper() != "CUBE"): - raise sa.ActionRefused(f"meshType {mesh_type!r} is not available; a MESH is a CUBE.") + def _createObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + object_type = command["objectType"] name = command.get("name") or f"Brokkr {object_type.title()}" - location = _vector(command.get("location"), 3, (0.0, 0.0, 0.0)) + location = tuple(command.get("location") or (0.0, 0.0, 0.0)) if object_type == "MESH": - self.bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, size=float(command.get("size", 1.0)), location=location) + self.bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, size=float(command["size"]), location=location) elif object_type == "LIGHT": - self.bpy.ops.object.light_add("EXEC_DEFAULT", False, type=command.get("lightType", "POINT"), location=location) + self.bpy.ops.object.light_add("EXEC_DEFAULT", False, type=command["lightType"], location=location) elif object_type == "CAMERA": self.bpy.ops.object.camera_add("EXEC_DEFAULT", False, location=location) else: # EMPTY - self.bpy.ops.object.empty_add("EXEC_DEFAULT", False, type=command.get("emptyDisplayType", "PLAIN_AXES"), location=location) + self.bpy.ops.object.empty_add("EXEC_DEFAULT", False, type=command["emptyDisplayType"], location=location) obj = context.object obj.name = name return self._receipt(command, "accepted", "Blender object created.", obj.name) - def _delete_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _deleteObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") self.bpy.data.objects.remove(obj, do_unlink=True) return self._receipt(command, "accepted", "Blender object deleted.", command.get("targetObjectName", "")) - def _set_object_transform(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setObjectTransform(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") if "location" in command: - obj.location = _vector(command["location"], 3, obj.location) + obj.location = tuple(command["location"]) if "rotationEuler" in command: - obj.rotation_euler = _vector(command["rotationEuler"], 3, obj.rotation_euler) + obj.rotation_euler = tuple(command["rotationEuler"]) if "scale" in command: - obj.scale = _vector(command["scale"], 3, obj.scale) + obj.scale = tuple(command["scale"]) return self._receipt(command, "accepted", "Blender object transform updated.", obj.name) - def _set_object_visibility(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setObjectVisibility(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") - visible = bool(command.get("visible", True)) + visible = command["visible"] obj.hide_viewport = not visible obj.hide_render = not visible return self._receipt(command, "accepted", "Blender object visibility updated.", obj.name) - def _set_object_parent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setObjectParent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") - parent_name = command.get("parentObjectName") or command.get("parentName") or "" + parent_name = command.get("parentObjectName") or "" parent = self.bpy.data.objects.get(parent_name) if parent_name else None if parent_name and parent is None: return self._receipt(command, "failed", f"Parent Blender object was not found: {parent_name}", obj.name) @@ -809,42 +767,43 @@ class BrokkrBlenderTarget: obj.parent = parent return self._receipt(command, "accepted", "Blender object parent updated.", obj.name) - def _set_object_custom_property(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setObjectCustomProperty(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") - property_name = command.get("propertyName") or "brokkrValue" + property_name = command["propertyName"] if property_name.startswith("customProperties."): property_name = property_name[len("customProperties."):] modifier_name = na.drives_modifier_input(obj, property_name) if modifier_name: return self._receipt(command, "failed", f"{property_name!r} is an input of Geometry Nodes modifier {modifier_name!r}; " "a custom property does not drive it, use setModifierInput.", obj.name) - obj[property_name] = command.get("value") + obj[property_name] = command["value"] return self._receipt(command, "accepted", "Blender custom property updated.", obj.name) - def _select_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _selectObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") - if command.get("clearSelection", True): + if command["clearSelection"]: for existing in context.selected_objects: existing.select_set(False) obj.select_set(True) context.view_layer.objects.active = obj return self._receipt(command, "accepted", "Blender object selected.", obj.name) - def _assign_material(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _assignMaterial(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") if not (obj.data and hasattr(obj.data, "materials")): return self._receipt(command, "failed", "Target object cannot receive materials.", obj.name) - rgba = sa.color_rgba(command) # refused before anything is created or changed - material_name = command.get("materialName") or "Brokkr Material" + color = command.get("color") + rgba = (*color, 1.0)[:4] if color is not None else None # the table admits [r,g,b] or [r,g,b,a] + material_name = command["materialName"] material = self.bpy.data.materials.get(material_name) or self.bpy.data.materials.new(material_name) if rgba is not None: if not material.use_nodes or material.node_tree is None: @@ -858,8 +817,8 @@ class BrokkrBlenderTarget: obj.data.materials.append(material) return self._receipt(command, "accepted", "Blender material assigned.", obj.name) - def _import_gltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - name = str(command.get("filepath") or "") + def _importGltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + name = command["filepath"] path = sa.resolve_inside(self.import_dir, name, "import") sa.require_gltf(path) stamped = sa.fingerprint([path]) # before the parse, so a swap during it shows @@ -877,28 +836,19 @@ class BrokkrBlenderTarget: added = sorted(set(self.bpy.data.objects.keys()) - before) return self._receipt(command, "accepted", f"Imported {len(added)} object(s) from {path.name}.", added[0] if added else "") - def _export_gltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _exportGltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: """Write the scene (or the named objects) as .glb or .gltf under the output directory.""" - name = command.get("filepath") - if not isinstance(name, str): - raise sa.ActionRefused("filepath must be a string.") + name = command["filepath"] if self.output_dir: _sweep_stale_stages(Path(self.output_dir).resolve()) path = sa.resolve_inside(self.output_dir, name, "output", new_file=True) suffix = path.suffix.lower() if suffix not in sa.GLTF_EXTENSIONS: raise sa.ActionRefused(f"Export path must end in {' or '.join(sa.GLTF_EXTENSIONS)}.") - options = {} - for field, key in (("extras", "export_extras"), ("yUp", "export_yup"), ("applyModifiers", "export_apply")): - value = command.get(field, True) - if not isinstance(value, bool): - raise sa.ActionRefused(f"{field} must be true or false.") - options[key] = value + options = {"export_extras": command["extras"], "export_yup": command["yUp"], "export_apply": command["applyModifiers"]} names = command.get("selection") chosen = [] if names is not None: - if not isinstance(names, list) or not names or not all(isinstance(n, str) and n for n in names): - raise sa.ActionRefused("selection must be a non-empty list of object names.") missing = [n for n in names if n not in self.bpy.data.objects] if missing: raise sa.ActionRefused(f"Selection object was not found: {missing[0]}") @@ -1002,58 +952,40 @@ class BrokkrBlenderTarget: raise sa.ActionRefused(f"Target Blender object is not a {object_type}.") return obj - def _set_camera(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setCamera(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_typed(command, "CAMERA") camera = obj.data - # Validate everything before changing anything, so a refused intent leaves the camera alone. - lens = sa.number(command, "lens", 1.0, sa.MAX_LENS_MM) - camera_type = sa.choice(command, "cameraType", sa.CAMERA_TYPES) - ortho_scale = sa.number(command, "orthoScale", 0.001, 100000.0) - clip_start = sa.number(command, "clipStart", 0.0001, 1.0e6) - clip_end = sa.number(command, "clipEnd", 0.001, 1.0e7) - panorama_type = sa.choice(command, "panoramaType", self._panorama_types(camera)) - if lens is not None: - camera.lens = lens - if camera_type is not None: - camera.type = camera_type - if ortho_scale is not None: - camera.ortho_scale = ortho_scale - if clip_start is not None: - camera.clip_start = clip_start - if clip_end is not None: - camera.clip_end = clip_end - if panorama_type is not None: - # Blender 4.2 moved panorama_type from camera.cycles to the camera itself. - holder = camera if hasattr(camera, "panorama_type") else camera.cycles - holder.panorama_type = panorama_type + # Nothing below can be refused: the table checked every value, so a camera is never half set. + if "lens" in command: + camera.lens = command["lens"] + if "cameraType" in command: + camera.type = command["cameraType"] + if "orthoScale" in command: + camera.ortho_scale = command["orthoScale"] + if "clipStart" in command: + camera.clip_start = command["clipStart"] + if "clipEnd" in command: + camera.clip_end = command["clipEnd"] + if "panoramaType" in command: + camera.panorama_type = command["panoramaType"] # on the camera since Blender 4.2 if command.get("active"): context.scene.camera = obj return self._receipt(command, "accepted", "Blender camera updated.", obj.name) - def _panorama_types(self, camera: Any) -> tuple[str, ...]: - holder = camera if hasattr(camera, "panorama_type") else getattr(camera, "cycles", camera) - try: - return tuple(item.identifier for item in holder.bl_rna.properties["panorama_type"].enum_items) - except (KeyError, AttributeError): - return ("EQUIRECTANGULAR", "EQUIDISTANT", "FISHEYE_EQUISOLID", "MIRRORBALL") - - def _set_light(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setLight(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_typed(command, "LIGHT") - energy = sa.number(command, "energy", 0.0, 1.0e7) - light_color = sa.color(command) - light_type = sa.choice(command, "lightType", sa.LIGHT_TYPES) - if energy is not None: - obj.data.energy = energy - if light_color is not None: - obj.data.color = light_color - if light_type is not None: - obj.data.type = light_type + if "energy" in command: + obj.data.energy = command["energy"] + if "color" in command: + obj.data.color = tuple(command["color"]) + if "lightType" in command: + obj.data.type = command["lightType"] return self._receipt(command, "accepted", "Blender light updated.", obj.name) - def _set_world(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - world_color = sa.color(command) - strength = sa.number(command, "strength", 0.0, 1.0e6) - name = str(command.get("worldName") or "") + def _setWorld(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + world_color = command.get("color") + strength = command.get("strength") + name = command.get("worldName") or "" scene = context.scene world = self.bpy.data.worlds.get(name) if name else scene.world if world is None: @@ -1069,22 +1001,19 @@ class BrokkrBlenderTarget: background.inputs["Strength"].default_value = strength return self._receipt(command, "accepted", "Blender world updated.", world.name) - def _render_still(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _renderStill(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: scene = context.scene render = scene.render - name = str(command.get("outputPath") or "") + name = command["outputPath"] path = sa.resolve_inside(self.output_dir, name, "output", new_file=True) file_format = sa.still_format(path) # The engine enum is dynamic (Cycles and add-on engines register at runtime), and RNA's # enum_items on a dynamic enum lists only its static defaults, so the running Blender is # asked by assignment below and a TypeError there is the refusal. - engine = command.get("engine") - if engine is not None and (not isinstance(engine, str) or not engine.strip()): - raise sa.ActionRefused("engine must be a render engine identifier.") - engine = engine.strip().upper() if engine else None - width = sa.integer(command, "resolutionX", 1, sa.MAX_RESOLUTION) - height = sa.integer(command, "resolutionY", 1, sa.MAX_RESOLUTION) - camera_name = str(command.get("cameraName") or "") + engine = command.get("engine") # an identifier, exactly as given: a name Blender does not have is a TypeError below + width = command.get("resolutionX") + height = command.get("resolutionY") + camera_name = command.get("cameraName") or "" camera = None if camera_name: camera = self.bpy.data.objects.get(camera_name) @@ -1301,7 +1230,7 @@ class BrokkrBlenderTarget: os.unlink(old) def _resolve_object(self, command: dict[str, Any]) -> Any: - name = command.get("targetObjectName") or command.get("objectName") + name = command.get("targetObjectName") return self.bpy.data.objects.get(name) if name else None def _scene_snapshot(self, scene: Any) -> dict[str, Any]: @@ -1742,15 +1671,6 @@ def _valid_command_id(value: Any) -> bool: return isinstance(value, str) and COMMAND_ID_SHAPE.fullmatch(value) is not None -def _vector(value: Any, size: int, fallback: Any) -> tuple[float, ...]: - if value is None: - return tuple(float(item) for item in fallback) - result = [float(item) for item in value[:size]] - while len(result) < size: - result.append(0.0) - return tuple(result) - - def _jsonable(value: Any) -> Any: if value is None or isinstance(value, (str, int, float, bool)): if isinstance(value, float) and not math.isfinite(value): diff --git a/surfaces/blender/brokkr_bridge/node_actions.py b/surfaces/blender/brokkr_bridge/node_actions.py index 389a536..3d856bc 100644 --- a/surfaces/blender/brokkr_bridge/node_actions.py +++ b/surfaces/blender/brokkr_bridge/node_actions.py @@ -1,33 +1,23 @@ """Geometry node graph command actions: createNodeGroup, addNode, linkSockets, addModifier, setModifierInput. Owner of how an intent becomes a node group, a node, a link or a modifier input on Blender 5.2. -Validation is plain Python and runs before bpy is touched; apply steps that can still fail after +Field shape is action_table's and arrives validated; apply steps that can still fail after Blender has been asked (an unknown node type, an enum that is not offered) undo what they made, so a refused intent leaves the tree as it was. Docs: docs/node-actions.md. The design is PR #3 (branch libby/blender-node-graphs-design). """ from __future__ import annotations import math -import re from typing import Any from .scene_actions import ActionRefused -ID_PATTERN = re.compile(r"[A-Za-z0-9._-]{1,63}") -KEY_PATTERN = re.compile(r"[A-Za-z0-9 ._-]{1,63}") -# A geometry tree may hold geometry, function and shader math nodes. Nodes that read or write files, -# run code, write caches, nest groups or sample images are not part of this cut. -NODE_IDNAME = re.compile(r"(GeometryNode|FunctionNode|ShaderNode)[A-Za-z0-9]+") -NODE_DENIED = ("Import", "Export", "Script", "Bake", "Group", "Simulation", "Repeat", "Foreach", "Viewer", "TexImage", "TexEnvironment", - "ImageTexture", "InputImage", "TexIES") MAX_NODES = 500 -MAX_INTERFACE = 64 MAX_MODIFIERS = 8 MAX_VALUE = 1.0e9 MAX_INT = 4096 # counts, levels and sizes multiply: a 4096 x 4096 grid is the ceiling SOCKET_TYPES = {"Geometry": "NodeSocketGeometry", "Float": "NodeSocketFloat", "Int": "NodeSocketInt", "Bool": "NodeSocketBool", "Vector": "NodeSocketVector"} -IN_OUT = {"INPUT", "OUTPUT"} # Node properties that are not node settings, or that make a node reach outside the tree. NODE_PROPERTY_DENIED = frozenset({"name", "label", "location", "width", "height", "parent", "node_tree", "select", "mute", "hide", "show_options", "show_preview", "show_texture", "use_custom_color", @@ -37,24 +27,6 @@ NODE_PROPERTY_DENIED = frozenset({"name", "label", "location", "width", "height" SETTABLE_PROPERTY_TYPES = ("ENUM", "BOOLEAN", "INT", "FLOAT") -def text(command: dict[str, Any], key: str, pattern: re.Pattern, label: str, *, required: bool = True) -> str: - value = command.get(key) - if value is None or value == "": - if required: - raise ActionRefused(f"{label} is required.") - return "" - if not isinstance(value, str) or not pattern.fullmatch(value): - raise ActionRefused(f"{label} must be 1..63 characters of letters, digits, space, '.', '_' or '-'.") - return value - - -def tree_key(command: dict[str, Any]) -> str: - kind = command.get("treeKind", "geometry") - if kind != "geometry": - raise ActionRefused(f"treeKind {kind!r} is not supported; only 'geometry'.") - return text(command, "treeKey", KEY_PATTERN, "treeKey") - - def finite(value: Any, label: str) -> float: if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or abs(value) > MAX_VALUE: raise ActionRefused(f"{label} must be a finite number within +-{MAX_VALUE:g}.") @@ -82,34 +54,19 @@ def typed_value(value: Any, kind: str, label: str) -> Any: raise ActionRefused(f"{label}: socket type {kind} cannot be set by an intent.") -def check_idname(idname: Any) -> str: - if not isinstance(idname, str) or not NODE_IDNAME.fullmatch(idname): - raise ActionRefused("blIdname must be a GeometryNode*, FunctionNode* or ShaderNode* type.") - for denied in NODE_DENIED: - if denied in idname: - raise ActionRefused(f"node type {idname} is not allowed in this cut ({denied}).") - return idname - - -def check_interface(items: Any) -> list[dict[str, str]]: - if not isinstance(items, list) or not items or len(items) > MAX_INTERFACE: - raise ActionRefused(f"interface must be a list of 1..{MAX_INTERFACE} sockets.") +def check_interface(items: list[dict[str, Any]]) -> list[dict[str, Any]]: + """The interface as the table admitted it, minus what only a typed read can judge: a repeated (inOut, name) + and a default that does not fit its socket type.""" seen: set[tuple[str, str]] = set() result = [] for i, item in enumerate(items): - if not isinstance(item, dict): - raise ActionRefused(f"interface[{i}] must be an object.") - in_out = str(item.get("inOut", "")).upper() - name = item.get("name") - socket_type = item.get("type") - if in_out not in IN_OUT or not isinstance(name, str) or not name or len(name) > 63 or socket_type not in SOCKET_TYPES: - raise ActionRefused(f"interface[{i}] needs inOut INPUT|OUTPUT, a name and a type of {sorted(SOCKET_TYPES)}.") - if (in_out, name) in seen: - raise ActionRefused(f"interface[{i}] repeats {in_out} socket {name!r}.") - seen.add((in_out, name)) - entry = {"inOut": in_out, "name": name, "type": socket_type} + key = (item["inOut"], item["name"]) + if key in seen: + raise ActionRefused(f"interface[{i}] repeats {key[0]} socket {key[1]!r}.") + seen.add(key) + entry = dict(item) if "default" in item: - entry["default"] = typed_value(item["default"], socket_type, f"interface[{i}].default") + entry["default"] = typed_value(item["default"], item["type"], f"interface[{i}].default") result.append(entry) return result @@ -117,8 +74,6 @@ def check_interface(items: Any) -> list[dict[str, str]]: class NodeActions: """Applies the node-graph actions to a bpy module. Stateless: every lookup goes to bpy.data.""" - ACTIONS = ("createNodeGroup", "addNode", "removeNode", "linkSockets", "unlinkSockets", "addModifier", "removeModifier", "setModifierInput") - def __init__(self, bpy_module: Any): self.bpy = bpy_module self.changed = False # whether the last execute wrote anything: an absent-target removal does not @@ -159,8 +114,8 @@ class NodeActions: # actions def _createNodeGroup(self, command: dict[str, Any]) -> tuple[str, str]: - key = tree_key(command) - interface = check_interface(command.get("interface")) + key = command["treeKey"] + interface = check_interface(command["interface"]) existing = self.bpy.data.node_groups.get(key) if existing is not None: raise ActionRefused(f"Node group {key!r} already exists.") @@ -181,17 +136,12 @@ class NodeActions: return "Created node group; interface identifiers: " + ", ".join(made), tree.name def _addNode(self, command: dict[str, Any]) -> tuple[str, str]: - tree = self._tree(tree_key(command)) - node_id = text(command, "id", ID_PATTERN, "id") - idname = check_idname(command.get("blIdname")) - location = command.get("location", [0, 0]) - if not isinstance(location, (list, tuple)) or len(location) != 2: - raise ActionRefused("location must be two numbers.") - location = [finite(part, "location") for part in location] - properties = command.get("properties") or {} - inputs = command.get("inputs") or {} - if not isinstance(properties, dict) or not isinstance(inputs, dict): - raise ActionRefused("properties and inputs must be objects.") + tree = self._tree(command["treeKey"]) + node_id = command["id"] + idname = command["blIdname"] + location = list(command["location"]) + properties = command.get("properties", {}) + inputs = command.get("inputs", {}) if any(n.get("brokkr_id") == node_id for n in tree.nodes): raise ActionRefused(f"Node id {node_id!r} already exists in {tree.name!r}.") if len(tree.nodes) >= MAX_NODES: @@ -204,7 +154,7 @@ class NodeActions: node["brokkr_id"] = node_id node.location = location if command.get("label"): - node.label = str(command["label"])[:63] + node.label = command["label"] for name, value in properties.items(): # node settings first: they decide which sockets exist self._set_property(node, name, value) for name, value in inputs.items(): @@ -232,8 +182,8 @@ class NodeActions: raise ActionRefused(f"property {name!r} cannot be {value!r}: {error}") from None def _removeNode(self, command: dict[str, Any]) -> tuple[str, str]: - tree = self._tree(tree_key(command)) - node_id = text(command, "id", ID_PATTERN, "id") + tree = self._tree(command["treeKey"]) + node_id = command["id"] if node_id in ("gin", "gout"): raise ActionRefused(f"{node_id!r} is the group's own input/output node and stays.") node = next((n for n in tree.nodes if n.get("brokkr_id") == node_id), None) @@ -244,13 +194,15 @@ class NodeActions: return "Node removed.", node_id def _unlinkSockets(self, command: dict[str, Any]) -> tuple[str, str]: - tree = self._tree(tree_key(command)) - target = self._node(tree, text(command, "toNode", ID_PATTERN, "toNode")) - into = self._socket(target.inputs, str(command.get("toSocket", "")), "toSocket") + tree = self._tree(command["treeKey"]) + target = self._node(tree, command["toNode"]) + into = self._socket(target.inputs, command["toSocket"], "toSocket") source = out = None - if command.get("fromNode") or command.get("fromSocket"): - source = self._node(tree, text(command, "fromNode", ID_PATTERN, "fromNode")) - out = self._socket(source.outputs, str(command.get("fromSocket", "")), "fromSocket") + if ("fromNode" in command) != ("fromSocket" in command): + raise ActionRefused("fromNode and fromSocket are given together or not at all.") + if "fromNode" in command: + source = self._node(tree, command["fromNode"]) + out = self._socket(source.outputs, command["fromSocket"], "fromSocket") doomed = [l for l in tree.links if l.to_socket == into and (out is None or l.from_socket == out)] for link in doomed: tree.links.remove(link) @@ -258,11 +210,11 @@ class NodeActions: return f"Removed {len(doomed)} link(s).", tree.name def _linkSockets(self, command: dict[str, Any]) -> tuple[str, str]: - tree = self._tree(tree_key(command)) - source = self._node(tree, text(command, "fromNode", ID_PATTERN, "fromNode")) - target = self._node(tree, text(command, "toNode", ID_PATTERN, "toNode")) - out = self._socket(source.outputs, str(command.get("fromSocket", "")), "fromSocket") - into = self._socket(target.inputs, str(command.get("toSocket", "")), "toSocket") + tree = self._tree(command["treeKey"]) + source = self._node(tree, command["fromNode"]) + target = self._node(tree, command["toNode"]) + out = self._socket(source.outputs, command["fromSocket"], "fromSocket") + into = self._socket(target.inputs, command["toSocket"], "toSocket") if reaches(tree, target, source): # includes a self link raise ActionRefused(f"Link {source.get('brokkr_id')} -> {target.get('brokkr_id')} would make a cycle.") displaced = [(l.from_socket, l.is_muted) for l in tree.links if l.to_socket == into] if not getattr(into, "is_multi_input", False) else [] @@ -275,7 +227,7 @@ class NodeActions: return f"Linked {source.get('brokkr_id')}.{out.identifier} -> {target.get('brokkr_id')}.{into.identifier}.", tree.name def _object(self, command: dict[str, Any]) -> Any: - name = command.get("objectName") or command.get("targetObjectName") + name = command["objectName"] obj = self.bpy.data.objects.get(name) if name else None if obj is None: raise ActionRefused(f"Object {name!r} was not found.") @@ -283,11 +235,8 @@ class NodeActions: def _addModifier(self, command: dict[str, Any]) -> tuple[str, str]: obj = self._object(command) - kind = command.get("modifierType", "NODES") - if kind != "NODES": - raise ActionRefused("modifierType must be NODES; other modifiers are not part of this cut.") - tree = self._tree(tree_key(command)) - name = text(command, "modifierName", KEY_PATTERN, "modifierName", required=False) or "Brokkr GeoNodes" + tree = self._tree(command["treeKey"]) + name = command["modifierName"] modifier = obj.modifiers.get(name) if modifier is not None and modifier.type != "NODES": raise ActionRefused(f"{obj.name!r} already has a non-Geometry-Nodes modifier named {name!r}.") @@ -304,9 +253,7 @@ class NodeActions: def _removeModifier(self, command: dict[str, Any]) -> tuple[str, str]: obj = self._object(command) # A lookup, not a creation: a modifier made by hand may have any name Blender allows. - name = command.get("modifierName") or "Brokkr GeoNodes" - if not isinstance(name, str) or len(name) > 255 or "\0" in name: - raise ActionRefused("modifierName must be a string of at most 255 characters.") + name = command["modifierName"] modifier = obj.modifiers.get(name) if modifier is None: self.changed = False @@ -319,11 +266,11 @@ class NodeActions: def _setModifierInput(self, command: dict[str, Any]) -> tuple[str, str]: obj = self._object(command) - modifier = obj.modifiers.get(str(command.get("modifierName") or "Brokkr GeoNodes")) + modifier = obj.modifiers.get(command["modifierName"]) if modifier is None or modifier.type != "NODES" or modifier.node_group is None: raise ActionRefused(f"{obj.name!r} has no Geometry Nodes modifier with a node group of that name.") - item = modifier_input(modifier.node_group, str(command.get("socket", ""))) - value = typed_value(command.get("value"), item.socket_type.replace("NodeSocket", ""), f"input {item.name!r}") + item = modifier_input(modifier.node_group, command["socket"]) + value = typed_value(command["value"], item.socket_type.replace("NodeSocket", ""), f"input {item.name!r}") # modifier.properties.inputs[id] is a raw IDPropertyGroup on 5.2.3; attribute access reaches the struct. getattr(modifier.properties.inputs, item.identifier).value = value obj.update_tag() # without it a headless re-evaluation returned the previous result diff --git a/surfaces/blender/brokkr_bridge/scene_actions.py b/surfaces/blender/brokkr_bridge/scene_actions.py index 98dcb40..c2a0b3c 100644 --- a/surfaces/blender/brokkr_bridge/scene_actions.py +++ b/surfaces/blender/brokkr_bridge/scene_actions.py @@ -1,13 +1,12 @@ -"""Validation for the Blender scene command actions. Stdlib only, no bpy. +"""Path and file safety for the Blender scene command actions. Stdlib only, no bpy. -Everything an intent can say is checked here before bpy is touched, so the rules -are testable without Blender. Failures raise ActionRefused; the target turns the -message into a failed receipt. +What an intent's fields may hold (names, types, enums, bounds) is action_table's. What a path or a glTF +may reach is checked here before bpy is touched, so the rules are testable without Blender. Failures raise +ActionRefused; the target turns the message into a failed receipt. """ from __future__ import annotations import json -import math import os import struct from pathlib import Path @@ -16,10 +15,6 @@ from urllib.parse import unquote GLTF_EXTENSIONS = (".gltf", ".glb") STILL_FORMATS = {".png": "PNG", ".jpg": "JPEG", ".jpeg": "JPEG", ".exr": "OPEN_EXR"} -CAMERA_TYPES = ("PERSP", "ORTHO", "PANO") -LIGHT_TYPES = ("POINT", "SUN", "SPOT", "AREA") -MAX_RESOLUTION = 16384 -MAX_LENS_MM = 5000.0 class ActionRefused(ValueError): @@ -166,72 +161,6 @@ def _glb_json_chunk(path: Path) -> bytes: return data -def number(command: dict[str, Any], key: str, low: float, high: float) -> float | None: - """A finite number in [low, high], or None when the key is absent.""" - if key not in command or command[key] is None: - return None - value = command[key] - if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): - raise ActionRefused(f"{key} must be a finite number.") - if not low <= value <= high: - raise ActionRefused(f"{key} must be between {low} and {high}.") - return float(value) - - -def integer(command: dict[str, Any], key: str, low: int, high: int) -> int | None: - value = number(command, key, low, high) - if value is None: - return None - if value != int(value): - raise ActionRefused(f"{key} must be a whole number.") - return int(value) - - -def unit_component(key: str, item: Any) -> float: - """One colour component: a number in [0, 1]. The range test comes first: it also refuses nan and inf, - and a huge int (10**400) never reaches math.isfinite, which would raise OverflowError instead of - naming the field.""" - if isinstance(item, bool) or not isinstance(item, (int, float)) or not 0.0 <= item <= 1.0: - raise ActionRefused(f"{key} components must be numbers between 0 and 1.") - return float(item) - - -def color(command: dict[str, Any], key: str = "color") -> tuple[float, float, float] | None: - """Linear RGB, three finite numbers in [0, 1], or None when absent.""" - if key not in command or command[key] is None: - return None - value = command[key] - if not isinstance(value, (list, tuple)) or len(value) != 3: - raise ActionRefused(f"{key} must be three numbers [r, g, b].") - parts = [] - for item in value: - parts.append(unit_component(key, item)) - return (parts[0], parts[1], parts[2]) - - -def color_rgba(command: dict[str, Any], key: str = "color") -> tuple[float, float, float, float] | None: - """Linear RGB or RGBA, finite numbers in [0, 1] (RGB gets alpha 1), or None when absent.""" - if key not in command or command[key] is None: - return None - value = command[key] - if not isinstance(value, (list, tuple)) or len(value) not in (3, 4): - raise ActionRefused(f"{key} must be [r, g, b] or [r, g, b, a].") - parts = [] - for item in value: - parts.append(unit_component(key, item)) - return (parts[0], parts[1], parts[2], parts[3] if len(parts) == 4 else 1.0) - - -def choice(command: dict[str, Any], key: str, allowed: Iterable[str]) -> str | None: - if key not in command or command[key] is None: - return None - allowed = tuple(allowed) - value = command[key] - if not isinstance(value, str) or value.upper() not in allowed: - raise ActionRefused(f"{key} must be one of {', '.join(allowed)}.") - return value.upper() - - def still_format(path: Path) -> str: try: return STILL_FORMATS[path.suffix.lower()] diff --git a/surfaces/blender/tests/action_cases.json b/surfaces/blender/tests/action_cases.json new file mode 100644 index 0000000..fb5a8e0 --- /dev/null +++ b/surfaces/blender/tests/action_cases.json @@ -0,0 +1,233 @@ +[ + {"action": "createObject", "fields": {}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "MESH", "name": "N", "location": [0, 0, 1], "size": 2, "meshType": "CUBE"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": null, "name": null, "location": null}, "expect": "ok"}, + {"action": "createObject", "fields": {"note": "n", "requestedBy": "a/b", "commandId": "x", "schema": "s"}, "expect": "ok"}, + {"action": "look", "fields": {}, "expect": "ok"}, + {"action": "deleteObject", "fields": {"targetObjectName": "Cube"}, "expect": "ok"}, + {"action": "deleteObject", "fields": {}, "expect": "targetObjectName is required."}, + {"action": "deleteObject", "fields": {"targetObjectName": null}, "expect": "targetObjectName is required."}, + {"action": "createObject", "fields": {"bogus": 1}, "expect": "createObject has no field 'bogus'; its fields: objectType, name, location, size, meshType, lightType, emptyDisplayType."}, + {"action": "createObject", "fields": {"zeta": 1, "alpha": 2}, "expect": "createObject has no field 'alpha'; its fields: objectType, name, location, size, meshType, lightType, emptyDisplayType."}, + {"action": "setObjectTransform", "fields": {"objectName": "x"}, "expect": "setObjectTransform has no field 'objectName'; its fields: targetObjectName, location, rotationEuler, scale."}, + {"action": "addModifier", "fields": {"targetObjectName": "x"}, "expect": "addModifier has no field 'targetObjectName'; its fields: objectName, modifierType, treeKind, treeKey, modifierName."}, + {"action": "setObjectParent", "fields": {"targetObjectName": "x", "parentName": "p"}, "expect": "setObjectParent has no field 'parentName'; its fields: targetObjectName, parentObjectName."}, + {"action": "look", "fields": {"x": 1}, "expect": "look has no field 'x'; its fields: none."}, + {"action": "runPython", "fields": {}, "expect": "Unsupported Blender command action: runPython"}, + {"action": "createobject", "fields": {}, "expect": "Unsupported Blender command action: createobject"}, + {"action": "createObject", "fields": {"name": 5}, "expect": "name must be a string."}, + {"action": "createObject", "fields": {"size": "x"}, "expect": "size must be a finite number."}, + {"action": "createObject", "fields": {"size": true}, "expect": "size must be a finite number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 1.5}, "expect": "resolutionX must be a whole number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": true}, "expect": "resolutionX must be a whole number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": "64"}, "expect": "resolutionX must be a whole number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 640.0}, "expect": "ok"}, + {"action": "setObjectVisibility", "fields": {"targetObjectName": "c", "visible": 1}, "expect": "visible must be true or false."}, + {"action": "setObjectVisibility", "fields": {"targetObjectName": "c", "visible": false}, "expect": "ok"}, + {"action": "createObject", "fields": {"location": "x"}, "expect": "location must be an array."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "properties": []}, "expect": "properties must be an object."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "properties": {"x": null, "y": 1}, "inputs": {"a": [1, 2]}}, "expect": "ok"}, + {"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": null}, "expect": "value is required."}, + {"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": {"a": [1]}}, "expect": "ok"}, + {"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": false}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "mesh"}, "expect": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY."}, + {"action": "createObject", "fields": {"objectType": " MESH"}, "expect": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY."}, + {"action": "createObject", "fields": {"objectType": 3}, "expect": "objectType must be a string."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "CUSTOM"}, "expect": "cameraType must be one of PERSP, ORTHO, PANO."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "ortho"}, "expect": "cameraType must be one of PERSP, ORTHO, PANO."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "EQUIDISTANT"}, "expect": "panoramaType must be one of EQUIRECTANGULAR, EQUIANGULAR_CUBEMAP_FACE, MIRRORBALL, FISHEYE_EQUIDISTANT, FISHEYE_EQUISOLID, FISHEYE_LENS_POLYNOMIAL, CENTRAL_CYLINDRICAL."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "CENTRAL_CYLINDRICAL", "cameraType": "PANO", "active": true}, "expect": "ok"}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "modifierType": "SUBSURF"}, "expect": "modifierType must be one of NODES."}, + {"action": "addNode", "fields": {"treeKind": "shader", "treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath"}, "expect": "treeKind must be one of geometry."}, + {"action": "createObject", "fields": {"objectType": "MESH", "lightType": "POINT"}, "expect": "lightType applies only when objectType is one of LIGHT."}, + {"action": "createObject", "fields": {"lightType": "POINT"}, "expect": "lightType applies only when objectType is one of LIGHT."}, + {"action": "createObject", "fields": {"objectType": "LIGHT", "emptyDisplayType": "CUBE"}, "expect": "emptyDisplayType applies only when objectType is one of EMPTY."}, + {"action": "createObject", "fields": {"objectType": "LIGHT", "meshType": "CUBE"}, "expect": "meshType applies only when objectType is one of MESH."}, + {"action": "createObject", "fields": {"objectType": "LIGHT", "lightType": "SPOT"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "EMPTY", "emptyDisplayType": "IMAGE"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "LIGHT", "lightType": "LASER"}, "expect": "lightType must be one of POINT, SUN, SPOT, AREA."}, + {"action": "createObject", "fields": {"objectType": "EMPTY", "emptyDisplayType": "BOX"}, "expect": "emptyDisplayType must be one of PLAIN_AXES, ARROWS, SINGLE_ARROW, CIRCLE, CUBE, SPHERE, CONE, IMAGE."}, + {"action": "createNodeGroup", "fields": {"treeKey": "", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "treeKey must have at least 1 characters."}, + {"action": "createNodeGroup", "fields": {"treeKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "treeKey must have at most 63 characters."}, + {"action": "createNodeGroup", "fields": {"treeKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "my group.1-x_y", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "a/b", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "treeKey may contain only letters, digits, space, '.', '_' or '-'."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a b"}, "expect": "id may contain only letters, digits, '.', '_' or '-'."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a\n"}, "expect": "id may contain only letters, digits, '.', '_' or '-'."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "\u00e9"}, "expect": "id may contain only letters, digits, '.', '_' or '-'."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "gin"}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "Math"}, "expect": "blIdname must start with one of GeometryNode, FunctionNode, ShaderNode and have at least one more character."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "GeometryNode"}, "expect": "blIdname must start with one of GeometryNode, FunctionNode, ShaderNode and have at least one more character."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "Geometry Node"}, "expect": "blIdname may contain only letters and digits."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "GeometryNodeGroup"}, "expect": "blIdname may not contain 'Group'."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeTexImage"}, "expect": "blIdname may not contain 'TexImage'."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "FunctionNodeCompare"}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "label": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "label must have at most 63 characters."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "label": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "ok"}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "a\u0000b"}, "expect": "modifierName may not contain '\u0000'."}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "modifierName must have at most 255 characters."}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "ok"}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": ""}, "expect": "modifierName must have at least 1 characters."}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "G\u00e9 x/y"}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "engine": ""}, "expect": "engine must have at least 1 characters."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "engine": "CYCLES"}, "expect": "ok"}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": []}, "expect": "selection must have at least 1 items."}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": [3]}, "expect": "selection[0] must be a string."}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": ["a", ""]}, "expect": "selection[1] must have at least 1 characters."}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": ["a", null]}, "expect": "selection[1] must be a string."}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": ["a"], "extras": "yes"}, "expect": "extras must be true or false."}, + {"action": "createObject", "fields": {"location": [1, 2]}, "expect": "location must have at least 3 items."}, + {"action": "createObject", "fields": {"location": [1, 2, 3, 4]}, "expect": "location must have at most 3 items."}, + {"action": "createObject", "fields": {"location": [1, "x", 3]}, "expect": "location[1] must be a finite number."}, + {"action": "createObject", "fields": {"location": [1, null, 3]}, "expect": "location[1] must be a finite number."}, + {"action": "createObject", "fields": {"location": [1, 2, true]}, "expect": "location[2] must be a finite number."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 0]}, "expect": "color must have at least 3 items."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 0, 0, 0, 0]}, "expect": "color must have at most 4 items."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 0, 0, 0.5]}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [1, 0, 0, 1]}, "expect": "color must have at most 3 items."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [1]}, "expect": "location must have at least 2 items."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G"}, "expect": "interface is required."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": []}, "expect": "interface must have at least 1 items."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "interface must have at most 64 items."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [1]}, "expect": "interface[0] must be an object."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "type": "Int"}]}, "expect": "interface[0].name is required."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": null, "type": "Int"}]}, "expect": "interface[1].name is required."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "input", "name": "a", "type": "Int"}]}, "expect": "interface[0].inOut must be one of INPUT, OUTPUT."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Mat"}]}, "expect": "interface[0].type must be one of Geometry, Float, Int, Bool, Vector."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "", "type": "Int"}]}, "expect": "interface[0].name must have at least 1 characters."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "type": "Int"}]}, "expect": "interface[0].name must have at most 63 characters."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int", "extra": 1}]}, "expect": "interface[0] has no field 'extra'; its fields: inOut, name, type, default."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int", "default": "anything"}]}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int", "default": null}]}, "expect": "ok"}, + {"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b"}, "expect": "toSocket is required."}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i"}, "expect": "ok"}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i", "fromNode": "a"}, "expect": "ok"}, + {"action": "createObject", "fields": {"location": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"}, + {"action": "createObject", "fields": {"location": [1000000000, 1000000000, 1000000000]}, "expect": "ok"}, + {"action": "createObject", "fields": {"location": [-1000000000, -1000000000, 1000000001]}, "expect": "location[2] must be between -1000000000 and 1000000000."}, + {"action": "createObject", "fields": {"location": [-1000000001, -1000000000, -1000000000]}, "expect": "location[0] must be between -1000000000 and 1000000000."}, + {"action": "createObject", "fields": {"size": 0.001}, "expect": "ok"}, + {"action": "createObject", "fields": {"size": 1000000}, "expect": "ok"}, + {"action": "createObject", "fields": {"size": 1000001}, "expect": "size must be between 0.001 and 1000000."}, + {"action": "createObject", "fields": {"size": -0.999}, "expect": "size must be between 0.001 and 1000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [1000000000, 1000000000, 1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [-1000000000, -1000000000, 1000000001]}, "expect": "location[2] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [-1000000001, -1000000000, -1000000000]}, "expect": "location[0] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [1000000000, 1000000000, 1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [-1000000000, -1000000000, 1000000001]}, "expect": "rotationEuler[2] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [-1000000001, -1000000000, -1000000000]}, "expect": "rotationEuler[0] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [1000000000, 1000000000, 1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [-1000000000, -1000000000, 1000000001]}, "expect": "scale[2] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [-1000000001, -1000000000, -1000000000]}, "expect": "scale[0] must be between -1000000000 and 1000000000."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [0, 0, 0]}, "expect": "ok"}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 1, 1]}, "expect": "ok"}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [0, 0, 2]}, "expect": "color[2] must be between 0 and 1."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [-1, 0, 0]}, "expect": "color[0] must be between 0 and 1."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 1}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 5000}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 5001}, "expect": "lens must be between 1 and 5000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 0}, "expect": "lens must be between 1 and 5000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": 0.001}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": 100000}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": 100001}, "expect": "orthoScale must be between 0.001 and 100000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": -0.999}, "expect": "orthoScale must be between 0.001 and 100000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": 0.0001}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": 1000000}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": 1000001}, "expect": "clipStart must be between 0.0001 and 1000000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": -0.9999}, "expect": "clipStart must be between 0.0001 and 1000000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": 0.001}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": 10000000}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": 10000001}, "expect": "clipEnd must be between 0.001 and 10000000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": -0.999}, "expect": "clipEnd must be between 0.001 and 10000000."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "energy": 0}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "energy": 10000000}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "energy": 10000001}, "expect": "energy must be between 0 and 10000000."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "energy": -1}, "expect": "energy must be between 0 and 10000000."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [0, 0, 0]}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [1, 1, 1]}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [0, 0, 2]}, "expect": "color[2] must be between 0 and 1."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [-1, 0, 0]}, "expect": "color[0] must be between 0 and 1."}, + {"action": "setWorld", "fields": {"color": [0, 0, 0]}, "expect": "ok"}, + {"action": "setWorld", "fields": {"color": [1, 1, 1]}, "expect": "ok"}, + {"action": "setWorld", "fields": {"color": [0, 0, 2]}, "expect": "color[2] must be between 0 and 1."}, + {"action": "setWorld", "fields": {"color": [-1, 0, 0]}, "expect": "color[0] must be between 0 and 1."}, + {"action": "setWorld", "fields": {"strength": 0}, "expect": "ok"}, + {"action": "setWorld", "fields": {"strength": 1000000}, "expect": "ok"}, + {"action": "setWorld", "fields": {"strength": 1000001}, "expect": "strength must be between 0 and 1000000."}, + {"action": "setWorld", "fields": {"strength": -1}, "expect": "strength must be between 0 and 1000000."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 4}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 16384}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 16385}, "expect": "resolutionX must be between 4 and 16384."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 3}, "expect": "resolutionX must be between 4 and 16384."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 4}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 16384}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 16385}, "expect": "resolutionY must be between 4 and 16384."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 3}, "expect": "resolutionY must be between 4 and 16384."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [-1000000000, -1000000000]}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [1000000000, 1000000000]}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [-1000000000, 1000000001]}, "expect": "location[1] must be between -1000000000 and 1000000000."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [-1000000001, -1000000000]}, "expect": "location[0] must be between -1000000000 and 1000000000."}, + {"action": "createObject", "fields": {"objectType": "MESH"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "LIGHT"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "CAMERA"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "EMPTY"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "mesh_"}, "expect": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "PERSP"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "ORTHO"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "PANO"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "persp_"}, "expect": "cameraType must be one of PERSP, ORTHO, PANO."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "EQUIRECTANGULAR"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "EQUIANGULAR_CUBEMAP_FACE"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "MIRRORBALL"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "FISHEYE_EQUIDISTANT"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "FISHEYE_EQUISOLID"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "FISHEYE_LENS_POLYNOMIAL"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "CENTRAL_CYLINDRICAL"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "equirectangular_"}, "expect": "panoramaType must be one of EQUIRECTANGULAR, EQUIANGULAR_CUBEMAP_FACE, MIRRORBALL, FISHEYE_EQUIDISTANT, FISHEYE_EQUISOLID, FISHEYE_LENS_POLYNOMIAL, CENTRAL_CYLINDRICAL."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "POINT"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "SUN"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "SPOT"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "AREA"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "point_"}, "expect": "lightType must be one of POINT, SUN, SPOT, AREA."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}], "treeKind": "geometry"}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}], "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b", "toSocket": "i", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b", "toSocket": "i", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "modifierType": "NODES"}, "expect": "ok"}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "modifierType": "nodes_"}, "expect": "modifierType must be one of NODES."}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "createObject", "fields": {}, "expect": "ok"}, + {"action": "deleteObject", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setObjectVisibility", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setObjectParent", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": 1}, "expect": "ok"}, + {"action": "selectObject", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "importGltf", "fields": {"filepath": "a.glb"}, "expect": "ok"}, + {"action": "exportGltf", "fields": {"filepath": "a.glb"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setWorld", "fields": {}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png"}, "expect": "ok"}, + {"action": "look", "fields": {}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath"}, "expect": "ok"}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a"}, "expect": "ok"}, + {"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b", "toSocket": "i"}, "expect": "ok"}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i"}, "expect": "ok"}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G"}, "expect": "ok"}, + {"action": "removeModifier", "fields": {"objectName": "o"}, "expect": "ok"}, + {"action": "setModifierInput", "fields": {"objectName": "o", "socket": "s", "value": 1}, "expect": "ok"} +] diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py index 1521ba0..5f8a68c 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.py +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -202,7 +202,7 @@ def q5_edit(): push("driver edit baseline") queue("aaaaaaaa-0006", action="setWorld", color=[1, 0, 0], requestedBy="nibu/hands") queue("aaaaaaaa-0007", action="exportGltf", filepath="edit.glb", requestedBy="nibu/hands") - queue("aaaaaaaa-0008", action="setObjectTransform", objectName="Cube", location=[0, 0, 9], requestedBy="nibu/hands") + queue("aaaaaaaa-0008", action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 9], requestedBy="nibu/hands") def q5_check(): diff --git a/surfaces/blender/tests/live/agent_turn_undo.py b/surfaces/blender/tests/live/agent_turn_undo.py index 9a9dc1b..c8bec53 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.py +++ b/surfaces/blender/tests/live/agent_turn_undo.py @@ -88,7 +88,7 @@ def s_create(): def s_transform(): - intent(action="setObjectTransform", objectName="AgentCube", location=[3, 2, 0]) + intent(action="setObjectTransform", targetObjectName="AgentCube", location=[3, 2, 0]) check("transform applied", loc("AgentCube") == [3.0, 2.0, 0.0], loc("AgentCube")) @@ -131,7 +131,7 @@ def s_edit_enter(): def s_edit_agent(): - r = intent(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + r = intent(action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 5]) R["editMode"].update(mode_after_intent=bpy.context.mode, loc_after_intent=loc("Cube"), receipt=r["status"], message=r["message"], undoLabel=r["undoLabel"]) check("edit mode: object-level intent refused, scene and her mode unchanged", diff --git a/surfaces/blender/tests/test_action_table.py b/surfaces/blender/tests/test_action_table.py new file mode 100644 index 0000000..d548b1b --- /dev/null +++ b/surfaces/blender/tests/test_action_table.py @@ -0,0 +1,181 @@ +"""The action table: the parity fixture, handler coverage, and the table's own load checks. No Blender.""" +from __future__ import annotations + +import copy +import json +import re +import unittest +from pathlib import Path +from unittest import mock + +import test_scene_actions as ts + +at = ts.at +bt = ts.bt +na = ts.bt.na +CASES = json.loads((Path(__file__).with_name("action_cases.json")).read_text(encoding="utf-8")) + + +def validate(action, fields): + try: + at.validate({"action": action, **fields}) + except at.IntentInvalid as error: + return str(error) + return "ok" + + +class ParityFixtureTests(unittest.TestCase): + """action_cases.json is also run by brokkr-ctl's actions.rs: one table, two interpreters, one set of messages.""" + + def test_every_case_yields_exactly_its_expected_message_or_ok(self): + wrong = [(c["action"], c["fields"], c["expect"], validate(c["action"], c["fields"])) + for c in CASES if validate(c["action"], c["fields"]) != c["expect"]] + self.assertEqual(wrong, []) + + def test_the_fixture_covers_every_rule_kind_and_every_number_field(self): + text = json.dumps(CASES) + for needle in ("is required.", "has no field", "must be one of", "must be between", "must have at least", "must have at most", + "may contain only", "must start with one of", "may not contain", "applies only when", "Unsupported Blender"): + self.assertIn(needle, text) + for action in at.table()["actions"]: + for field in action["fields"]: + if field["type"] in ("number", "integer") or field.get("items", {}).get("type") == "number": + pins = [c for c in CASES if c["action"] == action["name"] and field["name"] in c["fields"] + and c["expect"].startswith(f"{field['name']}") and "must be between" in c["expect"]] + self.assertGreaterEqual(len(pins), 2, f"{action['name']}.{field['name']}: both bounds") + self.assertTrue(any(c["action"] == action["name"] and c["expect"] == "ok" for c in CASES), action["name"]) + + def test_validate_normalizes_null_to_absent_and_fills_defaults(self): + normal = at.validate({"action": "createObject", "objectType": None, "location": None, "note": "n"}) + self.assertEqual(normal["objectType"], "EMPTY") + self.assertEqual((normal["size"], normal["lightType"], normal["emptyDisplayType"]), (1, "POINT", "PLAIN_AXES")) + self.assertNotIn("location", normal) + self.assertEqual(normal["note"], "n") + self.assertEqual(at.validate({"action": "setLight", "targetObjectName": "L"}).get("lightType"), None) # no default: absent stays absent + + def test_a_mutant_validator_fails_the_fixture(self): + """The fixture pins the rules: casefolding enums, widening a bound or letting bool pass as a number each break cases.""" + original = at._value + + def casefolded(spec, value, path): + if "enum" in spec and isinstance(value, str): + value = next((e for e in spec["enum"] if e.lower() == value.lower()), value) + return original(spec, value, path) + + for mutant in (casefolded,): + with mock.patch.object(at, "_value", mutant): + self.assertNotEqual([c for c in CASES if validate(c["action"], c["fields"]) != c["expect"]], []) + number = at._number + + def widened(spec, value, path): + return number({**spec, "maximum": spec["maximum"] * 10 + 10}, value, path) + + def boolish(spec, value, path): + return number(spec, int(value) if isinstance(value, bool) else value, path) + + for mutant in (widened, boolish): + with mock.patch.object(at, "_number", mutant): + self.assertNotEqual([c for c in CASES if validate(c["action"], c["fields"]) != c["expect"]], [], mutant.__name__) + + +class HandlerCoverageTests(unittest.TestCase): + def test_each_table_action_resolves_to_exactly_one_handler_and_each_handler_has_an_entry(self): + names = [a["name"] for a in at.table()["actions"]] + self.assertEqual(len(names), len(set(names))) + target = bt.BrokkrBlenderTarget + for name in names: + owners = [owner for owner in (target, na.NodeActions) if hasattr(owner, "_" + name)] + self.assertEqual(len(owners), 1, f"{name}: handlers {owners}") + camel = re.compile(r"_[a-z]+[A-Z][A-Za-z0-9]*") # every other private name of both classes is snake_case + handlers = {n[1:] for owner in (target, na.NodeActions) for n in vars(owner) if camel.fullmatch(n)} | {"look"} + self.assertEqual(sorted(handlers - set(names)), [], "a handler without a table entry") + self.assertEqual(sorted(set(names) - handlers), [], "a table entry without a handler") + + def test_node_socket_types_are_the_tables(self): + spec = next(a for a in at.table()["actions"] if a["name"] == "createNodeGroup") + interface = next(f for f in spec["fields"] if f["name"] == "interface") + kinds = next(p for p in interface["items"]["properties"] if p["name"] == "type")["enum"] + self.assertEqual(sorted(kinds), sorted(na.SOCKET_TYPES)) + + def test_removing_an_entry_makes_the_action_unsupported(self): + trimmed = copy.deepcopy(at.table()) + trimmed["actions"] = [a for a in trimmed["actions"] if a["name"] != "deleteObject"] + with mock.patch.object(at, "table", return_value=trimmed), mock.patch.object(at, "_by_name", return_value={a["name"]: a for a in trimmed["actions"]}): + self.assertEqual(validate("deleteObject", {"targetObjectName": "c"}), "Unsupported Blender command action: deleteObject") + + def test_undo_and_edit_mode_classes_are_the_tables(self): + rows = {a["name"]: a for a in at.table()["actions"]} + self.assertEqual(sorted(n for n, a in rows.items() if not a["changesScene"]), ["exportGltf", "look", "renderStill"]) + self.assertEqual(sorted(n for n, a in rows.items() if a["editModeSafe"]), ["look", "renderStill"]) + + +class TableCheckTests(unittest.TestCase): + def table(self): + return copy.deepcopy(at.table()) + + def test_an_unbounded_number_field_is_refused_at_load(self): + broken = self.table() + del next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "lens")["maximum"] + with self.assertRaisesRegex(at.TableInvalid, "lens.*maximum"): + at.check_table(broken) + broken = self.table() + del next(f for a in broken["actions"] if a["name"] == "createObject" for f in a["fields"] if f["name"] == "location")["items"]["minimum"] + with self.assertRaisesRegex(at.TableInvalid, "minimum"): + at.check_table(broken) + + def test_an_only_naming_a_missing_field_is_refused(self): + broken = self.table() + next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "lightType" and "only" in f)["only"]["field"] = "nope" + with self.assertRaisesRegex(at.TableInvalid, "only"): + at.check_table(broken) + + def test_an_unknown_charset_is_refused(self): + broken = self.table() + next(f for a in broken["actions"] for f in a["fields"] if f.get("chars") == "key")["chars"] = "nope" + with self.assertRaisesRegex(at.TableInvalid, "charset"): + at.check_table(broken) + + def test_a_default_that_breaks_its_own_field_is_refused(self): + broken = self.table() + next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "objectType")["default"] = "TEXT" + with self.assertRaisesRegex(at.TableInvalid, "default"): + at.check_table(broken) + + def test_a_bound_that_prints_differently_in_python_and_rust_is_refused(self): + broken = self.table() + next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "clipStart")["minimum"] = 1e-7 + with self.assertRaisesRegex(at.TableInvalid, "plain digits"): + at.check_table(broken) + + +class AdmissionTests(unittest.TestCase): + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + + def test_a_table_refusal_is_denied_pushes_no_undo_step_and_calls_no_operator(self): + for fields in ({"action": "createObject", "bogus": 1}, {"action": "createObject", "objectType": "mesh"}, + {"action": "renderStill", "outputPath": "a.png", "resolutionX": 2}, + {"action": "setObjectTransform", "objectName": "Cube", "location": [0, 0, 1]}): + receipt = self.run_action(**fields) + self.assertEqual(receipt["status"], "denied", fields) + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual((self.bpy.created, self.bpy.undo.pushes, self.bpy.rendered), ([], [], [])) + self.assertEqual(self.bpy.mesh.__dict__.get("location"), None) + + def test_the_unknown_action_message_and_the_order_of_admission(self): + self.assertEqual(self.run_action(action="runPython")["message"], "Unsupported Blender command action: runPython") + self.bpy.mesh.mode = "EDIT" + receipt = self.run_action(action="createObject", objectType="mesh") # invalid fields are named before the mode + self.assertNotIn("Edit Mode", receipt["message"]) + receipt = self.run_action(action="createObject", objectType="EMPTY") + self.assertIn("Edit Mode", receipt["message"]) + + def test_defaults_reach_the_handler(self): + self.assertEqual(self.run_action(action="createObject", objectType="MESH")["status"], "accepted") + self.assertEqual(self.bpy.created[-1][1]["size"], 1.0) + self.assertEqual(self.run_action(action="createObject", objectType="LIGHT")["status"], "accepted") + self.assertEqual(self.bpy.created[-1][1]["type"], "POINT") + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index b052cc9..523e0cb 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -11,6 +11,7 @@ from pathlib import Path import test_scene_actions as ts bt = ts.bt +at = ts.at SOURCE = Path(bt.__file__) @@ -30,7 +31,7 @@ class AgentTurnTests(unittest.TestCase): def test_object_intent_is_refused_while_an_object_is_in_edit_mode(self): self.bpy.mesh.mode = "EDIT" - receipt = self.run_action(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + receipt = self.run_action(action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 5]) self.assertEqual(receipt["status"], "denied") self.assertIn("Edit Mode", receipt["message"]) self.assertEqual(receipt["undoLabel"], "") @@ -76,13 +77,15 @@ class AgentTurnTests(unittest.TestCase): def test_refusal_pushes_nothing(self): receipt = self.run_action(action="createObject", objectType="BOGUS") - self.assertEqual(receipt["status"], "failed") + self.assertEqual(receipt["status"], "denied") self.assertEqual(receipt["undoLabel"], "") self.assertEqual(self.bpy.undo.pushes, []) + receipt = self.run_action(action="deleteObject", targetObjectName="Nope") # a scene refusal: ran, failed, no step + self.assertEqual(receipt["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, []) def test_read_action_pushes_nothing(self): - with unittest.mock.patch.object(bt, "READ_ACTIONS", ("createObject",)): - self.run_action(action="createObject", objectType="EMPTY") + self.assertNotEqual(self.run_action(action="look")["status"], "denied") # admitted; the fake has no 3D view to capture self.assertEqual(self.bpy.undo.pushes, []) def test_raise_after_admission_pushes_failed_step(self): @@ -131,7 +134,7 @@ class AgentTurnTests(unittest.TestCase): self.assertEqual(self.bpy.undo.pushes, []) def test_returned_failed_receipt_pushes_nothing(self): - receipt = self.run_action(action="setObjectTransform", objectName="NoSuchObject", location=[1, 2, 3]) + receipt = self.run_action(action="setObjectTransform", targetObjectName="NoSuchObject", location=[1, 2, 3]) self.assertEqual(receipt["status"], "failed") self.assertEqual(self.bpy.undo.pushes, []) @@ -162,7 +165,7 @@ class AgentTurnTests(unittest.TestCase): # fix batch s2 def test_no_scene_change_set_is_exactly_export_and_render(self): - self.assertEqual(bt.NO_SCENE_CHANGE_ACTIONS, ("exportGltf", "renderStill")) + self.assertEqual([a["name"] for a in at.table()["actions"] if not a["changesScene"]], ["exportGltf", "renderStill", "look"]) receipt = self.run_action(action="setWorld", color=[0.1, 0.2, 0.3]) self.assertEqual(receipt["status"], "accepted") self.assertEqual(len(self.bpy.undo.pushes), 1) diff --git a/surfaces/blender/tests/test_material_actions.py b/surfaces/blender/tests/test_material_actions.py index 0caa663..884bca2 100644 --- a/surfaces/blender/tests/test_material_actions.py +++ b/surfaces/blender/tests/test_material_actions.py @@ -121,7 +121,7 @@ class MaterialTests(unittest.TestCase): [float("nan"), 0, 0], [float("inf"), 0, 0], [-0.1, 0, 0], [1.1, 0, 0], [0, 0, 0, 2], [1.0000001, 0, 0], [-1e-9, 0, 0], [0, 0, 0, 1.0000001], [10**400, 0, 0], [0, -10**400, 0]): receipt = self.assign(materialName="oxide red", color=bad) - self.assertEqual(receipt["status"], "failed", bad) + self.assertEqual(receipt["status"], "denied", bad) self.assertIn("color", receipt["message"], bad) self.assertEqual(dict(self.bpy.data.materials), {}) self.assertEqual(self.bpy.mesh.data.materials, []) @@ -143,7 +143,7 @@ class MaterialTests(unittest.TestCase): def test_refused_colour_on_an_existing_material_leaves_it_alone(self): self.assign(materialName="oxide red", color=[0.5, 0.1, 0.1]) - self.assertEqual(self.assign(materialName="oxide red", color=[2, 0, 0])["status"], "failed") + self.assertEqual(self.assign(materialName="oxide red", color=[2, 0, 0])["status"], "denied") self.assertEqual(self.base_color(), (0.5, 0.1, 0.1, 1.0)) def test_existing_tree_without_a_principled_node_gets_one(self): diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index eff659b..2a24752 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -204,8 +204,9 @@ class NodeActionTests(unittest.TestCase): return receipt def refused(self, **command): + """Refused either at admission by the table ('denied') or by the handler against the scene ('failed').""" receipt = self.run_action(**command) - self.assertEqual(receipt["status"], "failed", receipt["message"]) + self.assertIn(receipt["status"], ("denied", "failed"), receipt["message"]) return receipt def group(self, interface=None): diff --git a/surfaces/blender/tests/test_perception.py b/surfaces/blender/tests/test_perception.py index 48ba6fb..e2a2017 100644 --- a/surfaces/blender/tests/test_perception.py +++ b/surfaces/blender/tests/test_perception.py @@ -593,7 +593,7 @@ class HumanEditTests(PerceptionFixture): # scene-last-writer-wins: an intent after her edit is accepted, and so is one that targets what she edited rich(self.bpy.mesh) self.target.track_human_edits(depsgraph(update("Cube", transform=True))) - receipt = self.run_action(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + receipt = self.run_action(action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 5]) self.assertEqual(receipt["status"], "accepted", receipt["message"]) self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted") self.assertEqual(len(self.bpy.undo.pushes), 2) diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index a36df4a..d9abebc 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -20,6 +20,7 @@ package = types.ModuleType("brokkr_bridge") package.__path__ = [str(ADDON)] sys.modules.setdefault("brokkr_bridge", package) +from brokkr_bridge import action_table as at # noqa: E402 from brokkr_bridge import blender_target as bt # noqa: E402 from brokkr_bridge import scene_actions as sa # noqa: E402 @@ -218,27 +219,18 @@ class ActionTests(unittest.TestCase): # setCamera def test_set_camera_sets_lens_type_panorama_and_active(self): - receipt = self.run_action(action="setCamera", targetObjectName="Cam", lens=35, cameraType="pano", + receipt = self.run_action(action="setCamera", targetObjectName="Cam", lens=35, cameraType="PANO", panoramaType="EQUIRECTANGULAR", active=True, clipEnd=500) self.assertEqual(receipt["status"], "accepted") d = self.bpy.camera_data self.assertEqual((d.lens, d.type, d.panorama_type, d.clip_end), (35.0, "PANO", "EQUIRECTANGULAR", 500.0)) self.assertIs(self.bpy.scene.camera, self.bpy.cam) - def test_set_camera_falls_back_to_the_cycles_panorama_property(self): - cycles = NS(panorama_type="FISHEYE_EQUISOLID", - bl_rna=NS(properties={"panorama_type": Enum("EQUIRECTANGULAR")})) - data = NS(lens=50.0, type="PERSP", cycles=cycles) - self.bpy.data.objects["Cam"] = NS(name="Cam", type="CAMERA", data=data) - receipt = self.run_action(action="setCamera", targetObjectName="Cam", panoramaType="EQUIRECTANGULAR") - self.assertEqual(receipt["status"], "accepted") - self.assertEqual(cycles.panorama_type, "EQUIRECTANGULAR") - def test_set_camera_refused_input_changes_nothing(self): for bad in ({"lens": -1}, {"lens": "wide"}, {"lens": float("nan")}, {"cameraType": "FISHEYE"}, {"panoramaType": "NOPE"}, {"lens": True}): receipt = self.run_action(action="setCamera", targetObjectName="Cam", clipEnd=9, **bad) - self.assertEqual(receipt["status"], "failed", bad) + self.assertEqual(receipt["status"], "denied", bad) # the table's refusal: admission, nothing ran self.assertEqual(self.bpy.camera_data.clip_end, 100.0) self.assertEqual(self.run_action(action="setCamera", targetObjectName="Lamp", lens=35)["status"], "failed") self.assertEqual(self.run_action(action="setCamera", targetObjectName="Nope", lens=35)["status"], "failed") @@ -251,7 +243,7 @@ class ActionTests(unittest.TestCase): def test_set_light_rejects_bad_values_whole(self): for bad in ({"energy": -5}, {"color": [2, 0, 0]}, {"color": [1, 0]}, {"color": "red"}, {"lightType": "LASER"}): - self.assertEqual(self.run_action(action="setLight", targetObjectName="Lamp", **bad)["status"], "failed", bad) + self.assertEqual(self.run_action(action="setLight", targetObjectName="Lamp", **bad)["status"], "denied", bad) self.assertEqual(self.bpy.light_data.energy, 1000.0) self.assertEqual(self.run_action(action="setLight", targetObjectName="Cam", energy=1)["status"], "failed") @@ -265,7 +257,7 @@ class ActionTests(unittest.TestCase): self.assertEqual(world.background.inputs["Strength"].default_value, 2.0) def test_set_world_refuses_bad_colour_before_creating_a_world(self): - self.assertEqual(self.run_action(action="setWorld", color=[9, 0, 0])["status"], "failed") + self.assertEqual(self.run_action(action="setWorld", color=[9, 0, 0])["status"], "denied") self.assertIsNone(self.bpy.scene.world) # exportGltf @@ -335,18 +327,16 @@ class ActionTests(unittest.TestCase): def test_export_refusals_never_reach_bpy_or_disk(self): (self.root / "out" / "taken.glb").write_bytes(b"old") + denied = [{"filepath": 5}, {"filepath": "a.glb", "selection": []}, {"filepath": "a.glb", "selection": "Cube"}, + {"filepath": "a.glb", "selection": [3]}, {"filepath": "a.glb", "extras": "yes"}, {"filepath": "a.glb", "yUp": 1}] + for case in denied: # the table refuses these at admission + self.assertEqual(self.run_action(action="exportGltf", **case)["status"], "denied", case) cases = [ - {"filepath": "a.obj"}, {"filepath": "a"}, {"filepath": ""}, {"filepath": 5}, + {"filepath": "a.obj"}, {"filepath": "a"}, {"filepath": ""}, {"filepath": "../a.glb"}, {"filepath": str(self.root / "a.glb")}, {"filepath": "taken.glb"}, {"filepath": "a.glb", "selection": ["Nope"]}, {"filepath": "a.glb", "selection": ["Cube", "Nope"]}, - {"filepath": "a.glb", "selection": []}, - {"filepath": "a.glb", "selection": "Cube"}, - {"filepath": "a.glb", "selection": [3]}, - {"filepath": "a.glb", "extras": "yes"}, - {"filepath": "a.glb", "yUp": 1}, - {"filepath": "a.glb", "applyModifiers": None}, ] for case in cases: self.assertEqual(self.run_action(action="exportGltf", **case)["status"], "failed", case) @@ -527,7 +517,7 @@ class ActionTests(unittest.TestCase): # renderStill def test_render_still_writes_inside_output_dir_and_restores_settings(self): - receipt = self.run_action(action="renderStill", outputPath="shots/a.png", engine="cycles", + receipt = self.run_action(action="renderStill", outputPath="shots/a.png", engine="CYCLES", resolutionX=640, resolutionY=360, cameraName="Cam") self.assertEqual(receipt["status"], "accepted") engine, x, y, filepath, fmt, camera = self.bpy.rendered[0] @@ -547,10 +537,13 @@ class ActionTests(unittest.TestCase): self.assertEqual(self.bpy.scene.render.engine, "BLENDER_EEVEE") def test_render_still_outside_the_output_dir_or_with_bad_input_never_renders(self): + for case in ({"outputPath": "a.png", "resolutionX": 0}, {"outputPath": "a.png", "resolutionX": 3}, + {"outputPath": "a.png", "resolutionX": 99999}, {"outputPath": "a.png", "resolutionX": 10.5}, + {"outputPath": "a.png", "engine": ""}, {"outputPath": "a.png", "resolutionY": "x"}): + self.assertEqual(self.run_action(action="renderStill", **case)["status"], "denied", case) cases = [{"outputPath": "../a.png"}, {"outputPath": str(self.root / "a.png")}, {"outputPath": "a.txt"}, - {"outputPath": ""}, {"outputPath": "a.png", "engine": "NOPE"}, - {"outputPath": "a.png", "resolutionX": 0}, {"outputPath": "a.png", "resolutionX": 99999}, - {"outputPath": "a.png", "resolutionX": 10.5}, {"outputPath": "a.png", "cameraName": "Lamp"}] + {"outputPath": ""}, {"outputPath": "a.png", "engine": "NOPE"}, {"outputPath": "a.png", "engine": "cycles"}, + {"outputPath": "a.png", "cameraName": "Lamp"}] for case in cases: self.assertEqual(self.run_action(action="renderStill", **case)["status"], "failed", case) self.assertEqual(self.bpy.rendered, []) @@ -563,35 +556,38 @@ class ActionTests(unittest.TestCase): receipt = self.run_action(action="createObject", objectType=kind, name="N") self.assertEqual(receipt["status"], "accepted", kind) self.assertEqual(self.bpy.created[-1][0], kind) - self.assertEqual(self.run_action(action="createObject", objectType="MESH", meshType="cube")["status"], "accepted") + self.assertEqual(self.run_action(action="createObject", objectType="MESH", meshType="CUBE")["status"], "accepted") - def test_create_object_refuses_other_types_naming_the_type_and_the_allowed_set(self): - for kind in ("TEXT", "CURVE", "mesh", "", None, 3): + def test_create_object_refuses_other_types_naming_the_field_and_the_allowed_set(self): + for kind in ("TEXT", "CURVE", "mesh", ""): receipt = self.run_action(action="createObject", objectType=kind) - self.assertEqual(receipt["status"], "failed", kind) - for allowed in ("MESH", "LIGHT", "CAMERA", "EMPTY"): - self.assertIn(allowed, receipt["message"]) - self.assertIn(repr(kind) if not isinstance(kind, str) else kind, receipt["message"]) + self.assertEqual(receipt["status"], "denied", kind) + self.assertEqual(receipt["message"], "objectType must be one of MESH, LIGHT, CAMERA, EMPTY.") + receipt = self.run_action(action="createObject", objectType=3) + self.assertEqual((receipt["status"], receipt["message"]), ("denied", "objectType must be a string.")) self.assertEqual(self.bpy.created, []) + self.assertEqual(self.run_action(action="createObject", objectType=None)["status"], "accepted") # null is absent: EMPTY + self.assertEqual(self.bpy.created[-1][0], "EMPTY") def test_create_object_refuses_a_mesh_type_other_than_cube(self): - for mesh_type in ("CYLINDER", "", 1, " CUBE", "CUBE "): + for mesh_type in ("CYLINDER", "", 1, " CUBE", "CUBE ", "cube"): receipt = self.run_action(action="createObject", objectType="MESH", meshType=mesh_type) - self.assertEqual(receipt["status"], "failed", mesh_type) - self.assertIn("CUBE", receipt["message"]) + self.assertEqual(receipt["status"], "denied", mesh_type) + self.assertIn("meshType must be", receipt["message"]) self.assertEqual(self.bpy.created, []) def test_mesh_type_on_a_non_mesh_object_is_refused_not_ignored(self): for object_type in ("LIGHT", "EMPTY", "CAMERA"): - receipt = self.run_action(action="createObject", objectType=object_type, meshType="CYLINDER") - self.assertEqual(receipt["status"], "failed", object_type) - self.assertIn("MESH", receipt["message"]) + receipt = self.run_action(action="createObject", objectType=object_type, meshType="CUBE") + self.assertEqual(receipt["status"], "denied", object_type) + self.assertEqual(receipt["message"], "meshType applies only when objectType is one of MESH.") + self.assertEqual(self.run_action(action="createObject", meshType="CUBE")["status"], "denied") # objectType absent is EMPTY self.assertEqual(self.bpy.created, []) # renderStill: GPU engines that would abort a headless Blender def test_render_still_refuses_gpu_engines_headless_when_a_test_render_fails(self): self.bpy.app.background = True - for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT", "blender_workbench"): + for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT"): self.bpy.scene.render.ENGINES = FakeRender.ENGINES + ("BLENDER_EEVEE_NEXT",) with mock.patch.object(bt, "gl_render_failure", return_value="a one-pixel test render exited with status 134"): receipt = self.run_action(action="renderStill", outputPath="a.png", engine=engine) @@ -844,10 +840,12 @@ class ActionTests(unittest.TestCase): def test_a_refused_render_leaves_no_folders_behind(self): (self.root / "out" / "taken").mkdir() (self.root / "out" / "taken" / "a.png").write_bytes(b"x") - for case in ({"outputPath": "new/deep/a.png", "resolutionX": 0}, {"outputPath": "new/deep/a.png", "engine": ""}, {"outputPath": "new/deep/a.png", "engine": "NOPE"}, + for case in ({"outputPath": "new/deep/a.png", "engine": "NOPE"}, {"outputPath": "new/deep/a.png", "cameraName": "Nope"}, {"outputPath": "new/deep/a.txt"}, {"outputPath": "taken/a.png"}): self.assertEqual(self.run_action(action="renderStill", **case)["status"], "failed", case) + for case in ({"outputPath": "new/deep/a.png", "resolutionX": 0}, {"outputPath": "new/deep/a.png", "engine": ""}): + self.assertEqual(self.run_action(action="renderStill", **case)["status"], "denied", case) self.assertIn("already exists", self.run_action(action="renderStill", outputPath="taken/a.png")["message"]) self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["taken"]) self.assertEqual(self.bpy.rendered, []) From 90695765513b349537a260c4614bc2f295eab03a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 02:51:35 +0100 Subject: [PATCH 045/223] brokkr-ctl: embed the action table for send --help and pre-validation brokkr-ctl/src/actions.rs include_str!s the add-on's actions.json, reads entries as data (serde_json Value, no generated types) and implements the same vocabulary and message text as action_table.py. `send --help` is built from it; `send` refuses an intent the table refuses with exit 1 and writes nothing; --set refuses the table's envelope names. Deleted: the hand-written ACTIONS/Field help table, RESERVED, the letters-and-digits action check and the source-scraping drift test. The shared fixture action_cases.json (231 cases) is run by both validators. Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/src/actions.rs | 456 ++++++++++++++++++++++++++++++++++++++ brokkr-ctl/src/blender.rs | 198 +---------------- brokkr-ctl/src/main.rs | 1 + brokkr-ctl/tests/cli.rs | 103 +++++++-- 4 files changed, 544 insertions(+), 214 deletions(-) create mode 100644 brokkr-ctl/src/actions.rs diff --git a/brokkr-ctl/src/actions.rs b/brokkr-ctl/src/actions.rs new file mode 100644 index 0000000..590b29c --- /dev/null +++ b/brokkr-ctl/src/actions.rs @@ -0,0 +1,456 @@ +//! The Blender action table, embedded: `send --help` is built from it and `send` refuses an intent it +//! refuses. The owner is the add-on's `actions.json` (schema brokkr.blender.actions.v0); this module reads +//! it as data and implements the same vocabulary and message text as `action_table.py`, pinned to it by +//! the shared fixture `surfaces/blender/tests/action_cases.json`. Anything that reaches the store is still +//! decided by the add-on. + +use serde_json::{Map, Value}; +use std::sync::LazyLock; + +const TABLE_JSON: &str = include_str!("../../surfaces/blender/brokkr_bridge/actions.json"); + +static TABLE: LazyLock = + LazyLock::new(|| serde_json::from_str(TABLE_JSON).expect("actions.json is valid JSON")); + +pub fn table() -> &'static Value { + &TABLE +} + +fn actions() -> &'static [Value] { + table()["actions"].as_array().map_or(&[], Vec::as_slice) +} + +fn entry(name: &str) -> Option<&'static Value> { + actions().iter().find(|a| a["name"] == name) +} + +/// The names brokkr-ctl writes itself: `--set` cannot name them, and the table does not validate them. +pub fn envelope() -> Vec<&'static str> { + table()["envelope"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect() +} + +fn type_words(kind: &str) -> &'static str { + match kind { + "string" => "a string", + "number" => "a finite number", + "integer" => "a whole number", + "boolean" => "true or false", + "array" => "an array", + "object" => "an object", + _ => "a value", + } +} + +fn join(items: &Value) -> String { + items + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect::>() + .join(", ") +} + +/// A bound as messages and help print it: whole values without a fraction, others as the shortest digits. +pub fn number_text(value: f64) -> String { + if value == value.trunc() { + format!("{}", value as i128) + } else { + format!("{value}") + } +} + +/// Refuses an intent the table refuses, with the add-on's message; nothing is normalized (the add-on fills defaults). +pub fn validate(command: &Map) -> Result<(), String> { + let action = command.get("action").and_then(Value::as_str).unwrap_or(""); + let Some(row) = entry(action) else { + return Err(format!("Unsupported Blender command action: {action}")); + }; + let present: Map = command + .iter() + .filter(|(_, v)| !v.is_null()) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + fields( + row["fields"].as_array().map_or(&[], Vec::as_slice), + &present, + None, + action, + &envelope(), + ) +} + +fn fields( + specs: &[Value], + values: &Map, + parent: Option<&str>, + whole: &str, + skip: &[&str], +) -> Result<(), String> { + let declared: Vec<&str> = specs.iter().filter_map(|s| s["name"].as_str()).collect(); + let mut unknown: Vec<&String> = values + .keys() + .filter(|k| !skip.contains(&k.as_str()) && !declared.contains(&k.as_str())) + .collect(); + unknown.sort(); + if let Some(key) = unknown.first() { + let listed = if declared.is_empty() { + "none".to_string() + } else { + declared.join(", ") + }; + return Err(format!( + "{whole} has no field '{key}'; its fields: {listed}." + )); + } + for spec in specs { + let name = spec["name"].as_str().unwrap_or(""); + let path = parent.map_or_else(|| name.to_string(), |p| format!("{p}.{name}")); + let Some(value) = values.get(name) else { + if spec["required"] == true { + return Err(format!("{path} is required.")); + } + continue; + }; + if let Some(only) = spec.get("only") { + let sibling = only["field"].as_str().and_then(|f| values.get(f)); + let allowed = only["in"].as_array().map_or(&[][..], Vec::as_slice); + if !sibling.is_some_and(|v| allowed.contains(v)) { + return Err(format!( + "{path} applies only when {} is one of {}.", + only["field"].as_str().unwrap_or(""), + join(&only["in"]) + )); + } + } + check_value(spec, value, &path)?; + } + Ok(()) +} + +fn check_value(spec: &Value, value: &Value, path: &str) -> Result<(), String> { + let kind = spec["type"].as_str().unwrap_or(""); + match kind { + "any" => {} + "number" | "integer" => check_number(spec, value, path, kind)?, + "string" => { + let Some(text) = value.as_str() else { + return Err(format!("{path} must be {}.", type_words(kind))); + }; + if let Some(allowed) = spec.get("enum") { + if !allowed + .as_array() + .is_some_and(|list| list.iter().any(|e| e.as_str() == Some(text))) + { + return Err(format!("{path} must be one of {}.", join(allowed))); + } + } else { + check_string(spec, text, path)?; + } + } + "boolean" => { + if !value.is_boolean() { + return Err(format!("{path} must be {}.", type_words(kind))); + } + } + "array" => { + let Some(items) = value.as_array() else { + return Err(format!("{path} must be {}.", type_words(kind))); + }; + if spec["minItems"] + .as_u64() + .is_some_and(|n| (items.len() as u64) < n) + { + return Err(format!( + "{path} must have at least {} items.", + spec["minItems"] + )); + } + if spec["maxItems"] + .as_u64() + .is_some_and(|n| (items.len() as u64) > n) + { + return Err(format!( + "{path} must have at most {} items.", + spec["maxItems"] + )); + } + let item_spec = &spec["items"]; + for (index, item) in items.iter().enumerate() { + if item.is_null() { + return Err(format!( + "{path}[{index}] must be {}.", + type_words(item_spec["type"].as_str().unwrap_or("")) + )); + } + check_value(item_spec, item, &format!("{path}[{index}]"))?; + } + } + "object" => { + let Some(map) = value.as_object() else { + return Err(format!("{path} must be {}.", type_words(kind))); + }; + if let Some(properties) = spec["properties"].as_array() { + let present: Map = map + .iter() + .filter(|(_, v)| !v.is_null()) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + fields(properties, &present, Some(path), path, &[])?; + } + } + _ => {} + } + Ok(()) +} + +fn check_number(spec: &Value, value: &Value, path: &str, kind: &str) -> Result<(), String> { + let wrong = || format!("{path} must be {}.", type_words(kind)); + let Value::Number(number) = value else { + return Err(wrong()); + }; + let x = number + .as_f64() + .filter(|x| x.is_finite()) + .ok_or_else(wrong)?; + if kind == "integer" && !(number.is_i64() || number.is_u64() || x == x.trunc()) { + return Err(wrong()); + } + let (min, max) = ( + spec["minimum"].as_f64().unwrap_or(f64::MIN), + spec["maximum"].as_f64().unwrap_or(f64::MAX), + ); + if x < min || x > max { + return Err(format!( + "{path} must be between {} and {}.", + number_text(min), + number_text(max) + )); + } + Ok(()) +} + +fn check_string(spec: &Value, text: &str, path: &str) -> Result<(), String> { + let length = text.chars().count() as u64; + if spec["minLength"].as_u64().is_some_and(|n| length < n) { + return Err(format!( + "{path} must have at least {} characters.", + spec["minLength"] + )); + } + if spec["maxLength"].as_u64().is_some_and(|n| length > n) { + return Err(format!( + "{path} must have at most {} characters.", + spec["maxLength"] + )); + } + if let Some(name) = spec["chars"].as_str() { + let set = &table()["charsets"][name]; + let allowed = set["allowed"].as_str().unwrap_or(""); + if text.chars().any(|c| !allowed.contains(c)) { + return Err(format!( + "{path} may contain only {}.", + set["text"].as_str().unwrap_or("") + )); + } + } + if let Some(prefixes) = spec["prefixes"].as_array() { + let fits = prefixes + .iter() + .filter_map(Value::as_str) + .any(|p| text.starts_with(p) && text.chars().count() > p.chars().count()); + if !fits { + return Err(format!( + "{path} must start with one of {} and have at least one more character.", + join(&spec["prefixes"]) + )); + } + } + for part in spec["forbid"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + if text.contains(part) { + return Err(format!("{path} may not contain '{part}'.")); + } + } + Ok(()) +} + +/// The actions section of `send --help`: every action with its fields, built from the table. +pub fn help() -> String { + let mut text = String::new(); + for action in actions() { + text.push_str(&format!( + " {}: {}\n", + action["name"].as_str().unwrap_or(""), + action["doc"].as_str().unwrap_or("") + )); + field_lines( + &mut text, + action["fields"].as_array().map_or(&[], Vec::as_slice), + 6, + ); + } + text +} + +fn field_lines(text: &mut String, specs: &[Value], indent: usize) { + for spec in specs { + let mut line = format!( + "{}{}: {}", + " ".repeat(indent), + spec["name"].as_str().unwrap_or(""), + describe(spec) + ); + if spec["required"] == true { + line.push_str(", required"); + } + if let Some(default) = spec.get("default") { + line.push_str(&format!(", default {default}")); + } + if let Some(only) = spec.get("only") { + line.push_str(&format!( + ", only when {} is {}", + only["field"].as_str().unwrap_or(""), + join(&only["in"]).replace(", ", "|") + )); + } + if let Some(doc) = spec["doc"].as_str() { + line.push_str(&format!(" ({doc})")); + } + text.push_str(&line); + text.push('\n'); + if let Some(properties) = spec["items"]["properties"].as_array() { + field_lines(text, properties, indent + 4); + } + } +} + +fn describe(spec: &Value) -> String { + let kind = spec["type"].as_str().unwrap_or(""); + let mut parts = vec![match kind { + "any" => "json".to_string(), + "boolean" => "bool".to_string(), + other => other.to_string(), + }]; + if let Some(values) = spec.get("enum") { + parts.push(join(values).replace(", ", "|")); + } + if let (Some(min), Some(max)) = (spec["minimum"].as_f64(), spec["maximum"].as_f64()) { + parts.push(format!("{}..{}", number_text(min), number_text(max))); + } + if spec.get("minLength").is_some() || spec.get("maxLength").is_some() { + let min = spec["minLength"].as_u64().unwrap_or(0); + parts.push(match spec["maxLength"].as_u64() { + Some(max) => format!("{min}..{max} characters"), + None => format!("at least {min} characters"), + }); + } + if let Some(name) = spec["chars"].as_str() { + parts.push( + table()["charsets"][name]["text"] + .as_str() + .unwrap_or("") + .to_string(), + ); + } + if spec.get("prefixes").is_some() { + parts.push(format!( + "starts with {}", + join(&spec["prefixes"]).replace(", ", "|") + )); + } + if spec.get("forbid").is_some() { + parts.push(format!( + "without {}", + join(&spec["forbid"]).replace(", ", "|") + )); + } + if kind == "array" { + let (min, max) = (spec["minItems"].as_u64(), spec["maxItems"].as_u64()); + let count = match (min, max) { + (Some(a), Some(b)) if a == b => format!("{a} items"), + (Some(a), Some(b)) => format!("{a}..{b} items"), + (Some(a), None) => format!("at least {a} items"), + (None, Some(b)) => format!("at most {b} items"), + (None, None) => String::new(), + }; + parts.push(format!("[{}]", describe(&spec["items"]))); + if !count.is_empty() { + parts.push(count); + } + } + parts.join(" ") +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The same cases the add-on's test_action_table runs through action_table.py: one table, two + /// interpreters, one set of messages. + #[test] + fn the_parity_fixture_yields_the_add_ons_messages() { + let cases: Vec = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/action_cases.json" + )) + .unwrap(); + assert!(cases.len() > 200, "{} cases", cases.len()); + let mut wrong = Vec::new(); + for case in &cases { + let mut command = case["fields"].as_object().unwrap().clone(); + command.insert("action".into(), case["action"].clone()); + let got = validate(&command).err().unwrap_or_else(|| "ok".to_string()); + if Some(got.as_str()) != case["expect"].as_str() { + wrong.push(format!( + "{} {} expected {} got {got}", + case["action"], case["fields"], case["expect"] + )); + } + } + assert!( + wrong.is_empty(), + "{} of {} differ:\n{}", + wrong.len(), + cases.len(), + wrong.join("\n") + ); + } + + #[test] + fn a_non_string_action_is_unsupported_and_the_envelope_is_the_tables() { + let mut command = Map::new(); + command.insert("action".into(), Value::from(3)); + assert_eq!( + validate(&command).unwrap_err(), + "Unsupported Blender command action: " + ); + assert_eq!( + envelope(), + ["schema", "commandId", "action", "requestedBy", "note"] + ); + } + + #[test] + fn numbers_print_the_way_the_add_on_prints_them() { + for (value, text) in [ + (0.0, "0"), + (4.0, "4"), + (1e7, "10000000"), + (0.001, "0.001"), + (0.0001, "0.0001"), + (1e9, "1000000000"), + (-1e9, "-1000000000"), + ] { + assert_eq!(number_text(value), text); + } + } +} diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index 9bb89d1..e404585 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -2,6 +2,7 @@ //! document per `send` and reads receipts and the host snapshot. The add-on decides. use anyhow::{Context, Result, anyhow, bail}; +use crate::actions; use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, SingleFileMessagePackBackingStore}; use serde_json::{Map, Value}; use std::path::PathBuf; @@ -14,7 +15,6 @@ pub const SNAPSHOT_SCHEMA: &str = "brokkr.blender.host_snapshot.v0"; const INTENT_PREFIX: &str = "blender/commands/"; const RECEIPT_PREFIX: &str = "blender/receipts/"; const SNAPSHOT_KEY: &str = "blender/host/current"; -const RESERVED: [&str; 5] = ["schema", "commandId", "action", "requestedBy", "note"]; const DEFAULT_TIMEOUT_SECS: u64 = 60; const POLL: Duration = Duration::from_millis(200); const MAX_TIMEOUT: Duration = Duration::from_secs(24 * 3600); @@ -215,15 +215,12 @@ fn build_intent( note: &str, sets: &[String], ) -> Result { - if action.is_empty() || !action.chars().all(|c| c.is_ascii_alphanumeric()) { - bail!("action must be letters and digits, e.g. createObject"); - } let mut map = Map::new(); for set in sets { let (key, raw) = set .split_once('=') .ok_or_else(|| anyhow!("--set wants key=json, got {set:?}"))?; - if key.is_empty() || RESERVED.contains(&key) { + if key.is_empty() || actions::envelope().contains(&key) { bail!("--set cannot name {key:?}: it is written by brokkr-ctl"); } let value: Value = serde_json::from_str(raw) @@ -235,6 +232,7 @@ fn build_intent( map.insert("action".into(), action.into()); map.insert("requestedBy".into(), requested_by.into()); map.insert("note".into(), note.into()); + actions::validate(&map).map_err(|message| anyhow!(message))?; Ok(Value::Object(map)) } @@ -414,8 +412,8 @@ brokkr-ctl blender: send typed intents to the live Blender add-on and read what Every command needs --store or $BROKKR_BLENDER_STORE (the add-on's .ccmp). send needs $EUREKA_INSTANCE and --agent or $BROKKR_AGENT; requestedBy is '/'. Output is 'key: value' lines. Exit: 0 accepted, 2 denied or failed, 3 stopped, 4 timeout, -1 usage or store error. brokkr-ctl validates nothing about an action: the add-on does, and -its refusal comes back in the receipt. +1 usage or store error. send refuses an intent the action table refuses (exit 1, nothing written); +the add-on decides the rest and its refusal comes back in the receipt. " .to_string() } @@ -426,196 +424,16 @@ pub fn send_help() -> String { brokkr-ctl blender send [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs] --set takes JSON: --set objectType='\"MESH\"' --set location='[0,0,1]'. brokkr-ctl writes schema, -commandId, action, requestedBy and note itself; --set cannot name them. Fields below are what the -add-on reads; it validates them and refuses in the receipt. Targets also accept objectName. +commandId, action, requestedBy and note itself; --set cannot name them. Below is the add-on's action +table (actions.json): every field an action reads; null means absent; a field not listed is refused. actions: ", ); - for (action, fields) in ACTIONS { - text.push_str(&format!(" {action}\n")); - for (name, kind, note) in *fields { - text.push_str(&format!(" {name}: {kind} {note}\n")); - } - } + text.push_str(&actions::help()); text } -type Field = (&'static str, &'static str, &'static str); - -/// Help text only: what the add-on's `execute_command` dispatches and reads at the base commit. -const ACTIONS: &[(&str, &[Field])] = &[ - ( - "createObject", - &[ - ("objectType", "string", "MESH | LIGHT | CAMERA | EMPTY (default EMPTY)"), - ("name", "string", ""), - ("location", "[x,y,z]", ""), - ("size", "number", "MESH"), - ("meshType", "string", "CUBE"), - ("lightType", "string", "LIGHT"), - ("emptyDisplayType", "string", "EMPTY"), - ], - ), - ("deleteObject", &[("targetObjectName", "string", "")]), - ( - "setObjectTransform", - &[ - ("targetObjectName", "string", ""), - ("location", "[x,y,z]", ""), - ("rotationEuler", "[x,y,z]", "radians"), - ("scale", "[x,y,z]", ""), - ], - ), - ( - "setObjectVisibility", - &[("targetObjectName", "string", ""), ("visible", "bool", "")], - ), - ( - "setObjectParent", - &[ - ("targetObjectName", "string", ""), - ("parentObjectName", "string", "empty clears the parent"), - ], - ), - ( - "setObjectCustomProperty", - &[ - ("targetObjectName", "string", ""), - ("propertyName", "string", ""), - ("value", "json", ""), - ], - ), - ( - "selectObject", - &[("targetObjectName", "string", ""), ("clearSelection", "bool", "default true")], - ), - ( - "assignMaterial", - &[ - ("targetObjectName", "string", ""), - ("materialName", "string", ""), - ("color", "[r,g,b] or [r,g,b,a]", "linear, 0..1"), - ], - ), - ( - "importGltf", - &[("filepath", "string", "inside the add-on's import directory")], - ), - ( - "exportGltf", - &[ - ("filepath", "string", ".glb or .gltf inside the add-on's output directory"), - ("extras", "bool", ""), - ("yUp", "bool", ""), - ("applyModifiers", "bool", ""), - ("selection", "[string]", "object names"), - ], - ), - ( - "setCamera", - &[ - ("targetObjectName", "string", ""), - ("lens", "number", "mm"), - ("cameraType", "string", ""), - ("orthoScale", "number", ""), - ("clipStart", "number", ""), - ("clipEnd", "number", ""), - ("panoramaType", "string", ""), - ("active", "bool", "make it the scene camera"), - ], - ), - ( - "setLight", - &[ - ("targetObjectName", "string", ""), - ("energy", "number", ""), - ("color", "[r,g,b]", "linear, 0..1"), - ("lightType", "string", ""), - ], - ), - ( - "setWorld", - &[ - ("worldName", "string", ""), - ("color", "[r,g,b]", "linear, 0..1"), - ("strength", "number", ""), - ], - ), - ( - "renderStill", - &[ - ("outputPath", "string", "inside the add-on's output directory"), - ("engine", "string", ""), - ("resolutionX", "integer", ""), - ("resolutionY", "integer", ""), - ("cameraName", "string", ""), - ], - ), - ("look", &[]), - ( - "createNodeGroup", - &[ - ("treeKey", "string", ""), - ("interface", "[{inOut,name,type,default?}]", "types: Geometry Float Int Bool Vector"), - ], - ), - ( - "addNode", - &[ - ("treeKey", "string", ""), - ("id", "string", "brokkr's key for the node"), - ("blIdname", "string", "GeometryNode*, FunctionNode* or ShaderNode*"), - ("location", "[x,y]", ""), - ("label", "string", ""), - ("properties", "object", "enum, bool, int or float node settings"), - ("inputs", "object", "unlinked input defaults"), - ], - ), - ("removeNode", &[("treeKey", "string", ""), ("id", "string", "")]), - ( - "linkSockets", - &[ - ("treeKey", "string", ""), - ("fromNode", "string", ""), - ("fromSocket", "string", ""), - ("toNode", "string", ""), - ("toSocket", "string", ""), - ], - ), - ( - "unlinkSockets", - &[ - ("treeKey", "string", ""), - ("toNode", "string", ""), - ("toSocket", "string", ""), - ("fromNode", "string", "optional"), - ("fromSocket", "string", "optional"), - ], - ), - ( - "addModifier", - &[ - ("objectName", "string", ""), - ("treeKey", "string", ""), - ("modifierName", "string", "default Brokkr GeoNodes"), - ], - ), - ( - "removeModifier", - &[("objectName", "string", ""), ("modifierName", "string", "")], - ), - ( - "setModifierInput", - &[ - ("objectName", "string", ""), - ("modifierName", "string", ""), - ("socket", "string", "identifier or unique interface name"), - ("value", "json", "Float, Int, Bool or Vector"), - ], - ), -]; - #[cfg(test)] mod tests { use super::*; diff --git a/brokkr-ctl/src/main.rs b/brokkr-ctl/src/main.rs index 1fc3dd8..41f1afc 100644 --- a/brokkr-ctl/src/main.rs +++ b/brokkr-ctl/src/main.rs @@ -1,5 +1,6 @@ //! brokkr-ctl: command-line hands for Brokkr's creative-tool surfaces. +mod actions; mod blender; fn main() { diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index a7293e1..59d0444 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -383,36 +383,91 @@ fn status_prints_the_snapshot_summary() { } } -/// A pin, not a copy: every action the add-on dispatches is in `send --help`, and every help field -/// name is a string the add-on source mentions. The add-on has no machine-readable action table. +fn table() -> Value { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../surfaces/blender/brokkr_bridge/actions.json"); + serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() +} + +fn bound(value: &Value) -> String { + let x = value.as_f64().unwrap(); + if x == x.trunc() { format!("{}", x as i64) } else { format!("{x}") } +} + +fn every_name(specs: &Value, out: &mut Vec) { + for spec in specs.as_array().unwrap() { + out.push(spec["name"].as_str().unwrap().to_string()); + if let Some(values) = spec["enum"].as_array() { + out.extend(values.iter().map(|v| v.as_str().unwrap().to_string())); + } + if let (Some(min), Some(max)) = (spec.get("minimum"), spec.get("maximum")) { + out.push(format!("{}..{}", bound(min), bound(max))); + } + if let Some(items) = spec.get("items") { + if let (Some(min), Some(max)) = (items.get("minimum"), items.get("maximum")) { + out.push(format!("{}..{}", bound(min), bound(max))); + } + if let Some(properties) = items.get("properties") { + every_name(properties, out); + } + } + } +} + +/// Help is the embedded table, not a copy: every action, field, enum value and bound in actions.json is +/// in `send --help`, and the help lists no action the table does not have. #[test] -fn help_names_every_dispatched_action_and_only_fields_the_addon_mentions() { - let addon = Path::new(env!("CARGO_MANIFEST_DIR")).join("../surfaces/blender/brokkr_bridge"); - let source: String = ["blender_target.py", "node_actions.py", "scene_actions.py"] - .iter() - .map(|file| std::fs::read_to_string(addon.join(file)).unwrap()) - .collect(); +fn help_names_every_action_field_enum_value_and_bound_of_the_table() { let help = stdout( &Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")).args(["blender", "send", "--help"]).output().unwrap(), ); - let mut dispatched: Vec = source - .lines() - .filter_map(|line| line.trim().strip_prefix("if action == \"")) - .filter_map(|rest| rest.split('"').next()) - .map(String::from) - .collect(); - let actions_line = source.lines().find(|l| l.trim_start().starts_with("ACTIONS = (\"")).unwrap(); - dispatched.extend(actions_line.split('"').skip(1).step_by(2).map(String::from)); - assert!(dispatched.len() >= 20, "{dispatched:?}"); - let listed: Vec<&str> = help.lines().filter_map(|l| l.strip_prefix(" ")).filter(|l| !l.starts_with(' ')).collect(); - for action in &dispatched { - assert!(listed.contains(&action.as_str()), "help lacks {action}"); + let table = table(); + let mut listed = Vec::new(); + for action in table["actions"].as_array().unwrap() { + let name = action["name"].as_str().unwrap(); + assert!(help.lines().any(|l| l.starts_with(&format!(" {name}: "))), "help lacks {name}"); + let mut wanted = Vec::new(); + every_name(&action["fields"], &mut wanted); + let section: Vec<&str> = help + .lines() + .skip_while(|l| !l.starts_with(&format!(" {name}: "))) + .skip(1) + .take_while(|l| l.starts_with(" ")) + .collect(); + let section = section.join(" +"); + for word in wanted { + assert!(section.contains(&word), "{name}: help lacks {word} +{section}"); + } + listed.push(name.to_string()); } - for action in &listed { - assert!(dispatched.iter().any(|d| d == action) || *action == "actions:", "help lists unknown {action}"); + for line in help.lines().filter(|l| l.starts_with(" ") && !l.starts_with(" ")) { + let name = line.trim().split(':').next().unwrap(); + assert!(listed.iter().any(|a| a == name), "help lists unknown {name}"); } - for field in help.lines().filter_map(|l| l.strip_prefix(" ")).filter_map(|l| l.split(':').next()) { - assert!(source.contains(&format!("\"{field}\"")), "add-on never mentions {field}"); + assert!(help.contains("cameraType: string PERSP|ORTHO|PANO"), "{help}"); + assert!(help.contains("resolutionX: integer 4..16384"), "{help}"); +} + +#[test] +fn an_intent_the_table_refuses_exits_1_and_writes_nothing() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let before = std::fs::read(&path).unwrap(); + let cases: [(&[&str], &str); 5] = [ + (&["send", "setCamera", "--set", "targetObjectName=\"Cam\"", "--set", "cameraType=\"CUSTOM\""], "cameraType must be one of PERSP, ORTHO, PANO."), + (&["send", "renderStill", "--set", "outputPath=\"a.png\"", "--set", "resolutionX=2"], "resolutionX must be between 4 and 16384."), + (&["send", "createObject", "--set", "bogus=1"], "createObject has no field 'bogus'"), + (&["send", "runPython"], "Unsupported Blender command action: runPython"), + (&["send", "deleteObject"], "targetObjectName is required."), + ]; + for (args, message) in cases { + let mut args = args.to_vec(); + args.extend(["--agent", "hands", "--no-wait"]); + let output = ctl(&path, &args, Some("nibu")); + assert_eq!(output.status.code(), Some(1), "{args:?}"); + assert!(String::from_utf8_lossy(&output.stderr).contains(message), "{args:?}: {}", String::from_utf8_lossy(&output.stderr)); + assert_eq!(std::fs::read(&path).unwrap(), before, "{args:?} wrote to the store"); } } From caf4b343626127caa055934c77b490159eb066d2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 02:53:03 +0100 Subject: [PATCH 046/223] Blender add-on: the drain claims an intent before it runs (at most once) drain_commands deleted the intent after writing its receipt, so a failed receipt write or a crash left an intent on the queue to run again. It now deletes the intent from the node first, then runs it, then writes the receipt; a receipt whose write raises is held (with its key suffix) and written first on the next drain, never read as truth. A delete that raises runs nothing and leaves the intent queued. Stop keeps receipt-then-delete: it runs nothing, so a re-stop cannot re-run an intent. A crash between claim and receipt loses the intent (the sender's wait times out, exit 4) rather than running it twice. Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/blender_target.py | 20 ++++- surfaces/blender/tests/test_agent_turn.py | 73 ++++++++++++++++++- surfaces/blender/tests/test_stop_presence.py | 2 +- 3 files changed, 89 insertions(+), 6 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index fab5357..4ab155d 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -121,6 +121,7 @@ class BrokkrBlenderTarget: self.agent_turn = False # true only inside run_intent self._wrote = True # run_intent: false when an accepted action changed nothing self._receipted: set[str] = set() + self._unsent: list[tuple[dict[str, Any], str]] = [] # receipts whose write failed: written first on the next drain, never read as truth self._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts self._receipts_loaded = False self.pending_count = 0 # display cache: intents queued in the node @@ -167,8 +168,15 @@ class BrokkrBlenderTarget: debug_mirror_root: str = "", limit: int | None = None, ) -> list[dict[str, Any]]: - """Run queued intents, oldest key first: all of them, or at most `limit`, the rest staying queued.""" + """Run queued intents, oldest key first: all of them, or at most `limit`, the rest staying queued. + + At most once: an intent is deleted from the node before it runs, so a failed receipt write or a + crash can never run it again. A receipt that could not be written is held and written first on + the next drain; the intent is not on the queue to be re-run.""" node, documents = self._open_node(cache_path, cultlib_py_src) + for receipt, suffix in list(self._unsent): + self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root, key_suffix=suffix) + self._unsent.pop(0) snapshot = node.database.snapshot() commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] @@ -178,6 +186,7 @@ class BrokkrBlenderTarget: command_id = command.get("commandId") valid = _valid_command_id(command_id) reused = valid and command_id in self._receipted + node.database.delete(documents["command_intent"], command_key) # claimed: nothing below can run it twice receipt = self.run_intent(context, command) if not valid: # No safe key exists for this id: the denial is receipted under a fresh key and names the @@ -185,10 +194,13 @@ class BrokkrBlenderTarget: receipt["message"] += f" (queue key {command_key})" # Receipts are write-once: a reused id's denial goes under '.denied', never over the # original. The sender learns of it by reading that key (and the drain's returned list). - self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root, - key_suffix=".denied" if reused else "") - node.database.delete(documents["command_intent"], command_key) + suffix = ".denied" if reused else "" receipts.append(receipt) + try: + self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root, key_suffix=suffix) + except Exception: + self._unsent.append((receipt, suffix)) + raise return receipts diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 523e0cb..9f23465 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -236,8 +236,11 @@ class FakeNode: """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" def __init__(self, intents, receipts=()): self.docs = {bt.COMMAND_INTENT_SCHEMA: dict(intents), bt.COMMAND_RECEIPT_SCHEMA: dict(receipts)} + self.initial = sorted(intents) self.puts = [] self.deleted = [] + self.put_failures = 0 # the next n puts raise + self.delete_failures = 0 # the next n deletes raise self.database = self self.runtime_id = "fake" @@ -248,10 +251,19 @@ class FakeNode: return {k: dict(v) for k, v in self.docs.items()} def put(self, document, key, value): + if self.put_failures: + self.put_failures -= 1 + raise OSError("store write failed") self.puts.append((key, value)) + if key.startswith("blender/receipts/"): + self.docs[bt.COMMAND_RECEIPT_SCHEMA][key] = value def delete(self, document, key): + if self.delete_failures: + self.delete_failures -= 1 + raise OSError("store delete failed") self.deleted.append(key) + self.docs[bt.COMMAND_INTENT_SCHEMA].pop(key, None) class DrainTests(unittest.TestCase): @@ -273,7 +285,7 @@ class DrainTests(unittest.TestCase): "blender/commands/c-good": self.intent("good-1"), }) receipts = self.drain(node) # must not raise - self.assertEqual(sorted(node.deleted), sorted(node.docs[bt.COMMAND_INTENT_SCHEMA])) + self.assertEqual(sorted(node.deleted), node.initial) self.assertEqual([r["status"] for r in receipts], ["denied", "denied", "accepted"]) keys = [k for k, _ in node.puts] self.assertTrue(all(isinstance(k, str) and "[" not in k for k in keys), keys) @@ -298,6 +310,65 @@ class DrainTests(unittest.TestCase): self.assertEqual(denial["status"], "denied") self.assertEqual(sorted(node.deleted), ["blender/commands/a", "blender/commands/b"]) + # claim-first: an intent leaves the queue before it runs, so no failure can run it twice + def test_the_intent_is_deleted_before_its_handler_runs(self): + node = FakeNode({"blender/commands/a": self.intent("claim-1")}) + seen = [] + original = self.bpy.ops.object.empty_add + self.bpy.ops.object.empty_add = lambda *a, **kw: (seen.append(list(node.deleted)), original(*a, **kw))[1] + self.drain(node) + self.assertEqual(seen, [["blender/commands/a"]]) + self.assertEqual(node.puts[0][0], "blender/receipts/claim-1") + + def test_a_failed_receipt_write_is_held_and_written_next_drain_and_the_intent_never_reruns(self): + node = FakeNode({"blender/commands/a": self.intent("held-1")}) + node.put_failures = 1 + with self.assertRaises(OSError): + self.drain(node) + self.assertEqual(len(self.bpy.created), 1) + self.assertEqual(node.docs[bt.COMMAND_INTENT_SCHEMA], {}) + self.assertEqual(node.puts, []) + self.assertEqual(self.drain(node), []) # nothing queued: it runs nothing and writes the held receipt + self.assertEqual([k for k, _ in node.puts], ["blender/receipts/held-1"]) # not '.denied' + self.assertEqual(node.puts[0][1]["status"], "accepted") + self.assertEqual(len(self.bpy.created), 1) + self.assertEqual(self.drain(node), []) + self.assertEqual(len(node.puts), 1) # written once + + def test_a_held_receipt_survives_a_second_failed_write(self): + node = FakeNode({"blender/commands/a": self.intent("held-2")}) + node.put_failures = 2 + with self.assertRaises(OSError): + self.drain(node) + with self.assertRaises(OSError): + self.drain(node) + self.assertEqual(self.drain(node), []) + self.assertEqual([k for k, _ in node.puts], ["blender/receipts/held-2"]) + self.assertEqual(len(self.bpy.created), 1) + + def test_a_fresh_target_on_the_same_node_runs_nothing_after_a_failed_write(self): + node = FakeNode({"blender/commands/a": self.intent("fresh-1")}) + node.put_failures = 1 + with self.assertRaises(OSError): + self.drain(node) + fresh = bt.BrokkrBlenderTarget(self.bpy) + docs = {"command_intent": "i", "command_receipt": "r"} + with unittest.mock.patch.object(fresh, "_open_node", return_value=(node, docs)): + self.assertEqual(fresh.drain_commands(self.context, "cache", "src"), []) + self.assertEqual(len(self.bpy.created), 1) # the intent is gone from the queue: nothing re-ran it + + def test_a_delete_that_raises_runs_nothing_and_leaves_the_intent_queued(self): + node = FakeNode({"blender/commands/a": self.intent("keep-1")}) + node.delete_failures = 1 + with self.assertRaises(OSError): + self.drain(node) + self.assertEqual(self.bpy.created, []) + self.assertEqual(node.puts, []) + self.assertIn("blender/commands/a", node.docs[bt.COMMAND_INTENT_SCHEMA]) + receipts = self.drain(node) # the retry claims and runs it + self.assertEqual([r["status"] for r in receipts], ["accepted"]) + self.assertEqual(len(self.bpy.created), 1) + if __name__ == "__main__": unittest.main() diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py index 4583ce0..5e732d9 100644 --- a/surfaces/blender/tests/test_stop_presence.py +++ b/surfaces/blender/tests/test_stop_presence.py @@ -52,7 +52,7 @@ class StopPendingTests(StopFixture): self.assertEqual(receipt["undoLabel"], "") self.assertEqual(receipt["action"], "createObject") self.assertEqual(receipts["blender/receipts/q-3"]["requestedBy"], "nibu/soul") - self.assertEqual(sorted(node.deleted), sorted(node.docs[bt.COMMAND_INTENT_SCHEMA])) + self.assertEqual(sorted(node.deleted), node.initial) self.assertEqual(self.bpy.created, []) # none dispatched self.assertEqual(self.bpy.undo.pushes, []) From 9d9c1178522b3463f62c68e84bcad3b0f393873f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 03:06:25 +0100 Subject: [PATCH 047/223] Action table: live proof in GUI Blender 5.3, live tests on the declared field names, docs point at the table tests/live/action_table.py (+ result): with the extension installed and the sink on, intents are queued as brokkr-ctl does and drained by the add-on's own timer. For all 23 actions of actions.json, 270 malformed intents generated from the table entries are each denied with no undo step and an unchanged scene (one undo reverts the canary before them); one valid intent per action is accepted and is exactly one undo step exactly when changesScene says so (undo restores, redo returns); one receipt write is held back and the intent still ran once. agent_turn_undo, agent_turn_queue, export_gltf, refusals, gn_actions and perception_fixes rerun on 5.3 with the declared field names and the denied/failed split; results refreshed. install.md, node-actions.md and provider-contract.md drop the field lists and point at actions.json and `send --help`. Co-Authored-By: Claude Sonnet 5.5 --- docs/provider-contract.md | 30 +- surfaces/blender/docs/install.md | 81 +- surfaces/blender/docs/node-actions.md | 27 +- surfaces/blender/tests/live/action_table.py | 388 +++ .../tests/live/action_table.result.json | 2543 +++++++++++++++++ .../tests/live/agent_turn_queue.result.json | 45 +- .../tests/live/agent_turn_undo.result.json | 4 +- .../tests/live/export_gltf.result.json | 10 +- surfaces/blender/tests/live/gn_actions.py | 4 +- .../blender/tests/live/gn_actions.result.json | 18 +- .../tests/live/perception_fixes.result.json | 114 +- surfaces/blender/tests/live/refusals.py | 4 +- .../blender/tests/live/refusals.result.json | 6 +- 13 files changed, 3098 insertions(+), 176 deletions(-) create mode 100644 surfaces/blender/tests/live/action_table.py create mode 100644 surfaces/blender/tests/live/action_table.result.json diff --git a/docs/provider-contract.md b/docs/provider-contract.md index 6ccbb10..e137bd7 100644 --- a/docs/provider-contract.md +++ b/docs/provider-contract.md @@ -207,30 +207,20 @@ id for each repetition. All Blender writes use `brokkr.blender.command_intent.v0` and receive `brokkr.blender.command_receipt.v0`. -- `createObject` -- `deleteObject` -- `setObjectTransform` -- `setObjectVisibility` -- `setObjectParent` -- `setObjectCustomProperty` -- `selectObject` -- `assignMaterial` -- `importGltf` -- `exportGltf` (writes under the add-on preference Render Output Directory, never overwriting) -- `setCamera` -- `setLight` -- `setWorld` -- `renderStill` -- `look` (a read: a PNG of her 3D view under the output directory's `look/`, her Edit Mode selection and her edit counters in the receipt) -- `createNodeGroup`, `addNode`, `removeNode`, `linkSockets`, `unlinkSockets`, `addModifier`, - `removeModifier`, `setModifierInput` (Geometry Nodes graphs; fields in - `surfaces/blender/docs/node-actions.md`) +The actions and their fields are one machine-readable table, +`surfaces/blender/brokkr_bridge/actions.json` (schema `brokkr.blender.actions.v0`): the add-on admits every +intent through it, and `brokkr-ctl blender send --help` prints it. It names each action's fields, types, enums, +bounds, defaults, whether the action changes the scene (one undo step), and whether it is safe in Edit Mode. An +intent the table refuses gets a `denied` receipt and changes nothing. Notes the table does not carry: +`exportGltf` writes under the add-on preference Render Output Directory, never overwriting; `look` is a read +(a PNG of her 3D view under the output directory's `look/`, her Edit Mode selection and her edit counters in the +receipt); the Geometry Nodes actions are described in `surfaces/blender/docs/node-actions.md`. Blender owns the mutation. Brokkr advertises the command surface; Verse clients write typed command intents; Blender executes recognized intents and publishes receipts. -`setObjectParent` uses `targetObjectName` and optional `parentObjectName`; an -empty parent reparents the object to the Blender scene root. +`setObjectParent` takes `targetObjectName` and an optional `parentObjectName`; an +empty or absent parent reparents the object to the Blender scene root. ## Operator Views diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index cf2c3c2..337b2e3 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -159,70 +159,55 @@ sync organ). 13. To publish an ad hoc sync variable, fill the `Ad Hoc Sync Var` fields in the sidebar or add-on preferences and click `Publish Sync Var`. -Admitted command actions: +Command actions and their fields are one table, `brokkr_bridge/actions.json` (schema +`brokkr.blender.actions.v0`): each action's fields with their types, enums, bounds, defaults and which +are required, and whether the action changes the scene (one undo step) and is safe in Edit Mode. +`brokkr-ctl blender send --help` prints it. The add-on admits every intent through that table and +nothing else: an unknown action, an unknown field (a name no action declares), a wrong type, an enum +that is not matched exactly (Blender's identifiers, case included), a number outside its bounds or a +missing required field is refused with a `denied` receipt that names the field and the rule; nothing +ran and no undo step was pushed. `null` counts as absent. `brokkr-ctl send` applies the same table +first and writes nothing for an intent it refuses. What only the scene can judge stays with the action +and answers `failed` (the object is not found or not the right type, a path escapes its directory, the +engine is not available in this Blender); a `failed` action that wrote part of its work is one labelled +undo step. Targets are named `targetObjectName` for the scene actions and `objectName` for the node +actions; there are no other spellings. -- `createObject` -- `deleteObject` -- `setObjectTransform` -- `setObjectVisibility` -- `setObjectParent` -- `setObjectCustomProperty` -- `selectObject` -- `assignMaterial` -- `importGltf` -- `exportGltf` -- `setCamera` -- `setLight` -- `setWorld` -- `renderStill` -- `look` +Behaviour the table does not say, per action: -Scene action fields (all other keys are ignored; a refused intent changes nothing and -gets a `failed` receipt whose message names the rule): - -- `createObject`: optional `objectType` (`MESH`, `LIGHT`, `CAMERA`, `EMPTY`; default `EMPTY`), - `name`, `location`. Any other `objectType` (for example `TEXT` or `CURVE`) is refused with - the allowed set named. A `MESH` is a cube (`size`); a `meshType` other than `CUBE` - (case-insensitive, no surrounding whitespace) is refused rather than ignored. - `meshType` on any other `objectType` is refused too; an explicit `objectType: null` is refused. +- `createObject`: a `MESH` is a cube of `size`. `lightType`, `emptyDisplayType` and `meshType` apply + only to their own `objectType`. +- `setObjectParent`: an empty or absent `parentObjectName` clears the parent. - `importGltf`: `filepath`, `.gltf` or `.glb`, relative to the add-on preference `Import Directory` (absolute paths, `..` and symlinks that resolve outside it are refused). Empty `Import Directory` disables the action. Needs Blender's glTF add-on. - `exportGltf`: `filepath`, `.glb` (binary) or `.gltf` (separate `.bin`), relative to the add-on preference `Render Output Directory` (the renderStill rules: no `..`, no links, and an existing name is refused; there is no overwrite). - Optional `extras` (custom properties become node `extras`), `yUp`, `applyModifiers` - (each true by default, must be a boolean) and `selection` (a non-empty list of object - names; any name not found, or not in the active view layer, refuses the export; the - selection is touched only when one is given, and restored afterwards). The exporter writes into a + `extras` makes custom properties node `extras`; a `selection` names objects, any name not found, + or not in the active view layer, refuses the export; the + selection is touched only when one is given, and restored afterwards. The exporter writes into a staging folder beside the target and Brokkr then moves each file into place (the `.glb`, or the `.gltf` with its `.bin` and texture files), refusing the whole export, naming the file, if any of those names is taken: nothing existing is overwritten. A refused or failed export leaves no file and no new folder, so the same name can be retried. Each export holds an OS lock on its staging folder; the next export removes any `.brokkr-export-*` folder under the output directory whose lock is free (its Blender died), and a rollback that itself fails is refused naming the files left, which that same sweep removes. Not checked: a link or swap made between the check and the move (the same residual as renderStill). The receipt message carries the written path and byte size. Needs Blender's glTF add-on. -- `setCamera`: `targetObjectName` (a camera object); optional `lens` (mm), - `cameraType` (`PERSP`, `ORTHO`, `PANO`), `panoramaType` (for example - `EQUIRECTANGULAR`; read from the camera, or from `camera.cycles` before Blender 4.2), - `orthoScale`, `clipStart`, `clipEnd`, `active` (true makes it the scene camera). - Panoramic cameras render in Cycles. -- `setLight`: `targetObjectName` (a light object); optional `energy` (>= 0), - `color` (linear `[r, g, b]`, each 0 to 1), `lightType` (`POINT`, `SUN`, `SPOT`, `AREA`). -- `setWorld`: optional `worldName` (default: the scene's world, created if there is - none), `color` (`[r, g, b]`), `strength`. Edits the world's Background node. -- `assignMaterial`: `targetObjectName` (an object with material slots, such as a mesh); - optional `materialName` (default `Brokkr Material`; an existing material of that name - is reused) and `color` (linear `[r, g, b]` or `[r, g, b, a]`, each a finite number 0 - to 1; alpha defaults to 1). `color` sets the Principled BSDF Base Color (the node tree - is created if the material has none) and `diffuse_color`; a malformed `color` is - refused naming the field and nothing is created or changed (`"color": null` counts as absent). Without `color` an +- `setCamera`: `targetObjectName` must be a camera object. `panoramaType` is a property of the camera + (Blender 4.2 and newer). Panoramic cameras render in Cycles. `cameraType` leaves out `CUSTOM`: it runs a script. +- `setLight`: `targetObjectName` must be a light object. `color` is linear. +- `setWorld`: without `worldName`, the scene's world, created if there is none. Edits the world's Background node. +- `assignMaterial`: `targetObjectName` must be an object with material slots, such as a mesh. An existing + material of that name is reused. `color` is linear `[r, g, b]` or `[r, g, b, a]`, alpha 1 when absent; it + sets the Principled BSDF Base Color (the node tree is created if the material has none) and + `diffuse_color`; a malformed `color` is refused and nothing is created or changed. Without `color` an existing material's colour is left as it is. Idempotent per (object, material): if the - object already has a slot with that material no second slot is added. Other keys are - ignored, as for every action. + object already has a slot with that material no second slot is added. - `renderStill`: `outputPath` relative to the preference `Render Output Directory`, - ending `.png`, `.jpg` or `.exr` (same containment rules as import); optional - `engine` (any engine of the running Blender, case-insensitive), `resolutionX`, - `resolutionY` (whole numbers, 1 to 16384), `cameraName`. Engine, resolution, + ending `.png`, `.jpg` or `.exr` (same containment rules as import). `engine` is an engine identifier of + the running Blender, matched exactly (Blender is asked by assignment; one it does not have is a `failed` + receipt). Resolutions are whole numbers of 4 or more: Blender stores 1 to 3 as 4 without a word, so + they are refused. Engine, resolution, camera, file path and format are restored after the render. The render blocks Blender's UI until it finishes. In a background (`-b`) Blender on Linux, the GL engines `BLENDER_WORKBENCH`, `BLENDER_EEVEE` and `BLENDER_EEVEE_NEXT` are refused diff --git a/surfaces/blender/docs/node-actions.md b/surfaces/blender/docs/node-actions.md index cdbb556..b481c21 100644 --- a/surfaces/blender/docs/node-actions.md +++ b/surfaces/blender/docs/node-actions.md @@ -1,20 +1,23 @@ # Geometry node graph actions Command intents (`brokkr.blender.command_intent.v0`) that build and drive a Geometry Nodes graph. -Owner: `brokkr_bridge/node_actions.py`; the target only dispatches. Every field is validated before -`bpy` is touched; a refused intent is a `failed` receipt naming the rule and leaves the tree as it was. +Owner of how an intent becomes a graph: `brokkr_bridge/node_actions.py`; the target only dispatches. The +actions' fields, types and bounds are `brokkr_bridge/actions.json` (printed by `brokkr-ctl blender send --help`): +a field the table refuses is a `denied` receipt naming the rule, before `bpy` is touched. What only the scene +can judge (an absent group, a node type Blender does not offer, a socket that does not exist, a cycle) is a +`failed` receipt that leaves the tree as it was. Node actions name their object `objectName`. Design and the parts not built yet: the design lives at tag `parked/blender-node-graphs-design` (branch `libby/blender-node-graphs-design`, PR #3, closed unmerged), not in this tree. -| action | fields | rule | -|---|---|---| -| `createNodeGroup` | `treeKey`, `interface` `[{inOut, name, type, default?}]` | New geometry node group with `gin` and `gout` nodes. Types: Geometry, Float, Int, Bool, Vector. Refuses an existing group. The receipt lists the interface identifiers (`Socket_N`). | -| `addNode` | `treeKey`, `id`, `blIdname`, `location?`, `label?`, `properties?`, `inputs?` | `id` is Brokkr's key (stored as the node's `brokkr_id`). Type must be a `GeometryNode*`, `FunctionNode*` or `ShaderNode*` name that is not an importer, exporter, script, bake, group, zone, viewer or image-texture node. Properties are enum/bool/int/float node settings (set first, they decide which sockets exist); inputs are unlinked defaults (float, int, bool, vector, colour). At most 500 nodes per group. | -| `removeNode` | `treeKey`, `id` | Removes the node and its links. Absent id: accepted. `gin` and `gout` stay. | -| `linkSockets` | `treeKey`, `fromNode`, `fromSocket`, `toNode`, `toSocket` | Sockets by identifier, or by display name when exactly one available socket has it (Group Input/Output sockets are addressed by interface name). A link Blender calls invalid (field into a single value, type mismatch) is removed and refused, and the single link it displaced is put back. A valid link into a single-link input replaces the old one (Blender's behaviour); a link that would close a cycle, or link a node to itself, is refused before Blender is asked. | -| `unlinkSockets` | `treeKey`, `toNode`, `toSocket`, `fromNode?`, `fromSocket?` | Removes the links into an input, or only the one from the given source. None to remove: accepted. | -| `addModifier` | `objectName`, `treeKey`, `modifierName?` (default `Brokkr GeoNodes`) | `NODES` only. Reuses a modifier of that name; at most 8 per object. | -| `removeModifier` | `objectName`, `modifierName?` | Geometry Nodes modifiers only (a Subdivision or other modifier is refused). Absent: accepted. | -| `setModifierInput` | `objectName`, `modifierName?`, `socket` (identifier or unique interface name), `value` | Float, Int, Bool, Vector inputs. Written as `getattr(modifier.properties.inputs, id).value = v` (indexing `inputs[id]` yields a raw ID property group without `.value` on 5.2.3), then `object.update_tag()`. | +| action | rule | +|---|---| +| `createNodeGroup` | New geometry node group with `gin` and `gout` nodes. Types: Geometry, Float, Int, Bool, Vector. Refuses an existing group. The receipt lists the interface identifiers (`Socket_N`). | +| `addNode` | `id` is Brokkr's key (stored as the node's `brokkr_id`). Type must be a `GeometryNode*`, `FunctionNode*` or `ShaderNode*` name that is not an importer, exporter, script, bake, group, zone, viewer or image-texture node. Properties are enum/bool/int/float node settings (set first, they decide which sockets exist); inputs are unlinked defaults (float, int, bool, vector, colour). At most 500 nodes per group. | +| `removeNode` | Removes the node and its links. Absent id: accepted. `gin` and `gout` stay. | +| `linkSockets` | Sockets by identifier, or by display name when exactly one available socket has it (Group Input/Output sockets are addressed by interface name). A link Blender calls invalid (field into a single value, type mismatch) is removed and refused, and the single link it displaced is put back. A valid link into a single-link input replaces the old one (Blender's behaviour); a link that would close a cycle, or link a node to itself, is refused before Blender is asked. | +| `unlinkSockets` | Removes the links into an input, or only the one from the given source. None to remove: accepted. | +| `addModifier` | `NODES` only. Reuses a modifier of that name; at most 8 per object. | +| `removeModifier` | Geometry Nodes modifiers only (a Subdivision or other modifier is refused). Absent: accepted. | +| `setModifierInput` | Float, Int, Bool, Vector inputs. Written as `getattr(modifier.properties.inputs, id).value = v` (indexing `inputs[id]` yields a raw ID property group without `.value` on 5.2.3), then `object.update_tag()`. | `setObjectCustomProperty` refuses a property whose name is the identifier (`Socket_N`) of an input of a Geometry Nodes modifier on that object; a custom property never drives a modifier input. A name that only equals an diff --git a/surfaces/blender/tests/live/action_table.py b/surfaces/blender/tests/live/action_table.py new file mode 100644 index 0000000..98cbdf8 --- /dev/null +++ b/surfaces/blender/tests/live/action_table.py @@ -0,0 +1,388 @@ +"""Live proof, in GUI Blender with the add-on installed as an extension, that the action table is the one admission. + + BROKKR_SCRATCH= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + blender --python action_table.py -- + +Run it in a Blender whose resource path is fresh (BLENDER_USER_RESOURCE_PATH). Every intent is put into the node +database as brokkr-ctl does and answered by the add-on's own 1 s drain (the sink is on). For every action in actions.json: + + * malformed intents generated from its table entry (an unknown field, a wrong type, an enum miss, a bound miss, + a missing required field, a string or array rule broken, an 'only' broken) are each 'denied', add no undo step + and leave the scene unchanged: one undo after them reverts the canary step that preceded them; + * one valid intent is accepted and, when the entry's changesScene is true, is exactly one undo step (undo restores the + scene, redo brings it back); when false it pushes none. + +A final check holds a receipt write back once and proves the intent still ran exactly once (the drain claims first). +Undo and redo are read only here, by this driver. Writes .result.json, then quits Blender. +""" +import importlib +import json +import os +import sys +import traceback +from pathlib import Path + +import bpy + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": [], "actions": {}} + +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") +at = importlib.import_module(MODULE + ".action_table") +prefs = bpy.context.preferences.addons[MODULE].preferences +bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "live.blend")) +CACHE = str(SCRATCH / "queue.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.debug_mirror_root = "" +prefs.output_dir = str(SCRATCH / "out") +prefs.import_dir = str(SCRATCH / "out") # importGltf reads what exportGltf wrote +prefs.auto_drain_commands = True # the sink +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +(SCRATCH / "out").mkdir(exist_ok=True) +adapter = addon.target() +R["table_actions"] = [a["name"] for a in at.table()["actions"]] + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + return bpy.context.temp_override(window=bpy.context.window_manager.windows[0]) + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def redo(): + with win(): + bpy.ops.ed.redo() + + +def node(): + return adapter._open_node(CACHE, prefs.cultlib_py_src) + + +N = [0] + + +def queue(**cmd): + N[0] += 1 + cid = "live-%04d" % N[0] + n, docs = node() + cmd.update(commandId=cid, schema=bt.COMMAND_INTENT_SCHEMA, requestedBy="nibu/hands") + n.database.put(docs["command_intent"], f"blender/commands/{cid}", cmd) + return cid + + +def receipt(cid): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{cid}") + + +def pending(): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {}) + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +def r3(values): + return [round(float(v), 4) for v in values] + + +def sig(): + """What an agent intent can change, as one comparable value.""" + scene = bpy.context.scene + world = scene.world + background = world.node_tree.nodes.get("Background") if world and world.node_tree else None + return json.dumps({ + "objects": [[o.name, o.type, r3(o.location), r3(o.rotation_euler), r3(o.scale), o.hide_viewport, o.hide_render, + o.parent.name if o.parent else "", sorted(k for k in o.keys() if not k.startswith("_")), + [[m.name, m.type] for m in o.modifiers], o.select_get()] for o in bpy.data.objects], + "active": bpy.context.view_layer.objects.active.name if bpy.context.view_layer.objects.active else "", + "materials": [[m.name, r3(m.diffuse_color)] for m in bpy.data.materials], + "groups": [[g.name, len(g.nodes), len(g.links)] for g in bpy.data.node_groups], + "cameras": [[c.name, c.lens, c.type, c.panorama_type] for c in bpy.data.cameras], + "lights": [[l.name, l.energy, r3(l.color), l.type] for l in bpy.data.lights], + "world": [world.name, r3(background.inputs["Color"].default_value), round(background.inputs["Strength"].default_value, 4)] if background else None, + "camera": scene.camera.name if scene.camera else "", + "render": [scene.render.engine, scene.render.resolution_x, scene.render.resolution_y], + "counts": [len(bpy.data.objects), len(bpy.data.meshes), len(bpy.data.images)], + }, sort_keys=True) + + +# ---- table-generated intents ------------------------------------------------------------------------------------- + +SAMPLES = [ # (action, prep intents queued and run unmeasured first, the valid sample) + ("createObject", [], {"objectType": "MESH", "name": "LiveCube", "location": [2, 0, 0], "size": 2}), + ("deleteObject", [{"action": "createObject", "objectType": "EMPTY", "name": "LiveDoomed"}], {"targetObjectName": "LiveDoomed"}), + ("setObjectTransform", [], {"targetObjectName": "LiveCube", "location": [2, 3, 0], "rotationEuler": [0, 0, 0.5], "scale": [1, 2, 1]}), + ("setObjectVisibility", [], {"targetObjectName": "LiveCube", "visible": False}), + ("setObjectParent", [], {"targetObjectName": "LiveCube", "parentObjectName": "Cube"}), + ("setObjectCustomProperty", [], {"targetObjectName": "LiveCube", "propertyName": "liveProp", "value": 3}), + ("selectObject", [], {"targetObjectName": "Camera"}), + ("assignMaterial", [], {"targetObjectName": "LiveCube", "materialName": "LiveMat", "color": [0.1, 0.2, 0.3]}), + ("exportGltf", [], {"filepath": "live.glb"}), + ("importGltf", [], {"filepath": "live.glb"}), + ("setCamera", [], {"targetObjectName": "Camera", "lens": 35, "cameraType": "PANO", "panoramaType": "FISHEYE_EQUIDISTANT", "active": True}), + ("setLight", [], {"targetObjectName": "Light", "energy": 500, "color": [1, 0.5, 0], "lightType": "SUN"}), + ("setWorld", [], {"color": [0.1, 0.1, 0.2], "strength": 1.5}), + ("renderStill", [], {"outputPath": "live.png", "engine": "CYCLES", "resolutionX": 8, "resolutionY": 8}), + ("look", [], {}), + ("createNodeGroup", [], {"treeKey": "LiveG", "interface": [{"inOut": "INPUT", "name": "Geometry", "type": "Geometry"}, + {"inOut": "OUTPUT", "name": "Geometry", "type": "Geometry"}, + {"inOut": "INPUT", "name": "Count", "type": "Int", "default": 8}]}), + ("addNode", [], {"treeKey": "LiveG", "id": "m1", "blIdname": "ShaderNodeMath", "location": [100, 0], "label": "live"}), + ("linkSockets", [], {"treeKey": "LiveG", "fromNode": "gin", "fromSocket": "Geometry", "toNode": "gout", "toSocket": "Geometry"}), + ("unlinkSockets", [], {"treeKey": "LiveG", "toNode": "gout", "toSocket": "Geometry"}), + ("removeNode", [], {"treeKey": "LiveG", "id": "m1"}), + ("addModifier", [], {"objectName": "LiveCube", "treeKey": "LiveG", "modifierName": "LiveMod"}), + ("setModifierInput", [], {"objectName": "LiveCube", "modifierName": "LiveMod", "socket": "Count", "value": 4}), + ("removeModifier", [], {"objectName": "LiveCube", "modifierName": "LiveMod"}), +] +WRONG = {"string": 5, "number": "x", "integer": "x", "boolean": "x", "array": "x", "object": []} + + +def malformed(action, sample): + """Intents the table refuses, each derived from one rule of the action's entry. [(label, fields)]""" + row = at.entry(action) + out = [("unknown field", {**sample, "zzUnknown": 1})] + specs = {f["name"]: f for f in row["fields"]} + for name, spec in specs.items(): + def vary(label, value): + out.append((f"{name}: {label}", {**sample, name: value})) + kind = spec["type"] + if kind in WRONG: + vary("wrong type", WRONG[kind]) + if spec.get("required") and name in sample: + out.append((f"{name}: required missing", {k: v for k, v in sample.items() if k != name})) + if "enum" in spec: + vary("enum miss", "nope_") + if kind in ("number", "integer"): + vary("above maximum", spec["maximum"] + 1) + vary("below minimum", spec["minimum"] - 1) + if kind == "string" and "enum" not in spec: + if spec.get("minLength", 0) >= 1: + vary("below minLength", "") + if "maxLength" in spec: + vary("above maxLength", "x" * (spec["maxLength"] + 1)) + if "chars" in spec: + vary("outside charset", "a\n") + if "prefixes" in spec: + vary("no prefix", "Q") + if "forbid" in spec and isinstance(sample.get(name), str): + vary("forbidden part", sample[name] + spec["forbid"][0]) + if kind == "array": + item = spec["items"] + if spec.get("minItems", 0) >= 1: + vary("below minItems", [None][:0] if spec["minItems"] == 1 else [0] * (spec["minItems"] - 1)) + if "maxItems" in spec and item["type"] == "number": + vary("above maxItems", [0] * (spec["maxItems"] + 1)) + if item["type"] == "number": + low = [item["minimum"]] * spec.get("minItems", 1) + vary("item above maximum", [item["maximum"] + 1] + low[1:]) + vary("item below minimum", [item["minimum"] - 1] + low[1:]) + vary("item wrong type", [WRONG.get(item["type"], 5)] + [0] * (spec.get("minItems", 1) - 1)) + if item["type"] == "object": + vary("item missing a property", [{"inOut": "INPUT", "type": "Int"}]) + vary("item unknown property", [{"inOut": "INPUT", "name": "a", "type": "Int", "zzUnknown": 1}]) + if "only" in spec: + sibling = specs[spec["only"]["field"]] + other = next(v for v in sibling["enum"] if v not in spec["only"]["in"]) + out.append((f"{name}: only applies to {spec['only']['field']} in {spec['only']['in']}", + {**{k: v for k, v in sample.items() if k != name}, spec["only"]["field"]: other, name: spec["enum"][0]})) + return out + + +# ---- steps ------------------------------------------------------------------------------------------------------- + +S = {} +WAIT = {"ticks": 0} + + +def until(pred, limit=40): + def step(): + WAIT["ticks"] += 1 + if pred(): + WAIT["ticks"] = 0 + return True + if WAIT["ticks"] > limit: + raise TimeoutError("the drain did not receipt in time") + return False + return step + + +def once(fn): + def step(): + fn() + return True + return step + + +def drained(key): + return lambda: all(receipt(c) for c in S[key]) + + +def run_all(key, intents): + S[key] = [queue(**fields) for fields in intents] + + +def per_action(action, prep, sample): + row = at.entry(action) + key = action + info = R["actions"][action] = {"changesScene": row["changesScene"]} + scene_changing = row["changesScene"] + + def baseline(): + S[key + ":sig0"] = sig() + S[key + ":names0"] = names() + + def malformed_queue(): + bad = malformed(action, sample) + S[key + ":labels"] = [label for label, _ in bad] + run_all(key + ":bad", [{"action": action, **fields} for _, fields in bad]) + + def malformed_check(): + got = [receipt(c) for c in S[key + ":bad"]] + labels = S[key + ":labels"] + not_denied = [(l, r["status"], r["message"]) for l, r in zip(labels, got) if r["status"] != "denied"] + info["malformed"] = len(got) + info["messages"] = {l: r["message"] for l, r in zip(labels, got)} + steps_added = [l for l, r in zip(labels, got) if r["undoLabel"]] + check(f"{action}: {len(got)} table-generated malformed intents are each denied", got and not not_denied, not_denied[:5]) + check(f"{action}: a denied intent carries no undoLabel", not steps_added, steps_added[:5]) + check(f"{action}: the scene is unchanged by the malformed intents", sig() == S[key + ":sig1"], None) + undo() # one undo: if a malformed intent had pushed a step, the canary would survive + check(f"{action}: no malformed intent added an undo step (one undo reverts the canary before them)", + sig() == S[key + ":sig0"], {"names": names(), "was": S[key + ":names0"]}) + + def canary_queue(tag): + run_all(key + ":canary" + tag, [{"action": "createObject", "objectType": "MESH", "name": "Canary" + tag, "location": [0, 0, 9]}]) + + def canary_check(): + r = receipt(S[key + ":canary1"][0]) + S[key + ":sig1"] = sig() + check(f"{action}: the canary is accepted with one undoLabel", r["status"] == "accepted" and r["undoLabel"], r) + + def valid_queue(): + S[key + ":sigv0"] = sig() + run_all(key + ":valid", [{"action": action, **sample}]) + + def valid_check(): + r = receipt(S[key + ":valid"][0]) + info["valid"] = {"status": r["status"], "message": r["message"], "undoLabel": r["undoLabel"]} + after = sig() + S[key + ":sigv1"] = after + check(f"{action}: the valid intent is accepted", r["status"] == "accepted", r) + if scene_changing: + check(f"{action}: changesScene is true, so the receipt carries an undoLabel", r["undoLabel"].startswith(f"Brokkr nibu/hands: {action} "), r["undoLabel"]) + if after != S[key + ":sigv0"]: + undo() + check(f"{action}: one undo restores the scene to before the intent", sig() == S[key + ":sigv0"], None) + redo() + check(f"{action}: redo brings the intent's result back", sig() == after, None) + else: + info["note"] = "the intent changed nothing the signature reads (checked by label only)" + else: + check(f"{action}: changesScene is false, so no undoLabel", r["undoLabel"] == "", r["undoLabel"]) + + def noscene_check(): + # a canary, then the valid intent, then one undo: the canary goes, so the intent pushed no step + undo() + check(f"{action}: it pushed no undo step (one undo reverts the canary before it)", sig() == S[key + ":sigc0"], None) + + out = [] + for p in prep: + out += [once(lambda p=p: run_all(key + ":prep", [p])), until(drained(key + ":prep"))] + out += [once(baseline), once(lambda: canary_queue("1")), until(drained(key + ":canary1")), once(canary_check), + once(malformed_queue), until(drained(key + ":bad")), once(malformed_check)] + if scene_changing: + out += [once(valid_queue), until(drained(key + ":valid")), once(valid_check)] + else: + out += [once(lambda: S.__setitem__(key + ":sigc0", sig())), once(lambda: canary_queue("2")), until(drained(key + ":canary2")), + once(valid_queue), until(drained(key + ":valid")), once(valid_check), once(noscene_check)] + return out + + +def covered(): + missing = [a for a in R["table_actions"] if a not in {s[0] for s in SAMPLES}] + extra = [s[0] for s in SAMPLES if s[0] not in R["table_actions"]] + check("every action of actions.json has a live sample and no sample names an action the table lacks", not missing and not extra, [missing, extra]) + + +def flaky_setup(): + """Hold one receipt write back: the intent must still have run exactly once, and its receipt arrive next drain.""" + S["flaky:objects"] = len([o for o in bpy.data.objects if o.name.startswith("FlakyCube")]) + original = adapter.publish_receipt + state = {"raised": 0} + S["flaky:id"] = None + + def flaky(*args, **kwargs): + receipt_doc = args[2] if len(args) > 2 else kwargs.get("receipt") + if receipt_doc and receipt_doc.get("commandId") == S["flaky:id"] and not state["raised"]: + state["raised"] += 1 + raise OSError("injected receipt write failure") + return original(*args, **kwargs) + + adapter.publish_receipt = flaky + S["flaky:restore"] = lambda: setattr(adapter, "publish_receipt", original) + S["flaky:state"] = state + cid = queue(action="createObject", objectType="MESH", name="FlakyCube", location=[0, 0, 12]) + S["flaky:id"] = cid + S["flaky:ids"] = [cid] + + +def flaky_check(): + S["flaky:restore"]() + r = receipt(S["flaky:id"]) + flakies = [o.name for o in bpy.data.objects if o.name.startswith("FlakyCube")] + check("claim-first: with one receipt write failing, the intent ran exactly once and its receipt was written by the next drain", + S["flaky:state"]["raised"] == 1 and len(flakies) == 1 and r and r["status"] == "accepted" + and f"blender/receipts/{S['flaky:id']}.denied" not in node()[0].database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}) + and S["flaky:id"] not in str(pending()), {"raised": S["flaky:state"]["raised"], "objects": flakies, "receipt": r and r["status"]}) + check("the queue is empty and the add-on's drain reports no error", not pending() and adapter.last_auto_drain_error == "", + [list(pending()), adapter.last_auto_drain_error]) + + +steps = [once(covered)] +for action, prep, sample in SAMPLES: + steps += per_action(action, prep, sample) +steps += [once(flaky_setup), until(lambda: receipt(S["flaky:id"]) is not None), once(flaky_check)] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def tick(): + global i + if i < len(steps): + try: + if steps[i](): + i += 1 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + i = len(steps) + write() + return 0.5 + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/surfaces/blender/tests/live/action_table.result.json b/surfaces/blender/tests/live/action_table.result.json new file mode 100644 index 0000000..b21b4c1 --- /dev/null +++ b/surfaces/blender/tests/live/action_table.result.json @@ -0,0 +1,2543 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "every action of actions.json has a live sample and no sample names an action the table lacks", + "ok": true, + "detail": [ + [], + [] + ] + }, + { + "name": "createObject: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0001", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0001", + "lookPath": "", + "observedAt": "2026-11-28T01:56:40.145813+00:00" + } + }, + { + "name": "createObject: 22 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "createObject: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "createObject: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "createObject: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light" + ], + "was": [ + "Camera", + "Cube", + "Light" + ] + } + }, + { + "name": "createObject: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0024", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0024", + "lookPath": "", + "observedAt": "2026-11-28T01:56:45.785882+00:00" + } + }, + { + "name": "createObject: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: createObject ive-0024" + }, + { + "name": "createObject: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "createObject: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "deleteObject: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0026", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0026", + "lookPath": "", + "observedAt": "2026-11-28T01:56:49.944500+00:00" + } + }, + { + "name": "deleteObject: 3 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "deleteObject: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "deleteObject: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "deleteObject: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube", + "LiveDoomed" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube", + "LiveDoomed" + ] + } + }, + { + "name": "deleteObject: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0030", + "action": "deleteObject", + "status": "accepted", + "message": "Blender object deleted.", + "objectName": "LiveDoomed", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: deleteObject ive-0030", + "lookPath": "", + "observedAt": "2026-11-28T01:56:54.485651+00:00" + } + }, + { + "name": "deleteObject: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: deleteObject ive-0030" + }, + { + "name": "deleteObject: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "deleteObject: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setObjectTransform: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0031", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0031", + "lookPath": "", + "observedAt": "2026-11-28T01:56:56.566254+00:00" + } + }, + { + "name": "setObjectTransform: 21 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setObjectTransform: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setObjectTransform: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setObjectTransform: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "setObjectTransform: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0053", + "action": "setObjectTransform", + "status": "accepted", + "message": "Blender object transform updated.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setObjectTransform ive-0053", + "lookPath": "", + "observedAt": "2026-11-28T01:57:03.202116+00:00" + } + }, + { + "name": "setObjectTransform: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setObjectTransform ive-0053" + }, + { + "name": "setObjectTransform: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setObjectTransform: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setObjectVisibility: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0054", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0054", + "lookPath": "", + "observedAt": "2026-11-28T01:57:05.306686+00:00" + } + }, + { + "name": "setObjectVisibility: 4 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setObjectVisibility: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setObjectVisibility: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setObjectVisibility: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "setObjectVisibility: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0059", + "action": "setObjectVisibility", + "status": "accepted", + "message": "Blender object visibility updated.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setObjectVisibility ive-0059", + "lookPath": "", + "observedAt": "2026-11-28T01:57:09.874099+00:00" + } + }, + { + "name": "setObjectVisibility: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setObjectVisibility ive-0059" + }, + { + "name": "setObjectVisibility: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setObjectVisibility: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setObjectParent: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0060", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0060", + "lookPath": "", + "observedAt": "2026-11-28T01:57:11.974525+00:00" + } + }, + { + "name": "setObjectParent: 4 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setObjectParent: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setObjectParent: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setObjectParent: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "setObjectParent: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0065", + "action": "setObjectParent", + "status": "accepted", + "message": "Blender object parent updated.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setObjectParent ive-0065", + "lookPath": "", + "observedAt": "2026-11-28T01:57:16.563563+00:00" + } + }, + { + "name": "setObjectParent: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setObjectParent ive-0065" + }, + { + "name": "setObjectParent: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setObjectParent: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setObjectCustomProperty: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0066", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0066", + "lookPath": "", + "observedAt": "2026-11-28T01:57:18.681337+00:00" + } + }, + { + "name": "setObjectCustomProperty: 5 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setObjectCustomProperty: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setObjectCustomProperty: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setObjectCustomProperty: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "setObjectCustomProperty: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0072", + "action": "setObjectCustomProperty", + "status": "accepted", + "message": "Blender custom property updated.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setObjectCustomProperty ive-0072", + "lookPath": "", + "observedAt": "2026-11-28T01:57:22.508309+00:00" + } + }, + { + "name": "setObjectCustomProperty: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setObjectCustomProperty ive-0072" + }, + { + "name": "setObjectCustomProperty: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setObjectCustomProperty: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "selectObject: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0073", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0073", + "lookPath": "", + "observedAt": "2026-11-28T01:57:24.630024+00:00" + } + }, + { + "name": "selectObject: 4 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "selectObject: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "selectObject: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "selectObject: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "selectObject: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0078", + "action": "selectObject", + "status": "accepted", + "message": "Blender object selected.", + "objectName": "Camera", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: selectObject ive-0078", + "lookPath": "", + "observedAt": "2026-11-28T01:57:29.310576+00:00" + } + }, + { + "name": "selectObject: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: selectObject ive-0078" + }, + { + "name": "selectObject: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "selectObject: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "assignMaterial: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0079", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0079", + "lookPath": "", + "observedAt": "2026-11-28T01:57:31.515585+00:00" + } + }, + { + "name": "assignMaterial: 10 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "assignMaterial: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "assignMaterial: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "assignMaterial: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "assignMaterial: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0090", + "action": "assignMaterial", + "status": "accepted", + "message": "Blender material assigned.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: assignMaterial ive-0090", + "lookPath": "", + "observedAt": "2026-11-28T01:57:37.550809+00:00" + } + }, + { + "name": "assignMaterial: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: assignMaterial ive-0090" + }, + { + "name": "assignMaterial: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "assignMaterial: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "exportGltf: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0091", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0091", + "lookPath": "", + "observedAt": "2026-11-28T01:57:39.704717+00:00" + } + }, + { + "name": "exportGltf: 9 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "exportGltf: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "exportGltf: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "exportGltf: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "exportGltf: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0102", + "action": "exportGltf", + "status": "accepted", + "message": "Exported glTF to F:\\aeth-wt\\brokkr-action-table-live\\scratch\\out\\live.glb (5028 bytes).", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T01:57:48.919027+00:00" + } + }, + { + "name": "exportGltf: changesScene is false, so no undoLabel", + "ok": true, + "detail": "" + }, + { + "name": "exportGltf: it pushed no undo step (one undo reverts the canary before it)", + "ok": true, + "detail": null + }, + { + "name": "importGltf: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0103", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0103", + "lookPath": "", + "observedAt": "2026-11-28T01:57:51.228716+00:00" + } + }, + { + "name": "importGltf: 3 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "importGltf: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "importGltf: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "importGltf: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "importGltf: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0107", + "action": "importGltf", + "status": "accepted", + "message": "Imported 3 object(s) from live.glb.", + "objectName": "Canary2", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: importGltf ive-0107", + "lookPath": "", + "observedAt": "2026-11-28T01:57:56.255504+00:00" + } + }, + { + "name": "importGltf: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: importGltf ive-0107" + }, + { + "name": "importGltf: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "importGltf: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setCamera: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0108", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0108", + "lookPath": "", + "observedAt": "2026-11-28T01:57:58.437908+00:00" + } + }, + { + "name": "setCamera: 20 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setCamera: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setCamera: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setCamera: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "setCamera: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0129", + "action": "setCamera", + "status": "accepted", + "message": "Blender camera updated.", + "objectName": "Camera", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setCamera ive-0129", + "lookPath": "", + "observedAt": "2026-11-28T01:58:11.054773+00:00" + } + }, + { + "name": "setCamera: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setCamera ive-0129" + }, + { + "name": "setCamera: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setCamera: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setLight: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0130", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0130", + "lookPath": "", + "observedAt": "2026-11-28T01:58:13.248452+00:00" + } + }, + { + "name": "setLight: 14 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setLight: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setLight: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setLight: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "setLight: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0145", + "action": "setLight", + "status": "accepted", + "message": "Blender light updated.", + "objectName": "Light", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setLight ive-0145", + "lookPath": "", + "observedAt": "2026-11-28T01:58:22.382198+00:00" + } + }, + { + "name": "setLight: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setLight ive-0145" + }, + { + "name": "setLight: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setLight: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setWorld: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0146", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0146", + "lookPath": "", + "observedAt": "2026-11-28T01:58:24.582227+00:00" + } + }, + { + "name": "setWorld: 11 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setWorld: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setWorld: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setWorld: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "setWorld: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0158", + "action": "setWorld", + "status": "accepted", + "message": "Blender world updated.", + "objectName": "World", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setWorld ive-0158", + "lookPath": "", + "observedAt": "2026-11-28T01:58:31.393393+00:00" + } + }, + { + "name": "setWorld: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setWorld ive-0158" + }, + { + "name": "setWorld: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setWorld: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "renderStill: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0159", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0159", + "lookPath": "", + "observedAt": "2026-11-28T01:58:33.598048+00:00" + } + }, + { + "name": "renderStill: 12 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "renderStill: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "renderStill: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "renderStill: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "renderStill: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0173", + "action": "renderStill", + "status": "accepted", + "message": "Rendered still to live.png.", + "objectName": "Scene", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T01:58:44.631878+00:00" + } + }, + { + "name": "renderStill: changesScene is false, so no undoLabel", + "ok": true, + "detail": "" + }, + { + "name": "renderStill: it pushed no undo step (one undo reverts the canary before it)", + "ok": true, + "detail": null + }, + { + "name": "look: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0174", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0174", + "lookPath": "", + "observedAt": "2026-11-28T01:58:47.857036+00:00" + } + }, + { + "name": "look: 1 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "look: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "look: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "look: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "look: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0177", + "action": "look", + "status": "accepted", + "message": "Captured the 3D view to look/live-0177.png.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch\\out\\look\\live-0177.png", + "observedAt": "2026-11-28T01:58:53.654873+00:00", + "captureSource": "region", + "sceneUpdateSeq": 95, + "sessionId": "3b3d62619afb43d0a8548fc3f2ce4a4f", + "humanEditSeq": 83, + "humanEditsSinceLook": 83, + "editedSinceLook": [ + "Camera", + "Canary2", + "Canary2.001", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001", + "LiveDoomed" + ], + "editedSinceLookCoarse": true, + "editedSinceLookNote": "Coarse: undo or redo flags all objects; editedSinceLook may name objects she did not touch.", + "editSelection": [] + } + }, + { + "name": "look: changesScene is false, so no undoLabel", + "ok": true, + "detail": "" + }, + { + "name": "look: it pushed no undo step (one undo reverts the canary before it)", + "ok": true, + "detail": null + }, + { + "name": "createNodeGroup: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0178", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0178", + "lookPath": "", + "observedAt": "2026-11-28T01:58:56.864241+00:00" + } + }, + { + "name": "createNodeGroup: 14 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "createNodeGroup: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "createNodeGroup: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "createNodeGroup: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "createNodeGroup: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0193", + "action": "createNodeGroup", + "status": "accepted", + "message": "Created node group; interface identifiers: input Geometry=Socket_0, output Geometry=Socket_1, input Count=Socket_2", + "objectName": "LiveG", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createNodeGroup ive-0193", + "lookPath": "", + "observedAt": "2026-11-28T01:59:10.270729+00:00" + } + }, + { + "name": "createNodeGroup: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: createNodeGroup ive-0193" + }, + { + "name": "createNodeGroup: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "createNodeGroup: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "addNode: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0194", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0194", + "lookPath": "", + "observedAt": "2026-11-28T01:59:12.510947+00:00" + } + }, + { + "name": "addNode: 28 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "addNode: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "addNode: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "addNode: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "addNode: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0223", + "action": "addNode", + "status": "accepted", + "message": "Node added.", + "objectName": "m1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: addNode ive-0223", + "lookPath": "", + "observedAt": "2026-11-28T01:59:47.731039+00:00" + } + }, + { + "name": "addNode: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: addNode ive-0223" + }, + { + "name": "addNode: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "addNode: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "linkSockets: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0224", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0224", + "lookPath": "", + "observedAt": "2026-11-28T01:59:49.993525+00:00" + } + }, + { + "name": "linkSockets: 22 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "linkSockets: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "linkSockets: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "linkSockets: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "linkSockets: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0247", + "action": "linkSockets", + "status": "accepted", + "message": "Linked gin.Socket_0 -> gout.Socket_1.", + "objectName": "LiveG", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: linkSockets ive-0247", + "lookPath": "", + "observedAt": "2026-11-28T02:00:17.375246+00:00" + } + }, + { + "name": "linkSockets: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: linkSockets ive-0247" + }, + { + "name": "linkSockets: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "linkSockets: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "unlinkSockets: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0248", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0248", + "lookPath": "", + "observedAt": "2026-11-28T02:00:19.737999+00:00" + } + }, + { + "name": "unlinkSockets: 20 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "unlinkSockets: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "unlinkSockets: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "unlinkSockets: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "unlinkSockets: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0269", + "action": "unlinkSockets", + "status": "accepted", + "message": "Removed 1 link(s).", + "objectName": "LiveG", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: unlinkSockets ive-0269", + "lookPath": "", + "observedAt": "2026-11-28T02:00:45.997967+00:00" + } + }, + { + "name": "unlinkSockets: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: unlinkSockets ive-0269" + }, + { + "name": "unlinkSockets: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "unlinkSockets: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "removeNode: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0270", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0270", + "lookPath": "", + "observedAt": "2026-11-28T02:00:48.315493+00:00" + } + }, + { + "name": "removeNode: 13 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "removeNode: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "removeNode: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "removeNode: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "removeNode: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0284", + "action": "removeNode", + "status": "accepted", + "message": "Node removed.", + "objectName": "m1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: removeNode ive-0284", + "lookPath": "", + "observedAt": "2026-11-28T02:01:03.364715+00:00" + } + }, + { + "name": "removeNode: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: removeNode ive-0284" + }, + { + "name": "removeNode: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "removeNode: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "addModifier: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0285", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0285", + "lookPath": "", + "observedAt": "2026-11-28T02:01:05.767376+00:00" + } + }, + { + "name": "addModifier: 16 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "addModifier: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "addModifier: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "addModifier: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "addModifier: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0302", + "action": "addModifier", + "status": "accepted", + "message": "Geometry Nodes modifier set.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: addModifier ive-0302", + "lookPath": "", + "observedAt": "2026-11-28T02:01:26.890644+00:00" + } + }, + { + "name": "addModifier: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: addModifier ive-0302" + }, + { + "name": "addModifier: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "addModifier: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setModifierInput: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0303", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0303", + "lookPath": "", + "observedAt": "2026-11-28T02:01:29.307569+00:00" + } + }, + { + "name": "setModifierInput: 7 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setModifierInput: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setModifierInput: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setModifierInput: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "setModifierInput: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0311", + "action": "setModifierInput", + "status": "accepted", + "message": "Modifier input Count set.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setModifierInput ive-0311", + "lookPath": "", + "observedAt": "2026-11-28T02:01:37.160827+00:00" + } + }, + { + "name": "setModifierInput: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setModifierInput ive-0311" + }, + { + "name": "removeModifier: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0312", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0312", + "lookPath": "", + "observedAt": "2026-11-28T02:01:39.514028+00:00" + } + }, + { + "name": "removeModifier: 7 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "removeModifier: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "removeModifier: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "removeModifier: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "removeModifier: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0320", + "action": "removeModifier", + "status": "accepted", + "message": "Modifier removed.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: removeModifier ive-0320", + "lookPath": "", + "observedAt": "2026-11-28T02:01:47.535687+00:00" + } + }, + { + "name": "removeModifier: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: removeModifier ive-0320" + }, + { + "name": "removeModifier: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "removeModifier: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "claim-first: with one receipt write failing, the intent ran exactly once and its receipt was written by the next drain", + "ok": true, + "detail": { + "raised": 1, + "objects": [ + "FlakyCube" + ], + "receipt": "accepted" + } + }, + { + "name": "the queue is empty and the add-on's drain reports no error", + "ok": true, + "detail": [ + [], + "" + ] + } + ], + "actions": { + "createObject": { + "changesScene": true, + "malformed": 22, + "messages": { + "unknown field": "createObject has no field 'zzUnknown'; its fields: objectType, name, location, size, meshType, lightType, emptyDisplayType.", + "objectType: wrong type": "objectType must be a string.", + "objectType: enum miss": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY.", + "name: wrong type": "name must be a string.", + "location: wrong type": "location must be an array.", + "location: below minItems": "location must have at least 3 items.", + "location: above maxItems": "location must have at most 3 items.", + "location: item above maximum": "location[0] must be between -1000000000 and 1000000000.", + "location: item below minimum": "location[0] must be between -1000000000 and 1000000000.", + "location: item wrong type": "location[0] must be a finite number.", + "size: wrong type": "size must be a finite number.", + "size: above maximum": "size must be between 0.001 and 1000000.", + "size: below minimum": "size must be between 0.001 and 1000000.", + "meshType: wrong type": "meshType must be a string.", + "meshType: enum miss": "meshType must be one of CUBE.", + "meshType: only applies to objectType in ['MESH']": "meshType applies only when objectType is one of MESH.", + "lightType: wrong type": "lightType applies only when objectType is one of LIGHT.", + "lightType: enum miss": "lightType applies only when objectType is one of LIGHT.", + "lightType: only applies to objectType in ['LIGHT']": "lightType applies only when objectType is one of LIGHT.", + "emptyDisplayType: wrong type": "emptyDisplayType applies only when objectType is one of EMPTY.", + "emptyDisplayType: enum miss": "emptyDisplayType applies only when objectType is one of EMPTY.", + "emptyDisplayType: only applies to objectType in ['EMPTY']": "emptyDisplayType applies only when objectType is one of EMPTY." + }, + "valid": { + "status": "accepted", + "message": "Blender object created.", + "undoLabel": "Brokkr nibu/hands: createObject ive-0024" + } + }, + "deleteObject": { + "changesScene": true, + "malformed": 3, + "messages": { + "unknown field": "deleteObject has no field 'zzUnknown'; its fields: targetObjectName.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required." + }, + "valid": { + "status": "accepted", + "message": "Blender object deleted.", + "undoLabel": "Brokkr nibu/hands: deleteObject ive-0030" + } + }, + "setObjectTransform": { + "changesScene": true, + "malformed": 21, + "messages": { + "unknown field": "setObjectTransform has no field 'zzUnknown'; its fields: targetObjectName, location, rotationEuler, scale.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "location: wrong type": "location must be an array.", + "location: below minItems": "location must have at least 3 items.", + "location: above maxItems": "location must have at most 3 items.", + "location: item above maximum": "location[0] must be between -1000000000 and 1000000000.", + "location: item below minimum": "location[0] must be between -1000000000 and 1000000000.", + "location: item wrong type": "location[0] must be a finite number.", + "rotationEuler: wrong type": "rotationEuler must be an array.", + "rotationEuler: below minItems": "rotationEuler must have at least 3 items.", + "rotationEuler: above maxItems": "rotationEuler must have at most 3 items.", + "rotationEuler: item above maximum": "rotationEuler[0] must be between -1000000000 and 1000000000.", + "rotationEuler: item below minimum": "rotationEuler[0] must be between -1000000000 and 1000000000.", + "rotationEuler: item wrong type": "rotationEuler[0] must be a finite number.", + "scale: wrong type": "scale must be an array.", + "scale: below minItems": "scale must have at least 3 items.", + "scale: above maxItems": "scale must have at most 3 items.", + "scale: item above maximum": "scale[0] must be between -1000000000 and 1000000000.", + "scale: item below minimum": "scale[0] must be between -1000000000 and 1000000000.", + "scale: item wrong type": "scale[0] must be a finite number." + }, + "valid": { + "status": "accepted", + "message": "Blender object transform updated.", + "undoLabel": "Brokkr nibu/hands: setObjectTransform ive-0053" + } + }, + "setObjectVisibility": { + "changesScene": true, + "malformed": 4, + "messages": { + "unknown field": "setObjectVisibility has no field 'zzUnknown'; its fields: targetObjectName, visible.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "visible: wrong type": "visible must be true or false." + }, + "valid": { + "status": "accepted", + "message": "Blender object visibility updated.", + "undoLabel": "Brokkr nibu/hands: setObjectVisibility ive-0059" + } + }, + "setObjectParent": { + "changesScene": true, + "malformed": 4, + "messages": { + "unknown field": "setObjectParent has no field 'zzUnknown'; its fields: targetObjectName, parentObjectName.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "parentObjectName: wrong type": "parentObjectName must be a string." + }, + "valid": { + "status": "accepted", + "message": "Blender object parent updated.", + "undoLabel": "Brokkr nibu/hands: setObjectParent ive-0065" + } + }, + "setObjectCustomProperty": { + "changesScene": true, + "malformed": 5, + "messages": { + "unknown field": "setObjectCustomProperty has no field 'zzUnknown'; its fields: targetObjectName, propertyName, value.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "propertyName: wrong type": "propertyName must be a string.", + "value: required missing": "value is required." + }, + "valid": { + "status": "accepted", + "message": "Blender custom property updated.", + "undoLabel": "Brokkr nibu/hands: setObjectCustomProperty ive-0072" + } + }, + "selectObject": { + "changesScene": true, + "malformed": 4, + "messages": { + "unknown field": "selectObject has no field 'zzUnknown'; its fields: targetObjectName, clearSelection.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "clearSelection: wrong type": "clearSelection must be true or false." + }, + "valid": { + "status": "accepted", + "message": "Blender object selected.", + "undoLabel": "Brokkr nibu/hands: selectObject ive-0078" + } + }, + "assignMaterial": { + "changesScene": true, + "malformed": 10, + "messages": { + "unknown field": "assignMaterial has no field 'zzUnknown'; its fields: targetObjectName, materialName, color.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "materialName: wrong type": "materialName must be a string.", + "color: wrong type": "color must be an array.", + "color: below minItems": "color must have at least 3 items.", + "color: above maxItems": "color must have at most 4 items.", + "color: item above maximum": "color[0] must be between 0 and 1.", + "color: item below minimum": "color[0] must be between 0 and 1.", + "color: item wrong type": "color[0] must be a finite number." + }, + "valid": { + "status": "accepted", + "message": "Blender material assigned.", + "undoLabel": "Brokkr nibu/hands: assignMaterial ive-0090" + } + }, + "exportGltf": { + "changesScene": false, + "malformed": 9, + "messages": { + "unknown field": "exportGltf has no field 'zzUnknown'; its fields: filepath, extras, yUp, applyModifiers, selection.", + "filepath: wrong type": "filepath must be a string.", + "filepath: required missing": "filepath is required.", + "extras: wrong type": "extras must be true or false.", + "yUp: wrong type": "yUp must be true or false.", + "applyModifiers: wrong type": "applyModifiers must be true or false.", + "selection: wrong type": "selection must be an array.", + "selection: below minItems": "selection must have at least 1 items.", + "selection: item wrong type": "selection[0] must be a string." + }, + "valid": { + "status": "accepted", + "message": "Exported glTF to F:\\aeth-wt\\brokkr-action-table-live\\scratch\\out\\live.glb (5028 bytes).", + "undoLabel": "" + } + }, + "importGltf": { + "changesScene": true, + "malformed": 3, + "messages": { + "unknown field": "importGltf has no field 'zzUnknown'; its fields: filepath.", + "filepath: wrong type": "filepath must be a string.", + "filepath: required missing": "filepath is required." + }, + "valid": { + "status": "accepted", + "message": "Imported 3 object(s) from live.glb.", + "undoLabel": "Brokkr nibu/hands: importGltf ive-0107" + } + }, + "setCamera": { + "changesScene": true, + "malformed": 20, + "messages": { + "unknown field": "setCamera has no field 'zzUnknown'; its fields: targetObjectName, lens, cameraType, orthoScale, clipStart, clipEnd, panoramaType, active.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "lens: wrong type": "lens must be a finite number.", + "lens: above maximum": "lens must be between 1 and 5000.", + "lens: below minimum": "lens must be between 1 and 5000.", + "cameraType: wrong type": "cameraType must be a string.", + "cameraType: enum miss": "cameraType must be one of PERSP, ORTHO, PANO.", + "orthoScale: wrong type": "orthoScale must be a finite number.", + "orthoScale: above maximum": "orthoScale must be between 0.001 and 100000.", + "orthoScale: below minimum": "orthoScale must be between 0.001 and 100000.", + "clipStart: wrong type": "clipStart must be a finite number.", + "clipStart: above maximum": "clipStart must be between 0.0001 and 1000000.", + "clipStart: below minimum": "clipStart must be between 0.0001 and 1000000.", + "clipEnd: wrong type": "clipEnd must be a finite number.", + "clipEnd: above maximum": "clipEnd must be between 0.001 and 10000000.", + "clipEnd: below minimum": "clipEnd must be between 0.001 and 10000000.", + "panoramaType: wrong type": "panoramaType must be a string.", + "panoramaType: enum miss": "panoramaType must be one of EQUIRECTANGULAR, EQUIANGULAR_CUBEMAP_FACE, MIRRORBALL, FISHEYE_EQUIDISTANT, FISHEYE_EQUISOLID, FISHEYE_LENS_POLYNOMIAL, CENTRAL_CYLINDRICAL.", + "active: wrong type": "active must be true or false." + }, + "valid": { + "status": "accepted", + "message": "Blender camera updated.", + "undoLabel": "Brokkr nibu/hands: setCamera ive-0129" + } + }, + "setLight": { + "changesScene": true, + "malformed": 14, + "messages": { + "unknown field": "setLight has no field 'zzUnknown'; its fields: targetObjectName, energy, color, lightType.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "energy: wrong type": "energy must be a finite number.", + "energy: above maximum": "energy must be between 0 and 10000000.", + "energy: below minimum": "energy must be between 0 and 10000000.", + "color: wrong type": "color must be an array.", + "color: below minItems": "color must have at least 3 items.", + "color: above maxItems": "color must have at most 3 items.", + "color: item above maximum": "color[0] must be between 0 and 1.", + "color: item below minimum": "color[0] must be between 0 and 1.", + "color: item wrong type": "color[0] must be a finite number.", + "lightType: wrong type": "lightType must be a string.", + "lightType: enum miss": "lightType must be one of POINT, SUN, SPOT, AREA." + }, + "valid": { + "status": "accepted", + "message": "Blender light updated.", + "undoLabel": "Brokkr nibu/hands: setLight ive-0145" + } + }, + "setWorld": { + "changesScene": true, + "malformed": 11, + "messages": { + "unknown field": "setWorld has no field 'zzUnknown'; its fields: worldName, color, strength.", + "worldName: wrong type": "worldName must be a string.", + "color: wrong type": "color must be an array.", + "color: below minItems": "color must have at least 3 items.", + "color: above maxItems": "color must have at most 3 items.", + "color: item above maximum": "color[0] must be between 0 and 1.", + "color: item below minimum": "color[0] must be between 0 and 1.", + "color: item wrong type": "color[0] must be a finite number.", + "strength: wrong type": "strength must be a finite number.", + "strength: above maximum": "strength must be between 0 and 1000000.", + "strength: below minimum": "strength must be between 0 and 1000000." + }, + "valid": { + "status": "accepted", + "message": "Blender world updated.", + "undoLabel": "Brokkr nibu/hands: setWorld ive-0158" + } + }, + "renderStill": { + "changesScene": false, + "malformed": 12, + "messages": { + "unknown field": "renderStill has no field 'zzUnknown'; its fields: outputPath, engine, resolutionX, resolutionY, cameraName.", + "outputPath: wrong type": "outputPath must be a string.", + "outputPath: required missing": "outputPath is required.", + "engine: wrong type": "engine must be a string.", + "engine: below minLength": "engine must have at least 1 characters.", + "resolutionX: wrong type": "resolutionX must be a whole number.", + "resolutionX: above maximum": "resolutionX must be between 4 and 16384.", + "resolutionX: below minimum": "resolutionX must be between 4 and 16384.", + "resolutionY: wrong type": "resolutionY must be a whole number.", + "resolutionY: above maximum": "resolutionY must be between 4 and 16384.", + "resolutionY: below minimum": "resolutionY must be between 4 and 16384.", + "cameraName: wrong type": "cameraName must be a string." + }, + "valid": { + "status": "accepted", + "message": "Rendered still to live.png.", + "undoLabel": "" + } + }, + "look": { + "changesScene": false, + "malformed": 1, + "messages": { + "unknown field": "look has no field 'zzUnknown'; its fields: none." + }, + "valid": { + "status": "accepted", + "message": "Captured the 3D view to look/live-0177.png.", + "undoLabel": "" + } + }, + "createNodeGroup": { + "changesScene": true, + "malformed": 14, + "messages": { + "unknown field": "createNodeGroup has no field 'zzUnknown'; its fields: treeKind, treeKey, interface.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "interface: wrong type": "interface must be an array.", + "interface: required missing": "interface is required.", + "interface: below minItems": "interface must have at least 1 items.", + "interface: item wrong type": "interface[0] must be an object.", + "interface: item missing a property": "interface[0].name is required.", + "interface: item unknown property": "interface[0] has no field 'zzUnknown'; its fields: inOut, name, type, default." + }, + "valid": { + "status": "accepted", + "message": "Created node group; interface identifiers: input Geometry=Socket_0, output Geometry=Socket_1, input Count=Socket_2", + "undoLabel": "Brokkr nibu/hands: createNodeGroup ive-0193" + } + }, + "addNode": { + "changesScene": true, + "malformed": 28, + "messages": { + "unknown field": "addNode has no field 'zzUnknown'; its fields: treeKind, treeKey, id, blIdname, location, label, properties, inputs.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "id: wrong type": "id must be a string.", + "id: required missing": "id is required.", + "id: below minLength": "id must have at least 1 characters.", + "id: above maxLength": "id must have at most 63 characters.", + "id: outside charset": "id may contain only letters, digits, '.', '_' or '-'.", + "blIdname: wrong type": "blIdname must be a string.", + "blIdname: required missing": "blIdname is required.", + "blIdname: outside charset": "blIdname may contain only letters and digits.", + "blIdname: no prefix": "blIdname must start with one of GeometryNode, FunctionNode, ShaderNode and have at least one more character.", + "blIdname: forbidden part": "blIdname may not contain 'Import'.", + "location: wrong type": "location must be an array.", + "location: below minItems": "location must have at least 2 items.", + "location: above maxItems": "location must have at most 2 items.", + "location: item above maximum": "location[0] must be between -1000000000 and 1000000000.", + "location: item below minimum": "location[0] must be between -1000000000 and 1000000000.", + "location: item wrong type": "location[0] must be a finite number.", + "label: wrong type": "label must be a string.", + "label: above maxLength": "label must have at most 63 characters.", + "properties: wrong type": "properties must be an object.", + "inputs: wrong type": "inputs must be an object." + }, + "valid": { + "status": "accepted", + "message": "Node added.", + "undoLabel": "Brokkr nibu/hands: addNode ive-0223" + } + }, + "linkSockets": { + "changesScene": true, + "malformed": 22, + "messages": { + "unknown field": "linkSockets has no field 'zzUnknown'; its fields: treeKind, treeKey, fromNode, fromSocket, toNode, toSocket.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "fromNode: wrong type": "fromNode must be a string.", + "fromNode: required missing": "fromNode is required.", + "fromNode: below minLength": "fromNode must have at least 1 characters.", + "fromNode: above maxLength": "fromNode must have at most 63 characters.", + "fromNode: outside charset": "fromNode may contain only letters, digits, '.', '_' or '-'.", + "fromSocket: wrong type": "fromSocket must be a string.", + "fromSocket: required missing": "fromSocket is required.", + "toNode: wrong type": "toNode must be a string.", + "toNode: required missing": "toNode is required.", + "toNode: below minLength": "toNode must have at least 1 characters.", + "toNode: above maxLength": "toNode must have at most 63 characters.", + "toNode: outside charset": "toNode may contain only letters, digits, '.', '_' or '-'.", + "toSocket: wrong type": "toSocket must be a string.", + "toSocket: required missing": "toSocket is required." + }, + "valid": { + "status": "accepted", + "message": "Linked gin.Socket_0 -> gout.Socket_1.", + "undoLabel": "Brokkr nibu/hands: linkSockets ive-0247" + } + }, + "unlinkSockets": { + "changesScene": true, + "malformed": 20, + "messages": { + "unknown field": "unlinkSockets has no field 'zzUnknown'; its fields: treeKind, treeKey, toNode, toSocket, fromNode, fromSocket.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "toNode: wrong type": "toNode must be a string.", + "toNode: required missing": "toNode is required.", + "toNode: below minLength": "toNode must have at least 1 characters.", + "toNode: above maxLength": "toNode must have at most 63 characters.", + "toNode: outside charset": "toNode may contain only letters, digits, '.', '_' or '-'.", + "toSocket: wrong type": "toSocket must be a string.", + "toSocket: required missing": "toSocket is required.", + "fromNode: wrong type": "fromNode must be a string.", + "fromNode: below minLength": "fromNode must have at least 1 characters.", + "fromNode: above maxLength": "fromNode must have at most 63 characters.", + "fromNode: outside charset": "fromNode may contain only letters, digits, '.', '_' or '-'.", + "fromSocket: wrong type": "fromSocket must be a string." + }, + "valid": { + "status": "accepted", + "message": "Removed 1 link(s).", + "undoLabel": "Brokkr nibu/hands: unlinkSockets ive-0269" + } + }, + "removeNode": { + "changesScene": true, + "malformed": 13, + "messages": { + "unknown field": "removeNode has no field 'zzUnknown'; its fields: treeKind, treeKey, id.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "id: wrong type": "id must be a string.", + "id: required missing": "id is required.", + "id: below minLength": "id must have at least 1 characters.", + "id: above maxLength": "id must have at most 63 characters.", + "id: outside charset": "id may contain only letters, digits, '.', '_' or '-'." + }, + "valid": { + "status": "accepted", + "message": "Node removed.", + "undoLabel": "Brokkr nibu/hands: removeNode ive-0284" + } + }, + "addModifier": { + "changesScene": true, + "malformed": 16, + "messages": { + "unknown field": "addModifier has no field 'zzUnknown'; its fields: objectName, modifierType, treeKind, treeKey, modifierName.", + "objectName: wrong type": "objectName must be a string.", + "objectName: required missing": "objectName is required.", + "modifierType: wrong type": "modifierType must be a string.", + "modifierType: enum miss": "modifierType must be one of NODES.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "modifierName: wrong type": "modifierName must be a string.", + "modifierName: below minLength": "modifierName must have at least 1 characters.", + "modifierName: above maxLength": "modifierName must have at most 63 characters.", + "modifierName: outside charset": "modifierName may contain only letters, digits, space, '.', '_' or '-'." + }, + "valid": { + "status": "accepted", + "message": "Geometry Nodes modifier set.", + "undoLabel": "Brokkr nibu/hands: addModifier ive-0302" + } + }, + "setModifierInput": { + "changesScene": true, + "malformed": 7, + "messages": { + "unknown field": "setModifierInput has no field 'zzUnknown'; its fields: objectName, modifierName, socket, value.", + "objectName: wrong type": "objectName must be a string.", + "objectName: required missing": "objectName is required.", + "modifierName: wrong type": "modifierName must be a string.", + "socket: wrong type": "socket must be a string.", + "socket: required missing": "socket is required.", + "value: required missing": "value is required." + }, + "valid": { + "status": "accepted", + "message": "Modifier input Count set.", + "undoLabel": "Brokkr nibu/hands: setModifierInput ive-0311" + }, + "note": "the intent changed nothing the signature reads (checked by label only)" + }, + "removeModifier": { + "changesScene": true, + "malformed": 7, + "messages": { + "unknown field": "removeModifier has no field 'zzUnknown'; its fields: objectName, modifierName.", + "objectName: wrong type": "objectName must be a string.", + "objectName: required missing": "objectName is required.", + "modifierName: wrong type": "modifierName must be a string.", + "modifierName: below minLength": "modifierName must have at least 1 characters.", + "modifierName: above maxLength": "modifierName must have at most 255 characters.", + "modifierName: forbidden part": "modifierName may not contain '\u0000'." + }, + "valid": { + "status": "accepted", + "message": "Modifier removed.", + "undoLabel": "Brokkr nibu/hands: removeModifier ive-0320" + } + } + }, + "table_actions": [ + "createObject", + "deleteObject", + "setObjectTransform", + "setObjectVisibility", + "setObjectParent", + "setObjectCustomProperty", + "selectObject", + "assignMaterial", + "importGltf", + "exportGltf", + "setCamera", + "setLight", + "setWorld", + "renderStill", + "look", + "createNodeGroup", + "addNode", + "removeNode", + "linkSockets", + "unlinkSockets", + "addModifier", + "removeModifier", + "setModifierInput" + ], + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json index e1c803e..ac8d776 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.result.json +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -16,7 +16,8 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", - "observedAt": "2026-11-27T20:02:43.826604+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:52.780549+00:00" } }, { @@ -47,7 +48,8 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", - "observedAt": "2026-11-27T20:02:43.826604+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:52.780549+00:00" } }, { @@ -63,7 +65,8 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:45.831074+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:54.875032+00:00" } }, { @@ -79,7 +82,8 @@ "requestedBy": "", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:47.837505+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:55.934781+00:00" } }, { @@ -135,7 +139,8 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", - "observedAt": "2026-11-27T20:02:43.826604+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:52.780549+00:00" }, "q2_original": { "schema": "brokkr.blender.command_receipt.v0", @@ -147,7 +152,8 @@ "requestedBy": "nibu/hands", "note": "queue test", "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", - "observedAt": "2026-11-27T20:02:43.826604+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:52.780549+00:00" }, "q2_denial": { "schema": "brokkr.blender.command_receipt.v0", @@ -159,7 +165,8 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:45.831074+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:54.875032+00:00" }, "q3": { "schema": "brokkr.blender.command_receipt.v0", @@ -171,12 +178,13 @@ "requestedBy": "", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:47.837505+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:03:55.934781+00:00" }, "q6": [ { "schema": "brokkr.blender.command_receipt.v0", - "commandId": "3414cf427aa549ea9e9a52c4cfc61908", + "commandId": "01683c810bbd449484c96d5984efccd7", "action": "createObject", "status": "denied", "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", @@ -184,11 +192,12 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:51.875508+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:04:00.170853+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", - "commandId": "3c53313e68aa4d07ab6e3e330396567d", + "commandId": "bea34b7535da46188b741f55b3592707", "action": "createObject", "status": "denied", "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", @@ -196,7 +205,8 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:51.901697+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:04:00.225976+00:00" } ], "q5": [ @@ -210,7 +220,8 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:53.881094+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:04:02.331449+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", @@ -222,7 +233,8 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:53.905589+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:04:02.387296+00:00" }, { "schema": "brokkr.blender.command_receipt.v0", @@ -234,11 +246,12 @@ "requestedBy": "nibu/hands", "note": "", "undoLabel": "", - "observedAt": "2026-11-27T20:02:53.944684+00:00" + "lookPath": "", + "observedAt": "2026-11-28T02:04:02.439331+00:00" } ] }, - "msgpack": "F:\\aeth-wt\\brokkr-live-pins.e2e\\res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", + "msgpack": "F:\\aeth-wt\\brokkr-action-table-live\\ext\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", "msgpack_packer": "msgpack.fallback", "msgpack_purepython_env": "", "ok": true diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json index 248b79b..1f3ef58 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.result.json +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -197,7 +197,7 @@ "name": "exportGltf and renderStill accepted with no undoLabel", "ok": true, "detail": [ - "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-0ge72kvx\\object.glb (3484 bytes).", + "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-lmbbnbpa\\object.glb (3484 bytes).", "Rendered still to object.png." ] }, @@ -270,7 +270,7 @@ "intent": "exportGltf", "status": "accepted", "undoLabel": "", - "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-0ge72kvx\\object.glb (3484 bytes)." + "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-lmbbnbpa\\object.glb (3484 bytes)." }, { "intent": "renderStill", diff --git a/surfaces/blender/tests/live/export_gltf.result.json b/surfaces/blender/tests/live/export_gltf.result.json index ff10cae..5a154ee 100644 --- a/surfaces/blender/tests/live/export_gltf.result.json +++ b/surfaces/blender/tests/live/export_gltf.result.json @@ -9,7 +9,7 @@ { "name": "glb accepted", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\all.glb (72752 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\all.glb (72752 bytes)." }, { "name": "glb written, no staging folder", @@ -26,12 +26,12 @@ { "name": "extras=false leaves them out", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\noextras.glb (72720 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\noextras.glb (72720 bytes)." }, { "name": "selection exports only the sphere", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\only.glb (70240 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\only.glb (70240 bytes)." }, { "name": "selection restored", @@ -44,7 +44,7 @@ { "name": "gltf accepted", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\sep\\s.gltf (2840 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\sep\\s.gltf (2840 bytes)." }, { "name": "gltf writes its bin and the texture beside it", @@ -108,7 +108,7 @@ { "name": "the same name then exports", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\fresh\\deep\\x.glb (72752 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\fresh\\deep\\x.glb (72752 bytes)." } ] } \ No newline at end of file diff --git a/surfaces/blender/tests/live/gn_actions.py b/surfaces/blender/tests/live/gn_actions.py index 9d86395..b5b2e0e 100644 --- a/surfaces/blender/tests/live/gn_actions.py +++ b/surfaces/blender/tests/live/gn_actions.py @@ -152,7 +152,7 @@ check("unwired exposed input leaves result", srt(evaluated(t, "ScatterHost")["in r = act(t, action="addNode", treeKey="Scatter", id="bad", blIdname="GeometryNodeMeshCube", inputs={"Nope": 1}); check("unknown input refused", r["status"] == "failed", r["message"]) check("refused addNode left no node", not any(n.get("brokkr_id") == "bad" for n in bpy.data.node_groups["Scatter"].nodes)) r = act(t, action="addNode", treeKey="Scatter", id="bad2", blIdname="GeometryNodeMeshCube", properties={"nope": 1}); check("unknown property refused", r["status"] == "failed", r["message"]) -r = act(t, action="addNode", treeKey="Scatter", id="bad3", blIdname="GeometryNodeImportOBJ"); check("file-reading node refused", r["status"] == "failed", r["message"]) +r = act(t, action="addNode", treeKey="Scatter", id="bad3", blIdname="GeometryNodeImportOBJ"); check("file-reading node refused", r["status"] == "denied", r["message"]) r = act(t, action="addNode", treeKey="Scatter", id="bad4", blIdname="GeometryNodeNoSuchThing"); check("unknown node type refused", r["status"] == "failed", r["message"]) r = act(t, action="linkSockets", treeKey="Scatter", fromNode="cone", fromSocket="Mesh", toNode="dist", toSocket="Density"); check("invalid link refused and removed", r["status"] == "failed" and not any(l.to_socket.name == "Density" for l in bpy.data.node_groups["Scatter"].links), r["message"]) r = act(t, action="setModifierInput", objectName="ScatterHost", modifierName="GN", socket="Seed", value="x"); check("wrong value type refused", r["status"] == "failed", r["message"]) @@ -167,7 +167,7 @@ after = [(l.from_node.get("brokkr_id"), l.to_socket.identifier) for l in bpy.dat check("refused link keeps the link it would have replaced", r["status"] == "failed" and before == after == [("cube", "Points")], (r["message"], before, after)) ok(t2, action="createObject", objectType="CAMERA", name="Cam") r = act(t2, action="addModifier", objectName="Cam", treeKey="L"); check("modifier on a camera refused clearly", r["status"] == "failed" and "CAMERA" in r["message"], r["message"]) -r = act(t2, action="addNode", treeKey="L", id="n\n", blIdname="ShaderNodeMath"); check("trailing newline in an id refused", r["status"] == "failed", r["message"]) +r = act(t2, action="addNode", treeKey="L", id="n\n", blIdname="ShaderNodeMath"); check("trailing newline in an id refused", r["status"] == "denied", r["message"]) # off-origin host: vertices are local, instances world, bounds kept apart t3 = fresh() graph(t3, "Off", GEO_OUT, [dict(id="circle", blIdname="GeometryNodeMeshCircle", inputs={"Vertices": 4, "Radius": 1.0}), dict(id="cube", blIdname="GeometryNodeMeshCube"), dict(id="iop", blIdname="GeometryNodeInstanceOnPoints"), dict(id="join", blIdname="GeometryNodeJoinGeometry")], diff --git a/surfaces/blender/tests/live/gn_actions.result.json b/surfaces/blender/tests/live/gn_actions.result.json index cdcc1f5..3253af1 100644 --- a/surfaces/blender/tests/live/gn_actions.result.json +++ b/surfaces/blender/tests/live/gn_actions.result.json @@ -1,5 +1,5 @@ { - "blender": "5.2.3 LTS", + "blender": "5.3.0", "checks": [ { "name": "createNodeGroup Ring", @@ -435,7 +435,7 @@ { "name": "file-reading node refused", "ok": true, - "detail": "node type GeometryNodeImportOBJ is not allowed in this cut (Import)." + "detail": "blIdname may not contain 'Import'." }, { "name": "unknown node type refused", @@ -514,7 +514,7 @@ { "name": "trailing newline in an id refused", "ok": true, - "detail": "id must be 1..63 characters of letters, digits, space, '.', '_' or '-'." + "detail": "id may contain only letters, digits, '.', '_' or '-'." }, { "name": "createNodeGroup Off", @@ -955,7 +955,7 @@ "detail": [ 59, 59, - 0.008 + 0.013 ] }, { @@ -1052,7 +1052,7 @@ "name": "2000x2000 instanced grid: capture is bounded", "ok": true, "detail": [ - 1.2, + 2.17, 99999, false ] @@ -1086,12 +1086,12 @@ "name": "2000x2000 mesh grid: counts only, bounded", "ok": true, "detail": [ - 0.05, + 0.0, 4000000 ] } ], - "cycle_probe_seconds": 0.008, - "capture_2000_grid_instanced_seconds": 1.198, - "capture_2000_grid_mesh_seconds": 0.045 + "cycle_probe_seconds": 0.013, + "capture_2000_grid_instanced_seconds": 2.173, + "capture_2000_grid_mesh_seconds": 0.002 } \ No newline at end of file diff --git a/surfaces/blender/tests/live/perception_fixes.result.json b/surfaces/blender/tests/live/perception_fixes.result.json index af2638c..11ca160 100644 --- a/surfaces/blender/tests/live/perception_fixes.result.json +++ b/surfaces/blender/tests/live/perception_fixes.result.json @@ -5,7 +5,7 @@ "name": "window up: the region capture, source named", "ok": true, "detail": { - "commandId": "01a21f023e60712180b8b5afee5b2621", + "commandId": "01a21fe56d007f03a2355733ee33a416", "action": "look", "captureSource": "region", "editSelection": [], @@ -14,15 +14,15 @@ "editedSinceLookNote": "", "humanEditSeq": 0, "humanEditsSinceLook": 0, - "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f023e60712180b8b5afee5b2621.png", - "message": "Captured the 3D view to look/01a21f023e60712180b8b5afee5b2621.png.", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe56d007f03a2355733ee33a416.png", + "message": "Captured the 3D view to look/01a21fe56d007f03a2355733ee33a416.png.", "note": "", "objectName": "", - "observedAt": "2026-11-27T21:56:11.107854+00:00", + "observedAt": "2026-11-28T02:04:19.958143+00:00", "requestedBy": "nibu/hands", "sceneUpdateSeq": 0, "schema": "brokkr.blender.command_receipt.v0", - "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", "status": "accepted", "undoLabel": "" } @@ -87,7 +87,7 @@ "name": "after her link of an object: the receipt says the attribution is coarse", "ok": true, "detail": { - "commandId": "01a21f02711f7571991decbd06059938", + "commandId": "01a21fe5a09b70728ba3f974ad47eecc", "action": "look", "captureSource": "region", "editSelection": [], @@ -101,15 +101,15 @@ "editedSinceLookNote": "Coarse: all objects flagged; editedSinceLook may name objects she did not touch.", "humanEditSeq": 4, "humanEditsSinceLook": 1, - "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f02711f7571991decbd06059938.png", - "message": "Captured the 3D view to look/01a21f02711f7571991decbd06059938.png.", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe5a09b70728ba3f974ad47eecc.png", + "message": "Captured the 3D view to look/01a21fe5a09b70728ba3f974ad47eecc.png.", "note": "", "objectName": "", - "observedAt": "2026-11-27T21:56:23.908406+00:00", + "observedAt": "2026-11-28T02:04:32.629832+00:00", "requestedBy": "nibu/hands", "sceneUpdateSeq": 5, "schema": "brokkr.blender.command_receipt.v0", - "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", "status": "accepted", "undoLabel": "" } @@ -118,7 +118,7 @@ "name": "after a plain move: not coarse, only the Cube named", "ok": true, "detail": { - "commandId": "01a21f027a1873a1a21df913136a4d49", + "commandId": "01a21fe5a8a677439cb3f76df5eed508", "action": "look", "captureSource": "region", "editSelection": [], @@ -129,15 +129,15 @@ "editedSinceLookNote": "", "humanEditSeq": 5, "humanEditsSinceLook": 1, - "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f027a1873a1a21df913136a4d49.png", - "message": "Captured the 3D view to look/01a21f027a1873a1a21df913136a4d49.png.", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe5a8a677439cb3f76df5eed508.png", + "message": "Captured the 3D view to look/01a21fe5a8a677439cb3f76df5eed508.png.", "note": "", "objectName": "", - "observedAt": "2026-11-27T21:56:26.306053+00:00", + "observedAt": "2026-11-28T02:04:34.918968+00:00", "requestedBy": "nibu/hands", "sceneUpdateSeq": 6, "schema": "brokkr.blender.command_receipt.v0", - "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", "status": "accepted", "undoLabel": "" } @@ -146,7 +146,7 @@ "name": "after her undo: coarse", "ok": true, "detail": { - "commandId": "01a21f027ec27dd0bda5c62b0974531a", + "commandId": "01a21fe5ad537f33846b930d41821f0e", "action": "look", "captureSource": "region", "editSelection": [], @@ -159,15 +159,15 @@ "editedSinceLookNote": "Coarse: all objects flagged; editedSinceLook may name objects she did not touch.", "humanEditSeq": 7, "humanEditsSinceLook": 2, - "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f027ec27dd0bda5c62b0974531a.png", - "message": "Captured the 3D view to look/01a21f027ec27dd0bda5c62b0974531a.png.", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe5ad537f33846b930d41821f0e.png", + "message": "Captured the 3D view to look/01a21fe5ad537f33846b930d41821f0e.png.", "note": "", "objectName": "", - "observedAt": "2026-11-27T21:56:27.505456+00:00", + "observedAt": "2026-11-28T02:04:36.080195+00:00", "requestedBy": "nibu/hands", "sceneUpdateSeq": 7, "schema": "brokkr.blender.command_receipt.v0", - "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", "status": "accepted", "undoLabel": "" } @@ -186,21 +186,21 @@ "ok": true, "detail": { "new": [ - 221, - 191, - 185, - 197, - 193 + 262, + 192, + 187, + 188, + 187 ], "old": [ - 977, - 950, - 974, - 1059, - 956 + 1044, + 1060, + 1010, + 1044, + 1313 ], - "new_median": 193, - "old_median": 974 + "new_median": 188, + "old_median": 1044 } }, { @@ -215,7 +215,7 @@ ], "minimised": { "a": { - "commandId": "01a21f02458877a186fe6a31fe3b32d6", + "commandId": "01a21fe575527fa0b4a36ecdbdd38ae6", "action": "look", "captureSource": "offscreen", "editSelection": [], @@ -224,20 +224,20 @@ "editedSinceLookNote": "", "humanEditSeq": 0, "humanEditsSinceLook": 0, - "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f02458877a186fe6a31fe3b32d6.png", - "message": "Captured the 3D view to look/01a21f02458877a186fe6a31fe3b32d6.png.", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe575527fa0b4a36ecdbdd38ae6.png", + "message": "Captured the 3D view to look/01a21fe575527fa0b4a36ecdbdd38ae6.png.", "note": "", "objectName": "", - "observedAt": "2026-11-27T21:56:13.275722+00:00", + "observedAt": "2026-11-28T02:04:22.160175+00:00", "requestedBy": "nibu/hands", "sceneUpdateSeq": 0, "schema": "brokkr.blender.command_receipt.v0", - "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", "status": "accepted", "undoLabel": "" }, "b": { - "commandId": "01a21f024b1876d0a4ec6281a49404a2", + "commandId": "01a21fe57bb173238bf0f2419a61ec46", "action": "look", "captureSource": "offscreen", "editSelection": [], @@ -248,15 +248,15 @@ "editedSinceLookNote": "", "humanEditSeq": 1, "humanEditsSinceLook": 1, - "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f024b1876d0a4ec6281a49404a2.png", - "message": "Captured the 3D view to look/01a21f024b1876d0a4ec6281a49404a2.png.", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe57bb173238bf0f2419a61ec46.png", + "message": "Captured the 3D view to look/01a21fe57bb173238bf0f2419a61ec46.png.", "note": "", "objectName": "", - "observedAt": "2026-11-27T21:56:14.485857+00:00", + "observedAt": "2026-11-28T02:04:23.398210+00:00", "requestedBy": "nibu/hands", "sceneUpdateSeq": 1, "schema": "brokkr.blender.command_receipt.v0", - "sessionId": "4385c8bd86ec421db23676bc4d03569f", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", "status": "accepted", "undoLabel": "" }, @@ -271,27 +271,27 @@ "edit_selection_parts_ms": { "from_edit_mesh": 0.0, "totals": 0.0, - "verts": 24.7, - "edges": 79.6, - "faces": 33.2 + "verts": 27.4, + "edges": 70.9, + "faces": 27.4 }, "edit_selection_ms": { "new": [ - 221, - 191, - 185, - 197, - 193 + 262, + 192, + 187, + 188, + 187 ], "old": [ - 977, - 950, - 974, - 1059, - 956 + 1044, + 1060, + 1010, + 1044, + 1313 ], - "new_median": 193, - "old_median": 974 + "new_median": 188, + "old_median": 1044 } }, "ok": true diff --git a/surfaces/blender/tests/live/refusals.py b/surfaces/blender/tests/live/refusals.py index 3abd794..16823cb 100644 --- a/surfaces/blender/tests/live/refusals.py +++ b/surfaces/blender/tests/live/refusals.py @@ -64,9 +64,9 @@ t.bpy = bpy for kind in ("LIGHT", "EMPTY", "CAMERA"): r = act("createObject", objectType=kind, meshType="CYLINDER") - check("meshType on %s is refused" % kind, r["status"] == "failed" and "MESH" in r["message"], r["message"]) + check("meshType on %s is refused" % kind, r["status"] == "denied" and "MESH" in r["message"], r["message"]) check("and nothing was created for them", len([o for o in bpy.data.objects if o.type in ("LIGHT", "EMPTY")]) == 0) -r = act("createObject", objectType="MESH", meshType="cube") +r = act("createObject", objectType="MESH", meshType="CUBE") check("meshType CUBE on a MESH still works", r["status"] == "accepted", r["message"]) shutil.rmtree(work, ignore_errors=True) diff --git a/surfaces/blender/tests/live/refusals.result.json b/surfaces/blender/tests/live/refusals.result.json index 0047130..9c06d28 100644 --- a/surfaces/blender/tests/live/refusals.result.json +++ b/surfaces/blender/tests/live/refusals.result.json @@ -31,17 +31,17 @@ { "name": "meshType on LIGHT is refused", "ok": true, - "detail": "meshType applies only to objectType MESH, not LIGHT." + "detail": "meshType applies only when objectType is one of MESH." }, { "name": "meshType on EMPTY is refused", "ok": true, - "detail": "meshType applies only to objectType MESH, not EMPTY." + "detail": "meshType applies only when objectType is one of MESH." }, { "name": "meshType on CAMERA is refused", "ok": true, - "detail": "meshType applies only to objectType MESH, not CAMERA." + "detail": "meshType applies only when objectType is one of MESH." }, { "name": "and nothing was created for them", From c348e5d6342ffcd1cb0146e8daa64220ac6a1a70 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 03:09:32 +0100 Subject: [PATCH 048/223] live/action_table.py: name the environment variables that really isolate Blender's extensions Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/tests/live/action_table.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/tests/live/action_table.py b/surfaces/blender/tests/live/action_table.py index 98cbdf8..0c3967a 100644 --- a/surfaces/blender/tests/live/action_table.py +++ b/surfaces/blender/tests/live/action_table.py @@ -5,7 +5,10 @@ BROKKR_CULTLIB= blender --python action_table.py -- -Run it in a Blender whose resource path is fresh (BLENDER_USER_RESOURCE_PATH). Every intent is put into the node +Run it in a Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(this Blender build ignores BLENDER_USER_RESOURCE_PATH, so `extension install-file` would land in the operator's own +extensions folder), the extension installed there with `blender --command extension install-file --repo user_default +--enable ` under the same variables. Every intent is put into the node database as brokkr-ctl does and answered by the add-on's own 1 s drain (the sink is on). For every action in actions.json: * malformed intents generated from its table entry (an unknown field, a wrong type, an enum miss, a bound miss, From f7a43c19fd4d3871abac1114b66a7c4722de0533 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 03:44:05 +0100 Subject: [PATCH 049/223] Soul s1 fixes: private Blender env enforced, whole floats for integers, validate never raises, parent loops refused, timeout says queued or claimed - Every live script that installs or enables the extension refuses to run unless BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are set and Blender's extensions folder is the one named (Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); every other live script and install.md say so; the stale docstrings are corrected. - validate returns integer fields as int (1920.0 reaches Blender as 1920); five fixture cases added for both validators. - validate sorts unknown keys by str, so a document with mixed key types is a denied receipt, not a raise after the claim; pinned with hostile documents and through the drain. - setObjectParent refuses a parent that is the object or one of its own children before any undo step. - brokkr-ctl on timeout prints whether the intent is still queued (not run) or was claimed with no receipt (may or may not have run); group help says so. - live action_table re-run: 205 of 205, renderStill sample sends 8.0. Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/src/blender.rs | 17 +++- brokkr-ctl/tests/cli.rs | 21 +++++ .../blender/brokkr_bridge/action_table.py | 7 +- .../blender/brokkr_bridge/blender_target.py | 5 + surfaces/blender/docs/install.md | 5 + surfaces/blender/tests/action_cases.json | 7 +- surfaces/blender/tests/live/action_table.py | 17 +++- .../tests/live/action_table.result.json | 94 +++++++++---------- .../blender/tests/live/agent_turn_queue.py | 9 ++ .../blender/tests/live/agent_turn_undo.py | 2 + surfaces/blender/tests/live/export_gltf.py | 2 + surfaces/blender/tests/live/gn_actions.py | 2 + surfaces/blender/tests/live/gn_recreation.py | 2 + surfaces/blender/tests/live/headless_smoke.py | 2 + .../blender/tests/live/material_colour.py | 2 + surfaces/blender/tests/live/perception.py | 12 ++- .../blender/tests/live/perception_fixes.py | 10 +- surfaces/blender/tests/live/refusals.py | 2 + surfaces/blender/tests/live/stop_presence.py | 9 ++ surfaces/blender/tests/test_action_table.py | 31 ++++++ surfaces/blender/tests/test_agent_turn.py | 19 ++++ 21 files changed, 219 insertions(+), 58 deletions(-) diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index e404585..dc47866 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -278,6 +278,20 @@ fn wait_for_receipt( } None => { println!("status: timeout"); + // The add-on deletes an intent when it claims it, before it runs, so the queue says which timeout this is. + let key = format!("{INTENT_PREFIX}{id}"); + let queued = store + .pull_all()? + .iter() + .any(|e| e.key == key && e.r#type == INTENT_SCHEMA); + println!( + "message: {}", + if queued { + "the intent is still queued: Blender has not claimed it (is Agent Commands on and the add-on running?); it has not run" + } else { + "Blender claimed the intent but wrote no receipt: it may or may not have run; look at the scene before sending it again" + } + ); Ok(Outcome::Timeout.code()) } } @@ -412,7 +426,8 @@ brokkr-ctl blender: send typed intents to the live Blender add-on and read what Every command needs --store or $BROKKR_BLENDER_STORE (the add-on's .ccmp). send needs $EUREKA_INSTANCE and --agent or $BROKKR_AGENT; requestedBy is '/'. Output is 'key: value' lines. Exit: 0 accepted, 2 denied or failed, 3 stopped, 4 timeout, -1 usage or store error. send refuses an intent the action table refuses (exit 1, nothing written); +1 usage or store error. On timeout a message says whether the intent is still queued (not run) or was claimed by +Blender with no receipt (it may or may not have run). send refuses an intent the action table refuses (exit 1, nothing written); the add-on decides the rest and its refusal comes back in the receipt. " .to_string() diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 59d0444..9936d7f 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -162,6 +162,27 @@ fn wait_matches_the_exact_receipt_key() { assert!(stdout(&output).contains("status: timeout")); } +/// Exit 4 is two situations the sender must tell apart: the intent was never claimed (still in the queue, not run), +/// or Blender claimed it (deleted it from the queue) and no receipt landed (it may have run). +#[test] +fn a_timeout_says_whether_the_intent_is_still_queued_or_was_claimed() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let sent = ctl(&path, &["send", "createObject", "--agent", "hands", "--timeout", "0.3"], Some("nibu")); + assert_eq!(sent.status.code(), Some(4)); + let text = stdout(&sent); + assert!(text.contains("status: timeout") && text.contains("still queued") && text.contains("it has not run"), "{text}"); + let id = text.lines().find_map(|l| l.strip_prefix("commandId: ")).unwrap().to_string(); + // Blender claims it: the intent leaves the queue, and no receipt is written + let mut store = SingleFileMessagePackBackingStore::new(&path); + let queued = store.pull_all().unwrap().into_iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap(); + store.delete(&queued).unwrap(); + let waited = ctl(&path, &["wait", &id, "--timeout", "0.3"], None); + assert_eq!(waited.status.code(), Some(4)); + let text = stdout(&waited); + assert!(text.contains("claimed the intent but wrote no receipt") && text.contains("may or may not have run"), "{text}"); +} + #[test] fn exit_code_follows_the_receipt() { let dir = tempfile::tempdir().unwrap(); diff --git a/surfaces/blender/brokkr_bridge/action_table.py b/surfaces/blender/brokkr_bridge/action_table.py index dafbe9e..3ecaa2f 100644 --- a/surfaces/blender/brokkr_bridge/action_table.py +++ b/surfaces/blender/brokkr_bridge/action_table.py @@ -117,7 +117,8 @@ def _check_spec(spec: dict[str, Any], where: str, charsets: dict, siblings: dict def validate(command: dict[str, Any]) -> dict[str, Any]: - """The normalized copy of an intent (nulls dropped, defaults filled), or IntentInvalid naming the rule.""" + """The normalized copy of an intent (nulls dropped, whole numbers of integer fields as int, defaults filled), or + IntentInvalid naming the rule. It raises nothing else, whatever the document holds.""" action = command.get("action", "") row = entry(action) if row is None: @@ -126,6 +127,8 @@ def validate(command: dict[str, Any]) -> dict[str, Any]: _fields(row["fields"], present, None, action, set(table()["envelope"])) result = dict(present) for field in row["fields"]: + if field["type"] == "integer" and field["name"] in result: + result[field["name"]] = int(result[field["name"]]) # a whole float (1920.0) is the same intent; Blender refuses a float for an int property if field["name"] not in result and "default" in field: result[field["name"]] = field["default"] return result @@ -135,7 +138,7 @@ def _fields(specs: list[dict[str, Any]], values: dict[str, Any], parent: str | N """The fields of an action (parent None) or of a closed object: unknown names first, sorted, then each declared field in table order.""" declared = [s["name"] for s in specs] - for key in sorted(k for k in values if k not in skip and k not in declared): + for key in sorted((k for k in values if k not in skip and k not in declared), key=str): # str: a store writer may mix key types raise IntentInvalid(f"{where} has no field '{key}'; its fields: {_list(declared) or 'none'}.") for spec in specs: path = spec["name"] if parent is None else f"{parent}.{spec['name']}" diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 4ab155d..f87da9c 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -775,6 +775,11 @@ class BrokkrBlenderTarget: parent = self.bpy.data.objects.get(parent_name) if parent_name else None if parent_name and parent is None: return self._receipt(command, "failed", f"Parent Blender object was not found: {parent_name}", obj.name) + ancestor = parent + while ancestor is not None: # Blender raises for a loop after the undo step is owed: refuse it before + if ancestor.name == obj.name: + raise sa.ActionRefused(f"{obj.name!r} cannot be parented to itself or to one of its own children.") + ancestor = getattr(ancestor, "parent", None) obj.parent = parent return self._receipt(command, "accepted", "Blender object parent updated.", obj.name) diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 337b2e3..1bd94b9 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -41,6 +41,11 @@ blender --command extension build --source-dir surfaces/blender/brokkr_bridge -- blender --command extension install-file --repo user_default --enable /brokkr_bridge-0.2.0.zip ``` +To try a build without touching your own Blender, run both commands (and any live test) with private +`BLENDER_USER_CONFIG`, `BLENDER_USER_EXTENSIONS` and `BLENDER_USER_SCRIPTS` directories set. Blender 5.3 ignores +`BLENDER_USER_RESOURCE_PATH`, so `install-file` under it replaces the `user_default` copy in your own extensions +folder. The live tests refuse to start without the three variables. + The wheel is one pure-Python msgpack, so the extension carries no platform restriction (Blender 5.3 or newer, any OS). msgpack then runs its pure-Python fallback, which CultLib `9fc4bdda` (PR #180) decodes. diff --git a/surfaces/blender/tests/action_cases.json b/surfaces/blender/tests/action_cases.json index fb5a8e0..2c082f1 100644 --- a/surfaces/blender/tests/action_cases.json +++ b/surfaces/blender/tests/action_cases.json @@ -229,5 +229,10 @@ {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i"}, "expect": "ok"}, {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G"}, "expect": "ok"}, {"action": "removeModifier", "fields": {"objectName": "o"}, "expect": "ok"}, - {"action": "setModifierInput", "fields": {"objectName": "o", "socket": "s", "value": 1}, "expect": "ok"} + {"action": "setModifierInput", "fields": {"objectName": "o", "socket": "s", "value": 1}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 1920.0, "resolutionY": 1080.0}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 4.0}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 3.0}, "expect": "resolutionX must be between 4 and 16384."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 1920.5}, "expect": "resolutionX must be a whole number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 16384.0}, "expect": "ok"} ] diff --git a/surfaces/blender/tests/live/action_table.py b/surfaces/blender/tests/live/action_table.py index 0c3967a..24db485 100644 --- a/surfaces/blender/tests/live/action_table.py +++ b/surfaces/blender/tests/live/action_table.py @@ -5,10 +5,9 @@ BROKKR_CULTLIB= blender --python action_table.py -- -Run it in a Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories -(this Blender build ignores BLENDER_USER_RESOURCE_PATH, so `extension install-file` would land in the operator's own -extensions folder), the extension installed there with `blender --command extension install-file --repo user_default ---enable ` under the same variables. Every intent is put into the node +Run it in Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH; without them the operator's own extensions folder is used). The script +refuses to run when they are unset. Every intent is put into the node database as brokkr-ctl does and answered by the add-on's own 1 s drain (the sink is on). For every action in actions.json: * malformed intents generated from its table entry (an unknown field, a wrong type, an enum miss, a bound miss, @@ -29,6 +28,14 @@ from pathlib import Path import bpy +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") + SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() SCRATCH.mkdir(parents=True, exist_ok=True) OUT = sys.argv[sys.argv.index("--") + 1] @@ -142,7 +149,7 @@ SAMPLES = [ # (action, prep intents queued and run unmeasured first, the valid ("setCamera", [], {"targetObjectName": "Camera", "lens": 35, "cameraType": "PANO", "panoramaType": "FISHEYE_EQUIDISTANT", "active": True}), ("setLight", [], {"targetObjectName": "Light", "energy": 500, "color": [1, 0.5, 0], "lightType": "SUN"}), ("setWorld", [], {"color": [0.1, 0.1, 0.2], "strength": 1.5}), - ("renderStill", [], {"outputPath": "live.png", "engine": "CYCLES", "resolutionX": 8, "resolutionY": 8}), + ("renderStill", [], {"outputPath": "live.png", "engine": "CYCLES", "resolutionX": 8.0, "resolutionY": 8}), # a whole float: the table hands Blender an int ("look", [], {}), ("createNodeGroup", [], {"treeKey": "LiveG", "interface": [{"inOut": "INPUT", "name": "Geometry", "type": "Geometry"}, {"inOut": "OUTPUT", "name": "Geometry", "type": "Geometry"}, diff --git a/surfaces/blender/tests/live/action_table.result.json b/surfaces/blender/tests/live/action_table.result.json index b21b4c1..981a3a6 100644 --- a/surfaces/blender/tests/live/action_table.result.json +++ b/surfaces/blender/tests/live/action_table.result.json @@ -24,7 +24,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0001", "lookPath": "", - "observedAt": "2026-11-28T01:56:40.145813+00:00" + "observedAt": "2026-11-28T02:36:27.076161+00:00" } }, { @@ -72,7 +72,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0024", "lookPath": "", - "observedAt": "2026-11-28T01:56:45.785882+00:00" + "observedAt": "2026-11-28T02:36:32.724431+00:00" } }, { @@ -104,7 +104,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0026", "lookPath": "", - "observedAt": "2026-11-28T01:56:49.944500+00:00" + "observedAt": "2026-11-28T02:36:36.860973+00:00" } }, { @@ -156,7 +156,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: deleteObject ive-0030", "lookPath": "", - "observedAt": "2026-11-28T01:56:54.485651+00:00" + "observedAt": "2026-11-28T02:36:41.174327+00:00" } }, { @@ -188,7 +188,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0031", "lookPath": "", - "observedAt": "2026-11-28T01:56:56.566254+00:00" + "observedAt": "2026-11-28T02:36:43.258961+00:00" } }, { @@ -238,7 +238,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setObjectTransform ive-0053", "lookPath": "", - "observedAt": "2026-11-28T01:57:03.202116+00:00" + "observedAt": "2026-11-28T02:36:49.152690+00:00" } }, { @@ -270,7 +270,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0054", "lookPath": "", - "observedAt": "2026-11-28T01:57:05.306686+00:00" + "observedAt": "2026-11-28T02:36:51.255025+00:00" } }, { @@ -320,7 +320,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setObjectVisibility ive-0059", "lookPath": "", - "observedAt": "2026-11-28T01:57:09.874099+00:00" + "observedAt": "2026-11-28T02:36:55.787695+00:00" } }, { @@ -352,7 +352,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0060", "lookPath": "", - "observedAt": "2026-11-28T01:57:11.974525+00:00" + "observedAt": "2026-11-28T02:36:57.891977+00:00" } }, { @@ -402,7 +402,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setObjectParent ive-0065", "lookPath": "", - "observedAt": "2026-11-28T01:57:16.563563+00:00" + "observedAt": "2026-11-28T02:37:02.443984+00:00" } }, { @@ -434,7 +434,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0066", "lookPath": "", - "observedAt": "2026-11-28T01:57:18.681337+00:00" + "observedAt": "2026-11-28T02:37:04.556676+00:00" } }, { @@ -484,7 +484,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setObjectCustomProperty ive-0072", "lookPath": "", - "observedAt": "2026-11-28T01:57:22.508309+00:00" + "observedAt": "2026-11-28T02:37:09.259197+00:00" } }, { @@ -516,7 +516,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0073", "lookPath": "", - "observedAt": "2026-11-28T01:57:24.630024+00:00" + "observedAt": "2026-11-28T02:37:11.382979+00:00" } }, { @@ -566,7 +566,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: selectObject ive-0078", "lookPath": "", - "observedAt": "2026-11-28T01:57:29.310576+00:00" + "observedAt": "2026-11-28T02:37:16.017922+00:00" } }, { @@ -598,7 +598,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0079", "lookPath": "", - "observedAt": "2026-11-28T01:57:31.515585+00:00" + "observedAt": "2026-11-28T02:37:18.151455+00:00" } }, { @@ -648,7 +648,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: assignMaterial ive-0090", "lookPath": "", - "observedAt": "2026-11-28T01:57:37.550809+00:00" + "observedAt": "2026-11-28T02:37:23.926592+00:00" } }, { @@ -680,7 +680,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0091", "lookPath": "", - "observedAt": "2026-11-28T01:57:39.704717+00:00" + "observedAt": "2026-11-28T02:37:26.063118+00:00" } }, { @@ -730,7 +730,7 @@ "note": "", "undoLabel": "", "lookPath": "", - "observedAt": "2026-11-28T01:57:48.919027+00:00" + "observedAt": "2026-11-28T02:37:33.358972+00:00" } }, { @@ -757,7 +757,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0103", "lookPath": "", - "observedAt": "2026-11-28T01:57:51.228716+00:00" + "observedAt": "2026-11-28T02:37:35.528127+00:00" } }, { @@ -807,7 +807,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: importGltf ive-0107", "lookPath": "", - "observedAt": "2026-11-28T01:57:56.255504+00:00" + "observedAt": "2026-11-28T02:37:40.218377+00:00" } }, { @@ -839,7 +839,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0108", "lookPath": "", - "observedAt": "2026-11-28T01:57:58.437908+00:00" + "observedAt": "2026-11-28T02:37:42.369543+00:00" } }, { @@ -895,7 +895,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setCamera ive-0129", "lookPath": "", - "observedAt": "2026-11-28T01:58:11.054773+00:00" + "observedAt": "2026-11-28T02:37:54.650323+00:00" } }, { @@ -927,7 +927,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0130", "lookPath": "", - "observedAt": "2026-11-28T01:58:13.248452+00:00" + "observedAt": "2026-11-28T02:37:56.820173+00:00" } }, { @@ -983,7 +983,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setLight ive-0145", "lookPath": "", - "observedAt": "2026-11-28T01:58:22.382198+00:00" + "observedAt": "2026-11-28T02:38:05.386213+00:00" } }, { @@ -1015,7 +1015,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0146", "lookPath": "", - "observedAt": "2026-11-28T01:58:24.582227+00:00" + "observedAt": "2026-11-28T02:38:07.578985+00:00" } }, { @@ -1071,7 +1071,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setWorld ive-0158", "lookPath": "", - "observedAt": "2026-11-28T01:58:31.393393+00:00" + "observedAt": "2026-11-28T02:38:14.740238+00:00" } }, { @@ -1103,7 +1103,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0159", "lookPath": "", - "observedAt": "2026-11-28T01:58:33.598048+00:00" + "observedAt": "2026-11-28T02:38:16.953350+00:00" } }, { @@ -1159,7 +1159,7 @@ "note": "", "undoLabel": "", "lookPath": "", - "observedAt": "2026-11-28T01:58:44.631878+00:00" + "observedAt": "2026-11-28T02:38:28.064380+00:00" } }, { @@ -1186,7 +1186,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0174", "lookPath": "", - "observedAt": "2026-11-28T01:58:47.857036+00:00" + "observedAt": "2026-11-28T02:38:31.281935+00:00" } }, { @@ -1242,10 +1242,10 @@ "note": "", "undoLabel": "", "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch\\out\\look\\live-0177.png", - "observedAt": "2026-11-28T01:58:53.654873+00:00", + "observedAt": "2026-11-28T02:38:37.045877+00:00", "captureSource": "region", "sceneUpdateSeq": 95, - "sessionId": "3b3d62619afb43d0a8548fc3f2ce4a4f", + "sessionId": "0cc3e9cdaf454a249a30cc24e617581c", "humanEditSeq": 83, "humanEditsSinceLook": 83, "editedSinceLook": [ @@ -1288,7 +1288,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0178", "lookPath": "", - "observedAt": "2026-11-28T01:58:56.864241+00:00" + "observedAt": "2026-11-28T02:38:39.309535+00:00" } }, { @@ -1344,7 +1344,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createNodeGroup ive-0193", "lookPath": "", - "observedAt": "2026-11-28T01:59:10.270729+00:00" + "observedAt": "2026-11-28T02:38:51.073058+00:00" } }, { @@ -1376,7 +1376,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0194", "lookPath": "", - "observedAt": "2026-11-28T01:59:12.510947+00:00" + "observedAt": "2026-11-28T02:38:53.324909+00:00" } }, { @@ -1432,7 +1432,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: addNode ive-0223", "lookPath": "", - "observedAt": "2026-11-28T01:59:47.731039+00:00" + "observedAt": "2026-11-28T02:39:29.096510+00:00" } }, { @@ -1464,7 +1464,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0224", "lookPath": "", - "observedAt": "2026-11-28T01:59:49.993525+00:00" + "observedAt": "2026-11-28T02:39:31.428197+00:00" } }, { @@ -1520,7 +1520,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: linkSockets ive-0247", "lookPath": "", - "observedAt": "2026-11-28T02:00:17.375246+00:00" + "observedAt": "2026-11-28T02:39:59.079008+00:00" } }, { @@ -1552,7 +1552,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0248", "lookPath": "", - "observedAt": "2026-11-28T02:00:19.737999+00:00" + "observedAt": "2026-11-28T02:40:01.374248+00:00" } }, { @@ -1608,7 +1608,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: unlinkSockets ive-0269", "lookPath": "", - "observedAt": "2026-11-28T02:00:45.997967+00:00" + "observedAt": "2026-11-28T02:40:29.839429+00:00" } }, { @@ -1640,7 +1640,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0270", "lookPath": "", - "observedAt": "2026-11-28T02:00:48.315493+00:00" + "observedAt": "2026-11-28T02:40:32.156639+00:00" } }, { @@ -1696,7 +1696,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: removeNode ive-0284", "lookPath": "", - "observedAt": "2026-11-28T02:01:03.364715+00:00" + "observedAt": "2026-11-28T02:40:48.986174+00:00" } }, { @@ -1728,7 +1728,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0285", "lookPath": "", - "observedAt": "2026-11-28T02:01:05.767376+00:00" + "observedAt": "2026-11-28T02:40:51.316429+00:00" } }, { @@ -1784,7 +1784,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: addModifier ive-0302", "lookPath": "", - "observedAt": "2026-11-28T02:01:26.890644+00:00" + "observedAt": "2026-11-28T02:41:12.934572+00:00" } }, { @@ -1816,7 +1816,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0303", "lookPath": "", - "observedAt": "2026-11-28T02:01:29.307569+00:00" + "observedAt": "2026-11-28T02:41:15.376364+00:00" } }, { @@ -1872,7 +1872,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: setModifierInput ive-0311", "lookPath": "", - "observedAt": "2026-11-28T02:01:37.160827+00:00" + "observedAt": "2026-11-28T02:41:23.279634+00:00" } }, { @@ -1894,7 +1894,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: createObject ive-0312", "lookPath": "", - "observedAt": "2026-11-28T02:01:39.514028+00:00" + "observedAt": "2026-11-28T02:41:25.653006+00:00" } }, { @@ -1950,7 +1950,7 @@ "note": "", "undoLabel": "Brokkr nibu/hands: removeModifier ive-0320", "lookPath": "", - "observedAt": "2026-11-28T02:01:47.535687+00:00" + "observedAt": "2026-11-28T02:41:34.791771+00:00" } }, { diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py index 5f8a68c..aa0204b 100644 --- a/surfaces/blender/tests/live/agent_turn_queue.py +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -8,6 +8,7 @@ are drained by the add-on's own 1 s timer as one undo step each, with write-once BROKKR_CULTLIB= BROKKR_PYLIBS= + Private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are required (refused otherwise). blender --factory-startup --python agent_turn_queue.py -- Intents are put into the node database as brokkr-ctl does; a command JSON dropped under the debug @@ -23,6 +24,14 @@ from pathlib import Path import bpy +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") + if os.environ.get("BROKKR_PYLIBS"): sys.path.insert(0, os.environ["BROKKR_PYLIBS"]) SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() diff --git a/surfaces/blender/tests/live/agent_turn_undo.py b/surfaces/blender/tests/live/agent_turn_undo.py index c8bec53..8347907 100644 --- a/surfaces/blender/tests/live/agent_turn_undo.py +++ b/surfaces/blender/tests/live/agent_turn_undo.py @@ -1,4 +1,6 @@ """Live proof, in GUI Blender, that every agent intent is one undo step. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_ADDON= \ blender --factory-startup --python agent_turn_undo.py -- diff --git a/surfaces/blender/tests/live/export_gltf.py b/surfaces/blender/tests/live/export_gltf.py index ff9e0bc..e133e7a 100644 --- a/surfaces/blender/tests/live/export_gltf.py +++ b/surfaces/blender/tests/live/export_gltf.py @@ -1,4 +1,6 @@ """Live proof of exportGltf on real bpy: the option names exist on the real exporter, extras reach the +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. file, selection filters, .gltf writes its .bin and textures without overwriting, a refused or failed export leaves nothing behind. diff --git a/surfaces/blender/tests/live/gn_actions.py b/surfaces/blender/tests/live/gn_actions.py index b5b2e0e..87eda23 100644 --- a/surfaces/blender/tests/live/gn_actions.py +++ b/surfaces/blender/tests/live/gn_actions.py @@ -1,4 +1,6 @@ """Live proof of the node-graph actions: rebuild three geometry-node setups through Brokkr actions only. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_ADDON= \ blender -b --factory-startup --python gn_actions.py -- result.json diff --git a/surfaces/blender/tests/live/gn_recreation.py b/surfaces/blender/tests/live/gn_recreation.py index c7dc47d..2281812 100644 --- a/surfaces/blender/tests/live/gn_recreation.py +++ b/surfaces/blender/tests/live/gn_recreation.py @@ -1,4 +1,6 @@ """Recreate geometry-node setups through the Brokkr scene/object actions and compare with the native result. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_ADDON= \ blender -b --factory-startup --python gn_recreation.py -- result.json diff --git a/surfaces/blender/tests/live/headless_smoke.py b/surfaces/blender/tests/live/headless_smoke.py index 1d21601..40e6fff 100644 --- a/surfaces/blender/tests/live/headless_smoke.py +++ b/surfaces/blender/tests/live/headless_smoke.py @@ -1,4 +1,6 @@ """Live Blender smoke for the scene actions. Not part of the unittest run: it needs Blender. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_RUN= BROKKR_ADDON= \ blender --background --factory-startup --python surfaces/blender/tests/live/headless_smoke.py diff --git a/surfaces/blender/tests/live/material_colour.py b/surfaces/blender/tests/live/material_colour.py index 07c2f4d..d31533d 100644 --- a/surfaces/blender/tests/live/material_colour.py +++ b/surfaces/blender/tests/live/material_colour.py @@ -1,4 +1,6 @@ """Live proof of assignMaterial colour and idempotence on real bpy. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_ADDON= \ blender -b --factory-startup --python material_colour.py -- result.json diff --git a/surfaces/blender/tests/live/perception.py b/surfaces/blender/tests/live/perception.py index a62aeb8..7523763 100644 --- a/surfaces/blender/tests/live/perception.py +++ b/surfaces/blender/tests/live/perception.py @@ -6,7 +6,9 @@ BROKKR_CULTLIB= blender --python perception.py -- -Run it in a Blender whose resource path is fresh (BLENDER_USER_RESOURCE_PATH) so the add-on's preferences are the +Run it in Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH; without them the operator's own extensions folder is used). The script +refuses to run when they are unset. The add-on's preferences are then the defaults. The driver stands in for the operator's hands only: it saves the blend, ticks the sink and sets the render output directory (the two preferences an operator sets), enters Edit Mode, selects, moves objects and presses undo. Every intent is sent by brokkr-ctl and answered by the add-on's own timer. Writes .result.json, then quits. @@ -25,6 +27,14 @@ from pathlib import Path import bmesh import bpy +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") + SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() SCRATCH.mkdir(parents=True, exist_ok=True) CTL = os.environ["BROKKR_CTL"] diff --git a/surfaces/blender/tests/live/perception_fixes.py b/surfaces/blender/tests/live/perception_fixes.py index 7facba2..d535a51 100644 --- a/surfaces/blender/tests/live/perception_fixes.py +++ b/surfaces/blender/tests/live/perception_fixes.py @@ -1,6 +1,6 @@ """Live proof of the live-5 fix batch, in GUI Blender with the add-on installed as an extension, real brokkr-ctl looks. -Same environment as perception.py (BROKKR_SCRATCH, BROKKR_CTL, BROKKR_CULTLIB; a fresh BLENDER_USER_RESOURCE_PATH). +Same environment as perception.py (BROKKR_SCRATCH, BROKKR_CTL, BROKKR_CULTLIB; private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS; the script refuses to run without them). blender --python perception_fixes.py -- The driver stands in for the operator: it saves the blend, ticks the sink, sets the output directory, minimises and restores the Blender window (Windows ShowWindow on this process's own window), moves objects, enters Edit Mode. @@ -19,6 +19,14 @@ from pathlib import Path import bmesh import bpy + +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") import numpy SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() diff --git a/surfaces/blender/tests/live/refusals.py b/surfaces/blender/tests/live/refusals.py index 16823cb..a7292ad 100644 --- a/surfaces/blender/tests/live/refusals.py +++ b/surfaces/blender/tests/live/refusals.py @@ -1,4 +1,6 @@ """Live proof of the renderStill GL refusal and the createObject meshType refusal on real bpy. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_ADDON= \ blender -b --factory-startup --python refusals.py -- result.json diff --git a/surfaces/blender/tests/live/stop_presence.py b/surfaces/blender/tests/live/stop_presence.py index b1889f8..9e0c8a3 100644 --- a/surfaces/blender/tests/live/stop_presence.py +++ b/surfaces/blender/tests/live/stop_presence.py @@ -4,6 +4,7 @@ BROKKR_CTL= BROKKR_ADDON_MODULE= BROKKR_CULTLIB= + Private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are required (refused otherwise). blender --factory-startup --python stop_presence.py -- Run a second Blender on the same store with BROKKR_PHASE=closed for the sink-off, node-closed answer. @@ -23,6 +24,14 @@ from pathlib import Path import bpy +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") + SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() SCRATCH.mkdir(parents=True, exist_ok=True) CTL = os.environ["BROKKR_CTL"] diff --git a/surfaces/blender/tests/test_action_table.py b/surfaces/blender/tests/test_action_table.py index d548b1b..858920a 100644 --- a/surfaces/blender/tests/test_action_table.py +++ b/surfaces/blender/tests/test_action_table.py @@ -78,6 +78,37 @@ class ParityFixtureTests(unittest.TestCase): self.assertNotEqual([c for c in CASES if validate(c["action"], c["fields"]) != c["expect"]], [], mutant.__name__) +class NormalizationTests(unittest.TestCase): + def test_a_whole_float_for_an_integer_field_reaches_the_handler_as_an_int(self): + normal = at.validate({"action": "renderStill", "outputPath": "a.png", "resolutionX": 1920.0, "resolutionY": 4.0}) + self.assertEqual((normal["resolutionX"], normal["resolutionY"]), (1920, 4)) + self.assertIs(type(normal["resolutionX"]), int) + + def test_validate_never_raises_whatever_the_document_holds(self): + """A store writer outside brokkr-ctl can put anything in an intent; the drain has already claimed it, so a raise + here would lose the intent without a receipt. Every hostile shape ends as ok or IntentInvalid.""" + hostile = [ + {"action": "createObject", 1: "a", "zz": "b"}, + {"action": "createObject", (1, 2): 1, None: 2, "zz": 3}, + {"action": "createNodeGroup", "treeKey": "G", "interface": [{1: "a", "name": "x", "inOut": "INPUT", "type": "Int"}]}, + {"action": "createNodeGroup", "treeKey": "G", "interface": [{"inOut": "INPUT", "name": "x", "type": "Int", 5: 6, None: 7}]}, + {"action": ["createObject"]}, {"action": {"a": 1}}, {"action": None}, {"action": 7}, {}, + {"action": "createObject", "location": [10 ** 400, float("nan"), float("inf")]}, + {"action": "renderStill", "outputPath": b"bytes", "resolutionX": 10 ** 400}, + {"action": "renderStill", "outputPath": "a.png", "resolutionX": float("inf")}, + {"action": "addNode", "treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "properties": {1: 2, (3,): 4}}, + {"action": "createObject", "objectType": ["MESH"]}, {"action": "createObject", "objectType": {"a": 1}}, + {"action": "setObjectCustomProperty", "targetObjectName": "c", "value": object()}, + ] + for command in hostile: + try: + at.validate(command) + except at.IntentInvalid: + pass + except Exception as error: # noqa: BLE001 + self.fail(f"{command!r} raised {error!r}") + + class HandlerCoverageTests(unittest.TestCase): def test_each_table_action_resolves_to_exactly_one_handler_and_each_handler_has_an_entry(self): names = [a["name"] for a in at.table()["actions"]] diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 9f23465..b9fa12e 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -310,6 +310,25 @@ class DrainTests(unittest.TestCase): self.assertEqual(denial["status"], "denied") self.assertEqual(sorted(node.deleted), ["blender/commands/a", "blender/commands/b"]) + def test_a_mixed_key_intent_in_the_queue_ends_as_a_denied_receipt(self): + # a store writer can mix key types; the drain has claimed the intent, so validate must not raise + node = FakeNode({"blender/commands/a": {"commandId": "mixed-1", "requestedBy": "nibu/hands", "action": "createObject", 1: "a", "zz": "b"}}) + receipts = self.drain(node) + self.assertEqual([r["status"] for r in receipts], ["denied"]) + self.assertEqual(node.puts[0][0], "blender/receipts/mixed-1") + self.assertEqual(node.docs[bt.COMMAND_INTENT_SCHEMA], {}) + + def test_parenting_an_object_to_itself_or_its_own_child_is_refused_before_any_undo_step(self): + self.bpy.lamp.parent = self.bpy.mesh + for target, parent in (("Cube", "Cube"), ("Cube", "Lamp")): # Lamp is Cube's child + receipt = self.run_action(action="setObjectParent", targetObjectName=target, parentObjectName=parent) + self.assertEqual(receipt["status"], "failed", (target, parent)) + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + self.bpy.lamp.parent = None + self.assertEqual(self.run_action(action="setObjectParent", targetObjectName="Lamp", parentObjectName="Cube")["status"], "accepted") + self.assertEqual(len(self.bpy.undo.pushes), 1) + # claim-first: an intent leaves the queue before it runs, so no failure can run it twice def test_the_intent_is_deleted_before_its_handler_runs(self): node = FakeNode({"blender/commands/a": self.intent("claim-1")}) From 692606ba75ee048aa55507362ae784426fa8357f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:10:08 +0100 Subject: [PATCH 050/223] Blender add-on: host add-ons add rows to the action table through brokkr_actions.json check_host, host_actions discovery with ownership and RNA checks, _run_host_operator in the agent turn, hostActions and hostActionErrors in the snapshot, hostResult in receipts, fixture host add-on and cases. Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/action_table.py | 74 +++++- .../blender/brokkr_bridge/blender_target.py | 154 +++++++++++- .../fixtures/brokkr_host_fixture/__init__.py | 72 ++++++ .../brokkr_host_fixture/brokkr_actions.json | 37 +++ surfaces/blender/tests/host_action_cases.json | 21 ++ surfaces/blender/tests/test_action_table.py | 68 ++++++ surfaces/blender/tests/test_agent_turn.py | 222 ++++++++++++++++++ .../blender/tests/test_material_actions.py | 2 +- surfaces/blender/tests/test_node_actions.py | 2 +- surfaces/blender/tests/test_scene_actions.py | 2 +- surfaces/blender/tests/test_stop_presence.py | 2 +- 11 files changed, 638 insertions(+), 18 deletions(-) create mode 100644 surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py create mode 100644 surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json create mode 100644 surfaces/blender/tests/host_action_cases.json diff --git a/surfaces/blender/brokkr_bridge/action_table.py b/surfaces/blender/brokkr_bridge/action_table.py index 3ecaa2f..48a888f 100644 --- a/surfaces/blender/brokkr_bridge/action_table.py +++ b/surfaces/blender/brokkr_bridge/action_table.py @@ -1,7 +1,9 @@ """The action table: which Blender intents exist, what fields each may carry, and each action's undo class. -actions.json (schema brokkr.blender.actions.v0) is the one owner. run_intent admits every intent through -validate(); brokkr-ctl embeds the same file for `send --help` and early refusal, with the same rules and +actions.json (schema brokkr.blender.actions.v0) owns the built-in rows; a host add-on adds rows of its own +operators in brokkr_actions.json (schema brokkr.blender.host_actions.v0: scalar fields only, no free JSON, +an optional result naming a WindowManager string property), checked by check_host and passed to validate() +and entry() as `host`. run_intent admits every intent through validate(); brokkr-ctl embeds the same file for `send --help` and early refusal, with the same rules and message text (surfaces/blender/tests/action_cases.json pins the two). Stdlib only, no bpy. Vocabulary: null means absent; a required field absent is refused; a field neither declared nor in the @@ -17,11 +19,15 @@ from __future__ import annotations import functools import json import math +import re from pathlib import Path from typing import Any TABLE_PATH = Path(__file__).with_name("actions.json") SCHEMA = "brokkr.blender.actions.v0" +HOST_SCHEMA = "brokkr.blender.host_actions.v0" +HOST_TYPES = ("string", "number", "integer", "boolean") +HOST_NAME = re.compile(r"^[a-z0-9_]+\.[a-z0-9_]+$") TYPES = ("string", "number", "integer", "boolean", "array", "object", "any") TYPE_WORDS = {"string": "a string", "number": "a finite number", "integer": "a whole number", "boolean": "true or false", "array": "an array", "object": "an object"} @@ -57,9 +63,14 @@ def table() -> dict[str, Any]: return document -def entry(action: Any) -> dict[str, Any] | None: - """The table row for an action name, or None.""" - return _by_name().get(action) if isinstance(action, str) else None +def entry(action: Any, host: Any = ()) -> dict[str, Any] | None: + """The row for an action name: the built-in row, else the first host row of that name, else None.""" + if not isinstance(action, str): + return None + row = _by_name().get(action) + if row is not None: + return row + return next((h for h in host if h.get("name") == action), None) @functools.lru_cache(maxsize=1) @@ -90,6 +101,55 @@ def check_table(document: dict[str, Any]) -> None: raise TableInvalid(f"{action['name']}.{field['name']} default: {error}") from None +def check_host(document: Any, charsets: dict[str, Any]) -> None: + """Refuse a host add-on's brokkr_actions.json unless its schema is the host schema, every name is a dotted + operator id and unique, every field is scalar and passes the built-in spec checks (and its default its own + rules), and result, if present, is an identifier. Raises TableInvalid naming the row and field.""" + if not isinstance(document, dict) or document.get("schema") != HOST_SCHEMA: + raise TableInvalid(f"host schema must be {HOST_SCHEMA}") + for key in document: + if key not in ("schema", "actions"): + raise TableInvalid(f"host file has no key '{key}'") + rows = document.get("actions") + if not isinstance(rows, list): + raise TableInvalid("host file actions must be an array") + names = set() + for row in rows: + name = row.get("name") if isinstance(row, dict) else None + if not isinstance(name, str) or not HOST_NAME.match(name): + raise TableInvalid(f"host action name {name!r} must look like addon.operator (a-z, 0-9, _)") + if name in names: + raise TableInvalid(f"host action {name} is listed twice") + names.add(name) + for key in ("doc", "changesScene", "editModeSafe", "fields"): + if key not in row: + raise TableInvalid(f"{name} lacks {key}") + if not isinstance(row["fields"], list): + raise TableInvalid(f"{name} fields must be an array") + for key in row: + if key not in ("name", "doc", "changesScene", "editModeSafe", "fields", "result"): + raise TableInvalid(f"{name} has no key '{key}'") + if "result" in row and not (isinstance(row["result"], str) and row["result"].isidentifier()): + raise TableInvalid(f"{name}.result must be an identifier") + fields = {} + for field in row["fields"]: + if not isinstance(field, dict) or not isinstance(field.get("name"), str) or field["name"] in fields: + raise TableInvalid(f"{name} has a missing or repeated field name") + fields[field["name"]] = field + for field in fields.values(): + where = f"{name}.{field['name']}" + if field.get("type") not in HOST_TYPES: + raise TableInvalid(f"{where}: a host field is one of {_list(list(HOST_TYPES))}") + if "only" in field: + raise TableInvalid(f"{where}: a host field has no 'only'") + _check_spec(field, where, charsets, fields, top=True) + if "default" in field: + try: + _value(field, field["default"], field["name"]) + except IntentInvalid as error: + raise TableInvalid(f"{where} default: {error}") from None + + def _check_spec(spec: dict[str, Any], where: str, charsets: dict, siblings: dict, top: bool) -> None: kind = spec.get("type") if kind not in TYPES: @@ -116,11 +176,11 @@ def _check_spec(spec: dict[str, Any], where: str, charsets: dict, siblings: dict _check_spec(prop, f"{where}.{prop['name']}", charsets, inner, top=False) -def validate(command: dict[str, Any]) -> dict[str, Any]: +def validate(command: dict[str, Any], host: Any = ()) -> dict[str, Any]: """The normalized copy of an intent (nulls dropped, whole numbers of integer fields as int, defaults filled), or IntentInvalid naming the rule. It raises nothing else, whatever the document holds.""" action = command.get("action", "") - row = entry(action) + row = entry(action, host) if row is None: raise IntentInvalid(f"Unsupported Blender command action: {action}") present = {k: v for k, v in command.items() if v is not None} diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index f87da9c..8bde4b0 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -42,6 +42,8 @@ CULTLIB_PY_PACKAGES = ("cultcache-py", "cultnet-py", "cultmesh-py") DEFAULT_DEBUG_MIRROR_ROOT = "//.brokkr/blender-editor-debug" HOST_SNAPSHOT_SCHEMA = "brokkr.blender.host_snapshot.v0" +HOST_ACTIONS_FILE = "brokkr_actions.json" +HOST_RESULT_LIMIT = 16000 # characters of a host operator's result copied into a receipt COMMAND_INTENT_SCHEMA = "brokkr.blender.command_intent.v0" COMMAND_RECEIPT_SCHEMA = "brokkr.blender.command_receipt.v0" SYNC_SESSION_SCHEMA = "brokkr.sync.session.v0" @@ -100,6 +102,14 @@ CAPABILITIES = ( ) +class _NoHostFile(Exception): + """The add-on has no brokkr_actions.json: it is not a host.""" + + +def _first_line(text: str) -> str: + return text.strip().splitlines()[0] if text.strip() else "failed" + + class BrokkrBlenderTarget: """Blender-owned adapter target for Brokkr mirror documents.""" @@ -121,6 +131,7 @@ class BrokkrBlenderTarget: self.agent_turn = False # true only inside run_intent self._wrote = True # run_intent: false when an accepted action changed nothing self._receipted: set[str] = set() + self._host_files: dict[str, tuple[tuple, Any]] = {} # module -> (file stamp, parsed document or error text): a cache of reads, never truth self._unsent: list[tuple[dict[str, Any], str]] = [] # receipts whose write failed: written first on the next drain, never read as truth self._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts self._receipts_loaded = False @@ -600,6 +611,7 @@ class BrokkrBlenderTarget: def capture_snapshot(self, context: Any, agent_commands_enabled: bool) -> dict[str, Any]: bpy = self.bpy + host_rows, host_errors = self.host_actions() scan = self._instance_scan() if any(o.type == "MESH" and len(o.modifiers) for o in bpy.data.objects) else None selected = [item.name for item in context.selected_objects if item is not None] active_object = context.active_object.name if context.active_object else "" @@ -630,8 +642,90 @@ class BrokkrBlenderTarget: "objects": [self._object_snapshot(obj, scan) for obj in bpy.data.objects], "materials": [self._material_snapshot(material) for material in bpy.data.materials], "collections": [self._collection_snapshot(collection) for collection in bpy.data.collections], + "hostActions": host_rows, + "hostActionErrors": host_errors, } + def host_actions(self) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """The one discovery of host rows: ([row + 'host' module], [{host, error}]). Each enabled add-on but this + one may carry brokkr_actions.json beside its __init__.py; the file is admitted whole or not at all. The + file is the add-on's word; what is checked here is what Brokkr can see: the operator exists and is a + Python class defined by that add-on, every field is a property of it of the matching type whose RNA hard + limits contain the row's bounds, and result is a WindowManager string property. Only the parse is cached + (on path, mtime and size); the live checks run each time, so a disabled add-on or an unregistered operator + is gone at the next intent. A name two files claim fails ownership in all but its owner.""" + rows: list[dict[str, Any]] = [] + errors: list[dict[str, Any]] = [] + own = __package__ or "" + modules = [m for m in self.bpy.context.preferences.addons.keys() if m != own] + for module in modules: + try: + document = self._host_document(module) + except _NoHostFile: + continue + except Exception as error: + errors.append({"host": module, "error": _first_line(f"{HOST_ACTIONS_FILE}: {error}")}) + continue + try: + for row in document["actions"]: + self._check_host_row(module, row) + except Exception as error: + errors.append({"host": module, "error": _first_line(f"{HOST_ACTIONS_FILE}: {error}")}) + continue + rows.extend({**row, "host": module} for row in document["actions"]) + return rows, errors + + def _host_document(self, module: str) -> dict[str, Any]: + loaded = sys.modules.get(module) + source = getattr(loaded, "__file__", None) + path = Path(source).with_name(HOST_ACTIONS_FILE) if source else None + if path is None or not path.is_file(): + self._host_files.pop(module, None) + raise _NoHostFile() + info = path.stat() + stamp = (str(path), info.st_mtime_ns, info.st_size) + cached = self._host_files.get(module) + if cached is None or cached[0] != stamp: + try: + document = json.loads(path.read_text(encoding="utf-8")) + at.check_host(document, at.table()["charsets"]) + cached = (stamp, document) + except Exception as error: + cached = (stamp, str(error)) + self._host_files[module] = cached + if isinstance(cached[1], str): + raise ValueError(cached[1]) + return cached[1] + + def _check_host_row(self, module: str, row: dict[str, Any]) -> None: + bpy = self.bpy + name = row["name"] + first, second = name.split(".") + operator = getattr(getattr(bpy.ops, first), second) + owner = getattr(bpy.types, operator.idname(), None) + owned = getattr(owner, "__module__", None) + if not isinstance(owner, type) or not isinstance(owned, str) or not (owned == module or owned.startswith(module + ".")): + raise ValueError(f"{name} is not an operator defined by {module}") + properties = {p.identifier: p for p in operator.get_rna_type().properties} + kinds = {"string": "STRING", "number": "FLOAT", "integer": "INT", "boolean": "BOOLEAN"} + for field in row["fields"]: + prop = properties.get(field["name"]) + where = f"{name}.{field['name']}" + if prop is None: + raise ValueError(f"{where} is not a property of the operator") + enum = field.get("enum") + if prop.type != ("ENUM" if enum is not None else kinds[field["type"]]): + raise ValueError(f"{where} is {prop.type} in the operator, not {field['type']}") + if enum is not None and {item.identifier for item in prop.enum_items} != set(enum): + raise ValueError(f"{where} enum differs from the operator's") + if field["type"] in ("number", "integer") and not (prop.hard_min <= field["minimum"] and field["maximum"] <= prop.hard_max): + raise ValueError(f"{where} bounds exceed the operator's own limits") + result = row.get("result") + if result is not None: + prop = bpy.types.WindowManager.bl_rna.properties.get(result) + if prop is None or prop.type != "STRING": + raise ValueError(f"{name} result {result} is not a string property of WindowManager") + def run_intent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: """The one agent turn: admit, run with operator undo off, push one labelled undo step, receipt. @@ -639,7 +733,8 @@ class BrokkrBlenderTarget: valid), then Edit Mode. While an object is in Edit Mode undo steps are edit-mesh steps, so a scene write is not reverted by one undo and some operators leave Edit Mode (brokkr-live:ruling:object-intents-refused-in-edit-mode); the table's editModeSafe actions write nothing - and change no mode. A refusal at admission is 'denied': nothing ran, no undo step.""" + and change no mode. Host add-on rows (host_actions) are admitted by the same table check and run through + the same turn. A refusal at admission is 'denied': nothing ran, no undo step.""" command_id = command.get("commandId") requested_by = command.get("requestedBy") action = command.get("action", "") @@ -653,8 +748,9 @@ class BrokkrBlenderTarget: denial = "Intent has no requestedBy of the form '/'." else: try: - command = at.validate(command) - row = at.entry(action) + host, _ = self.host_actions() + command = at.validate(command, host) + row = at.entry(action, host) except at.IntentInvalid as error: denial = str(error) if not denial and not row["editModeSafe"] and self._edit_mode_object() is not None: @@ -671,7 +767,7 @@ class BrokkrBlenderTarget: self._wrote = True try: try: - receipt = self._dispatch(context, command) + receipt = self._dispatch(context, command, row) if receipt["status"] != "accepted" or not self._wrote: push = False # a refusal, or an accepted no-op: it wrote nothing except sa.ActionRefused as error: # raised before any write: nothing to push @@ -707,16 +803,59 @@ class BrokkrBlenderTarget: else: self.bpy.ops.ed.undo_push(message=label) - def _dispatch(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - """Only run_intent calls it, with an intent the table admitted: the handler is '_' + the action's name, - on NodeActions for the node actions and on this target for the rest. It owns refusal, failure and the undo step.""" + def _dispatch(self, context: Any, command: dict[str, Any], row: dict[str, Any]) -> dict[str, Any]: + """Only run_intent calls it, with an intent the table admitted: a host row runs its operator; otherwise the + handler is '_' + the action's name, on NodeActions for the node actions and on this target for the rest. + It owns refusal, failure and the undo step.""" action = command["action"] + if "host" in row: + return self._run_host_operator(context, command, row) if hasattr(self.nodes, "_" + action): message, name = self.nodes.execute(action, command) self._wrote = self.nodes.changed return self._receipt(command, "accepted", message, name) return getattr(self, "_" + action)(context, command) + def _run_host_operator(self, context: Any, command: dict[str, Any], row: dict[str, Any]) -> dict[str, Any]: + """A host add-on's own operator, called with exactly the declared fields. FINISHED is accepted; CANCELLED + is failed and wrote nothing; an argument Blender will not convert raises ActionRefused before anything + ran; an ERROR report or exception is RuntimeError, failed (run_intent pushes '(failed)' for a changesScene + row). A row's result property is cleared before and copied, capped, into the receipt.""" + bpy = self.bpy + name = row["name"] + skip = set(at.table()["envelope"]) + kwargs = {k: v for k, v in command.items() if k not in skip} + result = row.get("result") + manager = bpy.context.window_manager + if result: + setattr(manager, result, "") + first, second = name.split(".") + operator = getattr(getattr(bpy.ops, first), second) + windows = manager.windows + try: + if windows: + with bpy.context.temp_override(window=windows[0]): + outcome = operator("EXEC_DEFAULT", False, **kwargs) + else: + outcome = operator("EXEC_DEFAULT", False, **kwargs) + except TypeError as error: + raise sa.ActionRefused(f"Operator {name} refused its arguments: {_first_line(str(error))}") from None + except RuntimeError as error: + raise RuntimeError(_first_line(str(error))) from None + text = "" + if result: + text = getattr(manager, result, "") or "" + if len(text) > HOST_RESULT_LIMIT: + text = text[:HOST_RESULT_LIMIT] + " [truncated]" + if "FINISHED" in outcome: + self._wrote = bool(row["changesScene"]) + receipt = self._receipt(command, "accepted", f"Operator {name} finished.", "") + else: + self._wrote = False + receipt = self._receipt(command, "failed", f"Operator {name} cancelled; nothing changed.", "") + receipt["hostResult"] = text + return receipt + def _createObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: object_type = command["objectType"] name = command.get("name") or f"Brokkr {object_type.title()}" @@ -1410,6 +1549,7 @@ class BrokkrBlenderTarget: "note": command["note"][:NOTE_LIMIT] if isinstance(command.get("note"), str) else "", "undoLabel": "", "lookPath": "", + "hostResult": "", "observedAt": _now(), } diff --git a/surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py b/surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py new file mode 100644 index 0000000..671d78c --- /dev/null +++ b/surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py @@ -0,0 +1,72 @@ +"""A legacy host add-on for Brokkr's host-action tests. It knows nothing of Brokkr: its brokkr_actions.json is +the whole contract. apply is registered but left out of that file, the shape of an operator only a human runs.""" +bl_info = {"name": "Brokkr host fixture", "blender": (4, 2, 0), "category": "Development"} + +import bpy + + +class BROKKR_HOST_FIXTURE_OT_add_empty(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.add_empty" + bl_label = "Fixture add empty" + bl_options = {"REGISTER", "UNDO"} + name: bpy.props.StringProperty(default="Fixture") + size: bpy.props.FloatProperty(default=1.0, min=0.0, max=100.0) + + def execute(self, context): + empty = bpy.data.objects.new(self.name, None) + empty.empty_display_size = self.size + context.scene.collection.objects.link(empty) + return {"FINISHED"} + + +class BROKKR_HOST_FIXTURE_OT_report(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.report" + bl_label = "Fixture report" + bl_options = {"REGISTER"} + + def execute(self, context): + context.window_manager.brokkr_host_fixture_result = f"objects: {len(bpy.data.objects)}\nscenes: {len(bpy.data.scenes)}" + return {"FINISHED"} + + +class BROKKR_HOST_FIXTURE_OT_refuse(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.refuse" + bl_label = "Fixture refuse" + + def execute(self, context): + self.report({"ERROR"}, "the fixture refuses") + return {"CANCELLED"} + + +class BROKKR_HOST_FIXTURE_OT_cancel(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.cancel" + bl_label = "Fixture cancel" + + def execute(self, context): + return {"CANCELLED"} + + +class BROKKR_HOST_FIXTURE_OT_apply(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.apply" + bl_label = "Fixture apply" + bl_options = {"REGISTER", "UNDO"} + + def execute(self, context): + bpy.data.objects.new("Applied", None) + return {"FINISHED"} + + +classes = (BROKKR_HOST_FIXTURE_OT_add_empty, BROKKR_HOST_FIXTURE_OT_report, BROKKR_HOST_FIXTURE_OT_refuse, + BROKKR_HOST_FIXTURE_OT_cancel, BROKKR_HOST_FIXTURE_OT_apply) + + +def register(): + bpy.types.WindowManager.brokkr_host_fixture_result = bpy.props.StringProperty() + for cls in classes: + bpy.utils.register_class(cls) + + +def unregister(): + for cls in reversed(classes): + bpy.utils.unregister_class(cls) + del bpy.types.WindowManager.brokkr_host_fixture_result diff --git a/surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json b/surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json new file mode 100644 index 0000000..160f67a --- /dev/null +++ b/surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json @@ -0,0 +1,37 @@ +{ + "schema": "brokkr.blender.host_actions.v0", + "actions": [ + { + "name": "brokkr_host_fixture.add_empty", + "doc": "Add an empty named for the agent.", + "changesScene": true, + "editModeSafe": false, + "fields": [ + {"name": "name", "type": "string", "required": true, "minLength": 1, "maxLength": 63, "doc": "the empty's name"}, + {"name": "size", "type": "number", "minimum": 0.1, "maximum": 10, "default": 1, "doc": "display size"} + ] + }, + { + "name": "brokkr_host_fixture.report", + "doc": "Write a report of the scene without changing it.", + "changesScene": false, + "editModeSafe": true, + "result": "brokkr_host_fixture_result", + "fields": [] + }, + { + "name": "brokkr_host_fixture.refuse", + "doc": "Report an error and cancel.", + "changesScene": false, + "editModeSafe": true, + "fields": [] + }, + { + "name": "brokkr_host_fixture.cancel", + "doc": "Cancel without a report.", + "changesScene": false, + "editModeSafe": true, + "fields": [] + } + ] +} diff --git a/surfaces/blender/tests/host_action_cases.json b/surfaces/blender/tests/host_action_cases.json new file mode 100644 index 0000000..91836a9 --- /dev/null +++ b/surfaces/blender/tests/host_action_cases.json @@ -0,0 +1,21 @@ +[ + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E"}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 0.1}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 10}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": null, "note": "n", "requestedBy": "a/b", "commandId": "x"}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {}, "expect": "name is required."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": ""}, "expect": "name must have at least 1 characters."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "name must have at most 63 characters."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": 5}, "expect": "name must be a string."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 0.05}, "expect": "size must be between 0.1 and 10."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 10.5}, "expect": "size must be between 0.1 and 10."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": true}, "expect": "size must be a finite number."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "bogus": 1}, "expect": "brokkr_host_fixture.add_empty has no field 'bogus'; its fields: name, size."}, + {"action": "brokkr_host_fixture.report", "fields": {}, "expect": "ok"}, + {"action": "brokkr_host_fixture.report", "fields": {"name": "E"}, "expect": "brokkr_host_fixture.report has no field 'name'; its fields: none."}, + {"action": "brokkr_host_fixture.refuse", "fields": {}, "expect": "ok"}, + {"action": "brokkr_host_fixture.cancel", "fields": {}, "expect": "ok"}, + {"action": "brokkr_host_fixture.apply", "fields": {}, "expect": "Unsupported Blender command action: brokkr_host_fixture.apply"}, + {"action": "wm.save_mainfile", "fields": {}, "expect": "Unsupported Blender command action: wm.save_mainfile"}, + {"action": "createObject", "fields": {}, "expect": "ok"} +] diff --git a/surfaces/blender/tests/test_action_table.py b/surfaces/blender/tests/test_action_table.py index 858920a..f3a5f6e 100644 --- a/surfaces/blender/tests/test_action_table.py +++ b/surfaces/blender/tests/test_action_table.py @@ -14,6 +14,8 @@ at = ts.at bt = ts.bt na = ts.bt.na CASES = json.loads((Path(__file__).with_name("action_cases.json")).read_text(encoding="utf-8")) +HOST_FILE = json.loads((Path(__file__).parent / "fixtures" / "brokkr_host_fixture" / "brokkr_actions.json").read_text(encoding="utf-8")) +HOST_CASES = json.loads((Path(__file__).with_name("host_action_cases.json")).read_text(encoding="utf-8")) def validate(action, fields): @@ -24,6 +26,72 @@ def validate(action, fields): return "ok" +class HostTableTests(unittest.TestCase): + """A host add-on's brokkr_actions.json adds rows; the same messages as for built-ins.""" + + def charsets(self): + return at.table()["charsets"] + + def host_file(self, **row): + base = copy.deepcopy(HOST_FILE) + base["actions"][0].update(row) + return base + + def test_the_fixture_file_is_admitted(self): + at.check_host(HOST_FILE, self.charsets()) + + def wrong_cases(self): + wrong = [] + for case in HOST_CASES: + try: + at.validate({"action": case["action"], **case["fields"]}, HOST_FILE["actions"]) + got = "ok" + except at.IntentInvalid as error: + got = str(error) + if got != case["expect"]: + wrong.append((case["action"], case["fields"], case["expect"], got)) + return wrong + + def test_every_host_case_yields_exactly_its_expected_message_or_ok(self): + self.assertEqual(self.wrong_cases(), []) + + def test_a_mutant_that_skips_host_rows_or_lets_an_undeclared_field_through_fails_a_case(self): + original = at.entry + with mock.patch.object(at, "entry", lambda action, host=(): original(action)): + self.assertTrue(self.wrong_cases()) + with mock.patch.object(at, "_fields", lambda *args: None): + self.assertTrue(self.wrong_cases()) + + def test_check_host_refuses_non_scalar_fields_bad_names_and_foreign_keys(self): + field = {"name": "f", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}} + for bad, why in ( + (self.host_file(fields=[field]), "array"), + (self.host_file(fields=[{"name": "f", "type": "object"}]), "object"), + (self.host_file(fields=[{"name": "f", "type": "any"}]), "any"), + (self.host_file(name="undotted"), "undotted"), + (self.host_file(name="Upper.case"), "uppercase"), + (self.host_file(fields=[{"name": "f", "type": "string", "chars": "nope"}]), "charset"), + (self.host_file(result="not an identifier"), "result"), + (self.host_file(fields=[{"name": "f", "type": "number"}]), "unbounded"), + ({**HOST_FILE, "envelope": []}, "envelope key"), + ({**HOST_FILE, "charsets": {}}, "charsets key"), + ({**HOST_FILE, "schema": at.SCHEMA}, "schema"), + ): + with self.assertRaises(at.TableInvalid, msg=why): + at.check_host(bad, self.charsets()) + twice = copy.deepcopy(HOST_FILE) + twice["actions"].append(copy.deepcopy(twice["actions"][0])) + with self.assertRaises(at.TableInvalid): + at.check_host(twice, self.charsets()) + + def test_a_host_row_never_shadows_a_built_in(self): + shadow = [{"name": "createObject", "doc": "", "changesScene": True, "editModeSafe": True, "fields": []}] + self.assertIs(at.entry("createObject", shadow), at.entry("createObject")) + self.assertEqual(at.entry("brokkr_host_fixture.report", HOST_FILE["actions"])["name"], "brokkr_host_fixture.report") + self.assertIsNone(at.entry("brokkr_host_fixture.report")) + self.assertTrue(all("." not in a["name"] for a in at.table()["actions"])) + + class ParityFixtureTests(unittest.TestCase): """action_cases.json is also run by brokkr-ctl's actions.rs: one table, two interpreters, one set of messages.""" diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index b9fa12e..6578b4b 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -232,6 +232,228 @@ class AgentTurnTests(unittest.TestCase): self.assertNotIn("requires CultLib's Python packages", str(caught.exception)) +FIXTURE = Path(__file__).parent / "fixtures" / "brokkr_host_fixture" +HOST = "brokkr_host_fixture" +NS = ts.NS + + +def types_module(name, file): + import types + module = types.ModuleType(name) + module.__file__ = str(file) + return module + + +class HostOp: + """bpy.ops..: callable with idname() and get_rna_type(), recording its calls.""" + + def __init__(self, name, props, behave): + self.cls = type(f"BROKKR_HOST_FIXTURE_OT_{name}", (), {"__module__": HOST}) + self.props = props + self.behave = behave + self.calls = [] + + def idname(self): + return self.cls.__name__ + + def get_rna_type(self): + return NS(properties=self.props) + + def __call__(self, mode, undo, **kwargs): + assert (mode, undo) == ("EXEC_DEFAULT", False) + self.calls.append(kwargs) + return self.behave(self, kwargs) + + +def prop(identifier, kind, lo=0.0, hi=1e30, enum=()): + return NS(identifier=identifier, type=kind, hard_min=lo, hard_max=hi, enum_items=[NS(identifier=e) for e in enum]) + + +def raising(error): + def behave(op, kwargs): + raise error + return behave + + +class HostActionTests(unittest.TestCase): + """Host rows from a host add-on's brokkr_actions.json, discovered through a fake bpy, run by run_intent.""" + + def setUp(self): + ts.ActionTests.setUp(self) + self.dir = Path(self.tmp.name) / HOST + self.dir.mkdir() + (self.dir / "brokkr_actions.json").write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) + patch = unittest.mock.patch.dict(sys.modules, {HOST: types_module(HOST, self.dir / "__init__.py")}) + patch.start() + self.addCleanup(patch.stop) + bpy = self.bpy + self.ops = { + "add_empty": HostOp("add_empty", [prop("name", "STRING"), prop("size", "FLOAT", 0.0, 100.0)], self.finish), + "report": HostOp("report", [], self.write_report), + "refuse": HostOp("refuse", [], raising(RuntimeError("Error: the fixture refuses"))), + "cancel": HostOp("cancel", [], lambda op, kw: {"CANCELLED"}), + "apply": HostOp("apply", [], self.finish), + } + bpy.ops.brokkr_host_fixture = NS(**self.ops) + bpy.types = NS(WindowManager=NS(bl_rna=NS(properties={"brokkr_host_fixture_result": NS(type="STRING")})), + **{op.idname(): op.cls for op in self.ops.values()}) + bpy.context.preferences.addons = {HOST: object(), "brokkr_bridge": object()} + bpy.context.window_manager.brokkr_host_fixture_result = "stale" + self.report_text = "objects: 3" + + def finish(self, op, kwargs): + return {"FINISHED"} + + def write_report(self, op, kwargs): + self.bpy.context.window_manager.brokkr_host_fixture_result = self.report_text + return {"FINISHED"} + + run_action = ts.ActionTests.run_action + + def send(self, operator, **fields): + return self.run_action(action=f"{HOST}.{operator}", **fields) + + def test_a_changing_host_operator_runs_with_exactly_its_declared_fields_and_is_one_undo_step(self): + receipt = self.send("add_empty", name="E", size=2) + self.assertEqual(receipt["status"], "accepted", receipt) + self.assertEqual(receipt["message"], f"Operator {HOST}.add_empty finished.") + self.assertEqual(receipt["hostResult"], "") + self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 2}]) + self.assertEqual(len(self.bpy.undo.pushes), 1) + self.assertTrue(self.bpy.undo.pushes[0].startswith("Brokkr nibu/hands: brokkr_host_fixture.add_empty ")) + self.assertEqual(receipt["undoLabel"], self.bpy.undo.pushes[0]) + + def test_the_default_is_filled_and_an_undeclared_field_never_reaches_the_operator(self): + self.assertEqual(self.send("add_empty", name="E")["status"], "accepted") + self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 1}]) + denied = self.send("add_empty", name="E", location=[1, 2, 3]) + self.assertEqual(denied["status"], "denied") + self.assertEqual(len(self.ops["add_empty"].calls), 1) + + def test_a_non_changing_operator_pushes_no_undo_step_and_returns_its_result(self): + receipt = self.send("report") + self.assertEqual((receipt["status"], receipt["hostResult"]), ("accepted", "objects: 3")) + self.assertEqual(self.bpy.undo.pushes, []) + self.assertEqual(self.run_action(action="createObject")["hostResult"], "") # a built-in's receipt carries the field empty + + def test_the_result_is_cleared_before_the_call_and_capped_after(self): + seen = [] + self.ops["report"].behave = lambda op, kw: (seen.append(self.bpy.context.window_manager.brokkr_host_fixture_result), {"CANCELLED"})[1] + self.assertEqual(self.send("report")["hostResult"], "") + self.assertEqual(seen, [""]) # 'stale' was cleared first + self.ops["report"].behave = self.write_report + self.report_text = "x" * (bt.HOST_RESULT_LIMIT + 50) + text = self.send("report")["hostResult"] + self.assertEqual(text, "x" * bt.HOST_RESULT_LIMIT + " [truncated]") + self.report_text = "y" * bt.HOST_RESULT_LIMIT + self.assertEqual(self.send("report")["hostResult"], "y" * bt.HOST_RESULT_LIMIT) + + def test_cancelled_is_failed_with_no_push(self): + receipt = self.send("cancel") + self.assertEqual((receipt["status"], receipt["message"]), ("failed", f"Operator {HOST}.cancel cancelled; nothing changed.")) + self.ops["add_empty"].behave = lambda op, kw: {"CANCELLED"} + self.assertEqual(self.send("add_empty", name="E")["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_a_conversion_error_is_failed_and_pushes_nothing(self): + self.ops["add_empty"].behave = raising(TypeError('keyword "size" could not be converted')) + receipt = self.send("add_empty", name="E") + self.assertEqual(receipt["status"], "failed") + self.assertIn("refused its arguments", receipt["message"]) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_a_runtime_error_is_failed_with_its_first_line_and_pushes_failed_only_for_a_changing_row(self): + receipt = self.send("refuse") + self.assertEqual((receipt["status"], receipt["message"]), ("failed", "Error: the fixture refuses")) + self.assertEqual(self.bpy.undo.pushes, []) + self.ops["add_empty"].behave = raising(RuntimeError("Traceback...\nboom")) + receipt = self.send("add_empty", name="E") + self.assertEqual((receipt["status"], receipt["message"]), ("failed", "Traceback...")) + self.assertEqual(len(self.bpy.undo.pushes), 1) + self.assertTrue(self.bpy.undo.pushes[0].endswith("(failed)")) + + def test_a_human_only_operator_and_a_c_operator_are_unsupported_and_leave_no_trace(self): + for action in (f"{HOST}.apply", "wm.save_mainfile", "brokkr.stop_agents"): + receipt = self.run_action(action=action) + self.assertEqual(receipt["status"], "denied", action) + self.assertIn("Unsupported Blender command action", receipt["message"]) + self.assertEqual(self.ops["apply"].calls, []) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_a_host_row_is_refused_in_edit_mode_unless_it_is_edit_mode_safe(self): + self.bpy.mesh.mode = "EDIT" + self.assertEqual(self.send("add_empty", name="E")["status"], "denied") + self.assertEqual(self.send("report")["status"], "accepted") + + def test_the_snapshot_lists_the_admitted_rows_with_their_host_and_no_human_only_row(self): + self.bpy.data = NS(objects=[], scenes=[], collections=[], materials=[], images=[], filepath="") + self.bpy.app = NS(version=(5, 3, 0), background=False) + context = NS(selected_objects=[], active_object=None, scene=None, mode="OBJECT") + snapshot = self.target.capture_snapshot(context, True) + names = [row["name"] for row in snapshot["hostActions"]] + self.assertEqual(names, [f"{HOST}.{n}" for n in ("add_empty", "report", "refuse", "cancel")]) + self.assertEqual({row["host"] for row in snapshot["hostActions"]}, {HOST}) + self.assertEqual(snapshot["hostActionErrors"], []) + + def refused(self): + rows, errors = self.target.host_actions() + self.assertEqual(rows, []) + self.assertEqual([e["host"] for e in errors], [HOST]) + self.assertIn("brokkr_actions.json", errors[0]["error"]) + self.assertEqual(self.send("report")["status"], "denied") # none of its rows is admitted + return errors[0]["error"] + + def test_a_row_naming_another_add_ons_operator_refuses_the_whole_file(self): + self.ops["report"].cls.__module__ = "other_addon" + self.assertIn("not an operator defined by", self.refused()) + self.ops["report"].cls.__module__ = HOST + ".sub" + self.assertEqual(len(self.target.host_actions()[0]), 4) # a submodule is its own + + def test_a_c_operator_refuses_the_whole_file(self): + self.bpy.types = NS(**{**vars(self.bpy.types), self.ops["cancel"].idname(): None}) + self.refused() + + def test_rna_disagreement_refuses_the_whole_file(self): + self.ops["add_empty"].props = [prop("name", "STRING")] # size missing + self.assertIn("size is not a property", self.refused()) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "INT", 0, 100)] + self.assertIn("is INT in the operator", self.refused()) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "FLOAT", 0.5, 100.0)] # hard min above the row's 0.1 + self.assertIn("bounds exceed", self.refused()) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "FLOAT", 0.0, 5.0)] # hard max below the row's 10 + self.assertIn("bounds exceed", self.refused()) + + def test_a_result_that_is_not_a_window_manager_string_refuses_the_whole_file(self): + self.bpy.types.WindowManager.bl_rna.properties["brokkr_host_fixture_result"] = NS(type="INT") + self.assertIn("not a string property", self.refused()) + self.bpy.types.WindowManager.bl_rna.properties.clear() + self.refused() + + def test_a_malformed_file_refuses_itself_and_a_changed_file_is_read_again(self): + path = self.dir / "brokkr_actions.json" + good = path.read_text(encoding="utf-8") + path.write_text(good.replace("host_actions.v0", "host_actions.v9"), encoding="utf-8") + self.assertIn("schema", self.refused()) + path.write_text(good, encoding="utf-8") + self.assertEqual(len(self.target.host_actions()[0]), 4) + path.write_text("not json", encoding="utf-8") + self.refused() + + def test_disabling_the_add_on_makes_its_action_unsupported_at_the_next_intent(self): + self.assertEqual(self.send("report")["status"], "accepted") + self.bpy.context.preferences.addons.pop(HOST) + receipt = self.send("report") + self.assertEqual(receipt["status"], "denied") + self.assertIn("Unsupported Blender command action", receipt["message"]) + self.assertEqual(self.target.host_actions(), ([], [])) + + def test_an_add_on_without_the_file_is_not_a_host_and_this_add_on_is_never_read(self): + (self.dir / "brokkr_actions.json").unlink() + self.assertEqual(self.target.host_actions(), ([], [])) + self.bpy.context.preferences.addons["brokkr_bridge"] = object() + self.assertEqual(self.target.host_actions(), ([], [])) + + class FakeNode: """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" def __init__(self, intents, receipts=()): diff --git a/surfaces/blender/tests/test_material_actions.py b/surfaces/blender/tests/test_material_actions.py index 884bca2..bf2baef 100644 --- a/surfaces/blender/tests/test_material_actions.py +++ b/surfaces/blender/tests/test_material_actions.py @@ -60,7 +60,7 @@ class FakeUndo: """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" def __init__(self, bpy): self.pushes = [] - bpy.context = NS(window_manager=NS(windows=[object()]), temp_override=lambda **kw: contextlib.nullcontext()) + bpy.context = NS(window_manager=NS(windows=[object()]), preferences=NS(addons={}), temp_override=lambda **kw: contextlib.nullcontext()) ops = getattr(bpy, "ops", None) or NS() ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) bpy.ops = ops diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index 2a24752..6d4a762 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -174,7 +174,7 @@ class FakeUndo: """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" def __init__(self, bpy): self.pushes = [] - bpy.context = NS(window_manager=NS(windows=[object()]), temp_override=lambda **kw: contextlib.nullcontext()) + bpy.context = NS(window_manager=NS(windows=[object()]), preferences=NS(addons={}), temp_override=lambda **kw: contextlib.nullcontext()) ops = getattr(bpy, "ops", None) or NS() ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) bpy.ops = ops diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index d9abebc..0281ba3 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -80,7 +80,7 @@ class FakeUndo: self.pushes = [] self.overrides = [] self.window = object() - bpy.context = NS(window_manager=NS(windows=[self.window]), + bpy.context = NS(window_manager=NS(windows=[self.window]), preferences=NS(addons={}), temp_override=lambda **kw: (self.overrides.append(kw), contextlib.nullcontext())[1]) ops = getattr(bpy, "ops", None) or NS() ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py index 5e732d9..ea796b7 100644 --- a/surfaces/blender/tests/test_stop_presence.py +++ b/surfaces/blender/tests/test_stop_presence.py @@ -364,7 +364,7 @@ class NoPreferenceWritesTests(unittest.TestCase): # the sink toggle is the human's: no intent or action code reaches add-on preferences for name in ("scene_actions.py", "node_actions.py", "blender_target.py"): source = (BRIDGE / name).read_text(encoding="utf-8") - self.assertEqual(re.findall(r"[.]preferences\b|\bprefs\b", source), [], name) + self.assertEqual(re.findall(r"[.]preferences\b(?![.]addons[.]keys\(\))|\bprefs\b", source), [], name) if __name__ == "__main__": From 7b47fa5b8319f148e42353750283f5b5de5d26a6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:11:51 +0100 Subject: [PATCH 051/223] brokkr-ctl: host rows from the host snapshot in validate, send --help and status Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/src/actions.rs | 65 +++++++++++++++++++--- brokkr-ctl/src/blender.rs | 79 ++++++++++++++++++++++++--- brokkr-ctl/tests/cli.rs | 111 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 240 insertions(+), 15 deletions(-) diff --git a/brokkr-ctl/src/actions.rs b/brokkr-ctl/src/actions.rs index 590b29c..40a3d40 100644 --- a/brokkr-ctl/src/actions.rs +++ b/brokkr-ctl/src/actions.rs @@ -2,7 +2,9 @@ //! refuses. The owner is the add-on's `actions.json` (schema brokkr.blender.actions.v0); this module reads //! it as data and implements the same vocabulary and message text as `action_table.py`, pinned to it by //! the shared fixture `surfaces/blender/tests/action_cases.json`. Anything that reaches the store is still -//! decided by the add-on. +//! decided by the add-on. Host add-ons' rows (`brokkr.blender.host_actions.v0`) are not embedded: they come +//! from the add-on's host snapshot (`hostActions`), are searched after the built-ins, and are pinned by +//! `surfaces/blender/tests/host_action_cases.json`; a stale snapshot can only make ctl refuse early. use serde_json::{Map, Value}; use std::sync::LazyLock; @@ -20,8 +22,12 @@ fn actions() -> &'static [Value] { table()["actions"].as_array().map_or(&[], Vec::as_slice) } -fn entry(name: &str) -> Option<&'static Value> { - actions().iter().find(|a| a["name"] == name) +/// The built-in row of that name, else the first host row of that name. +fn entry<'a>(name: &str, host: &'a [Value]) -> Option<&'a Value> { + actions() + .iter() + .chain(host) + .find(|a| a["name"] == name) } /// The names brokkr-ctl writes itself: `--set` cannot name them, and the table does not validate them. @@ -66,9 +72,9 @@ pub fn number_text(value: f64) -> String { } /// Refuses an intent the table refuses, with the add-on's message; nothing is normalized (the add-on fills defaults). -pub fn validate(command: &Map) -> Result<(), String> { +pub fn validate(command: &Map, host: &[Value]) -> Result<(), String> { let action = command.get("action").and_then(Value::as_str).unwrap_or(""); - let Some(row) = entry(action) else { + let Some(row) = entry(action, host) else { return Err(format!("Unsupported Blender command action: {action}")); }; let present: Map = command @@ -286,8 +292,13 @@ fn check_string(spec: &Value, text: &str, path: &str) -> Result<(), String> { /// The actions section of `send --help`: every action with its fields, built from the table. pub fn help() -> String { + help_rows(actions()) +} + +/// The help body for any rows: the built-ins, or the host rows a snapshot carries. +pub fn help_rows(rows: &[Value]) -> String { let mut text = String::new(); - for action in actions() { + for action in rows { text.push_str(&format!( " {}: {}\n", action["name"].as_str().unwrap_or(""), @@ -408,7 +419,7 @@ mod tests { for case in &cases { let mut command = case["fields"].as_object().unwrap().clone(); command.insert("action".into(), case["action"].clone()); - let got = validate(&command).err().unwrap_or_else(|| "ok".to_string()); + let got = validate(&command, &[]).err().unwrap_or_else(|| "ok".to_string()); if Some(got.as_str()) != case["expect"].as_str() { wrong.push(format!( "{} {} expected {} got {got}", @@ -425,12 +436,50 @@ mod tests { ); } + /// The host rows a fixture add-on publishes, run through the same validator as the add-on's + /// HostTableTests: one set of messages for host rows too. + #[test] + fn the_host_parity_fixture_yields_the_add_ons_messages() { + let file: Value = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json" + )) + .unwrap(); + let host = file["actions"].as_array().unwrap().clone(); + let cases: Vec = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/host_action_cases.json" + )) + .unwrap(); + assert!(cases.len() >= 15, "{} cases", cases.len()); + let mut wrong = Vec::new(); + for case in &cases { + let mut command = case["fields"].as_object().unwrap().clone(); + command.insert("action".into(), case["action"].clone()); + let got = validate(&command, &host) + .err() + .unwrap_or_else(|| "ok".to_string()); + if Some(got.as_str()) != case["expect"].as_str() { + wrong.push(format!( + "{} {} expected {} got {got}", + case["action"], case["fields"], case["expect"] + )); + } + } + assert!(wrong.is_empty(), "{}", wrong.join("\n")); + // Without the snapshot's rows the same host action is unsupported: ctl never invents rows. + let mut command = Map::new(); + command.insert("action".into(), "brokkr_host_fixture.report".into()); + assert_eq!( + validate(&command, &[]).unwrap_err(), + "Unsupported Blender command action: brokkr_host_fixture.report" + ); + } + #[test] fn a_non_string_action_is_unsupported_and_the_envelope_is_the_tables() { let mut command = Map::new(); command.insert("action".into(), Value::from(3)); assert_eq!( - validate(&command).unwrap_err(), + validate(&command, &[]).unwrap_err(), "Unsupported Blender command action: " ); assert_eq!( diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index dc47866..8a604ba 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -115,7 +115,7 @@ pub fn run(args: &[String]) -> Result { } let options = parse(rest)?; if options.help { - print!("{}", if sub == "send" { send_help() } else { group_help() }); + print!("{}", if sub == "send" { send_help(&options) } else { group_help() }); return Ok(0); } match sub.as_str() { @@ -214,6 +214,7 @@ fn build_intent( requested_by: &str, note: &str, sets: &[String], + host: &[Value], ) -> Result { let mut map = Map::new(); for set in sets { @@ -232,7 +233,7 @@ fn build_intent( map.insert("action".into(), action.into()); map.insert("requestedBy".into(), requested_by.into()); map.insert("note".into(), note.into()); - actions::validate(&map).map_err(|message| anyhow!(message))?; + actions::validate(&map, host).map_err(|message| anyhow!(message))?; Ok(Value::Object(map)) } @@ -240,7 +241,8 @@ fn send(options: &Options, action: &str) -> Result { let requested_by = requested_by(options)?; let mut store = open_store(options)?; let command_id = uuid::Uuid::now_v7().simple().to_string(); - let intent = build_intent(action, &command_id, &requested_by, &options.note, &options.sets)?; + let (host, _) = host_rows(&store)?; + let intent = build_intent(action, &command_id, &requested_by, &options.note, &options.sets, &host)?; store.push(&CultCacheEnvelope { key: format!("{INTENT_PREFIX}{command_id}"), r#type: INTENT_SCHEMA.to_string(), @@ -339,6 +341,27 @@ fn receipts(store: &SingleFileMessagePackBackingStore, last: Option) -> R Ok(0) } +/// The host snapshot as the add-on last published it, if any. +fn snapshot(store: &SingleFileMessagePackBackingStore) -> Result> { + for envelope in store.pull_all()? { + if envelope.key == SNAPSHOT_KEY && envelope.r#type == SNAPSHOT_SCHEMA { + return Ok(Some(decode(&envelope)?)); + } + } + Ok(None) +} + +/// The host rows the add-on published and when (`observedAt`); empty before any snapshot. A display and +/// early-refusal copy: the add-on admits or denies the intent itself. +fn host_rows(store: &SingleFileMessagePackBackingStore) -> Result<(Vec, String)> { + let Some(snapshot) = snapshot(store)? else { + return Ok((Vec::new(), String::new())); + }; + let rows = snapshot["hostActions"].as_array().cloned().unwrap_or_default(); + let observed = snapshot["observedAt"].as_str().unwrap_or("").to_string(); + Ok((rows, observed)) +} + fn status(store: &SingleFileMessagePackBackingStore) -> Result { for envelope in store.pull_all()? { if envelope.key == SNAPSHOT_KEY && envelope.r#type == SNAPSHOT_SCHEMA { @@ -358,6 +381,20 @@ fn status(store: &SingleFileMessagePackBackingStore) -> Result { print_field(key, value); } } + let names: Vec<&str> = snapshot["hostActions"] + .as_array() + .into_iter() + .flatten() + .filter_map(|row| row["name"].as_str()) + .collect(); + println!("hostActions: {}", names.join(", ")); + for error in snapshot["hostActionErrors"].as_array().into_iter().flatten() { + println!( + "hostActionErrors: {}: {}", + error["host"].as_str().unwrap_or(""), + error["error"].as_str().unwrap_or("") + ); + } return Ok(0); } } @@ -378,6 +415,10 @@ fn print_fields(value: &Value) { fn print_field(key: &str, value: &Value) { match value { + Value::String(text) if text.contains('\n') => { + println!("{key}:"); + text.lines().for_each(|line| println!(" {line}")); + } Value::String(text) => println!("{key}: {text}"), other => println!("{key}: {other}"), } @@ -433,7 +474,9 @@ the add-on decides the rest and its refusal comes back in the receipt. .to_string() } -pub fn send_help() -> String { +/// `send --help`: the built-ins, then, when a store is named (--store or $BROKKR_BLENDER_STORE), the host +/// rows its snapshot carries. It never fails for lack of a store. +fn send_help(options: &Options) -> String { let mut text = String::from( "\ brokkr-ctl blender send [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs] @@ -446,9 +489,31 @@ actions: ", ); text.push_str(&actions::help()); + text.push_str(&host_help(options)); text } +fn host_help(options: &Options) -> String { + let named = options.store.is_some() || std::env::var_os("BROKKR_BLENDER_STORE").is_some(); + if !named { + return "\nhost actions: add --store (or set BROKKR_BLENDER_STORE) to list the actions host add-ons publish.\n" + .to_string(); + } + match open_store(options).and_then(|store| host_rows(&store)) { + Err(error) => format!("\nhost actions: unavailable ({error}).\n"), + Ok((_, observed)) if observed.is_empty() => { + "\nhost actions: the store holds no host snapshot yet.\n".to_string() + } + Ok((rows, observed)) if rows.is_empty() => { + format!("\nhost actions (published by the add-on at {observed}): none.\n") + } + Ok((rows, observed)) => format!( + "\nhost actions (published by the add-on at {observed}):\n{}", + actions::help_rows(&rows) + ), + } +} + #[cfg(test)] mod tests { use super::*; @@ -462,17 +527,17 @@ mod tests { #[test] fn intent_carries_reserved_fields_and_refuses_overrides() { let sets = vec!["objectType=\"MESH\"".to_string(), "location=[0,0,1]".to_string()]; - let intent = build_intent("createObject", "abc", "nibu/hands", "n", &sets).unwrap(); + let intent = build_intent("createObject", "abc", "nibu/hands", "n", &sets, &[]).unwrap(); assert_eq!(intent["requestedBy"], "nibu/hands"); assert_eq!(intent["objectType"], "MESH"); assert_eq!(intent["location"][2], 1); for bad in ["requestedBy=\"x\"", "commandId=\"x\"", "action=\"x\"", "novalue", "k=notjson"] { assert!( - build_intent("createObject", "abc", "a/b", "", &[bad.to_string()]).is_err(), + build_intent("createObject", "abc", "a/b", "", &[bad.to_string()], &[]).is_err(), "{bad}" ); } - assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err()); + assert!(build_intent("../x", "abc", "a/b", "", &[], &[]).is_err()); } #[test] diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 9936d7f..1cd8847 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -502,3 +502,114 @@ fn a_json_payload_is_refused_not_guessed() { let output = ctl(&path, &["wait", "j", "--timeout", "1"], None); assert_eq!(output.status.code(), Some(1)); } + +/// A store whose snapshot carries the fixture add-on's rows the way the add-on publishes them, plus one refused file. +fn host_store(dir: &Path) -> PathBuf { + let path = store_with_receipts(dir, &[("seed", "accepted")]); + let file: Value = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json" + )) + .unwrap(); + let rows: Vec = file["actions"] + .as_array() + .unwrap() + .iter() + .map(|row| { + let mut row = row.clone(); + row["host"] = json!("brokkr_host_fixture"); + row + }) + .collect(); + let snapshot = json!({ + "observedAt": "2026-11-28T10:00:00.000000+00:00", "mode": "OBJECT", + "hostActions": rows, + "hostActionErrors": [{"host": "broken_addon", "error": "brokkr_actions.json: host schema must be brokkr.blender.host_actions.v0"}], + }); + push(&path, &[envelope_at("brokkr.blender.host_snapshot.v0", "blender/host/current", &snapshot)]); + path +} + +fn help_text(args: &[&str], store: Option<&Path>) -> String { + let mut command = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")); + command.arg("blender").args(args).env_remove("BROKKR_BLENDER_STORE"); + if let Some(store) = store { + command.arg("--store").arg(store); + } + stdout(&command.output().unwrap()) +} + +#[test] +fn send_help_with_a_store_lists_the_host_rows_with_their_bounds() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let text = help_text(&["send", "--help"], Some(&path)); + assert!(text.contains("host actions (published by the add-on at 2026-11-28T10:00:00.000000+00:00):"), "{text}"); + for needle in ["brokkr_host_fixture.add_empty", "size: number 0.1..10", "name: string", "brokkr_host_fixture.report"] { + assert!(text.contains(needle), "{needle} in {text}"); + } + assert!(!text.contains("brokkr_host_fixture.apply"), "human-only is absence"); + assert!(text.contains("createObject"), "the built-ins are still listed"); +} + +#[test] +fn send_help_without_a_store_says_host_actions_need_one_and_with_no_snapshot_says_so() { + let text = help_text(&["send", "--help"], None); + assert!(text.contains("host actions: add --store"), "{text}"); + assert!(text.contains("createObject")); + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + assert!(help_text(&["send", "--help"], Some(&path)).contains("the store holds no host snapshot yet")); +} + +#[test] +fn a_host_intent_out_of_bounds_exits_1_and_leaves_the_store_byte_identical() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let before = std::fs::read(&path).unwrap(); + let cases: [(&[&str], &str); 3] = [ + (&["send", "brokkr_host_fixture.add_empty", "--set", "name=\"E\"", "--set", "size=99"], "size must be between 0.1 and 10."), + (&["send", "brokkr_host_fixture.add_empty"], "name is required."), + (&["send", "brokkr_host_fixture.report", "--set", "x=1"], "has no field 'x'"), + ]; + for (args, message) in cases { + let mut args = args.to_vec(); + args.extend(["--agent", "hands", "--no-wait"]); + let output = ctl(&path, &args, Some("nibu")); + assert_eq!(output.status.code(), Some(1), "{args:?}"); + assert!(String::from_utf8_lossy(&output.stderr).contains(message), "{args:?}"); + assert_eq!(std::fs::read(&path).unwrap(), before, "{args:?} wrote to the store"); + } +} + +#[test] +fn a_human_only_operator_is_unsupported_and_a_published_host_action_is_written() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let before = std::fs::read(&path).unwrap(); + let output = ctl(&path, &["send", "brokkr_host_fixture.apply", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("Unsupported Blender command action: brokkr_host_fixture.apply")); + assert_eq!(std::fs::read(&path).unwrap(), before); + let sent = ctl(&path, &["send", "brokkr_host_fixture.add_empty", "--set", "name=\"E\"", "--set", "size=2", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(sent.status.code(), Some(0), "{}", String::from_utf8_lossy(&sent.stderr)); + let id = stdout(&sent).trim().strip_prefix("commandId: ").unwrap().to_string(); + let store = SingleFileMessagePackBackingStore::new(&path); + let intent = store.pull_all().unwrap().into_iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap(); + let value: Value = rmp_serde::from_slice(&intent.payload).unwrap(); + assert_eq!((value["action"].as_str(), value["size"].as_i64()), (Some("brokkr_host_fixture.add_empty"), Some(2))); +} + +#[test] +fn status_names_the_host_actions_and_each_refused_file_and_a_multiline_result_prints_indented() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let text = stdout(&ctl(&path, &["status"], None)); + assert!(text.contains("hostActions: brokkr_host_fixture.add_empty, brokkr_host_fixture.report"), "{text}"); + assert!(text.contains("hostActionErrors: broken_addon: brokkr_actions.json: host schema must be"), "{text}"); + push( + &path, + &[envelope_at(RECEIPT, "blender/receipts/h", &json!({"commandId": "h", "status": "accepted", "hostResult": "objects: 3\nscenes: 1", "observedAt": "2026-11-28T10:00:01+00:00"}))], + ); + let receipt = stdout(&ctl(&path, &["wait", "h"], None)); + assert!(receipt.contains("hostResult:\n objects: 3\n scenes: 1\n"), "{receipt}"); +} From 740a2c84c31b701cd693b13e9d0ecdd370b746d6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:12:09 +0100 Subject: [PATCH 052/223] install.md: host add-on actions Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/docs/install.md | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 1bd94b9..cbb17fe 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -246,6 +246,43 @@ Behaviour the table does not say, per action: object, or an undo or redo). Selection totals are the mesh's own counts and the index scan stops at the cap. They are observations: no intent is refused because of them. +### Host add-on actions + +A host add-on (Aetheria's `aetheria_ships`, say) lets agents run some of its own operators by putting a file +`brokkr_actions.json` beside its `__init__.py`: `{"schema": "brokkr.blender.host_actions.v0", "actions": [row]}`. +The add-on imports nothing from Brokkr and registers nothing; the file is the whole contract. +`surfaces/blender/tests/fixtures/brokkr_host_fixture/` is a worked example. + +A row is a built-in row (`name`, `doc`, `changesScene`, `editModeSafe`, `fields`) plus an optional `result`. +`name` is the `bl_idname` of an operator the same add-on registers (`addon.operator`, lower case, one dot, so +it never equals a built-in name). Fields are scalar only: `string` (with `enum`, `minLength`, `maxLength`, +`chars`, `prefixes`, `forbid`), `number` or `integer` (both with `minimum` and `maximum`) and `boolean`, +with `required` and `default` as for built-ins; no arrays, objects or free JSON, and no `envelope` or +`charsets` keys. The messages are the built-in ones. + +Brokkr admits a file whole or not at all, at every intent and snapshot (a changed file is re-read; a +disabled add-on's actions are unknown at its next intent). Beyond the file's own shape it checks that each +named operator exists and is a Python class defined by that add-on's module, that every field is a property +of the operator of the matching type (a string with an `enum` is an enum property with the same +identifiers), that the operator's RNA hard limits contain the row's bounds, and that `result` names a +`StringProperty` on `bpy.types.WindowManager`. A refused file is reported in the host snapshot as +`hostActionErrors` (`brokkr-ctl blender status` prints each) and none of its rows runs. + +An admitted action goes through the same agent turn as a built-in: Edit Mode refusal for rows that are not +`editModeSafe`, one labelled undo step when `changesScene`, a receipt. The operator is called with +`'EXEC_DEFAULT'` and exactly the declared fields. It runs on Blender's main thread, so a long operator +blocks the interface for as long as her own button would. `FINISHED` is `accepted`; `CANCELLED` is `failed` +with nothing pushed; an argument Blender will not convert, or an `ERROR` report or exception, is `failed` +(with the first line of the error). `result` is how an operator returns text (a dry-run's change lines): the +agent turn clears that WindowManager property before the call and copies it, up to 16000 characters and then +`[truncated]`, into the receipt's `hostResult` (empty for every other action). + +The admitted rows are published in the host snapshot as `hostActions` (each with its `host` module). +`brokkr-ctl blender send --help --store ` lists them after the built-ins, `send` refuses an intent +they refuse before writing anything, and the add-on still decides. Human-only is absence: an operator only a +person may run (one that applies a change to a game's data) is left out of the file, so an intent naming it +is `Unsupported Blender command action`, as `runPython` is; the person still presses her own button. + The scene actions were run against Blender 5.2.3 LTS headless with `surfaces/blender/tests/live/headless_smoke.py` (usage in its docstring). One real failure it found: Blender's `engine` enum is dynamic, so `bl_rna` lists only From c1aacd9f7b2066c8ac7595ff2b7ec1659722b70b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:16:29 +0100 Subject: [PATCH 053/223] live/host_action.py: GUI Blender 5.3 proof of host rows, undo steps, results and human-only absence Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/tests/cli.rs | 2 +- surfaces/blender/tests/live/host_action.py | 241 ++++++++++++++++++ .../tests/live/host_action.result.json | 218 ++++++++++++++++ surfaces/blender/tests/test_agent_turn.py | 4 +- 4 files changed, 462 insertions(+), 3 deletions(-) create mode 100644 surfaces/blender/tests/live/host_action.py create mode 100644 surfaces/blender/tests/live/host_action.result.json diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 1cd8847..6e3d124 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -582,7 +582,7 @@ fn a_host_intent_out_of_bounds_exits_1_and_leaves_the_store_byte_identical() { } #[test] -fn a_human_only_operator_is_unsupported_and_a_published_host_action_is_written() { +fn an_operator_left_out_of_the_file_is_unsupported_and_a_published_host_action_is_written() { let dir = tempfile::tempdir().unwrap(); let path = host_store(dir.path()); let before = std::fs::read(&path).unwrap(); diff --git a/surfaces/blender/tests/live/host_action.py b/surfaces/blender/tests/live/host_action.py new file mode 100644 index 0000000..898137a --- /dev/null +++ b/surfaces/blender/tests/live/host_action.py @@ -0,0 +1,241 @@ +"""Live proof, in GUI Blender with the add-on installed as an extension, that a host add-on's brokkr_actions.json adds +rows the agent turn admits, runs and undoes like a built-in, and that an operator left out of the file stays human-only. + + BROKKR_SCRATCH= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + blender --python host_action.py -- + +Run it in Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH; without them the operator's own extensions folder is used). The script +refuses to run when they are unset. It copies tests/fixtures/brokkr_host_fixture into BLENDER_USER_SCRIPTS/addons and +enables it there; it writes nothing else outside BROKKR_SCRATCH. Every intent is put into the node database as +brokkr-ctl does and answered by the add-on's own 1 s drain (the sink is on). Proves, with wm.undo_stack as the counter: + + * the snapshot lists the fixture's four rows (host, no apply) and no hostActionErrors; + * add_empty is accepted as exactly one new undo step, undo removes the empty, redo brings it back; + * report is accepted with hostResult equal to what the operator wrote, no new step, humanEditSeq unchanged; + * refuse is failed with the operator's text and cancel is failed, each with no new step; + * apply (registered, left out of the file) and wm.save_mainfile are denied Unsupported with no step, the scene + unchanged and no 'Applied' object. + +Writes .result.json, then quits Blender. +""" +import importlib +import json +import os +import shutil +import sys +import traceback +from pathlib import Path + +import bpy + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own folders are used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if os.path.normcase(os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != os.path.normcase(os.path.abspath(os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") +if os.path.normcase(os.path.abspath(bpy.utils.user_resource("SCRIPTS"))) != os.path.normcase(os.path.abspath(os.environ["BLENDER_USER_SCRIPTS"])): + raise SystemExit("Blender's scripts folder is not BLENDER_USER_SCRIPTS; refusing to touch it") + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +HOST = "brokkr_host_fixture" +FIXTURE = Path(__file__).resolve().parents[1] / "fixtures" / HOST +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": []} + +addons_dir = Path(os.environ["BLENDER_USER_SCRIPTS"]) / "addons" +addons_dir.mkdir(parents=True, exist_ok=True) +if (addons_dir / HOST).exists(): + shutil.rmtree(addons_dir / HOST) +shutil.copytree(FIXTURE, addons_dir / HOST, ignore=shutil.ignore_patterns("__pycache__")) +bpy.utils.refresh_script_paths() + +bpy.ops.preferences.addon_enable(module=MODULE) +bpy.ops.preferences.addon_enable(module=HOST) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") +prefs = bpy.context.preferences.addons[MODULE].preferences +bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "live.blend")) +CACHE = str(SCRATCH / "queue.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.debug_mirror_root = "" +prefs.auto_drain_commands = True # the sink +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +adapter = addon.target() + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + return bpy.context.temp_override(window=bpy.context.window_manager.windows[0]) + + +def steps_now(): + return [s.name for s in bpy.context.window_manager.undo_stack.steps] + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def redo(): + with win(): + bpy.ops.ed.redo() + + +def node(): + return adapter._open_node(CACHE, prefs.cultlib_py_src) + + +N = [0] + + +def queue(**cmd): + N[0] += 1 + cid = "host-%04d" % N[0] + n, docs = node() + cmd.update(commandId=cid, schema=bt.COMMAND_INTENT_SCHEMA, requestedBy="nibu/hands") + n.database.put(docs["command_intent"], f"blender/commands/{cid}", cmd) + return cid + + +def receipt(cid): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{cid}") + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +S = {} +WAIT = {"ticks": 0} + + +def until(pred, limit=40): + def step(): + WAIT["ticks"] += 1 + if pred(): + WAIT["ticks"] = 0 + return True + if WAIT["ticks"] > limit: + raise TimeoutError("the drain did not receipt in time") + return False + return step + + +def once(fn): + def step(): + fn() + return True + return step + + +def send(key, **fields): + S[key + ":before"] = {"steps": steps_now(), "names": names(), "seq": adapter.human_edit_seq} + S[key] = queue(**fields) + + +def done(key): + return lambda: receipt(S[key]) is not None + + +def same_world(key): + before = S[key + ":before"] + return (steps_now() == before["steps"] and names() == before["names"] and adapter.human_edit_seq == before["seq"]) + + +def snapshot_check(): + snapshot = adapter.capture_snapshot(bpy.context, True) + rows = snapshot["hostActions"] + expect = [f"{HOST}.{n}" for n in ("add_empty", "report", "refuse", "cancel")] + check("the snapshot lists the fixture's four rows with their host and none other (apply is left out)", + sorted(r["name"] for r in rows) == sorted(expect) and {r["host"] for r in rows} == {HOST}, [r["name"] for r in rows]) + check("the snapshot carries no hostActionErrors", snapshot["hostActionErrors"] == [], snapshot["hostActionErrors"]) + check("the operators are registered by the legacy add-on, apply included", + all(hasattr(getattr(bpy.ops, HOST), n) for n in ("add_empty", "report", "refuse", "cancel", "apply"))) + + +def add_check(): + r = receipt(S["add"]) + before = S["add:before"] + after = steps_now() + check("add_empty is accepted", r["status"] == "accepted", r) + check("add_empty is exactly one new undo step carrying the receipt's label", + len(after) == len(before["steps"]) + 1 and after[-1] == r["undoLabel"] and r["undoLabel"].startswith(f"Brokkr nibu/hands: {HOST}.add_empty "), + {"before": before["steps"][-2:], "after": after[-2:], "label": r["undoLabel"]}) + check("add_empty made the empty with the declared name and size", + "LiveEmpty" in bpy.data.objects and abs(bpy.data.objects["LiveEmpty"].empty_display_size - 2.0) < 1e-6, names()) + check("add_empty is the agent's write: humanEditSeq did not move", adapter.human_edit_seq == before["seq"]) + S["add:names"] = names() + undo() + check("one undo removes the empty", "LiveEmpty" not in bpy.data.objects, names()) + redo() + check("redo brings it back", names() == S["add:names"], names()) + + +def report_check(): + r = receipt(S["report"]) + expect = f"objects: {len(bpy.data.objects)}\nscenes: {len(bpy.data.scenes)}" + check("report is accepted with hostResult equal to what the operator wrote", r["status"] == "accepted" and r["hostResult"] == expect, [r["status"], r["hostResult"], expect]) + check("report pushed no undo step, added no object and left humanEditSeq alone", same_world("report"), [steps_now()[-2:], S["report:before"]["steps"][-2:]]) + + +def failure_check(key, text): + def run(): + r = receipt(S[key]) + check(f"{key} is failed{' with ' + repr(text) if text else ''}", r["status"] == "failed" and text in r["message"], r) + check(f"{key} pushed no undo step and changed nothing", same_world(key) and r["undoLabel"] == "", r["undoLabel"]) + return run + + +def denied_check(key, action): + def run(): + r = receipt(S[key]) + check(f"{action} is denied Unsupported", r["status"] == "denied" and "Unsupported Blender command action" in r["message"], r) + check(f"{action} ran nothing: no step, no new object, no 'Applied'", same_world(key) and "Applied" not in bpy.data.objects, names()) + return run + + +steps = [ + once(snapshot_check), + once(lambda: send("add", action=f"{HOST}.add_empty", name="LiveEmpty", size=2)), until(done("add")), once(add_check), + once(lambda: send("report", action=f"{HOST}.report")), until(done("report")), once(report_check), + once(lambda: send("refuse", action=f"{HOST}.refuse")), until(done("refuse")), once(failure_check("refuse", "the fixture refuses")), + once(lambda: send("cancel", action=f"{HOST}.cancel")), until(done("cancel")), once(failure_check("cancel", "cancelled; nothing changed")), + once(lambda: send("apply", action=f"{HOST}.apply")), until(done("apply")), once(denied_check("apply", f"{HOST}.apply")), + once(lambda: send("save", action="wm.save_mainfile")), until(done("save")), once(denied_check("save", "wm.save_mainfile")), +] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def tick(): + global i + if i < len(steps): + try: + if steps[i](): + i += 1 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + i = len(steps) + write() + return 0.5 + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/surfaces/blender/tests/live/host_action.result.json b/surfaces/blender/tests/live/host_action.result.json new file mode 100644 index 0000000..a493c29 --- /dev/null +++ b/surfaces/blender/tests/live/host_action.result.json @@ -0,0 +1,218 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "the snapshot lists the fixture's four rows with their host and none other (apply is left out)", + "ok": true, + "detail": [ + "brokkr_host_fixture.add_empty", + "brokkr_host_fixture.report", + "brokkr_host_fixture.refuse", + "brokkr_host_fixture.cancel" + ] + }, + { + "name": "the snapshot carries no hostActionErrors", + "ok": true, + "detail": [] + }, + { + "name": "the operators are registered by the legacy add-on, apply included", + "ok": true, + "detail": null + }, + { + "name": "add_empty is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0001", + "action": "brokkr_host_fixture.add_empty", + "status": "accepted", + "message": "Operator brokkr_host_fixture.add_empty finished.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:08.910684+00:00" + } + }, + { + "name": "add_empty is exactly one new undo step carrying the receipt's label", + "ok": true, + "detail": { + "before": [ + "Original" + ], + "after": [ + "Original", + "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + ], + "label": "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + } + }, + { + "name": "add_empty made the empty with the declared name and size", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "add_empty is the agent's write: humanEditSeq did not move", + "ok": true, + "detail": null + }, + { + "name": "one undo removes the empty", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] + }, + { + "name": "redo brings it back", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "report is accepted with hostResult equal to what the operator wrote", + "ok": true, + "detail": [ + "accepted", + "objects: 4\nscenes: 1", + "objects: 4\nscenes: 1" + ] + }, + { + "name": "report pushed no undo step, added no object and left humanEditSeq alone", + "ok": true, + "detail": [ + [ + "Original", + "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + ], + [ + "Original", + "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + ] + ] + }, + { + "name": "refuse is failed with 'the fixture refuses'", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0003", + "action": "brokkr_host_fixture.refuse", + "status": "failed", + "message": "Error: the fixture refuses", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:13.022948+00:00" + } + }, + { + "name": "refuse pushed no undo step and changed nothing", + "ok": true, + "detail": "" + }, + { + "name": "cancel is failed with 'cancelled; nothing changed'", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0004", + "action": "brokkr_host_fixture.cancel", + "status": "failed", + "message": "Operator brokkr_host_fixture.cancel cancelled; nothing changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:14.080400+00:00" + } + }, + { + "name": "cancel pushed no undo step and changed nothing", + "ok": true, + "detail": "" + }, + { + "name": "brokkr_host_fixture.apply is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0005", + "action": "brokkr_host_fixture.apply", + "status": "denied", + "message": "Unsupported Blender command action: brokkr_host_fixture.apply", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:16.137129+00:00" + } + }, + { + "name": "brokkr_host_fixture.apply ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "wm.save_mainfile is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0006", + "action": "wm.save_mainfile", + "status": "denied", + "message": "Unsupported Blender command action: wm.save_mainfile", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:18.194603+00:00" + } + }, + { + "name": "wm.save_mainfile ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + } + ], + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 6578b4b..60afb83 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -372,7 +372,7 @@ class HostActionTests(unittest.TestCase): self.assertEqual(len(self.bpy.undo.pushes), 1) self.assertTrue(self.bpy.undo.pushes[0].endswith("(failed)")) - def test_a_human_only_operator_and_a_c_operator_are_unsupported_and_leave_no_trace(self): + def test_an_operator_left_out_of_the_file_and_a_c_operator_are_unsupported_and_leave_no_trace(self): for action in (f"{HOST}.apply", "wm.save_mainfile", "brokkr.stop_agents"): receipt = self.run_action(action=action) self.assertEqual(receipt["status"], "denied", action) @@ -385,7 +385,7 @@ class HostActionTests(unittest.TestCase): self.assertEqual(self.send("add_empty", name="E")["status"], "denied") self.assertEqual(self.send("report")["status"], "accepted") - def test_the_snapshot_lists_the_admitted_rows_with_their_host_and_no_human_only_row(self): + def test_the_snapshot_lists_the_admitted_rows_with_their_host_and_no_left_out_row(self): self.bpy.data = NS(objects=[], scenes=[], collections=[], materials=[], images=[], filepath="") self.bpy.app = NS(version=(5, 3, 0), background=False) context = NS(selected_objects=[], active_object=None, scene=None, mode="OBJECT") From 26efb1b31a9814e5697ea7104785db8d3e64ee89 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:19:04 +0100 Subject: [PATCH 054/223] Host operator: drop the redundant _wrote writes; tests pin the envelope and the own add-on never read as a host Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_bridge/blender_target.py | 4 +--- surfaces/blender/tests/test_agent_turn.py | 11 ++++++++++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 8bde4b0..1c78e9b 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -847,11 +847,9 @@ class BrokkrBlenderTarget: text = getattr(manager, result, "") or "" if len(text) > HOST_RESULT_LIMIT: text = text[:HOST_RESULT_LIMIT] + " [truncated]" - if "FINISHED" in outcome: - self._wrote = bool(row["changesScene"]) + if "FINISHED" in outcome: # run_intent pushes an undo step for an accepted changesScene row only receipt = self._receipt(command, "accepted", f"Operator {name} finished.", "") else: - self._wrote = False receipt = self._receipt(command, "failed", f"Operator {name} cancelled; nothing changed.", "") receipt["hostResult"] = text return receipt diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 60afb83..8b8174b 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -326,9 +326,14 @@ class HostActionTests(unittest.TestCase): def test_the_default_is_filled_and_an_undeclared_field_never_reaches_the_operator(self): self.assertEqual(self.send("add_empty", name="E")["status"], "accepted") self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 1}]) + self.ops["add_empty"].calls.clear() + self.assertEqual(self.send("add_empty", name="E", note="why")["status"], "accepted") + self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 1}]) # the envelope never reaches the operator + self.ops["add_empty"].calls.clear() + self.ops["add_empty"].calls.append({}) denied = self.send("add_empty", name="E", location=[1, 2, 3]) self.assertEqual(denied["status"], "denied") - self.assertEqual(len(self.ops["add_empty"].calls), 1) + self.assertEqual(len(self.ops["add_empty"].calls), 1) # only the seeded marker: the denied intent ran nothing def test_a_non_changing_operator_pushes_no_undo_step_and_returns_its_result(self): receipt = self.send("report") @@ -452,6 +457,10 @@ class HostActionTests(unittest.TestCase): self.assertEqual(self.target.host_actions(), ([], [])) self.bpy.context.preferences.addons["brokkr_bridge"] = object() self.assertEqual(self.target.host_actions(), ([], [])) + (self.dir / "brokkr_actions.json").write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) + with unittest.mock.patch.object(sys.modules["brokkr_bridge"], "__file__", str(self.dir / "__init__.py"), create=True): + self.bpy.context.preferences.addons.pop(HOST) # a file sits beside this add-on itself: still not read as a host's + self.assertEqual(self.target.host_actions(), ([], [])) class FakeNode: From fb9696b6394b794100ceb752fb787936cff62813 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 07:07:18 +0100 Subject: [PATCH 055/223] Host actions: files are read only by the human's reload, never on an intent Reload Host Actions operator (refuses inside an agent turn) and one startup read; envelope-named fields, unknown row keys, read-only results and UNDO operators on non-changing rows refuse the file; a failed poll or unclearable result refuses before any undo step; tests pin the ownership prefix, enum, snapshot errors and the guards; live proof extended; docs say the flags are the host's word. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_bridge/__init__.py | 29 ++++ .../blender/brokkr_bridge/action_table.py | 3 + .../blender/brokkr_bridge/blender_target.py | 115 ++++++++------- surfaces/blender/docs/install.md | 27 +++- surfaces/blender/tests/live/host_action.py | 47 +++++- .../tests/live/host_action.result.json | 110 +++++++++++++- surfaces/blender/tests/test_action_table.py | 7 + surfaces/blender/tests/test_addon_ui.py | 31 ++++ surfaces/blender/tests/test_agent_turn.py | 134 +++++++++++++++++- 9 files changed, 434 insertions(+), 69 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index c9db1ec..0801c16 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -389,6 +389,7 @@ class BROKKR_PT_status(bpy.types.Panel): row = layout.row(align=True) row.operator("brokkr.capture_snapshot", icon="FILE_REFRESH") + layout.operator("brokkr.reload_host_actions", icon="FILE_REFRESH") row.operator("brokkr.drain_commands", icon="PLAY") layout.prop(prefs, "auto_drain_commands") @@ -495,6 +496,23 @@ class BROKKR_OT_stop_agents(bpy.types.Operator): return {"FINISHED"} +class BROKKR_OT_reload_host_actions(bpy.types.Operator): + bl_idname = "brokkr.reload_host_actions" + bl_label = "Reload Host Actions" + bl_description = ("Read each enabled add-on's brokkr_actions.json again. Only this button does: an agent cannot cause " + "a re-read, so an edited file admits nothing until you press it") + + def execute(self, context): + try: + found = target().reload_host_actions() + except PermissionError as exc: # inside an agent turn: a human acts here, never an agent + self.report({"ERROR"}, str(exc)) + return {"CANCELLED"} + rows, errors = target().host_actions() + self.report({"INFO"}, f"{found} host file(s) read; {len(rows)} host action(s) admitted, {len(errors)} file(s) refused.") + return {"FINISHED"} + + class BROKKR_OT_drain_commands(bpy.types.Operator): bl_idname = "brokkr.drain_commands" bl_label = "Drain Commands" @@ -741,6 +759,7 @@ classes = ( BROKKR_PT_status, BROKKR_OT_stop_agents, BROKKR_OT_capture_snapshot, + BROKKR_OT_reload_host_actions, BROKKR_OT_drain_commands, BROKKR_OT_start_server, BROKKR_OT_stop_server, @@ -752,6 +771,15 @@ classes = ( ) +def _load_host_actions_once(): + """One read of the host files shortly after startup, when the other add-ons are enabled (not an intent's doing).""" + try: + target().reload_host_actions() + except Exception: + pass + return None + + def register(): for cls in classes: bpy.utils.register_class(cls) @@ -762,6 +790,7 @@ def register(): getattr(bpy.app.handlers, name).append(handler) if not bpy.app.timers.is_registered(_auto_drain_commands): bpy.app.timers.register(_auto_drain_commands, first_interval=1.0, persistent=True) + bpy.app.timers.register(_load_host_actions_once, first_interval=3.0) def unregister(): diff --git a/surfaces/blender/brokkr_bridge/action_table.py b/surfaces/blender/brokkr_bridge/action_table.py index 48a888f..eba7e82 100644 --- a/surfaces/blender/brokkr_bridge/action_table.py +++ b/surfaces/blender/brokkr_bridge/action_table.py @@ -132,9 +132,12 @@ def check_host(document: Any, charsets: dict[str, Any]) -> None: if "result" in row and not (isinstance(row["result"], str) and row["result"].isidentifier()): raise TableInvalid(f"{name}.result must be an identifier") fields = {} + envelope = table()["envelope"] for field in row["fields"]: if not isinstance(field, dict) or not isinstance(field.get("name"), str) or field["name"] in fields: raise TableInvalid(f"{name} has a missing or repeated field name") + if field["name"] in envelope: + raise TableInvalid(f"{name}.{field['name']} is an envelope key; Brokkr writes it, so the operator would never receive the agent's value") fields[field["name"]] = field for field in fields.values(): where = f"{name}.{field['name']}" diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 1c78e9b..e030c89 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -1,5 +1,6 @@ from __future__ import annotations +import contextlib import ctypes import functools import json @@ -102,10 +103,6 @@ CAPABILITIES = ( ) -class _NoHostFile(Exception): - """The add-on has no brokkr_actions.json: it is not a host.""" - - def _first_line(text: str) -> str: return text.strip().splitlines()[0] if text.strip() else "failed" @@ -131,7 +128,7 @@ class BrokkrBlenderTarget: self.agent_turn = False # true only inside run_intent self._wrote = True # run_intent: false when an accepted action changed nothing self._receipted: set[str] = set() - self._host_files: dict[str, tuple[tuple, Any]] = {} # module -> (file stamp, parsed document or error text): a cache of reads, never truth + self._host_docs: dict[str, Any] = {} # module -> parsed host document or the error that refused it; written only by reload_host_actions self._unsent: list[tuple[dict[str, Any], str]] = [] # receipts whose write failed: written first on the next drain, never read as truth self._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts self._receipts_loaded = False @@ -646,25 +643,50 @@ class BrokkrBlenderTarget: "hostActionErrors": host_errors, } + def reload_host_actions(self) -> int: + """Read every enabled add-on's brokkr_actions.json (this add-on excepted) into the stored host documents, + replacing what was stored: the one place a host file is read. A human act: the panel's Reload Host Actions + button, and once shortly after this add-on registers. An intent never reaches it (an agent turn cannot + cause a re-read: this refuses inside one), so a file rewritten to list another operator admits nothing + until she reloads. A file is stored parsed and checked, or as the error that refused it; the live checks in + host_actions still run at every intent. Returns the number of host files found.""" + if self.agent_turn: + raise PermissionError("Host actions are reloaded by the human only, never inside an agent turn.") + own = __package__ or "" + docs: dict[str, Any] = {} + for module in self.bpy.context.preferences.addons.keys(): + if module == own: + continue + source = getattr(sys.modules.get(module), "__file__", None) + path = Path(source).with_name(HOST_ACTIONS_FILE) if source else None + if path is None or not path.is_file(): + continue + try: + document = json.loads(path.read_text(encoding="utf-8")) + at.check_host(document, at.table()["charsets"]) + docs[module] = document + except Exception as error: + docs[module] = str(error) + self._host_docs = docs + return len(docs) + def host_actions(self) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: - """The one discovery of host rows: ([row + 'host' module], [{host, error}]). Each enabled add-on but this - one may carry brokkr_actions.json beside its __init__.py; the file is admitted whole or not at all. The - file is the add-on's word; what is checked here is what Brokkr can see: the operator exists and is a - Python class defined by that add-on, every field is a property of it of the matching type whose RNA hard - limits contain the row's bounds, and result is a WindowManager string property. Only the parse is cached - (on path, mtime and size); the live checks run each time, so a disabled add-on or an unregistered operator - is gone at the next intent. A name two files claim fails ownership in all but its owner.""" + """The host rows admitted now: ([row + 'host' module], [{host, error}]), from the documents the last + reload stored (no file is read here). A document is admitted whole or not at all. The file is the add-on's + word; what is checked here, at every call, is what Brokkr can see: the add-on is still enabled, the operator + exists and is a Python class defined by that add-on (module equal to it or under it: 'aeth_ships' is not + under 'aeth'), every field is a property of it of the matching type whose RNA hard limits contain the row's + bounds, a row that changes nothing names no operator that pushes undo itself (bl_options UNDO), and result + is a writable WindowManager string property. A disabled add-on or an unregistered operator is gone at the + next intent. A name two files claim fails ownership in all but its owner.""" rows: list[dict[str, Any]] = [] errors: list[dict[str, Any]] = [] - own = __package__ or "" - modules = [m for m in self.bpy.context.preferences.addons.keys() if m != own] - for module in modules: - try: - document = self._host_document(module) - except _NoHostFile: + enabled = set(self.bpy.context.preferences.addons.keys()) + for module, document in self._host_docs.items(): + if module not in enabled: continue - except Exception as error: - errors.append({"host": module, "error": _first_line(f"{HOST_ACTIONS_FILE}: {error}")}) + if isinstance(document, str): + errors.append({"host": module, "error": _first_line(f"{HOST_ACTIONS_FILE}: {document}")}) continue try: for row in document["actions"]: @@ -675,28 +697,6 @@ class BrokkrBlenderTarget: rows.extend({**row, "host": module} for row in document["actions"]) return rows, errors - def _host_document(self, module: str) -> dict[str, Any]: - loaded = sys.modules.get(module) - source = getattr(loaded, "__file__", None) - path = Path(source).with_name(HOST_ACTIONS_FILE) if source else None - if path is None or not path.is_file(): - self._host_files.pop(module, None) - raise _NoHostFile() - info = path.stat() - stamp = (str(path), info.st_mtime_ns, info.st_size) - cached = self._host_files.get(module) - if cached is None or cached[0] != stamp: - try: - document = json.loads(path.read_text(encoding="utf-8")) - at.check_host(document, at.table()["charsets"]) - cached = (stamp, document) - except Exception as error: - cached = (stamp, str(error)) - self._host_files[module] = cached - if isinstance(cached[1], str): - raise ValueError(cached[1]) - return cached[1] - def _check_host_row(self, module: str, row: dict[str, Any]) -> None: bpy = self.bpy name = row["name"] @@ -706,6 +706,8 @@ class BrokkrBlenderTarget: owned = getattr(owner, "__module__", None) if not isinstance(owner, type) or not isinstance(owned, str) or not (owned == module or owned.startswith(module + ".")): raise ValueError(f"{name} is not an operator defined by {module}") + if "UNDO" in getattr(owner, "bl_options", ()) and not row["changesScene"]: + raise ValueError(f"{name} pushes undo itself (bl_options UNDO) but the row says changesScene is false") properties = {p.identifier: p for p in operator.get_rna_type().properties} kinds = {"string": "STRING", "number": "FLOAT", "integer": "INT", "boolean": "BOOLEAN"} for field in row["fields"]: @@ -723,8 +725,8 @@ class BrokkrBlenderTarget: result = row.get("result") if result is not None: prop = bpy.types.WindowManager.bl_rna.properties.get(result) - if prop is None or prop.type != "STRING": - raise ValueError(f"{name} result {result} is not a string property of WindowManager") + if prop is None or prop.type != "STRING" or prop.is_readonly: + raise ValueError(f"{name} result {result} is not a writable string property of WindowManager") def run_intent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: """The one agent turn: admit, run with operator undo off, push one labelled undo step, receipt. @@ -827,21 +829,32 @@ class BrokkrBlenderTarget: kwargs = {k: v for k, v in command.items() if k not in skip} result = row.get("result") manager = bpy.context.window_manager - if result: - setattr(manager, result, "") first, second = name.split(".") operator = getattr(getattr(bpy.ops, first), second) windows = manager.windows + override = bpy.context.temp_override(window=windows[0]) if windows else contextlib.nullcontext() + # Everything that can refuse before the operator runs does so here, as ActionRefused: no undo step is pushed. try: - if windows: - with bpy.context.temp_override(window=windows[0]): - outcome = operator("EXEC_DEFAULT", False, **kwargs) - else: + with override: + runnable = operator.poll() + except Exception as error: + raise sa.ActionRefused(f"Operator {name} cannot run here: {_first_line(str(error))}") from None + if not runnable: + raise sa.ActionRefused(f"Operator {name} cannot run in this context (its poll failed); nothing changed.") + if result: + try: + setattr(manager, result, "") + except Exception as error: + raise sa.ActionRefused(f"Operator {name} result {result} cannot be cleared: {_first_line(str(error))}") from None + try: + with override: outcome = operator("EXEC_DEFAULT", False, **kwargs) except TypeError as error: raise sa.ActionRefused(f"Operator {name} refused its arguments: {_first_line(str(error))}") from None except RuntimeError as error: - raise RuntimeError(_first_line(str(error))) from None + lines = [line for line in str(error).splitlines() if line.strip()] + cause = lines[-1] if lines and "Traceback" in lines[0] else (lines[0] if lines else "failed") # a traceback's cause is its last line + raise RuntimeError(cause.strip()) from None text = "" if result: text = getattr(manager, result, "") or "" diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index cbb17fe..9ef449e 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -260,13 +260,26 @@ it never equals a built-in name). Fields are scalar only: `string` (with `enum`, with `required` and `default` as for built-ins; no arrays, objects or free JSON, and no `envelope` or `charsets` keys. The messages are the built-in ones. -Brokkr admits a file whole or not at all, at every intent and snapshot (a changed file is re-read; a -disabled add-on's actions are unknown at its next intent). Beyond the file's own shape it checks that each -named operator exists and is a Python class defined by that add-on's module, that every field is a property -of the operator of the matching type (a string with an `enum` is an enum property with the same -identifiers), that the operator's RNA hard limits contain the row's bounds, and that `result` names a -`StringProperty` on `bpy.types.WindowManager`. A refused file is reported in the host snapshot as -`hostActionErrors` (`brokkr-ctl blender status` prints each) and none of its rows runs. +Brokkr admits a file whole or not at all, and reads it only when a human asks: once shortly after Brokkr +registers, and whenever she presses `Reload Host Actions` in the Brokkr panel. No intent, snapshot or agent +turn re-reads a file (the operator refuses inside a turn), so rewriting `brokkr_actions.json` to list +another operator admits nothing until she reloads; press it after enabling a host add-on or editing its +file. A file is checked when it is read, and the live checks below run at every intent and snapshot, so a +disabled add-on's actions are unknown at its next intent. A field may not be named like an envelope key +(`schema`, `commandId`, `action`, `requestedBy`, `note`): Brokkr writes those itself, so the operator would +never receive the agent's value. The live checks: each named operator exists and is a Python class defined by +that add-on's module (the module itself or under it: `aetheria_ships` is not `aetheria`'s), every field is a +property of the operator of the matching type (a string with an `enum` is an enum property with the same +identifiers), the operator's RNA hard limits contain the row's bounds, a row with `changesScene` false names +no operator whose `bl_options` has `UNDO`, and `result` names a writable `StringProperty` on +`bpy.types.WindowManager`. A refused file is reported in the host snapshot as `hostActionErrors` +(`brokkr-ctl blender status` prints each) and none of its rows runs. + +`changesScene` and `editModeSafe` are the host's word: Brokkr cannot see what an operator writes. A row that +claims to change nothing but writes gets no undo step and no Edit Mode refusal, so keep the flags honest. An +operator that calls `bpy.ops.ed.undo_push` itself adds that step to Brokkr's own (two for one action), or +one with `changesScene` false; that is a documented limit, not checked. A `poll` that fails, or a result +property that cannot be cleared, refuses before anything runs and pushes no undo step. An admitted action goes through the same agent turn as a built-in: Edit Mode refusal for rows that are not `editModeSafe`, one labelled undo step when `changesScene`, a receipt. The operator is called with diff --git a/surfaces/blender/tests/live/host_action.py b/surfaces/blender/tests/live/host_action.py index 898137a..930a51a 100644 --- a/surfaces/blender/tests/live/host_action.py +++ b/surfaces/blender/tests/live/host_action.py @@ -17,7 +17,10 @@ brokkr-ctl does and answered by the add-on's own 1 s drain (the sink is on). Pro * report is accepted with hostResult equal to what the operator wrote, no new step, humanEditSeq unchanged; * refuse is failed with the operator's text and cancel is failed, each with no new step; * apply (registered, left out of the file) and wm.save_mainfile are denied Unsupported with no step, the scene - unchanged and no 'Applied' object. + unchanged and no 'Applied' object; + * the file is then rewritten to list apply: apply and the reload operator sent as intents are still denied (no + re-read on an intent), the operator refuses inside an agent turn, and only the human's reload (this driver + calling bpy.ops.brokkr.reload_host_actions outside a turn) admits apply, as one undo step. Writes .result.json, then quits Blender. """ @@ -66,6 +69,7 @@ prefs.debug_mirror_root = "" prefs.auto_drain_commands = True # the sink prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) adapter = addon.target() +bpy.ops.brokkr.reload_host_actions() # the human's button: the host files are read here def check(name, ok, detail=None): @@ -204,6 +208,42 @@ def denied_check(key, action): return run +def rewrite_listing_apply(): + path = addons_dir / HOST / "brokkr_actions.json" + document = json.loads(path.read_text(encoding="utf-8")) + document["actions"].append({"name": f"{HOST}.apply", "doc": "applies", "changesScene": True, "editModeSafe": False, "fields": []}) + path.write_text(json.dumps(document), encoding="utf-8") + + +def reload_refused_in_a_turn(): + adapter.agent_turn = True + try: + try: + bpy.ops.brokkr.reload_host_actions() + refused = False + except RuntimeError as error: + refused = "human only" in str(error) + finally: + adapter.agent_turn = False + check("the Reload Host Actions operator refuses inside an agent turn", refused) + names_now = [r["name"] for r in adapter.host_actions()[0]] + check("and re-read nothing: the edited file's apply row is still not admitted", f"{HOST}.apply" not in names_now, names_now) + + +def human_reload_check(): + bpy.ops.brokkr.reload_host_actions() + names_now = [r["name"] for r in adapter.host_actions()[0]] + check("the human's reload admits the edited file's apply row", f"{HOST}.apply" in names_now, names_now) + + +def applied_check(): + r = receipt(S["apply2"]) + after = steps_now() + before = S["apply2:before"] + check("apply is accepted after the human's reload as one labelled undo step", + r["status"] == "accepted" and len(after) == len(before["steps"]) + 1 and after[-1] == r["undoLabel"] and "Applied" in bpy.data.objects, r) + + steps = [ once(snapshot_check), once(lambda: send("add", action=f"{HOST}.add_empty", name="LiveEmpty", size=2)), until(done("add")), once(add_check), @@ -212,6 +252,11 @@ steps = [ once(lambda: send("cancel", action=f"{HOST}.cancel")), until(done("cancel")), once(failure_check("cancel", "cancelled; nothing changed")), once(lambda: send("apply", action=f"{HOST}.apply")), until(done("apply")), once(denied_check("apply", f"{HOST}.apply")), once(lambda: send("save", action="wm.save_mainfile")), until(done("save")), once(denied_check("save", "wm.save_mainfile")), + once(rewrite_listing_apply), + once(lambda: send("apply1", action=f"{HOST}.apply")), until(done("apply1")), once(denied_check("apply1", f"{HOST}.apply after the file was edited")), + once(lambda: send("reload", action="brokkr.reload_host_actions")), until(done("reload")), once(denied_check("reload", "brokkr.reload_host_actions")), + once(reload_refused_in_a_turn), once(human_reload_check), + once(lambda: send("apply2", action=f"{HOST}.apply")), until(done("apply2")), once(applied_check), ] i = 0 diff --git a/surfaces/blender/tests/live/host_action.result.json b/surfaces/blender/tests/live/host_action.result.json index a493c29..5ef9544 100644 --- a/surfaces/blender/tests/live/host_action.result.json +++ b/surfaces/blender/tests/live/host_action.result.json @@ -37,7 +37,7 @@ "undoLabel": "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:08.910684+00:00" + "observedAt": "2026-11-28T06:03:04.276267+00:00" } }, { @@ -126,7 +126,7 @@ "undoLabel": "", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:13.022948+00:00" + "observedAt": "2026-11-28T06:03:08.396168+00:00" } }, { @@ -149,7 +149,7 @@ "undoLabel": "", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:14.080400+00:00" + "observedAt": "2026-11-28T06:03:10.456189+00:00" } }, { @@ -172,7 +172,7 @@ "undoLabel": "", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:16.137129+00:00" + "observedAt": "2026-11-28T06:03:12.513224+00:00" } }, { @@ -200,7 +200,7 @@ "undoLabel": "", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:18.194603+00:00" + "observedAt": "2026-11-28T06:03:14.572017+00:00" } }, { @@ -212,6 +212,106 @@ "Light", "LiveEmpty" ] + }, + { + "name": "brokkr_host_fixture.apply after the file was edited is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0007", + "action": "brokkr_host_fixture.apply", + "status": "denied", + "message": "Unsupported Blender command action: brokkr_host_fixture.apply", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:16.631534+00:00" + } + }, + { + "name": "brokkr_host_fixture.apply after the file was edited ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "brokkr.reload_host_actions is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0008", + "action": "brokkr.reload_host_actions", + "status": "denied", + "message": "Unsupported Blender command action: brokkr.reload_host_actions", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:18.693145+00:00" + } + }, + { + "name": "brokkr.reload_host_actions ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "the Reload Host Actions operator refuses inside an agent turn", + "ok": true, + "detail": null + }, + { + "name": "and re-read nothing: the edited file's apply row is still not admitted", + "ok": true, + "detail": [ + "brokkr_host_fixture.add_empty", + "brokkr_host_fixture.report", + "brokkr_host_fixture.refuse", + "brokkr_host_fixture.cancel" + ] + }, + { + "name": "the human's reload admits the edited file's apply row", + "ok": true, + "detail": [ + "brokkr_host_fixture.add_empty", + "brokkr_host_fixture.report", + "brokkr_host_fixture.refuse", + "brokkr_host_fixture.cancel", + "brokkr_host_fixture.apply" + ] + }, + { + "name": "apply is accepted after the human's reload as one labelled undo step", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0009", + "action": "brokkr_host_fixture.apply", + "status": "accepted", + "message": "Operator brokkr_host_fixture.apply finished.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: brokkr_host_fixture.apply ost-0009", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:21.755767+00:00" + } } ], "ok": true diff --git a/surfaces/blender/tests/test_action_table.py b/surfaces/blender/tests/test_action_table.py index f3a5f6e..af2938b 100644 --- a/surfaces/blender/tests/test_action_table.py +++ b/surfaces/blender/tests/test_action_table.py @@ -79,6 +79,13 @@ class HostTableTests(unittest.TestCase): ): with self.assertRaises(at.TableInvalid, msg=why): at.check_host(bad, self.charsets()) + for key in ("note", "action", "commandId", "requestedBy", "schema"): # Brokkr writes these: the operator would never receive the agent's value + with self.assertRaises(at.TableInvalid, msg=key): + at.check_host(self.host_file(fields=[{"name": key, "type": "string"}]), self.charsets()) + with self.assertRaises(at.TableInvalid): + at.check_host(self.host_file(unknown=1), self.charsets()) + with self.assertRaises(at.TableInvalid): + at.check_host(self.host_file(fields=[{"name": "a", "type": "string"}, {"name": "b", "type": "string", "only": {"field": "a", "in": ["x"]}}]), self.charsets()) twice = copy.deepcopy(HOST_FILE) twice["actions"].append(copy.deepcopy(twice["actions"][0])) with self.assertRaises(at.TableInvalid): diff --git a/surfaces/blender/tests/test_addon_ui.py b/surfaces/blender/tests/test_addon_ui.py index 74c8a24..2240371 100644 --- a/surfaces/blender/tests/test_addon_ui.py +++ b/surfaces/blender/tests/test_addon_ui.py @@ -113,6 +113,37 @@ class CopyOperatorTests(unittest.TestCase): self.assertIn(addon.BROKKR_OT_copy_session_token, addon.classes) +class ReloadHostActionsTests(unittest.TestCase): + """The panel's Reload Host Actions button is the human's: it reads the files; it refuses inside an agent turn.""" + + def press(self, target): + operator = addon.BROKKR_OT_reload_host_actions() + operator.reported = None + with mock.patch.object(addon, "_target", target): + return operator.execute(None), operator.reported + + def test_pressed_it_reloads_and_reports_the_counts(self): + target = bt.BrokkrBlenderTarget(NS()) + target.reload_host_actions = mock.Mock(return_value=2) + target.host_actions = mock.Mock(return_value=([{"name": "a.b"}], [])) + result, reported = self.press(target) + self.assertEqual(result, {"FINISHED"}) + target.reload_host_actions.assert_called_once_with() + self.assertIn("2 host file(s) read; 1 host action(s) admitted", reported[1]) + + def test_inside_an_agent_turn_it_refuses_and_reads_nothing(self): + target = bt.BrokkrBlenderTarget(NS()) + target.agent_turn = True + target._host_docs = {"kept": {}} + result, reported = self.press(target) + self.assertEqual((result, reported[0]), ({"CANCELLED"}, {"ERROR"})) + self.assertEqual(target._host_docs, {"kept": {}}) + + def test_it_is_registered_and_drawn_in_the_panel(self): + self.assertIn(addon.BROKKR_OT_reload_host_actions, addon.classes) + self.assertIn("brokkr.reload_host_actions", (ADDON / "__init__.py").read_text(encoding="utf-8")) + + class PanelTests(unittest.TestCase): def test_the_panel_never_draws_the_token(self): target = running_target() diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 8b8174b..17b80e3 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -1,6 +1,7 @@ """run_intent: admission, one labelled undo step, receipts. A fake bpy records ops calls.""" from __future__ import annotations +import json import re import sys import tempfile @@ -252,6 +253,10 @@ class HostOp: self.props = props self.behave = behave self.calls = [] + self.pollable = True + + def poll(self): + return self.pollable def idname(self): return self.cls.__name__ @@ -266,7 +271,7 @@ class HostOp: def prop(identifier, kind, lo=0.0, hi=1e30, enum=()): - return NS(identifier=identifier, type=kind, hard_min=lo, hard_max=hi, enum_items=[NS(identifier=e) for e in enum]) + return NS(identifier=identifier, type=kind, hard_min=lo, hard_max=hi, enum_items=[NS(identifier=e) for e in enum], is_readonly=False) def raising(error): @@ -295,11 +300,12 @@ class HostActionTests(unittest.TestCase): "apply": HostOp("apply", [], self.finish), } bpy.ops.brokkr_host_fixture = NS(**self.ops) - bpy.types = NS(WindowManager=NS(bl_rna=NS(properties={"brokkr_host_fixture_result": NS(type="STRING")})), + bpy.types = NS(WindowManager=NS(bl_rna=NS(properties={"brokkr_host_fixture_result": NS(type="STRING", is_readonly=False)})), **{op.idname(): op.cls for op in self.ops.values()}) bpy.context.preferences.addons = {HOST: object(), "brokkr_bridge": object()} bpy.context.window_manager.brokkr_host_fixture_result = "stale" self.report_text = "objects: 3" + self.target.reload_host_actions() # the human's act: the files are read here and nowhere else def finish(self, op, kwargs): return {"FINISHED"} @@ -373,7 +379,7 @@ class HostActionTests(unittest.TestCase): self.assertEqual(self.bpy.undo.pushes, []) self.ops["add_empty"].behave = raising(RuntimeError("Traceback...\nboom")) receipt = self.send("add_empty", name="E") - self.assertEqual((receipt["status"], receipt["message"]), ("failed", "Traceback...")) + self.assertEqual((receipt["status"], receipt["message"]), ("failed", "boom")) self.assertEqual(len(self.bpy.undo.pushes), 1) self.assertTrue(self.bpy.undo.pushes[0].endswith("(failed)")) @@ -430,20 +436,65 @@ class HostActionTests(unittest.TestCase): def test_a_result_that_is_not_a_window_manager_string_refuses_the_whole_file(self): self.bpy.types.WindowManager.bl_rna.properties["brokkr_host_fixture_result"] = NS(type="INT") - self.assertIn("not a string property", self.refused()) + self.assertIn("not a writable string property", self.refused()) self.bpy.types.WindowManager.bl_rna.properties.clear() self.refused() - def test_a_malformed_file_refuses_itself_and_a_changed_file_is_read_again(self): + def test_a_malformed_file_refuses_itself_and_a_reload_reads_the_changed_file(self): path = self.dir / "brokkr_actions.json" good = path.read_text(encoding="utf-8") path.write_text(good.replace("host_actions.v0", "host_actions.v9"), encoding="utf-8") + self.target.reload_host_actions() self.assertIn("schema", self.refused()) path.write_text(good, encoding="utf-8") + self.target.reload_host_actions() self.assertEqual(len(self.target.host_actions()[0]), 4) path.write_text("not json", encoding="utf-8") + self.target.reload_host_actions() self.refused() + def listing_apply(self): + path = self.dir / "brokkr_actions.json" + document = json.loads(path.read_text(encoding="utf-8")) + document["actions"].append({"name": f"{HOST}.apply", "doc": "applies", "changesScene": True, "editModeSafe": False, "fields": []}) + path.write_text(json.dumps(document), encoding="utf-8") + + def test_an_edited_file_admits_nothing_until_a_human_reload(self): + self.assertEqual(self.send("apply")["status"], "denied") + self.listing_apply() + for _ in range(3): # the file changed; intents and snapshots come and go + receipt = self.send("apply") + self.assertEqual(receipt["status"], "denied", receipt) + self.assertIn("Unsupported Blender command action", receipt["message"]) + self.assertNotIn(f"{HOST}.apply", [r["name"] for r in self.target.host_actions()[0]]) + self.assertEqual(self.ops["apply"].calls, []) + self.assertEqual(self.bpy.undo.pushes, []) + self.target.reload_host_actions() # she presses the button + self.assertEqual(self.send("apply")["status"], "accepted") + self.assertEqual(len(self.ops["apply"].calls), 1) + + def test_a_reload_inside_an_agent_turn_is_refused_whatever_asks_for_it(self): + self.target.agent_turn = True + try: + with self.assertRaises(PermissionError): + self.target.reload_host_actions() + finally: + self.target.agent_turn = False + self.assertEqual(self.send("reload_host_actions")["status"], "denied") # not an action at all + self.assertEqual(self.run_action(action="brokkr.reload_host_actions")["status"], "denied") + self.listing_apply() + self.ops["add_empty"].behave = lambda op, kw: self.target.reload_host_actions() # a host operator that tries + receipt = self.send("add_empty", name="E") + self.assertEqual(receipt["status"], "failed") + self.assertIn("human only", receipt["message"]) + self.assertEqual(self.send("apply")["status"], "denied") # the attempt re-read nothing + + def test_a_reload_drops_what_the_files_no_longer_say(self): + (self.dir / "brokkr_actions.json").unlink() + self.assertEqual(len(self.target.host_actions()[0]), 4) # until she reloads + self.assertEqual(self.target.reload_host_actions(), 0) + self.assertEqual(self.target.host_actions(), ([], [])) + def test_disabling_the_add_on_makes_its_action_unsupported_at_the_next_intent(self): self.assertEqual(self.send("report")["status"], "accepted") self.bpy.context.preferences.addons.pop(HOST) @@ -454,14 +505,87 @@ class HostActionTests(unittest.TestCase): def test_an_add_on_without_the_file_is_not_a_host_and_this_add_on_is_never_read(self): (self.dir / "brokkr_actions.json").unlink() + self.target.reload_host_actions() self.assertEqual(self.target.host_actions(), ([], [])) self.bpy.context.preferences.addons["brokkr_bridge"] = object() + self.target.reload_host_actions() self.assertEqual(self.target.host_actions(), ([], [])) (self.dir / "brokkr_actions.json").write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) with unittest.mock.patch.object(sys.modules["brokkr_bridge"], "__file__", str(self.dir / "__init__.py"), create=True): self.bpy.context.preferences.addons.pop(HOST) # a file sits beside this add-on itself: still not read as a host's + self.assertEqual(self.target.reload_host_actions(), 0) self.assertEqual(self.target.host_actions(), ([], [])) + def test_a_sibling_add_on_whose_name_starts_with_the_hosts_is_not_the_host(self): + # aetheria_ships' operator is not aetheria's: the ownership guard is module equality or module + '.', never a bare prefix + self.ops["report"].cls.__module__ = HOST + "_ships" + self.assertIn("not an operator defined by", self.refused()) + self.ops["report"].cls.__module__ = HOST + "x.sub" + self.refused() + self.ops["report"].cls.__module__ = HOST + self.assertEqual(len(self.target.host_actions()[0]), 4) + + def rewrite_row(self, **changes): + path = self.dir / "brokkr_actions.json" + document = json.loads(path.read_text(encoding="utf-8")) + document["actions"][0].update(changes) + path.write_text(json.dumps(document), encoding="utf-8") + self.target.reload_host_actions() + + def test_a_file_with_an_unknown_row_key_or_an_only_is_refused_whole(self): + self.rewrite_row(unknown=1) + self.assertIn("no key", self.refused()) + self.rewrite_row(unknown=None) # restore: a null is still a key + path = self.dir / "brokkr_actions.json" + path.write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) + self.rewrite_row(fields=[{"name": "name", "type": "string"}, {"name": "size", "type": "number", "minimum": 0.1, "maximum": 10, + "only": {"field": "name", "in": ["a"]}}]) + self.assertIn("no 'only'", self.refused()) + + def test_an_enum_field_must_list_the_operators_identifiers(self): + field = {"name": "kind", "type": "string", "enum": ["A", "B"]} + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "FLOAT", 0.0, 100.0), prop("kind", "ENUM", enum=("A", "B"))] + self.rewrite_row(fields=[{"name": "name", "type": "string"}, field]) + self.assertEqual(len(self.target.host_actions()[0]), 4) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("kind", "ENUM", enum=("A", "C"))] + self.assertIn("enum differs", self.refused()) + + def test_a_refused_file_is_reported_in_the_snapshot(self): + self.ops["report"].cls.__module__ = "other_addon" + self.bpy.data = NS(objects=[], scenes=[], collections=[], materials=[], images=[], filepath="") + self.bpy.app = NS(version=(5, 3, 0), background=False) + snapshot = self.target.capture_snapshot(NS(selected_objects=[], active_object=None, scene=None, mode="OBJECT"), True) + self.assertEqual(snapshot["hostActions"], []) + self.assertEqual([e["host"] for e in snapshot["hostActionErrors"]], [HOST]) + self.assertIn("not an operator defined by", snapshot["hostActionErrors"][0]["error"]) + + def test_a_poll_that_fails_refuses_before_the_operator_and_before_any_undo_step(self): + self.ops["add_empty"].pollable = False + receipt = self.send("add_empty", name="E") + self.assertEqual(receipt["status"], "failed") + self.assertIn("poll failed", receipt["message"]) + self.assertEqual((self.ops["add_empty"].calls, self.bpy.undo.pushes), ([], [])) + + def test_a_poll_that_raises_refuses_too(self): + self.ops["add_empty"].poll = raising(RuntimeError("Operator bpy.ops.x.poll() failed, context is incorrect")) + receipt = self.send("add_empty", name="E") + self.assertEqual((receipt["status"], self.ops["add_empty"].calls, self.bpy.undo.pushes), ("failed", [], [])) + + def test_a_read_only_result_property_refuses_the_whole_file_at_load(self): + self.bpy.types.WindowManager.bl_rna.properties["brokkr_host_fixture_result"].is_readonly = True + self.assertIn("writable string property", self.refused()) + + def test_an_operator_that_pushes_undo_itself_may_not_be_a_row_that_changes_nothing(self): + self.ops["report"].cls.bl_options = {"REGISTER", "UNDO"} # report says changesScene false + self.assertIn("bl_options UNDO", self.refused()) + self.ops["report"].cls.bl_options = {"REGISTER"} + self.ops["add_empty"].cls.bl_options = {"REGISTER", "UNDO"} # a changing row may + self.assertEqual(len(self.target.host_actions()[0]), 4) + + def test_a_runtime_error_names_its_cause_not_the_traceback_header(self): + self.ops["add_empty"].behave = raising(RuntimeError("Error: Python: Traceback (most recent call last):" + chr(10) + " File x.py, line 1" + chr(10) + "ValueError: boom")) + self.assertEqual(self.send("add_empty", name="E")["message"], "ValueError: boom") + class FakeNode: """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" From 6667f523aa551cbc5673c2bd8c1c173ae09d00c1 Mon Sep 17 00:00:00 2001 From: Eureka Date: Sat, 28 Nov 2026 06:25:32 +0000 Subject: [PATCH 056/223] Blender add-on: glTF export error paths survive kills and concurrent sweeps (#21) --- .../blender/brokkr_bridge/blender_target.py | 98 ++++++++++++++----- surfaces/blender/tests/test_scene_actions.py | 90 ++++++++++++++++- 2 files changed, 160 insertions(+), 28 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index e030c89..db3a939 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -13,6 +13,7 @@ import struct import subprocess import sys import tempfile +import time import uuid import zlib from array import array @@ -59,7 +60,8 @@ SYNC_RECEIPT_SCHEMA = "brokkr.sync.receipt.v0" GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT") GL_PROBE_TIMEOUT_SECONDS = 120 EXPORT_STAGE_PREFIX = ".brokkr-export-" -STAGE_LOCK = ".brokkr-lock" +LEGACY_STAGE_LOCK = ".brokkr-lock" # older layout: the lock file inside the stage folder +STAGE_LOCK_SUFFIX = ".lock" # the lock file sits beside its stage folder: .lock STAGE_JOURNAL = ".brokkr-journal" LOOK_DIR = "look" # under the output directory: scratch captures named by command id (brush-tree:ruling:look-files-are-scratch) @@ -1062,7 +1064,7 @@ class BrokkrBlenderTarget: raise sa.ActionRefused(f"glTF export did not finish: {sorted(result)}") if not staged.is_file(): raise sa.ActionRefused("glTF export wrote no file.") - written = sorted(f.relative_to(stage) for f in stage.rglob("*") if f.is_file() and f != stage / STAGE_LOCK) + written = sorted(f.relative_to(stage) for f in stage.rglob("*") if f.is_file()) taken = [str(f) for f in written if os.path.lexists(path.parent / f)] if taken: raise sa.ActionRefused("output path already exists; output actions never overwrite: " + taken[0]) @@ -1083,19 +1085,21 @@ class BrokkrBlenderTarget: os.rename(target, source) except OSError: stuck.append(target) - if lock_fd is not None: - os.close(lock_fd) if stage is not None and stuck: # The rollback itself failed: keep the stage with a journal of the files left in the - # target. Its lock is released, so the next export's sweep removes them and the retry works. - (stage / STAGE_JOURNAL).write_text( - "\n".join(t.relative_to(path.parent).as_posix() for t in stuck), encoding="utf-8") + # target. The journal is written while the lock is held, so no sweep can take the stage + # first; once the lock is released the next export's sweep removes them and the retry works. + try: + (stage / STAGE_JOURNAL).write_text( + "\n".join(t.relative_to(path.parent).as_posix() for t in stuck), encoding="utf-8") + finally: + os.close(lock_fd) raise sa.ActionRefused( "glTF export failed and could not be rolled back; files left in the output directory: " + ", ".join(t.relative_to(Path(self.output_dir).resolve()).as_posix() for t in stuck) + ". The next export removes them.") from failure if stage is not None: - shutil.rmtree(stage, ignore_errors=True) + _close_stage(stage, lock_fd) for folder in sorted(set(new_dirs), key=lambda f: -len(f.parts)): try: folder.rmdir() @@ -1107,8 +1111,7 @@ class BrokkrBlenderTarget: except OSError: pass raise - os.close(lock_fd) - shutil.rmtree(stage, ignore_errors=True) + _close_stage(stage, lock_fd) return self._receipt(command, "accepted", f"Exported glTF to {path} ({path.stat().st_size} bytes).", "") def _resolve_typed(self, command: dict[str, Any], object_type: str) -> Any: @@ -1704,34 +1707,78 @@ def _try_lock(fd: int) -> bool: return True +def _stage_lock_path(stage: Path) -> Path: + return stage.with_name(stage.name + STAGE_LOCK_SUFFIX) + + def _open_stage(parent: Path) -> tuple[Path, int]: - """A fresh staging folder in parent whose lock file this export holds, locked, until it closes the - descriptor or dies: a held lock is how a sweep knows the stage is live.""" - stage = Path(tempfile.mkdtemp(prefix=EXPORT_STAGE_PREFIX, dir=parent)) - fd = os.open(stage / STAGE_LOCK, os.O_RDWR | os.O_CREAT) - if not _try_lock(fd): + """A fresh staging folder in parent, guarded by a lock file beside it that this export holds until it + closes the descriptor or dies. The lock file is created and locked first and the folder second, so + every stage on disk is either locked-live or sweepable: a kill at any step leaves a lock file a sweep + can take, never a folder no sweep can see.""" + while True: + stage = parent / (EXPORT_STAGE_PREFIX + uuid.uuid4().hex[:16]) + try: + fd = os.open(_stage_lock_path(stage), os.O_RDWR | os.O_CREAT | os.O_EXCL) + except FileExistsError: + continue + break + try: + for attempt in range(5): # a sweep may hold a fresh lock file for an instant + if _try_lock(fd): + break + time.sleep(0.02 * (attempt + 1)) + else: + raise OSError(f"could not lock staging folder {stage}") + stage.mkdir() + except BaseException: os.close(fd) - raise OSError(f"could not lock staging folder {stage}") + _unlink_quietly(_stage_lock_path(stage)) + raise return stage, fd +def _close_stage(stage: Path, fd: int) -> None: + """End a finished stage: remove the folder while the lock is held, then the lock file.""" + shutil.rmtree(stage, ignore_errors=True) + os.close(fd) + _unlink_quietly(_stage_lock_path(stage)) + + +def _unlink_quietly(path: Path) -> None: + """Remove a lock file; where the OS refuses (Windows, a sweeper holds it) the next sweep removes it.""" + try: + path.unlink(missing_ok=True) + except OSError: + pass + + def _sweep_stale_stages(top: Path) -> None: """Remove every staging folder under top whose lock can be taken: its export is over or its Blender - died. A held lock (an export running now, in any process) leaves the folder alone, and so does a - folder with no lock file yet (an export between creating it and locking it).""" - for root, dirs, _ in os.walk(top): + died. A held lock (an export running now, in any process) leaves the stage alone. A lock file with + no folder is a stage killed before its folder existed. A folder with no sibling lock file is the + older layout, locked by a file inside it, or never locked at all.""" + for root, dirs, files in os.walk(top): for name in [d for d in dirs if d.startswith(EXPORT_STAGE_PREFIX)]: dirs.remove(name) - _sweep_stage(Path(root) / name) + stage = Path(root) / name + if not _stage_lock_path(stage).exists(): + _sweep_stage(stage, stage / LEGACY_STAGE_LOCK) + for name in files: + if name.startswith(EXPORT_STAGE_PREFIX) and name.endswith(STAGE_LOCK_SUFFIX): + stage = Path(root) / name[:-len(STAGE_LOCK_SUFFIX)] + _sweep_stage(stage, Path(root) / name) -def _sweep_stage(stage: Path) -> None: +def _sweep_stage(stage: Path, lock_path: Path) -> None: try: - fd = os.open(stage / STAGE_LOCK, os.O_RDWR) + fd = os.open(lock_path, os.O_RDWR) + except FileNotFoundError: + fd = None # no lock was ever made for this folder: nothing can hold it except OSError: return try: - if not _try_lock(fd): + if fd is not None and not _try_lock(fd): return journal = stage / STAGE_JOURNAL if journal.is_file(): # a failed rollback's leftovers in the target @@ -1750,8 +1797,11 @@ def _sweep_stage(stage: Path) -> None: except OSError: break finally: - os.close(fd) + if fd is not None: + os.close(fd) shutil.rmtree(stage, ignore_errors=True) + if lock_path.parent != stage: + _unlink_quietly(lock_path) def _kill_tree(process: "subprocess.Popen[str]") -> None: diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index 0281ba3..ef3ae3b 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -435,11 +435,93 @@ class ActionTests(unittest.TestCase): bt._sweep_stale_stages(self.root / "out") self.assertFalse(stage.exists()) - def test_a_sweep_leaves_a_folder_whose_lock_is_not_made_yet(self): - early = self.root / "out" / ".brokkr-export-early" - early.mkdir() + def test_a_stage_killed_at_each_step_is_swept_by_the_next_export(self): + out = self.root / "out" + lock_only = out / ".brokkr-export-1.lock" # killed after taking the lock, before making the folder + lock_only.write_bytes(b"") + empty = out / ".brokkr-export-2" # killed after making the folder, before staging anything + empty.mkdir() + (out / ".brokkr-export-2.lock").write_bytes(b"") + mid = out / ".brokkr-export-3" # killed mid-export with files staged + mid.mkdir() + (mid / "a.glb").write_bytes(b"half") + (out / ".brokkr-export-3.lock").write_bytes(b"") + self.assertEqual(self.run_action(action="exportGltf", filepath="b.glb")["status"], "accepted") + self.assertEqual([p.name for p in out.iterdir()], ["b.glb"]) + + def test_a_stage_made_the_old_way_is_swept_with_its_journal_so_the_export_can_retry(self): + out = self.root / "out" + out.mkdir(exist_ok=True) + (out / "a.glb").write_bytes(b"left by a failed rollback") + old = out / ".brokkr-export-old" + old.mkdir() + (old / ".brokkr-lock").write_bytes(b"") + (old / ".brokkr-journal").write_text("a.glb", encoding="utf-8") + unlocked = out / ".brokkr-export-nolock" + unlocked.mkdir() + self.assertEqual(self.run_action(action="exportGltf", filepath="a.glb")["status"], "accepted") + self.assertEqual([p.name for p in out.iterdir()], ["a.glb"]) + self.assertNotEqual((out / "a.glb").read_bytes(), b"left by a failed rollback") + + def test_a_stage_whose_lock_a_sweep_briefly_holds_is_locked_after_a_short_wait(self): + calls = [] + real = bt._try_lock + + def busy_twice(fd): + calls.append(fd) + return len(calls) > 2 and real(fd) + + with mock.patch.object(bt, "_try_lock", busy_twice): + stage, fd = bt._open_stage(self.root / "out") + os.close(fd) + self.assertEqual(len(calls), 3) + + def test_a_lock_file_the_os_will_not_unlink_is_left_for_the_next_sweep(self): + stage, fd = bt._open_stage(self.root / "out") + with mock.patch.object(Path, "unlink", side_effect=PermissionError("held")): + bt._close_stage(stage, fd) # no error + self.assertTrue(bt._stage_lock_path(stage).exists()) bt._sweep_stale_stages(self.root / "out") - self.assertTrue(early.exists()) + self.assertEqual(list((self.root / "out").iterdir()), []) + + def test_every_stage_is_locked_before_its_folder_exists(self): + real_mkdir = Path.mkdir + seen = [] + + def watch(path, *args, **kw): + if path.name.startswith(bt.EXPORT_STAGE_PREFIX): + seen.append(bt._stage_lock_path(path).exists()) + return real_mkdir(path, *args, **kw) + + with mock.patch.object(Path, "mkdir", watch): + stage, fd = bt._open_stage(self.root / "out") + os.close(fd) + self.assertEqual(seen, [True]) + + def test_a_concurrent_sweep_during_a_failed_move_never_loses_the_journal(self): + self.bpy.export_siblings = ["tex1.png"] + real_rename = os.rename + real_write = Path.write_text + calls = [] + + def fail_forever_from_third(src, dst): + calls.append(dst) + if len(calls) >= 3: + raise OSError("disk gone") + return real_rename(src, dst) + + def sweep_then_write(path, *args, **kw): + if path.name == bt.STAGE_JOURNAL: + bt._sweep_stale_stages(self.root / "out") # another export's sweep, mid-failure + self.assertTrue(path.parent.is_dir()) + return real_write(path, *args, **kw) + + with mock.patch.object(bt.os, "rename", fail_forever_from_third), mock.patch.object(Path, "write_text", sweep_then_write): + receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertIn("could not be rolled back", receipt["message"]) + journals = list((self.root / "out").glob("**/" + bt.STAGE_JOURNAL)) + self.assertEqual(len(journals), 1) + self.assertIn("a.bin", journals[0].read_text(encoding="utf-8")) def test_a_failed_rollback_is_refused_loudly_naming_the_files_and_the_next_export_recovers(self): self.bpy.export_siblings = ["tex1.png"] From 72258d9288475e15072bd4cd25622006d4ea6c9e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 01:08:04 +0100 Subject: [PATCH 057/223] Blender tools: run an intent recipe in a background Blender; write a turntable recipe run_intents.py sends a JSON list of intents through BrokkrBlenderTarget.run_intent in a background Blender (the action table admits or denies each, host rows included) and writes the receipts to a file. It refuses to start without private Blender user directories. turntable_recipe.py writes such a recipe from Brokkr's own scene actions, so a before and an after of one subject are framed identically. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tools/run_intents.py | 106 +++++++++++++++++++++ surfaces/blender/tools/turntable_recipe.py | 75 +++++++++++++++ 2 files changed, 181 insertions(+) create mode 100644 surfaces/blender/tools/run_intents.py create mode 100644 surfaces/blender/tools/turntable_recipe.py diff --git a/surfaces/blender/tools/run_intents.py b/surfaces/blender/tools/run_intents.py new file mode 100644 index 0000000..9c06c01 --- /dev/null +++ b/surfaces/blender/tools/run_intents.py @@ -0,0 +1,106 @@ +"""Run a list of Brokkr intents in a background Blender, through the add-on's own agent turn. + + blender --background --factory-startup --python surfaces/blender/tools/run_intents.py -- [] + +For batch work on files (polishing a generated mesh, rendering a turntable) where no person has a Blender open. +Every intent goes through BrokkrBlenderTarget.run_intent: the action table admits or denies it, host add-on +rows are checked as in a live session, and each gets a receipt. No CultMesh node is opened: the receipts are +written to (default: the recipe's name with .receipts.json) and nowhere else, so nothing here +shows in a person's Agents panel. This script is the human of its own Blender: it enables the host add-ons the +recipe names, reloads host actions once, and opens and saves the .blend. It refuses to start unless +BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are set, so it never reads or writes a +person's own Blender folders (docs/install.md). + +The recipe: + + {"requestedBy": "/", + "importDir": "", "outputDir": "", + "hostAddons": ["brokkr_mesh_polish"], optional; modules found beside brokkr_bridge or in hostAddonDirs + "hostAddonDirs": [""], optional; extra directories holding host add-on packages + "openBlend": "", "saveBlend": "", optional; without openBlend the scene starts empty; saveBlend + is written after the last intent + "keepGoing": false, optional; true runs the rest after a refusal + "intents": [{"action": "importGltf", "filepath": "ship.glb"}, ...]} + +commandId defaults to -; requestedBy to the recipe's. Exit status: 0 when every intent was +accepted, 3 when one was not (the receipts file says which), 2 when the recipe could not be run at all. +""" +import importlib +import json +import os +import sys +import types +from pathlib import Path + +import bpy + + +def fail(message: str) -> None: + print(f"run_intents: {message}", file=sys.stderr, flush=True) + sys.exit(2) + + +def main() -> int: + for name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not os.environ.get(name): + fail(f"{name} is not set: run in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") + arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] + if not arguments: + fail("usage: blender --background --factory-startup --python run_intents.py -- []") + recipe_path = Path(arguments[0]).resolve() + receipts_path = Path(arguments[1]).resolve() if len(arguments) > 1 else recipe_path.with_suffix(".receipts.json") + try: + recipe = json.loads(recipe_path.read_text(encoding="utf-8")) + except (OSError, ValueError) as error: + fail(f"cannot read {recipe_path}: {error}") + unknown = set(recipe) - {"requestedBy", "importDir", "outputDir", "hostAddons", "hostAddonDirs", "openBlend", + "saveBlend", "keepGoing", "intents"} + if unknown or not isinstance(recipe.get("intents"), list): + fail(f"recipe has unknown keys {sorted(unknown)} or no intents array") + + surface = Path(__file__).resolve().parents[1] + package = types.ModuleType("brokkr_bridge") # the add-on's modules without registering its panel or timers + package.__path__ = [str(surface / "brokkr_bridge")] + sys.modules["brokkr_bridge"] = package + target_module = importlib.import_module("brokkr_bridge.blender_target") + + if recipe.get("openBlend"): + bpy.ops.wm.open_mainfile(filepath=str(Path(recipe["openBlend"]).resolve())) + else: + bpy.ops.wm.read_factory_settings(use_empty=True) # no default cube, camera or light + import addon_utils + for directory in [str(surface)] + [str(Path(d).resolve()) for d in recipe.get("hostAddonDirs", [])]: + if directory not in sys.path: + sys.path.append(directory) + for module in recipe.get("hostAddons", []): + if addon_utils.enable(module, default_set=True) is None: + fail(f"host add-on {module!r} could not be enabled") + + target = target_module.BrokkrBlenderTarget(bpy) + target.configure_action_dirs(recipe.get("importDir", ""), recipe.get("outputDir", "")) + target.reload_host_actions() + _, errors = target.host_actions() + if errors: + fail(f"host actions refused: {errors}") + + receipts, status = [], 0 + for index, intent in enumerate(recipe["intents"]): + command = dict(intent) + command.setdefault("commandId", f"{recipe_path.stem}-{index}") + command.setdefault("requestedBy", recipe.get("requestedBy", "")) + receipt = target.run_intent(bpy.context, command) + receipts.append(receipt) + print("RECEIPT", command["commandId"], command.get("action"), receipt["status"], + str(receipt.get("message", "")).replace("\n", " | ")[:300], flush=True) + if receipt["status"] != "accepted": + status = 3 + if not recipe.get("keepGoing"): + break + receipts_path.write_text(json.dumps(receipts, indent=1, default=str), encoding="utf-8") + if recipe.get("saveBlend") and (status == 0 or recipe.get("keepGoing")): + bpy.ops.wm.save_as_mainfile(filepath=str(Path(recipe["saveBlend"]).resolve())) + return status + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/surfaces/blender/tools/turntable_recipe.py b/surfaces/blender/tools/turntable_recipe.py new file mode 100644 index 0000000..ccb2a59 --- /dev/null +++ b/surfaces/blender/tools/turntable_recipe.py @@ -0,0 +1,75 @@ +"""Write a run_intents recipe that renders a turntable of a .blend with Brokkr's own scene actions. + + python surfaces/blender/tools/turntable_recipe.py --blend ship.blend --output-dir renders --prefix ship_before \ + --radius 0.75 --requested-by nibu/hands > turntable.json + +The subject is assumed centred on the origin (brokkr_mesh_polish.orient leaves it there); --radius is half the +length the frame must hold. Each view is an orthographic still from a camera on a circle at --elevation degrees, +so two recipes with the same numbers frame two files identically: a before and an after can be compared view +by view. --look lit adds a sun over a dim grey world; --look flat lights with a uniform white world alone, which +shows a base colour texture as it is stored, baked shadows included. renderStill never overwrites, so a +recipe runs once per prefix. +""" +from __future__ import annotations + +import argparse +import json +import math +import sys + + +def camera_pose(azimuth_deg: float, elevation_deg: float, distance: float) -> tuple[list[float], list[float]]: + """(location, XYZ Euler radians) of a camera on the circle that looks at the origin with +Z up. Azimuth 0 + looks along +Y from behind the subject's -Y end; it grows counter-clockwise seen from above.""" + azimuth, elevation = math.radians(azimuth_deg), math.radians(elevation_deg) + x = distance * math.cos(elevation) * math.sin(azimuth) + y = -distance * math.cos(elevation) * math.cos(azimuth) + z = distance * math.sin(elevation) + return [x, y, z], [math.pi / 2 - elevation, 0.0, azimuth] + + +def recipe(blend: str, output_dir: str, prefix: str, radius: float, views: int, elevation: float, size: int, + engine: str, look: str, requested_by: str) -> dict: + distance = radius * 6 + intents: list[dict] = [ + {"action": "setWorld", "color": [1, 1, 1] if look == "flat" else [0.5, 0.5, 0.5], "strength": 1.0 if look == "flat" else 0.4}, + {"action": "createObject", "objectType": "CAMERA", "name": "TurntableCamera"}, + {"action": "setCamera", "targetObjectName": "TurntableCamera", "cameraType": "ORTHO", "orthoScale": radius * 2.1, + "clipStart": radius * 0.01, "clipEnd": radius * 20, "active": True}, + ] + if look == "lit": + intents += [ + {"action": "createObject", "objectType": "LIGHT", "lightType": "SUN", "name": "TurntableSun"}, + {"action": "setLight", "targetObjectName": "TurntableSun", "energy": 3.0, "color": [1, 1, 1]}, + {"action": "setObjectTransform", "targetObjectName": "TurntableSun", "rotationEuler": [math.radians(40), 0.0, math.radians(35)]}, + ] + poses = [(360.0 * i / views, elevation) for i in range(views)] + [(0.0, 90.0), (0.0, -90.0)] + names = [f"{round(a):03d}" for a, _ in poses[:views]] + ["top", "bottom"] + for name, (azimuth, tilt) in zip(names, poses): + location, rotation = camera_pose(azimuth, tilt, distance) + intents.append({"action": "setObjectTransform", "targetObjectName": "TurntableCamera", "location": location, "rotationEuler": rotation}) + intents.append({"action": "renderStill", "outputPath": f"{prefix}_{look}_{name}.png", "engine": engine, + "resolutionX": size, "resolutionY": size, "cameraName": "TurntableCamera"}) + return {"requestedBy": requested_by, "outputDir": output_dir, "openBlend": blend, "intents": intents} + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--blend", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--prefix", required=True) + parser.add_argument("--radius", type=float, required=True) + parser.add_argument("--views", type=int, default=8) + parser.add_argument("--elevation", type=float, default=25.0) + parser.add_argument("--size", type=int, default=1024) + parser.add_argument("--engine", default="BLENDER_EEVEE") + parser.add_argument("--look", choices=("lit", "flat"), default="lit") + parser.add_argument("--requested-by", required=True) + a = parser.parse_args(argv) + json.dump(recipe(a.blend, a.output_dir, a.prefix, a.radius, a.views, a.elevation, a.size, a.engine, a.look, + a.requested_by), sys.stdout, indent=1) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) From 6eb372525454d3de20ce02dfd7409d73bd110786 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 01:08:04 +0100 Subject: [PATCH 058/223] brokkr_mesh_polish: a host add-on that measures and polishes generated meshes Seven agent-callable operators for image-to-3D output (Tripo and its kin): audit (welded topology, UV overlap, texel density), repair, orient, delight (undo baked lighting that normals and occlusion explain), pick, scrub_markings (paint out baked lettering) and cut_parts (cut a fused skin into capped, rooted, parented parts from seeds). The arithmetic is core.py, numpy only, tested without Blender; the host file is tested against Brokkr's own checker; tests/live/mesh_polish.py proves every row through run_intent in Blender 5.3.0. Co-Authored-By: Claude Fable 5.2 --- .../blender/brokkr_mesh_polish/__init__.py | 698 ++++++++++++++++++ .../brokkr_mesh_polish/brokkr_actions.json | 102 +++ surfaces/blender/brokkr_mesh_polish/core.py | 414 +++++++++++ surfaces/blender/tests/live/mesh_polish.py | 234 ++++++ .../tests/live/mesh_polish.result.json | 471 ++++++++++++ surfaces/blender/tests/test_mesh_polish.py | 390 ++++++++++ 6 files changed, 2309 insertions(+) create mode 100644 surfaces/blender/brokkr_mesh_polish/__init__.py create mode 100644 surfaces/blender/brokkr_mesh_polish/brokkr_actions.json create mode 100644 surfaces/blender/brokkr_mesh_polish/core.py create mode 100644 surfaces/blender/tests/live/mesh_polish.py create mode 100644 surfaces/blender/tests/live/mesh_polish.result.json create mode 100644 surfaces/blender/tests/test_mesh_polish.py diff --git a/surfaces/blender/brokkr_mesh_polish/__init__.py b/surfaces/blender/brokkr_mesh_polish/__init__.py new file mode 100644 index 0000000..af1916c --- /dev/null +++ b/surfaces/blender/brokkr_mesh_polish/__init__.py @@ -0,0 +1,698 @@ +"""Mesh polish for generated meshes (Tripo and other image-to-3D output): measure, repair, orient, undo baked +lighting, scrub baked markings, cut a fused skin into articulated parts. + +A host add-on for Brokkr: it imports nothing from Brokkr, and brokkr_actions.json beside this file lists the +operators agents may run (docs/mesh-polish.md). The arithmetic is core.py (numpy, tested without Blender); +this file is the bpy around it. Every operator writes a JSON report to WindowManager.brokkr_mesh_polish_result. +""" +bl_info = {"name": "Brokkr Mesh Polish", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), + "category": "Mesh", "description": "Measure and polish generated meshes; agent-callable through Brokkr."} + +import json +import math + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix, Vector +from mathutils.bvhtree import BVHTree + +from . import core + +RESULT = "brokkr_mesh_polish_result" +CAP_MATERIAL = "Polish Cap" +CAP_COLOUR = (0.02, 0.02, 0.025, 1.0) + + +class Refused(Exception): + """The request cannot run on this scene; the message is the receipt.""" + + +def mesh_object(name: str): + obj = bpy.data.objects.get(name) + if obj is None or obj.type != "MESH": + raise Refused(f"No mesh object named {name!r}.") + return obj + + +def mesh_objects(name: str) -> list: + if name: + return [mesh_object(name)] + found = [o for o in bpy.context.scene.objects if o.type == "MESH"] + if not found: + raise Refused("The scene has no mesh objects.") + return found + + +def arrays(obj) -> dict: + """World-space triangle arrays of a mesh object: V, T, UV (per corner, or None), N (vertex normals), + polygon (the polygon each triangle came from).""" + mesh = obj.data + mesh.calc_loop_triangles() + count = len(mesh.loop_triangles) + V = np.empty(len(mesh.vertices) * 3, dtype=np.float32) + mesh.vertices.foreach_get("co", V) + N = np.empty(len(mesh.vertices) * 3, dtype=np.float32) + mesh.vertex_normals.foreach_get("vector", N) + T = np.empty(count * 3, dtype=np.int32) + mesh.loop_triangles.foreach_get("vertices", T) + L = np.empty(count * 3, dtype=np.int32) + mesh.loop_triangles.foreach_get("loops", L) + P = np.empty(count, dtype=np.int32) + mesh.loop_triangles.foreach_get("polygon_index", P) + world = np.array(obj.matrix_world, dtype=np.float64) + V = V.reshape(-1, 3).astype(np.float64) @ world[:3, :3].T + world[:3, 3] + N = N.reshape(-1, 3).astype(np.float64) @ np.linalg.inv(world[:3, :3]) + N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-30) + UV = None + if mesh.uv_layers.active is not None: + flat = np.empty(len(mesh.loops) * 2, dtype=np.float32) + mesh.uv_layers.active.uv.foreach_get("vector", flat) + UV = flat.reshape(-1, 2).astype(np.float64)[L.reshape(-1, 3)] + return {"V": V, "T": T.reshape(-1, 3).astype(np.int64), "UV": UV, "N": N, "polygon": P} + + +def merged(objects: list) -> dict: + """The arrays of several objects as one mesh (vertex indices offset).""" + parts = [arrays(o) for o in objects] + offsets = np.cumsum([0] + [len(p["V"]) for p in parts[:-1]]) + uv = None if any(p["UV"] is None for p in parts) else np.concatenate([p["UV"] for p in parts]) + return {"V": np.concatenate([p["V"] for p in parts]), "N": np.concatenate([p["N"] for p in parts]), + "T": np.concatenate([p["T"] + o for p, o in zip(parts, offsets)]), "UV": uv} + + +def base_color_nodes(obj) -> list: + """Image Texture nodes feeding a Principled BSDF Base Color in the object's materials, nearest first.""" + found = [] + for slot in obj.material_slots: + material = slot.material + if material is None or material.node_tree is None: + continue + for node in material.node_tree.nodes: + if node.type != "BSDF_PRINCIPLED": + continue + queue = [link.from_node for link in node.inputs["Base Color"].links] + seen = set() + while queue: + upstream = queue.pop(0) + if upstream.name in seen: + continue + seen.add(upstream.name) + if upstream.type == "TEX_IMAGE" and upstream.image is not None: + found.append(upstream) + break + queue.extend(link.from_node for socket in upstream.inputs for link in socket.links) + return found + + +def base_color_image(obj): + nodes = base_color_nodes(obj) + if not nodes: + raise Refused(f"Object {obj.name!r} has no image texture on a Principled Base Color.") + return nodes[0].image + + +def image_users(image) -> list: + return [o for o in bpy.context.scene.objects + if o.type == "MESH" and any(n.image == image for n in base_color_nodes(o))] + + +def read_pixels(image) -> np.ndarray: + """(h, w, 4) float32, row 0 at v = 0, in the image's stored values (sRGB-encoded for an sRGB image).""" + width, height = image.size + if width == 0 or height == 0: + raise Refused(f"Image {image.name!r} has no pixels.") + flat = np.empty(width * height * 4, dtype=np.float32) + image.pixels.foreach_get(flat) + return flat.reshape(height, width, 4) + + +def replace_image(old, pixels: np.ndarray, suffix: str): + """A new packed image holding pixels, swapped in for old on every image texture node that used it. Nothing + is written to disk: the image lives in the .blend and in any glTF exported from it.""" + height, width = pixels.shape[:2] + stem = old.name.rsplit(".", 1)[0] if old.name.lower().endswith((".jpg", ".jpeg", ".png")) else old.name + ours = old.get("brokkr_mesh_polish", False) + name = old.name if ours and old.name.endswith("." + suffix) else f"{stem}.{suffix}" + image = bpy.data.images.new(name, width, height, alpha=False) + image["brokkr_mesh_polish"] = True + image.colorspace_settings.name = old.colorspace_settings.name + image.pixels.foreach_set(np.ascontiguousarray(pixels, dtype=np.float32).reshape(-1)) + image.pack() + for material in bpy.data.materials: + if material.node_tree is not None: + for node in material.node_tree.nodes: + if node.type == "TEX_IMAGE" and node.image == old: + node.image = image + if ours and old.users == 0: # an intermediate this add-on made: a chain of edits keeps one image, not one per step + bpy.data.images.remove(old) + image.name = name + return image + + +def ambient_occlusion(V: np.ndarray, T: np.ndarray, N: np.ndarray, rays: int, reach: float, seed: int = 0) -> np.ndarray: + """Open-sky share (0..1) at each vertex: cosine-weighted rays from just above it, against the mesh itself.""" + tree = BVHTree.FromPolygons([tuple(v) for v in V], [tuple(int(i) for i in t) for t in T]) + rng = np.random.default_rng(seed) + u, phi = rng.random(rays), rng.random(rays) * 2 * math.pi + local = np.stack([np.sqrt(u) * np.cos(phi), np.sqrt(u) * np.sin(phi), np.sqrt(1 - u)], axis=1) + helper = np.where(np.abs(N[:, [0]]) < 0.9, [[1.0, 0.0, 0.0]], [[0.0, 1.0, 0.0]]) + tangent = np.cross(N, helper) + tangent /= np.maximum(np.linalg.norm(tangent, axis=1, keepdims=True), 1e-30) + bitangent = np.cross(N, tangent) + open_sky = np.empty(len(V)) + offset = reach * 1e-3 + for i in range(len(V)): + directions = local[:, [0]] * tangent[i] + local[:, [1]] * bitangent[i] + local[:, [2]] * N[i] + origin = Vector(V[i] + N[i] * offset) + hits = sum(1 for d in directions if tree.ray_cast(origin, Vector(d), reach)[0] is not None) + open_sky[i] = 1.0 - hits / rays + return open_sky + + +def resample(pixels: np.ndarray, size: int) -> np.ndarray: + """pixels (h,w,c) at size x size: block mean when the sides divide evenly, nearest texel otherwise.""" + h, w = pixels.shape[:2] + if h == size and w == size: + return pixels + if h % size == 0 and w % size == 0: + return pixels.reshape(size, h // size, size, w // size, -1).mean(axis=(1, 3)) + rows = np.minimum(((np.arange(size) + 0.5) * h / size).astype(int), h - 1) + cols = np.minimum(((np.arange(size) + 0.5) * w / size).astype(int), w - 1) + return pixels[rows][:, cols] + + +def upsample(field: np.ndarray, height: int, width: int) -> np.ndarray: + """A (s,s) field bilinearly resampled to (height, width), texel centres aligned.""" + s = field.shape[0] + y = np.clip((np.arange(height) + 0.5) * s / height - 0.5, 0, s - 1) + x = np.clip((np.arange(width) + 0.5) * s / width - 0.5, 0, s - 1) + y0, x0 = np.floor(y).astype(int), np.floor(x).astype(int) + y1, x1 = np.minimum(y0 + 1, s - 1), np.minimum(x0 + 1, s - 1) + fy, fx = (y - y0)[:, None].astype(np.float32), (x - x0)[None, :].astype(np.float32) + top = field[y0][:, x0] * (1 - fx) + field[y0][:, x1] * fx + bottom = field[y1][:, x0] * (1 - fx) + field[y1][:, x1] * fx + return top * (1 - fy) + bottom * fy + + +def pin_uvs(bm, faces) -> None: + """Give each new face (a filled hole, a cap) one UV point, taken from an old face beside it, so it shows + that texel's colour and takes no area of the texture: a face made by filling has no place in the UV map, + and corners copied from several islands would smear the atlas across it and overlap everything.""" + layer = bm.loops.layers.uv.active + if layer is None: + return + fresh = set(faces) + for face in faces: + anchor = None + for loop in face.loops: + for other in loop.vert.link_loops: + if other.face not in fresh: + anchor = other[layer].uv.copy() + break + if anchor is not None: + break + if anchor is None: + anchor = face.loops[0][layer].uv.copy() + for loop in face.loops: + loop[layer].uv = anchor + + +def cap_surface(): + """The dark, rough material of cut faces and joints: what shows in the gap when a part swings away.""" + material = bpy.data.materials.get(CAP_MATERIAL) + if material is None: + material = bpy.data.materials.new(CAP_MATERIAL) + material.use_nodes = True + material.diffuse_color = CAP_COLOUR + shader = next((n for n in material.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None) + if shader is not None: + shader.inputs["Base Color"].default_value = CAP_COLOUR + shader.inputs["Roughness"].default_value = 0.7 + return material + + +class PolishOperator(bpy.types.Operator): + """Runs work(context) and stores its report; a Refused is an ERROR report (a failed receipt through Brokkr).""" + bl_options = {"REGISTER", "UNDO"} + + def execute(self, context): + try: + report = self.work(context) + except Refused as refusal: + self.report({"ERROR"}, str(refusal)) + return {"CANCELLED"} + setattr(context.window_manager, RESULT, json.dumps(report, separators=(",", ":"))) + return {"FINISHED"} + + +class BROKKR_MESH_POLISH_OT_audit(PolishOperator): + """Measure the meshes: triangles, welded topology (open and non-manifold edges, shells), UV overlap, UV + islands, texel density, and the size of the base colour texture""" + bl_idname = "brokkr_mesh_polish.audit" + bl_label = "Audit Mesh" + bl_options = {"REGISTER"} + object_name: bpy.props.StringProperty(name="Object", description="A mesh object; every mesh in the scene when empty") + raster: bpy.props.IntProperty(name="UV Raster", default=1024, min=64, max=4096) + + def work(self, context): + report = {} + for obj in mesh_objects(self.object_name): + data = arrays(obj) + nodes = base_color_nodes(obj) + size = max(nodes[0].image.size) if nodes else 0 + entry = core.audit(data["V"], data["T"], data["UV"], size, raster=self.raster) + entry["baseColorImage"] = nodes[0].image.name if nodes else "" + entry["baseColorSize"] = list(nodes[0].image.size) if nodes else [0, 0] + entry["customNormals"] = "custom_normal" in obj.data.attributes + report[obj.name] = entry + return report + + +class BROKKR_MESH_POLISH_OT_repair(PolishOperator): + """Weld coincident vertices (UV seams keep their UVs), drop degenerate and loose geometry, drop shells + below an area share, close small holes, make normals consistent and recompute shading from a sharp angle""" + bl_idname = "brokkr_mesh_polish.repair" + bl_label = "Repair Mesh" + object_name: bpy.props.StringProperty(name="Object") + weld_fraction: bpy.props.FloatProperty(name="Weld", default=1e-4, min=0.0, max=0.02, precision=6, + description="Weld distance as a share of the bounding diagonal") + min_shell_area: bpy.props.FloatProperty(name="Min Shell Area", default=0.0, min=0.0, max=0.5, precision=5, + description="Delete shells holding less than this share of the surface; 0 keeps all") + fill_holes_sides: bpy.props.IntProperty(name="Fill Holes", default=0, min=0, max=1000, + description="Close holes of up to this many edges; 0 leaves holes") + sharp_angle: bpy.props.FloatProperty(name="Sharp Angle", default=0.0, min=0.0, max=180.0, + description="Degrees; above 0, generated custom normals are dropped and edges sharper than this shade hard") + + def work(self, context): + obj = mesh_object(self.object_name) + mesh = obj.data + before = core.audit(arrays(obj)["V"], arrays(obj)["T"], None) + bm = bmesh.new() + bm.from_mesh(mesh) + diagonal = (Vector(obj.bound_box[6]) - Vector(obj.bound_box[0])).length + counts = {"vertices": len(bm.verts)} + if self.weld_fraction > 0: + bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=diagonal * self.weld_fraction) + counts["welded"] = counts.pop("vertices") - len(bm.verts) + faces = len(bm.faces) + bmesh.ops.dissolve_degenerate(bm, edges=bm.edges[:], dist=diagonal * 1e-7) + counts["degenerateFacesRemoved"] = faces - len(bm.faces) + loose_edges = [e for e in bm.edges if not e.link_faces] + bmesh.ops.delete(bm, geom=loose_edges, context="EDGES") + loose_verts = [v for v in bm.verts if not v.link_edges] + bmesh.ops.delete(bm, geom=loose_verts, context="VERTS") + counts["looseEdgesRemoved"], counts["looseVertsRemoved"] = len(loose_edges), len(loose_verts) + counts["shellsRemoved"] = 0 + if self.min_shell_area > 0: + bm.verts.index_update() + pairs = np.array([[e.verts[0].index, e.verts[1].index] for e in bm.edges], dtype=np.int64).reshape(-1, 2) + labels = core.components(len(bm.verts), pairs) + face_label = np.array([f.verts[0].index for f in bm.faces], dtype=np.int64) + face_label = labels[face_label] if len(face_label) else face_label + area = np.array([f.calc_area() for f in bm.faces]) + shells, inverse = np.unique(face_label, return_inverse=True) + share = np.bincount(inverse, weights=area, minlength=len(shells)) / max(area.sum(), 1e-30) + small = share < self.min_shell_area + doomed = [f for f, s in zip(bm.faces[:], small[inverse]) if s] + bmesh.ops.delete(bm, geom=doomed, context="FACES") + counts["shellsRemoved"] = int(small.sum()) + counts["holesFilled"] = 0 + if self.fill_holes_sides > 0: + filled = bmesh.ops.holes_fill(bm, edges=[e for e in bm.edges if e.is_boundary], sides=self.fill_holes_sides) + counts["holesFilled"] = len(filled["faces"]) + pin_uvs(bm, filled["faces"]) + bmesh.ops.triangulate(bm, faces=[f for f in filled["faces"] if len(f.verts) > 3]) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + bm.to_mesh(mesh) + bm.free() + if self.sharp_angle > 0: + if "custom_normal" in mesh.attributes: + mesh.attributes.remove(mesh.attributes["custom_normal"]) + mesh.polygons.foreach_set("use_smooth", [True] * len(mesh.polygons)) + mesh.set_sharp_from_angle(angle=math.radians(self.sharp_angle)) + mesh.update() + after = core.audit(arrays(obj)["V"], arrays(obj)["T"], None) + return {"object": obj.name, "changes": counts, + "before": {k: before[k] for k in ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells")}, + "after": {k: after[k] for k in ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells")}} + + +class BROKKR_MESH_POLISH_OT_orient(PolishOperator): + """Turn every mesh in the scene, as one rigid body, onto its principal axes (longest on Y, shortest on Z), + centre it at the origin, scale its longest side to a length, and bake that into the mesh data""" + bl_idname = "brokkr_mesh_polish.orient" + bl_label = "Orient Meshes" + length: bpy.props.FloatProperty(name="Length", default=0.0, min=0.0, max=1e6, + description="Longest side after scaling, in scene units; 0 keeps the size") + flip_forward: bpy.props.BoolProperty(name="Flip Forward", description="Turn half a turn about Z: swap bow and stern") + roll_quarter_turns: bpy.props.IntProperty(name="Roll", default=0, min=0, max=3, + description="Quarter turns about the long axis, to choose which side is up") + principal: bpy.props.BoolProperty(name="Principal Axes", default=True, + description="Off keeps the current axes and only applies the turns, centre and scale") + + def work(self, context): + objects = mesh_objects("") + data = merged(objects) + centre, rotation = core.principal_frame(data["V"], data["T"]) + if self.principal: + rotation = np.array([rotation[1], rotation[0], -rotation[2]]) # long on Y, middle on X, right-handed + if np.linalg.det(rotation) < 0: + rotation[2] *= -1 + else: + rotation = np.eye(3) + turn = Matrix.Rotation(math.radians(90 * self.roll_quarter_turns), 3, "Y") + if self.flip_forward: + turn = Matrix.Rotation(math.pi, 3, "Z") @ turn + rotation = np.array(turn) @ rotation + local = (data["V"] - centre) @ rotation.T + low, high = local.min(axis=0), local.max(axis=0) + scale = self.length / float((high - low).max()) if self.length > 0 else 1.0 + middle = (low + high) / 2.0 + frame = Matrix.Translation(Vector(-middle * scale)) @ Matrix.Diagonal((scale, scale, scale, 1.0)) \ + @ Matrix([list(row) + [0.0] for row in rotation] + [[0, 0, 0, 1]]) @ Matrix.Translation(Vector(-centre)) + originals = {o.name: frame @ o.matrix_world for o in objects} + for obj in objects: + if obj.data.users > 1: + obj.data = obj.data.copy() + obj.data.transform(originals[obj.name]) + obj.data.update() + for obj in objects: + obj.parent = None + obj.matrix_world = Matrix.Identity(4) + final = (local - middle) * scale + return {"objects": [o.name for o in objects], "scale": scale, + "extent": [round(float(x), 6) for x in (high - low) * scale], + "mirrorError": {axis: core.mirror_error(final, index) for index, axis in enumerate("XYZ")}} + + +class BROKKR_MESH_POLISH_OT_delight(PolishOperator): + """Undo lighting baked into a base colour texture: fit the light that the surface's own normals and ambient + occlusion explain, then raise shaded texels to the level of the lit ones. The result is a new packed image""" + bl_idname = "brokkr_mesh_polish.delight" + bl_label = "Delight Base Colour" + object_name: bpy.props.StringProperty(name="Object", description="Any object using the texture; all its users are treated together") + strength: bpy.props.FloatProperty(name="Strength", default=1.0, min=0.0, max=1.0) + max_gain: bpy.props.FloatProperty(name="Max Gain", default=3.0, min=1.0, max=8.0, + description="No texel is brightened or darkened by more than this factor") + clusters: bpy.props.IntProperty(name="Colour Clusters", default=3, min=1, max=8, + description="How many distinct paints the texture is assumed to hold") + fit_size: bpy.props.IntProperty(name="Fit Size", default=1024, min=128, max=2048) + occlusion_rays: bpy.props.IntProperty(name="Occlusion Rays", default=48, min=8, max=256) + + def work(self, context): + image = base_color_image(mesh_object(self.object_name)) + users = image_users(image) + data = merged(users) + if data["UV"] is None: + raise Refused("An object using the texture has no UV map.") + V, T, N = data["V"], data["T"], data["N"] + diagonal = float(np.linalg.norm(V.max(axis=0) - V.min(axis=0))) + occlusion = ambient_occlusion(V, T, N, self.occlusion_rays, 0.35 * diagonal) + owner, bary, _ = core.rasterize(data["UV"], self.fit_size) + covered = owner >= 0 + if covered.sum() < 64: + raise Refused("The UV map covers too little of the texture to fit lighting.") + normals = core.interpolate(owner, bary, N[T])[covered] + normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-30) + sky = core.interpolate(owner, bary, occlusion[T][..., None])[covered][:, 0] + pixels = read_pixels(image) + encoded = image.colorspace_settings.name == "sRGB" + linear = core.srgb_to_linear(pixels[..., :3]) if encoded else pixels[..., :3] + small = resample(linear, self.fit_size)[covered].astype(np.float64) + log_l = np.log(core.luminance(small) + 1e-4) + basis = core.shading_basis(normals, sky) + # Texels below 4% of the white point are unpainted fill (what the generator never saw): no paint to judge. + judged = np.flatnonzero(core.luminance(small) > 0.04 * np.percentile(core.luminance(small), 95)) + if len(judged) < 64: + raise Refused("The texture is too dark to fit lighting.") + fit = np.random.default_rng(0).choice(judged, size=min(len(judged), 200000), replace=False) + labels = core.chroma_clusters(small[fit], min(self.clusters, len(fit))) + weights, explained = core.fit_shading(log_l[fit], basis[fit], labels) + gain = core.delight_gain(basis, weights, self.strength, self.max_gain) + after_log = np.log(core.luminance(small * gain[:, None]) + 1e-4) + _, explained_after = core.fit_shading(after_log[fit], basis[fit], labels) + field = np.ones((self.fit_size, self.fit_size, 1), dtype=np.float32) + field[covered] = gain[:, None] + field = core.push_pull(field, covered)[..., 0] + full = upsample(field, pixels.shape[0], pixels.shape[1]) + out = pixels.copy() + lit = linear * full[..., None] + out[..., :3] = core.linear_to_srgb(lit) if encoded else np.clip(lit, 0.0, None) + source = image.name + new = replace_image(image, out, "delit") # may remove image, when it was this add-on's own + return {"image": source, "newImage": new.name, "objects": [o.name for o in users], + "explainedByLight": {"before": explained, "after": explained_after}, + "before": core.lighting_signature(log_l[judged], normals[judged], sky[judged]), + "after": core.lighting_signature(after_log[judged], normals[judged], sky[judged]), + "gain": {"min": float(gain.min()), "median": float(np.median(gain)), "max": float(gain.max()), + "clamped": float(((gain >= self.max_gain * 0.999) | (gain <= 1.001 / self.max_gain)).mean())}} + + +class BROKKR_MESH_POLISH_OT_scrub_markings(PolishOperator): + """Paint out markings (garbled text, stray decals) on the base colour texture inside a sphere: texels far + from the sphere's median colour are replaced by a blend of their surroundings, with the surroundings' grain""" + bl_idname = "brokkr_mesh_polish.scrub_markings" + bl_label = "Scrub Markings" + object_name: bpy.props.StringProperty(name="Object") + x: bpy.props.FloatProperty(name="X", min=-1e6, max=1e6) + y: bpy.props.FloatProperty(name="Y", min=-1e6, max=1e6) + z: bpy.props.FloatProperty(name="Z", min=-1e6, max=1e6) + radius: bpy.props.FloatProperty(name="Radius", default=0.1, min=1e-4, max=1e6) + tolerance: bpy.props.FloatProperty(name="Tolerance", default=0.12, min=0.0, max=2.0, + description="Colour distance (0..1 texture values) from the region's median that counts as a marking") + grow: bpy.props.IntProperty(name="Grow", default=2, min=0, max=32, description="Texels to widen the marking mask by") + + def work(self, context): + obj = mesh_object(self.object_name) + image = base_color_image(obj) + data = arrays(obj) + if data["UV"] is None: + raise Refused(f"Object {obj.name!r} has no UV map.") + centre = np.array([self.x, self.y, self.z]) + corners = data["V"][data["T"]] + middle = corners.mean(axis=1) + reach = np.linalg.norm(corners - middle[:, None, :], axis=2).max(axis=1) + near = np.linalg.norm(middle - centre, axis=1) <= self.radius + reach + if not near.any(): + raise Refused("No surface lies inside the sphere.") + pixels = read_pixels(image) + height, width = pixels.shape[:2] + if height != width: + raise Refused("The base colour texture is not square.") + owner, bary, _ = core.rasterize(data["UV"][near], height) + position = core.interpolate(owner, bary, corners[near]) + region = (owner >= 0) & (np.linalg.norm(position - centre, axis=2) <= self.radius) + mask = core.marking_mask(pixels[..., :3], region, self.tolerance, self.grow) + if not mask.any(): + return {"object": obj.name, "image": image.name, "regionTexels": int(region.sum()), "scrubbedTexels": 0} + rows, cols = np.nonzero(mask) + pad = 24 + y0, y1 = max(rows.min() - pad, 0), min(rows.max() + pad + 1, height) + x0, x1 = max(cols.min() - pad, 0), min(cols.max() + pad + 1, width) + crop = pixels[y0:y1, x0:x1, :3].copy() + hole = mask[y0:y1, x0:x1] + source = region[y0:y1, x0:x1] & ~hole # fill from the same panel only, never from another UV island + if not source.any(): + raise Refused("The whole region counts as marking: raise the tolerance or the radius.") + filled = core.push_pull(crop, source) + grain = crop - core.box_blur(filled, 3) + donors = np.flatnonzero(source) + picks = np.random.default_rng(0).choice(donors, size=int(hole.sum())) + filled[hole] = np.clip(filled[hole] + grain.reshape(-1, 3)[picks], 0.0, 1.0) + out = pixels.copy() + out[y0:y1, x0:x1, :3][hole] = filled[hole] + source = image.name + new = replace_image(image, out, "scrubbed") # may remove image, when it was this add-on's own + return {"object": obj.name, "image": source, "newImage": new.name, + "regionTexels": int(region.sum()), "scrubbedTexels": int(mask.sum())} + + +class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): + """Cut one fused skin into named parts grown from seed points along its concave creases, cap both sides of + every cut, and give each part an origin at the centre of its cut, parented to the first-named part""" + bl_idname = "brokkr_mesh_polish.cut_parts" + bl_label = "Cut Parts" + object_name: bpy.props.StringProperty(name="Object") + seeds: bpy.props.StringProperty(name="Seeds", maxlen=4000, + description="name=x,y,z; name=x,y,z ... world-space points on the surface; the first name is the body") + crease_cost: bpy.props.FloatProperty(name="Crease Cost", default=40.0, min=0.0, max=1000.0, + description="How strongly parts stop at concave creases; 0 splits by distance alone") + through: bpy.props.FloatProperty(name="Through", default=0.0, min=0.0, max=1.0, + description="Above 0, each seed off the body also seeds the far face of its part, found by a ray inward no longer than this share of the bounding diagonal: for thin shells") + joint_scale: bpy.props.FloatProperty(name="Joint Scale", default=0.0, min=0.0, max=10.0, + description="Above 0, a ball joint is added at each cut: radius = this x the cut's mean radius") + + def work(self, context): + obj = mesh_object(self.object_name) + try: + seeds = core.parse_seeds(self.seeds) + except ValueError as error: + raise Refused(str(error)) from None + names = list(dict.fromkeys(name for name, _ in seeds)) + if len(names) < 2: + raise Refused("Cutting needs seeds for at least two parts.") + mesh = obj.data + world = obj.matrix_world.copy() + bm = bmesh.new() + bm.from_mesh(mesh) + diagonal = (Vector(obj.bound_box[6]) - Vector(obj.bound_box[0])).length + bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=diagonal * 1e-5) + bmesh.ops.triangulate(bm, faces=[f for f in bm.faces if len(f.verts) > 3]) + bm.verts.index_update() + bm.faces.index_update() + matrix = np.array(world) + V = np.array([v.co[:] for v in bm.verts]) @ matrix[:3, :3].T + matrix[:3, 3] + T = np.array([[v.index for v in f.verts] for f in bm.faces], dtype=np.int64) + pairs = core.face_adjacency(T) + costs = core.crease_costs(V, T, pairs, self.crease_cost) + centroid = V[T].mean(axis=1) + placed = [(int(np.argmin(((centroid - np.array(point)) ** 2).sum(axis=1))), names.index(name)) for name, point in seeds] + if self.through > 0: # a thin part's far face: where a ray from the seed, going inward, comes out again + tree = BVHTree.FromPolygons([tuple(v) for v in V], [tuple(int(i) for i in t) for t in T]) + for triangle, index in list(placed): + if index == 0: + continue + a, b, c = V[T[triangle]] + inward = -np.cross(b - a, c - a) + inward /= max(np.linalg.norm(inward), 1e-30) + hit = tree.ray_cast(Vector(centroid[triangle] + inward * diagonal * 1e-4), Vector(inward), self.through * diagonal) + if hit[0] is not None and hit[2] != triangle: + placed.append((int(hit[2]), index)) + part, _ = core.grow_parts(len(T), pairs, costs, placed) + part[part < 0] = 0 # shells no seed reaches stay with the body + label = bm.faces.layers.int.new("polish_part") + was_open = bm.edges.layers.int.new("polish_was_open") + for face, value in zip(bm.faces, part): + face[label] = int(value) + for edge in bm.edges: + edge[was_open] = int(edge.is_boundary) + cap_material = cap_surface() + cap_slot = len(mesh.materials) + materials = list(mesh.materials) + [cap_material] + collection = obj.users_collection[0] if obj.users_collection else context.scene.collection + made, report = [], [] + for index, name in enumerate(names): + piece = bm.copy() + piece_label = piece.faces.layers.int["polish_part"] + piece_open = piece.edges.layers.int["polish_was_open"] + bmesh.ops.delete(piece, geom=[f for f in piece.faces if f[piece_label] != index], context="FACES") + cut = [e for e in piece.edges if e.is_boundary and not e[piece_open]] + if not piece.faces: + piece.free() + raise Refused(f"Part {name!r} came out empty: move its seed onto the surface.") + lengths = np.array([e.calc_length() for e in cut]) + mids = np.array([((e.verts[0].co + e.verts[1].co) / 2)[:] for e in cut]).reshape(-1, 3) + root_local = (mids * lengths[:, None]).sum(axis=0) / lengths.sum() if len(cut) else np.zeros(3) + spread = mids - root_local + normal_local = np.linalg.eigh((spread * lengths[:, None]).T @ spread)[1][:, 0] if len(cut) >= 3 else np.array([0.0, 0.0, 1.0]) + mean_radius = float((np.linalg.norm(spread, axis=1) * lengths).sum() / lengths.sum()) if len(cut) else 0.0 + caps = bmesh.ops.holes_fill(piece, edges=cut, sides=0)["faces"] if cut else [] + pin_uvs(piece, caps) + caps = bmesh.ops.triangulate(piece, faces=caps)["faces"] if caps else [] + for face in caps: + face.material_index = cap_slot + face.smooth = False + bmesh.ops.recalc_face_normals(piece, faces=piece.faces[:]) + new_mesh = bpy.data.meshes.new(f"{obj.name}.{name}") + root_world = world @ Vector(root_local) if index else world.translation.copy() + piece.to_mesh(new_mesh) + piece.free() + for material in materials: + new_mesh.materials.append(material) + new_obj = bpy.data.objects.new(f"{obj.name}.{name}", new_mesh) + collection.objects.link(new_obj) + new_obj.matrix_world = world + if index: # move the origin to the cut centre without moving the surface + new_mesh.transform(Matrix.Translation(-Vector(root_local))) + new_obj.matrix_world = world @ Matrix.Translation(Vector(root_local)) + normal_world = (world.to_3x3() @ Vector(normal_local)).normalized() + new_obj["polish_cut_normal"] = [round(c, 6) for c in normal_world] + new_obj["polish_cut_radius"] = mean_radius + made.append(new_obj) + report.append({"name": new_obj.name, "triangles": len(new_mesh.polygons), "capTriangles": len(caps), + "cutEdges": len(cut), "root": [round(c, 6) for c in root_world], + "cutNormal": [round(c, 6) for c in normal_world], "cutRadius": mean_radius}) + bm.free() + body = made[0] + for child, entry in zip(made[1:], report[1:]): + child.parent = body + child.matrix_parent_inverse = body.matrix_world.inverted() + if self.joint_scale > 0 and entry["cutRadius"] > 0: + ball = bmesh.new() + bmesh.ops.create_uvsphere(ball, u_segments=16, v_segments=8, radius=entry["cutRadius"] * self.joint_scale) + joint_mesh = bpy.data.meshes.new(f"{child.name}.joint") + ball.to_mesh(joint_mesh) + ball.free() + joint_mesh.materials.append(cap_material) + joint_mesh.polygons.foreach_set("use_smooth", [True] * len(joint_mesh.polygons)) + joint = bpy.data.objects.new(f"{child.name}.joint", joint_mesh) + collection.objects.link(joint) + joint.matrix_world = Matrix.Translation(Vector(entry["root"])) + joint.parent = body + joint.matrix_parent_inverse = body.matrix_world.inverted() + entry["joint"] = joint.name + bpy.data.objects.remove(obj) + if mesh.users == 0: + bpy.data.meshes.remove(mesh) + return {"body": body.name, "parts": report} + + +class BROKKR_MESH_POLISH_OT_pick(PolishOperator): + """Name the surface point seen at a place in a camera's frame: where a render shows something, this says + where it is, so a region can be given to another action""" + bl_idname = "brokkr_mesh_polish.pick" + bl_label = "Pick Surface Point" + bl_options = {"REGISTER"} + camera_name: bpy.props.StringProperty(name="Camera") + u: bpy.props.FloatProperty(name="U", default=0.5, min=0.0, max=1.0, description="Across the frame, 0 left to 1 right") + v: bpy.props.FloatProperty(name="V", default=0.5, min=0.0, max=1.0, description="Up the frame, 0 bottom to 1 top") + resolution_x: bpy.props.IntProperty(name="Resolution X", default=0, min=0, max=16384, + description="Width of the picture (u, v) was read from; 0 is the scene's render width") + resolution_y: bpy.props.IntProperty(name="Resolution Y", default=0, min=0, max=16384, + description="Height of the picture (u, v) was read from; 0 is the scene's render height") + + def work(self, context): + camera = bpy.data.objects.get(self.camera_name) + if camera is None or camera.type != "CAMERA": + raise Refused(f"No camera named {self.camera_name!r}.") + scene = context.scene + context.view_layer.update() + render = scene.render + kept = (render.resolution_x, render.resolution_y) + try: # the frame's shape is the picture's: the same numbers the still was rendered with + render.resolution_x = self.resolution_x or kept[0] + render.resolution_y = self.resolution_y or kept[1] + top_right, bottom_right, bottom_left, top_left = camera.data.view_frame(scene=scene) + finally: + render.resolution_x, render.resolution_y = kept + on_frame = bottom_left + (bottom_right - bottom_left) * self.u + (top_left - bottom_left) * self.v + world = camera.matrix_world + if camera.data.type == "ORTHO": + origin = world @ Vector((on_frame.x, on_frame.y, 0.0)) + direction = (world.to_3x3() @ Vector((0.0, 0.0, -1.0))).normalized() + else: + origin = world.translation.copy() + direction = (world.to_3x3() @ on_frame).normalized() + hit, location, normal, _, obj, _ = scene.ray_cast(context.evaluated_depsgraph_get(), origin, direction) + if not hit: + return {"hit": False} + return {"hit": True, "object": obj.name, "point": [round(c, 6) for c in location], + "normal": [round(c, 6) for c in normal]} + + +classes = (BROKKR_MESH_POLISH_OT_audit, BROKKR_MESH_POLISH_OT_repair, BROKKR_MESH_POLISH_OT_orient, + BROKKR_MESH_POLISH_OT_delight, BROKKR_MESH_POLISH_OT_scrub_markings, BROKKR_MESH_POLISH_OT_cut_parts, + BROKKR_MESH_POLISH_OT_pick) + + +def register(): + setattr(bpy.types.WindowManager, RESULT, bpy.props.StringProperty()) + for cls in classes: + bpy.utils.register_class(cls) + + +def unregister(): + for cls in reversed(classes): + bpy.utils.unregister_class(cls) + delattr(bpy.types.WindowManager, RESULT) diff --git a/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json b/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json new file mode 100644 index 0000000..d2950b7 --- /dev/null +++ b/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json @@ -0,0 +1,102 @@ +{ + "schema": "brokkr.blender.host_actions.v0", + "actions": [ + { + "name": "brokkr_mesh_polish.audit", + "doc": "Measure meshes: triangles, welded topology, shells, UV overlap and islands, texel density. Changes nothing.", + "changesScene": false, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "maxLength": 63, "doc": "a mesh object; every mesh in the scene when absent"}, + {"name": "raster", "type": "integer", "minimum": 64, "maximum": 4096, "default": 1024, "doc": "grid the UV overlap is counted on"} + ] + }, + { + "name": "brokkr_mesh_polish.repair", + "doc": "Weld coincident vertices, drop degenerate and loose geometry and small shells, close small holes, fix normals.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, + {"name": "weld_fraction", "type": "number", "minimum": 0, "maximum": 0.01, "default": 0.0001, "doc": "weld distance as a share of the bounding diagonal"}, + {"name": "min_shell_area", "type": "number", "minimum": 0, "maximum": 0.5, "default": 0, "doc": "delete shells below this share of the surface; 0 keeps all"}, + {"name": "fill_holes_sides", "type": "integer", "minimum": 0, "maximum": 1000, "default": 0, "doc": "close holes of up to this many edges"}, + {"name": "sharp_angle", "type": "number", "minimum": 0, "maximum": 180, "default": 0, "doc": "degrees; above 0 drops generated custom normals and shades edges sharper than this hard"} + ] + }, + { + "name": "brokkr_mesh_polish.orient", + "doc": "Turn all meshes as one body onto their principal axes (long on Y, short on Z), centre, scale, and bake it in.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "length", "type": "number", "minimum": 0, "maximum": 1000000, "default": 0, "doc": "longest side after scaling; 0 keeps the size"}, + {"name": "flip_forward", "type": "boolean", "default": false, "doc": "half a turn about Z"}, + {"name": "roll_quarter_turns", "type": "integer", "minimum": 0, "maximum": 3, "default": 0, "doc": "quarter turns about the long axis"}, + {"name": "principal", "type": "boolean", "default": true, "doc": "false keeps the current axes and only turns, centres and scales"} + ] + }, + { + "name": "brokkr_mesh_polish.delight", + "doc": "Undo lighting baked into the base colour texture, as far as normals and ambient occlusion explain it.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63, "doc": "any object using the texture"}, + {"name": "strength", "type": "number", "minimum": 0, "maximum": 1, "default": 1}, + {"name": "max_gain", "type": "number", "minimum": 1, "maximum": 8, "default": 3, "doc": "largest brightening or darkening factor"}, + {"name": "clusters", "type": "integer", "minimum": 1, "maximum": 8, "default": 3, "doc": "distinct paints assumed"}, + {"name": "fit_size", "type": "integer", "minimum": 128, "maximum": 2048, "default": 1024}, + {"name": "occlusion_rays", "type": "integer", "minimum": 8, "maximum": 256, "default": 48} + ] + }, + { + "name": "brokkr_mesh_polish.scrub_markings", + "doc": "Paint out markings (garbled text, decals) on the base colour texture inside a world-space sphere.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, + {"name": "x", "type": "number", "minimum": -1000000, "maximum": 1000000, "required": true}, + {"name": "y", "type": "number", "minimum": -1000000, "maximum": 1000000, "required": true}, + {"name": "z", "type": "number", "minimum": -1000000, "maximum": 1000000, "required": true}, + {"name": "radius", "type": "number", "minimum": 0.0001, "maximum": 1000000, "required": true}, + {"name": "tolerance", "type": "number", "minimum": 0, "maximum": 2, "default": 0.12, "doc": "colour distance from the region's median that counts as a marking"}, + {"name": "grow", "type": "integer", "minimum": 0, "maximum": 32, "default": 2, "doc": "texels to widen the mask by"} + ] + }, + { + "name": "brokkr_mesh_polish.cut_parts", + "doc": "Cut one fused skin into named parts grown from seeds along concave creases; cap the cuts; root each part at its cut.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "object_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, + {"name": "seeds", "type": "string", "required": true, "minLength": 3, "maxLength": 4000, "doc": "name=x,y,z; name=x,y,z ... world-space; the first name is the body"}, + {"name": "crease_cost", "type": "number", "minimum": 0, "maximum": 1000, "default": 40, "doc": "how strongly parts stop at sharp concave creases; 0 splits by distance alone"}, + {"name": "through", "type": "number", "minimum": 0, "maximum": 1, "default": 0, "doc": "above 0, each seed off the body also seeds the far face of its part, by a ray inward no longer than this share of the bounding diagonal (thin shells)"}, + {"name": "joint_scale", "type": "number", "minimum": 0, "maximum": 10, "default": 0, "doc": "above 0 adds a ball joint at each cut, radius = this x the cut's mean radius"} + ] + }, + { + "name": "brokkr_mesh_polish.pick", + "doc": "The surface point seen at (u, v) of a camera's frame, so a place found in a render can be named to another action. Changes nothing.", + "changesScene": false, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + {"name": "camera_name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, + {"name": "u", "type": "number", "minimum": 0, "maximum": 1, "required": true, "doc": "across the frame, 0 left to 1 right"}, + {"name": "v", "type": "number", "minimum": 0, "maximum": 1, "required": true, "doc": "up the frame, 0 bottom to 1 top"}, + {"name": "resolution_x", "type": "integer", "minimum": 0, "maximum": 16384, "default": 0, "doc": "width of the picture (u, v) was read from; 0 is the scene's render width"}, + {"name": "resolution_y", "type": "integer", "minimum": 0, "maximum": 16384, "default": 0, "doc": "height of the picture; 0 is the scene's render height"} + ] + } + ] +} diff --git a/surfaces/blender/brokkr_mesh_polish/core.py b/surfaces/blender/brokkr_mesh_polish/core.py new file mode 100644 index 0000000..0ae197a --- /dev/null +++ b/surfaces/blender/brokkr_mesh_polish/core.py @@ -0,0 +1,414 @@ +"""The arithmetic of mesh polish: numpy only, no bpy, so every rule here is tested without Blender. + +A mesh is three arrays: V (n,3) positions, T (m,3) vertex indices of triangles, UV (m,3,2) per-corner texture +coordinates. Generated meshes (Tripo and its kin) and glTF imports split vertices at every UV seam, so topology +is always judged on welded positions (weld), never on the raw indices. +""" +from __future__ import annotations + +import numpy as np + + +def weld(V: np.ndarray, T: np.ndarray, tolerance: float) -> tuple[np.ndarray, np.ndarray]: + """(welded vertex id per vertex, T rewritten to welded ids): vertices in the same tolerance cell are one.""" + cells = np.round(np.asarray(V, dtype=np.float64) / max(tolerance, 1e-12)).astype(np.int64) + _, ids = np.unique(cells, axis=0, return_inverse=True) + ids = ids.reshape(-1) + return ids, ids[T] + + +def components(count: int, pairs: np.ndarray) -> np.ndarray: + """Connected-component label (the smallest member id) for each of count nodes joined by pairs (k,2).""" + parent = np.arange(count, dtype=np.int64) + if len(pairs) == 0: + return parent + a, b = pairs[:, 0], pairs[:, 1] + while True: + pa, pb = parent[a], parent[b] + if np.array_equal(pa, pb): + return parent + np.minimum.at(parent, np.maximum(pa, pb), np.minimum(pa, pb)) + while True: + hop = parent[parent] + if np.array_equal(hop, parent): + break + parent = hop + + +def triangle_areas(V: np.ndarray, T: np.ndarray) -> np.ndarray: + a, b, c = V[T[:, 0]], V[T[:, 1]], V[T[:, 2]] + return 0.5 * np.linalg.norm(np.cross(b - a, c - a), axis=1) + + +def edge_census(TW: np.ndarray) -> dict[str, int]: + """Edges of the welded triangles by how many triangles use them: 1 is an open boundary, 3 or more is + non-manifold. Triangles that collapsed in the weld (two corners equal) are left out.""" + live = (TW[:, 0] != TW[:, 1]) & (TW[:, 1] != TW[:, 2]) & (TW[:, 0] != TW[:, 2]) + tw = TW[live] + edges = np.sort(np.concatenate([tw[:, [0, 1]], tw[:, [1, 2]], tw[:, [2, 0]]]), axis=1) + _, counts = np.unique(edges, axis=0, return_counts=True) + return {"edges": int(len(counts)), "boundaryEdges": int((counts == 1).sum()), + "nonManifoldEdges": int((counts > 2).sum()), "collapsedTriangles": int((~live).sum())} + + +def triangle_components(TW: np.ndarray) -> np.ndarray: + """Component label per triangle: triangles sharing a welded vertex are one shell.""" + count = int(TW.max()) + 1 if len(TW) else 0 + labels = components(count, np.concatenate([TW[:, [0, 1]], TW[:, [1, 2]]])) + return labels[TW[:, 0]] + + +def rasterize(UV: np.ndarray, size: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Texel centres covered by the UV triangles, on a size x size grid with v up (row 0 is v = 0). + + Returns (owner, bary, cover): owner[y, x] is the last triangle covering the texel centre or -1, bary[y, x] + its barycentric weights there, cover[y, x] how many triangles cover it (2 or more is UV overlap).""" + owner = np.full((size, size), -1, dtype=np.int32) + bary = np.zeros((size, size, 3), dtype=np.float32) + cover = np.zeros((size, size), dtype=np.uint16) + P = np.asarray(UV, dtype=np.float64) * size - 0.5 # texel index space: centre of texel i is i + lo = np.clip(np.ceil(P.min(axis=1)).astype(np.int64), 0, size) + hi = np.clip(np.floor(P.max(axis=1)).astype(np.int64) + 1, 0, size) + det = ((P[:, 1, 0] - P[:, 0, 0]) * (P[:, 2, 1] - P[:, 0, 1]) - (P[:, 2, 0] - P[:, 0, 0]) * (P[:, 1, 1] - P[:, 0, 1])) + for t in np.nonzero((np.abs(det) > 1e-12) & (hi[:, 0] > lo[:, 0]) & (hi[:, 1] > lo[:, 1]))[0]: + x0, y0, x1, y1 = lo[t, 0], lo[t, 1], hi[t, 0], hi[t, 1] + xs = np.arange(x0, x1, dtype=np.float64)[None, :] + ys = np.arange(y0, y1, dtype=np.float64)[:, None] + a, b, c = P[t] + w1 = ((xs - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (ys - a[1])) / det[t] + w2 = ((b[0] - a[0]) * (ys - a[1]) - (xs - a[0]) * (b[1] - a[1])) / det[t] + w0 = 1.0 - w1 - w2 + inside = (w0 >= 0) & (w1 >= 0) & (w2 >= 0) + if not inside.any(): + continue + block = (slice(y0, y1), slice(x0, x1)) + cover[block] += inside + owner[block][inside] = t + bary[block][inside] = np.stack([w0, w1, w2], axis=-1)[inside] + return owner, bary, cover + + +def interpolate(owner: np.ndarray, bary: np.ndarray, corners: np.ndarray) -> np.ndarray: + """Per-texel value of a per-corner attribute corners (m,3,k); zero where no triangle covers.""" + out = np.zeros(owner.shape + (corners.shape[-1],), dtype=np.float32) + hit = owner >= 0 + out[hit] = np.einsum("pc,pck->pk", bary[hit], corners[owner[hit]]) + return out + + +def uv_islands(TW: np.ndarray, UV: np.ndarray) -> int: + """UV islands: triangles joined where they share a welded vertex at the same UV coordinate.""" + keys = np.concatenate([TW.reshape(-1, 1).astype(np.float64), np.round(UV.reshape(-1, 2) * 65536.0)], axis=1) + _, ids = np.unique(keys, axis=0, return_inverse=True) + ids = ids.reshape(-1, 3) + labels = components(int(ids.max()) + 1, np.concatenate([ids[:, [0, 1]], ids[:, [1, 2]]])) + return int(len(np.unique(labels[ids[:, 0]]))) + + +def weighted_quantile(values: np.ndarray, weights: np.ndarray, q: float) -> float: + order = np.argsort(values) + cumulative = np.cumsum(weights[order]) + return float(values[order][min(np.searchsorted(cumulative, q * cumulative[-1]), len(values) - 1)]) + + +def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int = 0, + weld_fraction: float = 1e-5, raster: int = 1024) -> dict: + """The measurements a polish pass is judged by. Lengths are in the mesh's own units. + + Topology is counted after welding positions within weld_fraction of the bounding diagonal. UV overlap is + the share of covered texels (on a raster x raster grid) that more than one triangle covers. Texel density is + texels per unit length for a texture_size texture, area-weighted over triangles; its spread is p95 / p5.""" + V = np.asarray(V, dtype=np.float64) + T = np.asarray(T, dtype=np.int64) + extent = V.max(axis=0) - V.min(axis=0) if len(V) else np.zeros(3) + diagonal = float(np.linalg.norm(extent)) + areas = triangle_areas(V, T) + ids, TW = weld(V, T, diagonal * weld_fraction) + report = {"triangles": int(len(T)), "vertices": int(len(V)), "weldedVertices": int(ids.max()) + 1 if len(V) else 0, + "extent": [round(float(x), 6) for x in extent], "surfaceArea": float(areas.sum()), + "degenerateTriangles": int((areas <= 1e-14 * diagonal * diagonal).sum())} + report.update(edge_census(TW)) + shells = triangle_components(TW) + _, shell_sizes = np.unique(shells, return_counts=True) + report["shells"] = int(len(shell_sizes)) + report["shellTriangles"] = sorted((int(s) for s in shell_sizes), reverse=True)[:12] + if UV is None: + return report + UV = np.asarray(UV, dtype=np.float64) + signed = 0.5 * ((UV[:, 1, 0] - UV[:, 0, 0]) * (UV[:, 2, 1] - UV[:, 0, 1]) + - (UV[:, 2, 0] - UV[:, 0, 0]) * (UV[:, 1, 1] - UV[:, 0, 1])) + _, _, cover = rasterize(UV, raster) + covered = int((cover > 0).sum()) + report.update({ + "uvIslands": uv_islands(TW, UV), + "uvFlippedTriangles": int((signed < 0).sum()), + "uvZeroAreaTriangles": int((np.abs(signed) < 1e-12).sum()), + "uvOutsideUnitTriangles": int(((UV < -1e-6) | (UV > 1 + 1e-6)).any(axis=(1, 2)).sum()), + "uvCoverage": covered / float(raster * raster), + "uvOverlap": float((cover > 1).sum()) / covered if covered else 0.0, + }) + usable = (areas > 0) & (np.abs(signed) > 0) + if texture_size and usable.any(): + density = np.sqrt(np.abs(signed[usable]) * texture_size * texture_size / areas[usable]) + p5, p50, p95 = (weighted_quantile(density, areas[usable], q) for q in (0.05, 0.5, 0.95)) + report.update({"texelDensityMedian": p50, "texelDensityP5": p5, "texelDensityP95": p95, + "texelDensitySpread": p95 / p5 if p5 > 0 else float("inf")}) + return report + + +# --- orientation ----------------------------------------------------------------------------------------- + +def principal_frame(V: np.ndarray, T: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """(centre, R): the area-weighted centroid and a right-handed rotation whose rows are the principal axes, + longest first. R @ (p - centre) puts the longest axis on x, the shortest on z.""" + a, b, c = V[T[:, 0]], V[T[:, 1]], V[T[:, 2]] + areas = triangle_areas(V, T) + mids = (a + b + c) / 3.0 + centre = (mids * areas[:, None]).sum(axis=0) / areas.sum() + d = mids - centre + _, vectors = np.linalg.eigh((d * areas[:, None]).T @ d) + R = vectors[:, ::-1].T.copy() + if np.linalg.det(R) < 0: + R[2] *= -1 + return centre, R + + +def mirror_error(V: np.ndarray, axis: int, samples: int = 800, seed: int = 0) -> float: + """How far the point set is from mirror-symmetric across the plane axis = 0: the mean distance from a + mirrored sample to its nearest original, as a fraction of the bounding diagonal. 0 is a perfect mirror.""" + rng = np.random.default_rng(seed) + pick = V[rng.choice(len(V), size=min(samples, len(V)), replace=False)] + mirrored = pick.copy() + mirrored[:, axis] *= -1 + base = V[rng.choice(len(V), size=min(4 * samples, len(V)), replace=False)] + nearest = np.sqrt(((mirrored[:, None, :] - base[None, :, :]) ** 2).sum(axis=2).min(axis=1)) + return float(nearest.mean() / np.linalg.norm(V.max(axis=0) - V.min(axis=0))) + + +# --- parts ----------------------------------------------------------------------------------------------- + +def face_adjacency(TW: np.ndarray) -> np.ndarray: + """Pairs (k,2) of triangles that share a welded edge (each manifold edge once; an edge of three or more + triangles joins them in a chain).""" + count = len(TW) + edges = np.sort(np.concatenate([TW[:, [0, 1]], TW[:, [1, 2]], TW[:, [2, 0]]]), axis=1) + face = np.tile(np.arange(count), 3) + order = np.lexsort((edges[:, 1], edges[:, 0])) + edges, face = edges[order], face[order] + same = (edges[1:] == edges[:-1]).all(axis=1) + return np.stack([face[:-1][same], face[1:][same]], axis=1) + + +def crease_costs(V: np.ndarray, T: np.ndarray, pairs: np.ndarray, crease_cost: float) -> np.ndarray: + """Cost of stepping between two adjacent triangles: the distance between their centroids as a fraction of + the bounding diagonal, plus crease_cost times the square of how concave the fold between them is (0 flat + or convex, 1 a fold back on itself). A sharp concave crease is where one part of a fused skin meets another; + the square keeps the gentle concavity of a bowl, many small folds, far cheaper than one such crease.""" + a, b, c = V[T[:, 0]], V[T[:, 1]], V[T[:, 2]] + normal = np.cross(b - a, c - a) + normal /= np.maximum(np.linalg.norm(normal, axis=1, keepdims=True), 1e-30) + centre = (a + b + c) / 3.0 + diagonal = np.linalg.norm(V.max(axis=0) - V.min(axis=0)) + i, j = pairs[:, 0], pairs[:, 1] + step = centre[j] - centre[i] + angle = np.arccos(np.clip((normal[i] * normal[j]).sum(axis=1), -1.0, 1.0)) / np.pi + concave = ((step * normal[i]).sum(axis=1) - (step * normal[j]).sum(axis=1)) > 0 + return np.linalg.norm(step, axis=1) / diagonal + crease_cost * np.where(concave, angle * angle, 0.0) + + +def grow_parts(count: int, pairs: np.ndarray, costs: np.ndarray, seeds: list[tuple[int, int]]) -> tuple[np.ndarray, np.ndarray]: + """(part, cost) per triangle: each triangle joins the seed it is cheapest to walk to, at that cost; part is + -1 and cost infinite where no seed reaches. seeds are (triangle, part) and several seeds may name one part.""" + import heapq + + order = np.argsort(np.concatenate([pairs[:, 0], pairs[:, 1]]), kind="stable") + source = np.concatenate([pairs[:, 0], pairs[:, 1]])[order] + target = np.concatenate([pairs[:, 1], pairs[:, 0]])[order].tolist() + weight = np.concatenate([costs, costs])[order].tolist() + start = np.searchsorted(source, np.arange(count + 1)).tolist() + best = [float("inf")] * count + part = [-1] * count + heap = [] + for triangle, label in seeds: + best[triangle], part[triangle] = 0.0, label + heap.append((0.0, triangle, label)) + heapq.heapify(heap) + while heap: + cost, triangle, label = heapq.heappop(heap) + if cost > best[triangle] or part[triangle] != label: + continue + for k in range(start[triangle], start[triangle + 1]): + other, reach = target[k], cost + weight[k] + if reach < best[other]: + best[other], part[other] = reach, label + heapq.heappush(heap, (reach, other, label)) + return np.asarray(part, dtype=np.int64), np.asarray(best) + + +def parse_seeds(text: str) -> list[tuple[str, tuple[float, float, float]]]: + """'hull=0,0,0; pod1=1,0,0.5; pod1=1.2,0,0.4' as [(name, (x, y, z))]; ValueError names the bad entry.""" + seeds = [] + for entry in (piece.strip() for piece in text.split(";")): + if not entry: + continue + name, _, numbers = entry.partition("=") + values = numbers.split(",") + try: + point = tuple(float(v) for v in values) + except ValueError: + point = () + if not name.strip() or len(point) != 3: + raise ValueError(f"seed {entry!r} is not name=x,y,z") + seeds.append((name.strip(), point)) + if not seeds: + raise ValueError("no seeds given") + return seeds + + +# --- baked lighting -------------------------------------------------------------------------------------- + +def srgb_to_linear(c: np.ndarray) -> np.ndarray: + return np.where(c <= 0.04045, c / 12.92, ((np.maximum(c, 0.0) + 0.055) / 1.055) ** 2.4) + + +def linear_to_srgb(c: np.ndarray) -> np.ndarray: + c = np.clip(c, 0.0, 1.0) + return np.where(c <= 0.0031308, c * 12.92, 1.055 * c ** (1.0 / 2.4) - 0.055) + + +def luminance(rgb: np.ndarray) -> np.ndarray: + return rgb[..., 0] * 0.2126 + rgb[..., 1] * 0.7152 + rgb[..., 2] * 0.0722 + + +def shading_basis(normals: np.ndarray, occlusion: np.ndarray) -> np.ndarray: + """What baked light can depend on at a surface point: the eight non-constant order-2 spherical harmonics of + the unit normal (a smooth distant light) and the log of ambient occlusion (0..1, 1 is open sky).""" + x, y, z = normals[:, 0], normals[:, 1], normals[:, 2] + return np.stack([x, y, z, x * y, y * z, x * z, x * x - y * y, 3 * z * z - 1, + np.log(np.clip(occlusion, 0.02, 1.0))], axis=1) + + +def chroma_clusters(rgb: np.ndarray, count: int) -> np.ndarray: + """A cluster per sample by chromaticity alone (r and g as shares of the sum): paint of one hue stays one + cluster whether lit or shaded, so each cluster can stand for one family of paint.""" + return kmeans((rgb / (rgb.sum(axis=1, keepdims=True) + 1e-4))[:, :2], count) + + +def fit_shading(log_l: np.ndarray, basis: np.ndarray, clusters: np.ndarray, expectile: float = 0.85, + rounds: int = 12) -> tuple[np.ndarray, float]: + """(weights, explained): log luminance = an intercept per cluster + basis @ weights (the light). + + The fit follows the upper envelope of luminance (an expectile regression: samples above the fit weigh + expectile, samples below weigh 1 - expectile). Within one hue the brightest paint at a given normal and + occlusion shows how much light the bake put there; darker paint in the same place, such as machinery in a + crevice of a pale hull, is paint and must not be read as shadow. explained is the share of the + within-cluster variance of log luminance that the light accounts for: near 0, no baked light was found.""" + count = int(clusters.max()) + 1 + weight = np.ones(len(log_l)) + + def demean(values: np.ndarray) -> np.ndarray: + scaled = values * (weight[:, None] if values.ndim == 2 else weight) + sums = np.stack([np.bincount(clusters, weights=column, minlength=count) for column in scaled.reshape(len(values), -1).T], axis=1) + means = sums / np.maximum(np.bincount(clusters, weights=weight, minlength=count), 1e-12)[:, None] + return values - means[clusters].reshape(values.shape) + + w = np.zeros(basis.shape[1]) + for _ in range(rounds): + x, y = demean(basis), demean(log_l) + root = np.sqrt(weight) + w, *_ = np.linalg.lstsq(x * root[:, None], y * root, rcond=None) + weight = np.where(y - x @ w > 0, expectile, 1.0 - expectile) + weight = np.ones(len(log_l)) + x, y = demean(basis), demean(log_l) + total = float((y * y).sum()) + residual = demean(log_l - basis @ w) + return w, max(1.0 - float((residual * residual).sum()) / total, 0.0) if total > 0 else 0.0 + + +def lighting_signature(log_l: np.ndarray, normals: np.ndarray, occlusion: np.ndarray, up: int = 2) -> dict: + """Model-free signs of baked light: how much brighter up-facing surface is than down-facing (a ratio of + geometric-mean luminance, 1 is none) and how log luminance correlates with ambient occlusion (0 is none).""" + top, bottom = normals[:, up] > 0.5, normals[:, up] < -0.5 + ratio = float(np.exp(log_l[top].mean() - log_l[bottom].mean())) if top.any() and bottom.any() else 1.0 + spread = float(np.std(occlusion)) + correlation = float(np.corrcoef(log_l, occlusion)[0, 1]) if spread > 1e-6 and np.std(log_l) > 1e-9 else 0.0 + return {"upDownLuminanceRatio": ratio, "occlusionCorrelation": correlation} + + +def kmeans(features: np.ndarray, count: int, rounds: int = 12, seed: int = 0) -> np.ndarray: + rng = np.random.default_rng(seed) + centres = features[rng.choice(len(features), size=count, replace=False)].copy() + labels = np.zeros(len(features), dtype=np.int64) + for _ in range(rounds): + labels = np.argmin(((features[:, None, :] - centres[None, :, :]) ** 2).sum(axis=2), axis=1) + for k in range(count): + if (labels == k).any(): + centres[k] = features[labels == k].mean(axis=0) + return labels + + +def delight_gain(basis: np.ndarray, weights: np.ndarray, strength: float, max_gain: float) -> np.ndarray: + """The factor that undoes the fitted light at each sample. Surface the light favoured (the 90th percentile + of fitted light) is left as it is and shaded surface rises to meet it; nothing changes by more than + max_gain either way.""" + light = basis @ weights + return np.clip(np.exp(strength * (np.percentile(light, 90) - light)), 1.0 / max_gain, max_gain) + + +# --- texture filling ------------------------------------------------------------------------------------- + +def push_pull(image: np.ndarray, known: np.ndarray) -> np.ndarray: + """image (h,w,c) with the texels where known is False replaced by a smooth blend of the known texels around + them (push-pull: average down a pyramid, fill up from the coarser level). Known texels are returned as given.""" + h, w = known.shape + if known.all() or not known.any() or min(h, w) < 2: + return image.copy() + value = np.where(known[..., None], image, 0.0).astype(np.float32) + mass = known.astype(np.float32) + h2, w2 = (h + 1) // 2, (w + 1) // 2 + padded_v = np.zeros((h2 * 2, w2 * 2, image.shape[2]), dtype=np.float32) + padded_m = np.zeros((h2 * 2, w2 * 2), dtype=np.float32) + padded_v[:h, :w], padded_m[:h, :w] = value, mass + small_m = padded_m.reshape(h2, 2, w2, 2).sum(axis=(1, 3)) + small_v = padded_v.reshape(h2, 2, w2, 2, -1).sum(axis=(1, 3)) / np.maximum(small_m, 1e-9)[..., None] + filled = push_pull(small_v, small_m > 0) + up = np.repeat(np.repeat(filled, 2, axis=0), 2, axis=1)[:h, :w] + return np.where(known[..., None], image, up).astype(image.dtype) + + +def box_blur(image: np.ndarray, radius: int) -> np.ndarray: + """Mean over a (2 radius + 1) square, edges clamped; image is (h,w) or (h,w,c).""" + if radius <= 0: + return image.copy() + out = image.astype(np.float64) + for axis in (0, 1): + pad = [(0, 0)] * out.ndim + pad[axis] = (radius + 1, radius) + summed = np.cumsum(np.pad(out, pad, mode="edge"), axis=axis) + n = out.shape[axis] + upper = np.take(summed, np.arange(2 * radius + 1, 2 * radius + 1 + n), axis=axis) + lower = np.take(summed, np.arange(0, n), axis=axis) + out = (upper - lower) / (2 * radius + 1) + return out.astype(image.dtype) + + +def dilate(mask: np.ndarray, steps: int) -> np.ndarray: + out = mask.copy() + for _ in range(steps): + grown = out.copy() + grown[1:, :] |= out[:-1, :] + grown[:-1, :] |= out[1:, :] + grown[:, 1:] |= out[:, :-1] + grown[:, :-1] |= out[:, 1:] + out = grown + return out + + +def marking_mask(rgb: np.ndarray, region: np.ndarray, tolerance: float, grow: int) -> np.ndarray: + """Texels inside region whose colour is further than tolerance (Euclidean, in the image's own 0..1 values) + from the region's median colour, grown by grow texels within the region: the ink on a painted panel.""" + if not region.any(): + return np.zeros(region.shape, dtype=bool) + background = np.median(rgb[region], axis=0) + ink = region & (np.linalg.norm(rgb - background, axis=-1) > tolerance) + return dilate(ink, grow) & region diff --git a/surfaces/blender/tests/live/mesh_polish.py b/surfaces/blender/tests/live/mesh_polish.py new file mode 100644 index 0000000..4284585 --- /dev/null +++ b/surfaces/blender/tests/live/mesh_polish.py @@ -0,0 +1,234 @@ +"""Live proof, in a background Blender, that every brokkr_mesh_polish row is admitted by Brokkr as a host action +and does what its doc says to real bpy meshes and images. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/mesh_polish.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). Every action is sent through BrokkrBlenderTarget.run_intent, as tools/run_intents.py sends it. +Writes .result.json and exits 1 when a check failed. +""" +import json +import math +import os +import sys +import types +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not os.environ.get(_name): + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") + +SURFACE = Path(__file__).resolve().parents[2] +OUT = sys.argv[sys.argv.index("--") + 1] +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 + +sys.path.append(str(SURFACE)) +bpy.ops.wm.read_factory_settings(use_empty=True) +addon_utils.enable("brokkr_mesh_polish", default_set=True) +target = bt.BrokkrBlenderTarget(bpy) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], + "hostRows": [row["name"] for row in target.host_actions()[0]]} +COUNT = [0] + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +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 = json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None + return receipt, result + + +def new_object(name, build, image=None): + mesh = bpy.data.meshes.new(name) + bm = bmesh.new() + bm.loops.layers.uv.new("UVMap") # calc_uvs fills a layer that exists + build(bm) + bm.to_mesh(mesh) + bm.free() + obj = bpy.data.objects.new(name, mesh) + bpy.context.scene.collection.objects.link(obj) + if image is not None: + material = bpy.data.materials.new(name) + material.use_nodes = True + node = material.node_tree.nodes.new("ShaderNodeTexImage") + node.image = image + shader = next(n for n in material.node_tree.nodes if n.type == "BSDF_PRINCIPLED") + material.node_tree.links.new(node.outputs["Color"], shader.inputs["Base Color"]) + mesh.materials.append(material) + return obj + + +def new_image(name, pixels): + height, width = pixels.shape[:2] + image = bpy.data.images.new(name, width, height, alpha=False) + image.colorspace_settings.name = "Non-Color" # stored values are the paint: the checks read them back as written + rgba = np.ones((height, width, 4), dtype=np.float32) + rgba[..., :3] = pixels + image.pixels.foreach_set(rgba.reshape(-1)) + return image + + +def pixels_of(obj): + image = obj.material_slots[0].material.node_tree.nodes["Image Texture"].image + flat = np.empty(image.size[0] * image.size[1] * 4, dtype=np.float32) + image.pixels.foreach_get(flat) + return flat.reshape(image.size[1], image.size[0], 4)[..., :3], image + + +check("host file admitted", not R["hostErrors"] and len(R["hostRows"]) == 7, R["hostErrors"] or R["hostRows"]) + +# --- audit and repair: a sphere torn into loose faces is welded back into one closed shell ----------------------- +size = 256 +rows = (np.arange(size) + 0.5) / size # v: 0 at the south pole, 1 at the north pole of Blender's UV sphere +baked = np.repeat((0.8 * (0.2 + 0.8 * rows))[:, None, None], size, axis=1) * np.ones((1, 1, 3)) +sphere = new_object("Ball", lambda bm: bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True), + new_image("ball_bake", baked.astype(np.float32))) +sphere.data.polygons.foreach_set("use_smooth", [True] * len(sphere.data.polygons)) +torn = bmesh.new() +torn.from_mesh(sphere.data) +bmesh.ops.split_edges(torn, edges=torn.edges[:]) +torn.to_mesh(sphere.data) +torn.free() +receipt, before = send("brokkr_mesh_polish.audit", object_name="Ball") +check("audit: accepted, no undo step", receipt["status"] == "accepted" and not receipt.get("undoLabel"), receipt["message"]) +check("audit: welded topology sees one closed shell in the torn sphere", + before["Ball"]["shells"] == 1 and before["Ball"]["boundaryEdges"] == 0 and before["Ball"]["nonManifoldEdges"] == 0, before["Ball"]) +check("audit: texture and UV facts", before["Ball"]["baseColorSize"] == [size, size] and before["Ball"]["uvOverlap"] < 0.02 + and before["Ball"]["texelDensityMedian"] > 0, before["Ball"]) +torn_vertices = len(sphere.data.vertices) +receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball", sharp_angle=30) +check("repair: accepted as one undo step", receipt["status"] == "accepted" and "repair" in receipt.get("undoLabel", ""), receipt) +check("repair: welds the torn vertices", repaired["changes"]["welded"] == torn_vertices - len(sphere.data.vertices) + and len(sphere.data.vertices) == 48 * 23 + 2, repaired) +edges = [e for e in sphere.data.edges] +check("repair: every edge has two faces again", sum(1 for _ in edges) == 48 * 23 + 48 * 24, len(edges)) + +# --- delight: a bake that darkens with latitude is levelled ------------------------------------------------------ +receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=256, occlusion_rays=8) +after_pixels, after_image = pixels_of(sphere) +column = after_pixels[:, size // 2, 0] +# top/bottom brightness of the stored texture, rows at v = 0.9 and v = 0.1 +ratio_before = float(baked[int(size * 0.9), 0, 0] / baked[int(size * 0.1), 0, 0]) +ratio_after = float(column[int(size * 0.9)] / column[int(size * 0.1)]) +R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after} +check("delight: accepted, new packed image on the material", receipt["status"] == "accepted" and after_image.name == "ball_bake.delit" + and after_image.packed_file is not None, receipt["message"]) +check("delight: finds the baked light", lit["explainedByLight"]["before"] > 0.5 and lit["before"]["upDownLuminanceRatio"] > 2.0, lit) +# bound: shipped ratioAfter 1.12, the no-op mutant leaves 3.29: sqrt(1.12 * 3.29) = 1.92 +check("delight: levels top against bottom", ratio_before > 1.92 * 1.2 and ratio_after < 1.92 / 1.2, [ratio_before, ratio_after]) + +# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled ------------------------------------------ +slab = new_object("Slab", lambda bm: bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Diagonal((3.0, 1.0, 0.5, 1.0)))) +slab.matrix_world = Matrix.Translation((4, 5, 6)) @ Matrix.Rotation(math.radians(37), 4, (0.3, 0.5, 0.8)) +sphere.hide_viewport = True +bpy.context.scene.collection.objects.unlink(sphere) # orient turns every mesh in the scene as one body +receipt, oriented = send("brokkr_mesh_polish.orient", length=12.0) +corners = np.array([slab.matrix_world @ v.co for v in slab.data.vertices]) +extent = corners.max(axis=0) - corners.min(axis=0) +check("orient: long on Y, thin on Z, scaled to the length, centred", + receipt["status"] == "accepted" and np.allclose(extent, [4.0, 12.0, 2.0], atol=1e-3) + and np.allclose((corners.max(axis=0) + corners.min(axis=0)) / 2, 0, atol=1e-4), [list(map(float, extent)), oriented]) +check("orient: reports the mirror error of a symmetric body as small", max(oriented["mirrorError"].values()) < 0.05, oriented["mirrorError"]) +bpy.data.objects.remove(slab) + +# --- cut_parts: a knob fused to a block is cut off at the crease, capped, and rooted at its cut ----------------- +def knobbed(bm): + bmesh.ops.create_cube(bm, size=2.0) + top = next(f for f in bm.faces if f.normal.z > 0.9) + bmesh.ops.inset_region(bm, faces=[top], thickness=0.6) + extruded = bmesh.ops.extrude_face_region(bm, geom=[top]) + bmesh.ops.translate(bm, verts=[g for g in extruded["geom"] if isinstance(g, bmesh.types.BMVert)], vec=(0, 0, 1.0)) + bmesh.ops.delete(bm, geom=[top], context="FACES") + bmesh.ops.triangulate(bm, faces=bm.faces[:]) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + + +block = new_object("Block", knobbed) +receipt, single = send("brokkr_mesh_polish.audit", object_name="Block") +check("cut fixture is one closed skin", single["Block"]["shells"] == 1 and single["Block"]["boundaryEdges"] == 0, single["Block"]) +receipt, cut = send("brokkr_mesh_polish.cut_parts", object_name="Block", seeds="body=0,0,-1; knob=0,0,2", joint_scale=0.5) +R["cut"] = cut +check("cut_parts: accepted, one undo step, the fused object is replaced", receipt["status"] == "accepted" and bool(receipt.get("undoLabel")) + and "Block" not in bpy.data.objects and {"Block.body", "Block.knob"} <= set(bpy.data.objects.keys()), receipt["message"]) +if receipt["status"] == "accepted": + knob, body = bpy.data.objects["Block.knob"], bpy.data.objects["Block.body"] + part = {entry["name"]: entry for entry in cut["parts"]} + check("cut_parts: the knob is cut at the crease and rooted at the centre of the cut", + np.allclose(part["Block.knob"]["root"], [0, 0, 1], atol=1e-5) and np.allclose(knob.matrix_world.translation, [0, 0, 1], atol=1e-5) + and abs(abs(part["Block.knob"]["cutNormal"][2]) - 1) < 1e-5, part["Block.knob"]) + check("cut_parts: the knob hangs from the body and has not moved", knob.parent == body + and abs(max((knob.matrix_world @ v.co).z for v in knob.data.vertices) - 2.0) < 1e-5, None) + _, closed = send("brokkr_mesh_polish.audit") + check("cut_parts: both sides of the cut are capped (closed shells)", + all(closed[name]["boundaryEdges"] == 0 and closed[name]["shells"] == 1 for name in ("Block.body", "Block.knob")), + {name: [closed[name]["boundaryEdges"], closed[name]["shells"]] for name in ("Block.body", "Block.knob")}) + check("cut_parts: caps carry the cap material and a joint sits at the root", "Polish Cap" in [m.name for m in knob.data.materials] + and np.allclose(bpy.data.objects[part["Block.knob"]["joint"]].matrix_world.translation, [0, 0, 1], atol=1e-5), part["Block.knob"].get("joint")) +receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Block.body", seeds="only=0,0,-1") +check("cut_parts: one part is refused with nothing changed", receipt["status"] == "failed" and "Block.body" in bpy.data.objects, receipt["message"]) + +# --- pick and scrub_markings: lettering on one panel is found from a camera and painted out ---------------------- +panel = np.full((128, 128, 3), [0.1, 0.35, 0.4], dtype=np.float32) +panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32) +for column_start in range(8, 120, 8): # yellow strokes over the whole texture + panel[:, column_start:column_start + 2] = [0.85, 0.75, 0.2] + + +def plate(bm): + bmesh.ops.create_grid(bm, x_segments=2, y_segments=1, size=1.0, matrix=Matrix.Diagonal((2.0, 1.0, 1.0, 1.0)), calc_uvs=True) + + +sign = new_object("Sign", plate, new_image("sign_paint", panel)) # 4 x 2, flat on z = 0, u along x +sign.location = (0, 0, 5) +bpy.context.view_layer.update() +camera = bpy.data.objects.new("Eye", bpy.data.cameras.new("Eye")) +bpy.context.scene.collection.objects.link(camera) +camera.data.type = "ORTHO" +camera.data.ortho_scale = 4.0 +camera.location = (0, 0, 9) +receipt, picked = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.25, v=0.5, resolution_x=400, resolution_y=200) +check("pick: names the surface point under (u, v) of a picture of that shape", receipt["status"] == "accepted" and picked["hit"] + and picked["object"] == "Sign" and np.allclose(picked["point"], [-1.0, 0.0, 5.0], atol=1e-4), picked) +receipt, missed = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.5, v=0.99, resolution_x=200, resolution_y=400) +check("pick: off the surface is a miss, not an error", receipt["status"] == "accepted" and missed == {"hit": False}, missed) + + +def ink(pixels): + return np.linalg.norm(pixels - [0.1, 0.35, 0.4], axis=-1) > 0.25 + + +receipt, scrubbed = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=picked["point"][0], y=0.0, z=5.0, radius=0.5, tolerance=0.25) +after, image = pixels_of(sign) +inside = np.zeros((128, 128), dtype=bool) +inside[48:80, 20:44] = True # well within the sphere: u 0.25 +- 0.09, v 0.5 +- 0.12 +far = np.zeros((128, 128), dtype=bool) +far[:, 72:] = True # the other half of the sign +R["scrub"] = {"report": scrubbed, "inkInsideBefore": int(ink(panel)[inside].sum()), "inkInsideAfter": int(ink(after)[inside].sum())} +check("scrub_markings: accepted, the lettering inside the sphere is gone", receipt["status"] == "accepted" + and ink(panel)[inside].sum() > 100 and ink(after)[inside].sum() == 0, R["scrub"]) +check("scrub_markings: nothing outside the sphere is touched (to the 8 bits the image stores)", np.allclose(after[far], panel[far], atol=0.6 / 255) and image.name == "sign_paint.scrubbed", image.name) +receipt, _ = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=50.0, y=0.0, z=0.0, radius=0.5) +check("scrub_markings: a sphere off the surface is refused", receipt["status"] == "failed", receipt["message"]) +receipt, _ = send("brokkr_mesh_polish.delight", object_name="Sign", max_gain=9) +check("a bound miss is denied by Brokkr's table before the operator runs", receipt["status"] == "denied", receipt["message"]) + +R["ok"] = all(c["ok"] for c in R["checks"]) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") +for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/mesh_polish.result.json b/surfaces/blender/tests/live/mesh_polish.result.json new file mode 100644 index 0000000..9f3bae1 --- /dev/null +++ b/surfaces/blender/tests/live/mesh_polish.result.json @@ -0,0 +1,471 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "host file admitted", + "ok": true, + "detail": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick" + ] + }, + { + "name": "audit: accepted, no undo step", + "ok": true, + "detail": "Operator brokkr_mesh_polish.audit finished." + }, + { + "name": "audit: welded topology sees one closed shell in the torn sphere", + "ok": true, + "detail": { + "triangles": 2208, + "vertices": 4512, + "weldedVertices": 1106, + "extent": [ + 2.000001, + 2.000002, + 2.0 + ], + "surfaceArea": 12.521572614010894, + "degenerateTriangles": 0, + "edges": 3312, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 0, + "shells": 1, + "shellTriangles": [ + 2208 + ], + "uvIslands": 1, + "uvFlippedTriangles": 0, + "uvZeroAreaTriangles": 0, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 0.95831298828125, + "uvOverlap": 0.0, + "texelDensityMedian": 61.97425923665604, + "texelDensityP5": 57.66165269744736, + "texelDensityP95": 113.44982327717632, + "texelDensitySpread": 1.9675090457856172, + "baseColorImage": "ball_bake", + "baseColorSize": [ + 256, + 256 + ], + "customNormals": false + } + }, + { + "name": "audit: texture and UV facts", + "ok": true, + "detail": { + "triangles": 2208, + "vertices": 4512, + "weldedVertices": 1106, + "extent": [ + 2.000001, + 2.000002, + 2.0 + ], + "surfaceArea": 12.521572614010894, + "degenerateTriangles": 0, + "edges": 3312, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 0, + "shells": 1, + "shellTriangles": [ + 2208 + ], + "uvIslands": 1, + "uvFlippedTriangles": 0, + "uvZeroAreaTriangles": 0, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 0.95831298828125, + "uvOverlap": 0.0, + "texelDensityMedian": 61.97425923665604, + "texelDensityP5": 57.66165269744736, + "texelDensityP95": 113.44982327717632, + "texelDensitySpread": 1.9675090457856172, + "baseColorImage": "ball_bake", + "baseColorSize": [ + 256, + 256 + ], + "customNormals": false + } + }, + { + "name": "repair: accepted as one undo step", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-2", + "action": "brokkr_mesh_polish.repair", + "status": "accepted", + "message": "Operator brokkr_mesh_polish.repair finished.", + "objectName": "", + "requestedBy": "test/driver", + "note": "", + "undoLabel": "Brokkr test/driver: brokkr_mesh_polish.repair live-2", + "lookPath": "", + "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1}}", + "observedAt": "2026-12-01T00:06:45.524772+00:00" + } + }, + { + "name": "repair: welds the torn vertices", + "ok": true, + "detail": { + "object": "Ball", + "changes": { + "welded": 3406, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0 + }, + "before": { + "triangles": 2208, + "vertices": 4512, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1 + }, + "after": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1 + } + } + }, + { + "name": "repair: every edge has two faces again", + "ok": true, + "detail": 2256 + }, + { + "name": "delight: accepted, new packed image on the material", + "ok": true, + "detail": "Operator brokkr_mesh_polish.delight finished." + }, + { + "name": "delight: finds the baked light", + "ok": true, + "detail": { + "image": "ball_bake", + "newImage": "ball_bake.delit", + "objects": [ + "Ball" + ], + "explainedByLight": { + "before": 0.9722586649734903, + "after": 0.005096664890544278 + }, + "before": { + "upDownLuminanceRatio": 2.5686425388668988, + "occlusionCorrelation": 0.0 + }, + "after": { + "upDownLuminanceRatio": 1.0190418174045521, + "occlusionCorrelation": 0.0 + }, + "gain": { + "min": 0.9849698054726783, + "median": 1.454503966956526, + "max": 3.0, + "clamped": 0.05147808358817533 + } + } + }, + { + "name": "delight: levels top against bottom", + "ok": true, + "detail": [ + 3.2905027932960893, + 1.119760513305664 + ] + }, + { + "name": "orient: long on Y, thin on Z, scaled to the length, centred", + "ok": true, + "detail": [ + [ + 4.0, + 12.0, + 2.000000476837158 + ], + { + "objects": [ + "Slab" + ], + "scale": 4.000000308302869, + "extent": [ + 4.0, + 12.0, + 2.0 + ], + "mirrorError": { + "X": 7.4458642458520986e-09, + "Y": 7.225481440456122e-09, + "Z": 1.962464589014781e-09 + } + } + ] + }, + { + "name": "orient: reports the mirror error of a symmetric body as small", + "ok": true, + "detail": { + "X": 7.4458642458520986e-09, + "Y": 7.225481440456122e-09, + "Z": 1.962464589014781e-09 + } + }, + { + "name": "cut fixture is one closed skin", + "ok": true, + "detail": { + "triangles": 28, + "vertices": 16, + "weldedVertices": 16, + "extent": [ + 2.0, + 2.0, + 3.0 + ], + "surfaceArea": 28.605887413024902, + "degenerateTriangles": 0, + "edges": 42, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 0, + "shells": 1, + "shellTriangles": [ + 28 + ], + "uvIslands": 1, + "uvFlippedTriangles": 0, + "uvZeroAreaTriangles": 28, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 0.0, + "uvOverlap": 0.0, + "baseColorImage": "", + "baseColorSize": [ + 0, + 0 + ], + "customNormals": false + } + }, + { + "name": "cut_parts: accepted, one undo step, the fused object is replaced", + "ok": true, + "detail": "Operator brokkr_mesh_polish.cut_parts finished." + }, + { + "name": "cut_parts: the knob is cut at the crease and rooted at the centre of the cut", + "ok": true, + "detail": { + "name": "Block.knob", + "triangles": 12, + "capTriangles": 2, + "cutEdges": 4, + "root": [ + 0.0, + 0.0, + 1.0 + ], + "cutNormal": [ + 0.0, + 0.0, + 1.0 + ], + "cutRadius": 0.5757359266281128, + "joint": "Block.knob.joint" + } + }, + { + "name": "cut_parts: the knob hangs from the body and has not moved", + "ok": true, + "detail": null + }, + { + "name": "cut_parts: both sides of the cut are capped (closed shells)", + "ok": true, + "detail": { + "Block.body": [ + 0, + 1 + ], + "Block.knob": [ + 0, + 1 + ] + } + }, + { + "name": "cut_parts: caps carry the cap material and a joint sits at the root", + "ok": true, + "detail": "Block.knob.joint" + }, + { + "name": "cut_parts: one part is refused with nothing changed", + "ok": true, + "detail": "Error: Cutting needs seeds for at least two parts." + }, + { + "name": "pick: names the surface point under (u, v) of a picture of that shape", + "ok": true, + "detail": { + "hit": true, + "object": "Sign", + "point": [ + -1.0, + 0.0, + 5.0 + ], + "normal": [ + 0.0, + 0.0, + 1.0 + ] + } + }, + { + "name": "pick: off the surface is a miss, not an error", + "ok": true, + "detail": { + "hit": false + } + }, + { + "name": "scrub_markings: accepted, the lettering inside the sphere is gone", + "ok": true, + "detail": { + "report": { + "object": "Sign", + "image": "sign_paint", + "newImage": "sign_paint.scrubbed", + "regionTexels": 1612, + "scrubbedTexels": 1130 + }, + "inkInsideBefore": 192, + "inkInsideAfter": 0 + } + }, + { + "name": "scrub_markings: nothing outside the sphere is touched (to the 8 bits the image stores)", + "ok": true, + "detail": "sign_paint.scrubbed" + }, + { + "name": "scrub_markings: a sphere off the surface is refused", + "ok": true, + "detail": "Error: No surface lies inside the sphere." + }, + { + "name": "a bound miss is denied by Brokkr's table before the operator runs", + "ok": true, + "detail": "max_gain must be between 1 and 8." + } + ], + "hostErrors": [], + "hostRows": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick" + ], + "delight": { + "report": { + "image": "ball_bake", + "newImage": "ball_bake.delit", + "objects": [ + "Ball" + ], + "explainedByLight": { + "before": 0.9722586649734903, + "after": 0.005096664890544278 + }, + "before": { + "upDownLuminanceRatio": 2.5686425388668988, + "occlusionCorrelation": 0.0 + }, + "after": { + "upDownLuminanceRatio": 1.0190418174045521, + "occlusionCorrelation": 0.0 + }, + "gain": { + "min": 0.9849698054726783, + "median": 1.454503966956526, + "max": 3.0, + "clamped": 0.05147808358817533 + } + }, + "ratioBefore": 3.2905027932960893, + "ratioAfter": 1.119760513305664 + }, + "cut": { + "body": "Block.body", + "parts": [ + { + "name": "Block.body", + "triangles": 20, + "capTriangles": 2, + "cutEdges": 4, + "root": [ + 0.0, + 0.0, + 0.0 + ], + "cutNormal": [ + 0.0, + 0.0, + 1.0 + ], + "cutRadius": 0.5757359266281128 + }, + { + "name": "Block.knob", + "triangles": 12, + "capTriangles": 2, + "cutEdges": 4, + "root": [ + 0.0, + 0.0, + 1.0 + ], + "cutNormal": [ + 0.0, + 0.0, + 1.0 + ], + "cutRadius": 0.5757359266281128, + "joint": "Block.knob.joint" + } + ] + }, + "scrub": { + "report": { + "object": "Sign", + "image": "sign_paint", + "newImage": "sign_paint.scrubbed", + "regionTexels": 1612, + "scrubbedTexels": 1130 + }, + "inkInsideBefore": 192, + "inkInsideAfter": 0 + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_mesh_polish.py b/surfaces/blender/tests/test_mesh_polish.py new file mode 100644 index 0000000..7205f81 --- /dev/null +++ b/surfaces/blender/tests/test_mesh_polish.py @@ -0,0 +1,390 @@ +"""Mesh polish tests. No Blender: the arithmetic in brokkr_mesh_polish/core.py on small hand-built meshes and +textures, the host action file against Brokkr's own checker, and the turntable recipe against the action table. + +Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) +The operators around this arithmetic are exercised in a real Blender by tests/live/mesh_polish.py. + +Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped reading +and the reading of the nearest mutant named beside it, and both are at least 1.2 away. +""" +from __future__ import annotations + +import importlib.util +import json +import math +import sys +import types +import unittest +from pathlib import Path + +SURFACE = Path(__file__).resolve().parents[1] +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules.setdefault("brokkr_bridge", package) +from brokkr_bridge import action_table as at # noqa: E402 + +try: + import numpy as np +except ImportError: # pragma: no cover + np = None + + +def load(name: str, path: Path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +turntable = load("turntable_recipe", SURFACE / "tools" / "turntable_recipe.py") +core = load("brokkr_mesh_polish_core", SURFACE / "brokkr_mesh_polish" / "core.py") if np is not None else None + + +def quad_strip(count: int, fold_after: int | None = None): + """count unit quads along x as 2 * count triangles, every triangle with its own three vertices (as a glTF + import leaves a seamed mesh). After fold_after quads the strip turns straight up: a 90 degree concave fold + seen from above.""" + V, T = [], [] + for i in range(count): + def at_station(s): + if fold_after is None or s <= fold_after: + return (float(s), 0.0) + return (float(fold_after), float(s - fold_after)) + (x0, z0), (x1, z1) = at_station(i), at_station(i + 1) + corners = [(x0, 0.0, z0), (x1, 0.0, z1), (x1, 1.0, z1), (x0, 1.0, z0)] + for tri in ((0, 1, 2), (0, 2, 3)): + T.append([len(V), len(V) + 1, len(V) + 2]) + V.extend(corners[k] for k in tri) + return np.array(V, dtype=float), np.array(T, dtype=np.int64) + + +@unittest.skipIf(np is None, "numpy is not installed") +class TopologyTests(unittest.TestCase): + def test_weld_joins_split_vertices_so_only_the_rim_is_open(self): + V, T = quad_strip(3) + _, TW = core.weld(V, T, 1e-6) + census = core.edge_census(TW) + self.assertEqual(census["boundaryEdges"], 8) # the rim of a 3 x 1 strip; unwelded, all 18 edges are open + self.assertEqual(census["nonManifoldEdges"], 0) + self.assertEqual(len(np.unique(core.triangle_components(TW))), 1) + + def test_three_triangles_on_one_edge_are_non_manifold(self): + V = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1]], dtype=float) + T = np.array([[0, 1, 2], [0, 1, 3], [0, 1, 4]]) + self.assertEqual(core.edge_census(T)["nonManifoldEdges"], 1) + report = core.audit(V, T, None) + self.assertEqual((report["nonManifoldEdges"], report["shells"], report["triangles"]), (1, 1, 3)) + + def test_separate_pieces_are_separate_shells(self): + V, T = quad_strip(2) + V2 = np.concatenate([V, V + [0, 5, 0]]) + T2 = np.concatenate([T, T + len(V)]) + report = core.audit(V2, T2, None) + self.assertEqual(report["shells"], 2) + self.assertEqual(report["shellTriangles"], [4, 4]) + + def test_components_follow_long_chains(self): + pairs = np.array([[i, i + 1] for i in range(999)]) + self.assertEqual(len(np.unique(core.components(1000, pairs[::-1]))), 1) + self.assertEqual(len(np.unique(core.components(1000, pairs[:500]))), 500) + + +@unittest.skipIf(np is None, "numpy is not installed") +class UvTests(unittest.TestCase): + SQUARE_V = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], dtype=float) + SQUARE_T = np.array([[0, 1, 2], [0, 2, 3]]) + SQUARE_UV = np.array([[[0, 0], [1, 0], [1, 1]], [[0, 0], [1, 1], [0, 1]]], dtype=float) + + def test_a_square_filling_the_texture_has_full_coverage_no_overlap_and_density_of_the_texture_size(self): + report = core.audit(self.SQUARE_V, self.SQUARE_T, self.SQUARE_UV, texture_size=1024, raster=128) + self.assertAlmostEqual(report["uvCoverage"], 1.0, places=2) + self.assertLess(report["uvOverlap"], 0.02) # only texel centres exactly on the shared diagonal + self.assertAlmostEqual(report["texelDensityMedian"], 1024.0, places=3) + self.assertAlmostEqual(report["texelDensitySpread"], 1.0, places=6) + self.assertEqual((report["uvIslands"], report["uvFlippedTriangles"]), (1, 0)) + + def test_two_triangles_on_the_same_texels_overlap(self): + stacked = np.array([self.SQUARE_UV[0], self.SQUARE_UV[0]]) + report = core.audit(self.SQUARE_V, self.SQUARE_T, stacked, texture_size=1024, raster=128) + self.assertGreater(report["uvOverlap"], 0.98) + + def test_a_mirrored_island_counts_as_flipped_and_half_the_area_doubles_nothing_but_density(self): + mirrored = self.SQUARE_UV.copy() + mirrored[..., 0] = 1 - mirrored[..., 0] + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64)["uvFlippedTriangles"], 2) + half = core.audit(self.SQUARE_V, self.SQUARE_T, self.SQUARE_UV * 0.5, 1024, raster=64) + self.assertAlmostEqual(half["texelDensityMedian"], 512.0, places=3) + self.assertAlmostEqual(half["uvCoverage"], 0.25, places=2) + + def test_rasterize_gives_each_texel_its_triangle_and_weights(self): + owner, bary, cover = core.rasterize(self.SQUARE_UV, 8) + self.assertEqual(owner[0, 7], 0) # low v, high u: the first triangle + self.assertEqual(owner[7, 0], 1) + self.assertTrue(np.allclose(bary.sum(axis=2)[owner >= 0], 1.0, atol=1e-5)) + position = core.interpolate(owner, bary, self.SQUARE_V[self.SQUARE_T]) + self.assertTrue(np.allclose(position[2, 5, :2], [(5 + 0.5) / 8, (2 + 0.5) / 8], atol=1e-5)) + + +@unittest.skipIf(np is None, "numpy is not installed") +class OrientTests(unittest.TestCase): + def test_principal_frame_puts_the_long_side_on_x_and_the_thin_side_on_z(self): + V, T = quad_strip(6) # 6 x 1 x 0 + turn = np.array([[0.36, 0.48, -0.8], [-0.8, 0.6, 0.0], [0.48, 0.64, 0.6]]) # a rotation + centre, R = core.principal_frame(V @ turn.T + [3, -2, 5], T) + local = (V @ turn.T + [3, -2, 5] - centre) @ R.T + extent = local.max(axis=0) - local.min(axis=0) + # the diagonal split of each quad skews the area-weighted axes by under a degree + self.assertTrue(np.allclose(extent, [6, 1, 0], atol=0.08)) + self.assertLess(extent[2], 1e-9) + self.assertAlmostEqual(float(np.linalg.det(R)), 1.0, places=9) + + def test_mirror_error_tells_a_symmetric_cloud_from_a_lopsided_one(self): + rng = np.random.default_rng(1) + half = rng.random((400, 3)) + symmetric = np.concatenate([half, half * [-1, 1, 1]]) + lopsided = np.concatenate([half, half * [-0.3, 1, 1] - [0.4, 0, 0]]) + shipped, mutant = core.mirror_error(symmetric, 0), core.mirror_error(lopsided, 0) + # shipped 0.0 exactly (every mirrored sample is itself a point); the lopsided cloud reads 0.0426 + self.assertEqual(shipped, 0.0) + self.assertGreater(mutant, 0.0426 / 1.2) + + +@unittest.skipIf(np is None, "numpy is not installed") +class PartTests(unittest.TestCase): + def grown(self, crease_cost: float): + V, T = quad_strip(10, fold_after=7) + _, TW = core.weld(V, T, 1e-6) + pairs = core.face_adjacency(TW) + costs = core.crease_costs(V, T, pairs, crease_cost) + part, cost = core.grow_parts(len(T), pairs, costs, [(0, 0), (len(T) - 1, 1)]) + return part, cost + + def test_parts_stop_at_a_sharp_concave_crease(self): + part, _ = self.grown(40.0) + self.assertEqual(part.tolist(), [0] * 14 + [1] * 6) # the fold is after quad 7: 14 triangles before it + + def test_without_crease_cost_parts_split_by_distance_alone(self): + part, _ = self.grown(0.0) + self.assertEqual(part.tolist(), [0] * 10 + [1] * 10) + + def test_a_convex_fold_costs_nothing(self): + V, T = quad_strip(10, fold_after=7) + V[:, 2] *= -1 # the same strip folded down, normals unchanged: convex seen from the side they face + _, TW = core.weld(V, T, 1e-6) + pairs = core.face_adjacency(TW) + part, _ = core.grow_parts(len(T), pairs, core.crease_costs(V, T, pairs, 40.0), [(0, 0), (len(T) - 1, 1)]) + self.assertEqual(int((part == 0).sum()), 10) + + def test_a_bowl_of_gentle_folds_costs_far_less_than_one_sharp_crease_of_the_same_turn(self): + def crease_total(turns): # a strip of quads that turns upward by these degrees after each quad + V, T, x, z, heading = [], [], 0.0, 0.0, 0.0 + for turn in [0.0] + turns: + heading += math.radians(turn) + x1, z1 = x + math.cos(heading), z + math.sin(heading) + corners = [(x, 0.0, z), (x1, 0.0, z1), (x1, 1.0, z1), (x, 1.0, z)] + for tri in ((0, 1, 2), (0, 2, 3)): + T.append([len(V), len(V) + 1, len(V) + 2]) + V.extend(corners[k] for k in tri) + x, z = x1, z1 + V, T = np.array(V), np.array(T, dtype=np.int64) + _, TW = core.weld(V, T, 1e-6) + pairs = core.face_adjacency(TW) + return float((core.crease_costs(V, T, pairs, 1.0) - core.crease_costs(V, T, pairs, 0.0)).sum()) + + sharp, gentle = crease_total([90.0]), crease_total([10.0] * 9) + # shipped ratio 9.0 (the square: 0.5 ** 2 against 9 * (1 / 18) ** 2); a cost linear in the fold reads 1.0. Bound 3. + self.assertGreater(sharp / gentle, 3.0 * 1.2) + self.assertAlmostEqual(sharp, 0.25, places=9) + + def test_unseeded_shells_are_unreached_and_several_seeds_may_name_one_part(self): + V, T = quad_strip(2) + V2, T2 = np.concatenate([V, V + [0, 5, 0]]), np.concatenate([T, T + len(V)]) + _, TW = core.weld(V2, T2, 1e-6) + pairs = core.face_adjacency(TW) + part, cost = core.grow_parts(len(T2), pairs, core.crease_costs(V2, T2, pairs, 1.0), [(0, 0), (3, 0)]) + self.assertEqual(part.tolist(), [0, 0, 0, 0, -1, -1, -1, -1]) + self.assertTrue(np.isinf(cost[4:]).all()) + + def test_seed_text(self): + self.assertEqual(core.parse_seeds("hull=0,0,0; pod 1=1,-2.5,3e-1;"), [("hull", (0.0, 0.0, 0.0)), ("pod 1", (1.0, -2.5, 0.3))]) + for bad in ("", "hull", "hull=1,2", "=1,2,3", "hull=a,b,c"): + with self.assertRaises(ValueError): + core.parse_seeds(bad) + + +@unittest.skipIf(np is None, "numpy is not installed") +class DelightTests(unittest.TestCase): + """A synthetic bake: 40000 surface samples, pale paint with a tenth of it dark machinery (same hue), lit by + a sky brighter above than below and dimmed by occlusion.""" + + def setUp(self): + rng = np.random.default_rng(7) + count = 40000 + normals = rng.normal(size=(count, 3)) + self.normals = normals / np.linalg.norm(normals, axis=1, keepdims=True) + self.occlusion = rng.uniform(0.1, 1.0, count) + self.light = (0.55 + 0.45 * self.normals[:, 2]) * self.occlusion ** 0.7 + 0.05 + self.paint = np.where(rng.random(count) < 0.1, 0.08, 0.8) + self.rgb = (self.paint * self.light)[:, None] * np.array([1.0, 0.97, 0.9]) + self.basis = core.shading_basis(self.normals, self.occlusion) + self.log_l = np.log(core.luminance(self.rgb) + 1e-4) + self.clusters = core.chroma_clusters(self.rgb, 1) + + def delit(self, weights): + gain = core.delight_gain(self.basis, weights, 1.0, 8.0) + return np.log(core.luminance(self.rgb * gain[:, None]) + 1e-4) + + def test_the_fit_finds_the_light_and_dividing_it_out_levels_up_and_down(self): + weights, explained = core.fit_shading(self.log_l, self.basis, self.clusters) + before = core.lighting_signature(self.log_l, self.normals, self.occlusion) + after = core.lighting_signature(self.delit(weights), self.normals, self.occlusion) + self.assertGreater(explained, 0.2) + # up/down ratio: shipped 1.029; with no correction (a gain of 1) 3.323. Bound sqrt(1.029 * 3.323) = 1.849. + self.assertGreater(before["upDownLuminanceRatio"], 1.849 * 1.2) + self.assertLess(after["upDownLuminanceRatio"], 1.849 / 1.2) + # occlusion correlation: shipped 0.0032; uncorrected 0.356. Bound sqrt(0.0032 * 0.356) = 0.0337. + self.assertGreater(before["occlusionCorrelation"], 0.0337 * 1.2) + self.assertLess(abs(after["occlusionCorrelation"]), 0.0337 / 1.2) + + def test_dark_paint_in_crevices_is_not_read_as_shadow(self): + # All the dark machinery sits in the occluded third. A mean fit (expectile 0.5) reads it as shadow and + # overstates the occlusion weight; the envelope fit follows the pale paint. + crevice = self.occlusion < 0.4 + paint = np.where(crevice & (np.random.default_rng(3).random(len(crevice)) < 0.6), 0.08, 0.8) + rgb = (paint * self.light)[:, None] * np.array([1.0, 0.97, 0.9]) + log_l = np.log(core.luminance(rgb) + 1e-4) + true_weight = 0.7 # light ~ occlusion ** 0.7, up to the small ambient floor + envelope, _ = core.fit_shading(log_l, self.basis, self.clusters) + mean, _ = core.fit_shading(log_l, self.basis, self.clusters, expectile=0.5) + # occlusion weight: shipped 0.921, mean-fit mutant 1.502. Bound sqrt(0.921 * 1.502) = 1.176. + self.assertLess(envelope[-1], 1.176 / 1.2) + self.assertGreater(mean[-1], 1.176 * 1.2) + self.assertGreater(envelope[-1], true_weight * 0.8) + + def test_gain_leaves_the_lit_side_alone_and_respects_the_limit(self): + weights, _ = core.fit_shading(self.log_l, self.basis, self.clusters) + gain = core.delight_gain(self.basis, weights, 1.0, 3.0) + self.assertLessEqual(float(gain.max()), 3.0) + self.assertGreaterEqual(float(gain.min()), 1 / 3.0 - 1e-12) + light = self.basis @ weights + reference = np.abs(light - np.percentile(light, 90)) < 0.01 # the surface the light favoured + self.assertTrue(np.allclose(gain[reference], 1.0, atol=0.011)) + self.assertGreater(float(np.median(gain[self.occlusion < 0.3])), 1.5) # shaded surface is raised + self.assertTrue(np.allclose(core.delight_gain(self.basis, weights, 0.0, 3.0), 1.0)) + + def test_flat_paint_shows_no_light(self): + flat = np.tile([0.5, 0.4, 0.3], (len(self.normals), 1)) * np.random.default_rng(5).uniform(0.9, 1.1, (len(self.normals), 1)) + _, explained = core.fit_shading(np.log(core.luminance(flat)), self.basis, core.chroma_clusters(flat, 1)) + self.assertLess(explained, 0.01) + + def test_chroma_clusters_ignore_brightness(self): + teal, yellow = np.array([0.1, 0.4, 0.45]), np.array([0.8, 0.7, 0.1]) + shade = np.random.default_rng(2).uniform(0.1, 1.0, (200, 1)) + labels = core.chroma_clusters(np.concatenate([teal * shade, yellow * shade]), 2) + self.assertEqual(len(set(labels[:200])), 1) + self.assertEqual(len(set(labels[200:])), 1) + self.assertNotEqual(labels[0], labels[200]) + + def test_srgb_round_trip(self): + values = np.linspace(0, 1, 101) + self.assertTrue(np.allclose(core.linear_to_srgb(core.srgb_to_linear(values)), values, atol=1e-6)) + + +@unittest.skipIf(np is None, "numpy is not installed") +class TextureFillTests(unittest.TestCase): + def test_push_pull_fills_a_hole_from_its_surroundings_and_keeps_known_texels(self): + image = np.zeros((32, 32, 3), dtype=np.float32) + image[:, :16] = [0.2, 0.4, 0.6] + image[:, 16:] = [0.6, 0.4, 0.2] + known = np.ones((32, 32), dtype=bool) + known[10:20, 2:10] = False + holed = image.copy() + holed[~known] = 9.0 + filled = core.push_pull(holed, known) + self.assertTrue(np.array_equal(filled[known], image[known])) + self.assertTrue(np.allclose(filled[12:18, 3:8], [0.2, 0.4, 0.6], atol=0.05)) + + def test_push_pull_without_a_hole_or_without_anything_known_returns_the_image(self): + image = np.random.default_rng(0).random((8, 8, 3)).astype(np.float32) + self.assertTrue(np.array_equal(core.push_pull(image, np.ones((8, 8), dtype=bool)), image)) + self.assertTrue(np.array_equal(core.push_pull(image, np.zeros((8, 8), dtype=bool)), image)) + + def test_marking_mask_takes_the_ink_and_leaves_the_panel(self): + panel = np.full((40, 40, 3), [0.1, 0.35, 0.4], dtype=np.float32) + panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32) + panel[18:22, 8:30] = [0.85, 0.75, 0.2] # a stroke of yellow lettering + region = np.zeros((40, 40), dtype=bool) + region[5:35, 5:35] = True + mask = core.marking_mask(panel, region, 0.25, 1) + self.assertTrue(mask[18:22, 8:30].all()) + self.assertEqual(int(mask.sum()), 4 * 22 + 2 * 22 + 2 * 4) # the stroke grown by one texel edgewise, nothing else + outside = np.zeros((40, 40), dtype=bool) + self.assertFalse(core.marking_mask(panel, outside, 0.25, 1).any()) + + def test_box_blur_keeps_a_flat_field_and_spreads_a_point(self): + flat = np.full((9, 9), 0.5) + self.assertTrue(np.allclose(core.box_blur(flat, 2), 0.5)) + point = np.zeros((9, 9)) + point[4, 4] = 1.0 + blurred = core.box_blur(point, 1) + self.assertTrue(np.allclose(blurred[3:6, 3:6], 1 / 9)) + self.assertAlmostEqual(float(blurred.sum()), 1.0, places=9) + + +class HostFileTests(unittest.TestCase): + """brokkr_actions.json is the add-on's whole contract with Brokkr: it must pass Brokkr's own checker.""" + + def setUp(self): + self.document = json.loads((SURFACE / "brokkr_mesh_polish" / "brokkr_actions.json").read_text(encoding="utf-8")) + + def test_brokkr_admits_the_file(self): + at.check_host(self.document, at.table()["charsets"]) + + def test_every_row_names_an_operator_and_property_the_add_on_defines(self): + source = (SURFACE / "brokkr_mesh_polish" / "__init__.py").read_text(encoding="utf-8") + for row in self.document["actions"]: + self.assertIn(f'bl_idname = "{row["name"]}"', source) + self.assertEqual(row.get("result"), "brokkr_mesh_polish_result") + body = source.split(f'bl_idname = "{row["name"]}"')[1].split("def work")[0] + for field in row["fields"]: + self.assertIn(f" {field['name']}: bpy.props.", body, f"{row['name']}.{field['name']}") + + def test_a_valid_intent_is_admitted_and_a_bound_miss_is_refused(self): + host = [{**row, "host": "brokkr_mesh_polish"} for row in self.document["actions"]] + envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver"} + admitted = at.validate({**envelope, "action": "brokkr_mesh_polish.delight", "object_name": "Hull"}, host) + self.assertEqual(admitted["object_name"], "Hull") + with self.assertRaises(at.IntentInvalid): + at.validate({**envelope, "action": "brokkr_mesh_polish.delight", "object_name": "Hull", "max_gain": 9}, host) + with self.assertRaises(at.IntentInvalid): + at.validate({**envelope, "action": "brokkr_mesh_polish.cut_parts", "object_name": "Hull"}, host) # seeds required + + +class TurntableRecipeTests(unittest.TestCase): + def test_every_pose_looks_at_the_origin_with_z_up(self): + for azimuth in (0, 45, 90, 200, 315): + for elevation in (-90, -30, 0, 25, 90): + location, (rx, _, rz) = turntable.camera_pose(azimuth, elevation, 5.0) + forward = (-math.sin(rx) * math.sin(rz), math.sin(rx) * math.cos(rz), -math.cos(rx)) # camera -Z after XYZ Euler (rx, 0, rz) + for axis in range(3): + self.assertAlmostEqual(forward[axis], -location[axis] / 5.0, places=9) + + def test_every_intent_of_a_recipe_is_admitted_by_the_action_table(self): + for look in ("lit", "flat"): + recipe = turntable.recipe("ship.blend", "out", "ship", 0.7, 8, 25.0, 512, "BLENDER_EEVEE", look, "nibu/hands") + renders = [i for i in recipe["intents"] if i["action"] == "renderStill"] + self.assertEqual(len(renders), 10) # eight around, top, bottom + self.assertEqual(len({i["outputPath"] for i in renders}), 10) + for index, intent in enumerate(recipe["intents"]): + at.validate({"schema": "brokkr.blender.command_intent.v0", "commandId": f"t-{index}", + "requestedBy": recipe["requestedBy"], **intent}, []) + + def test_two_recipes_with_the_same_numbers_frame_identically(self): + a = turntable.recipe("a.blend", "out", "a", 0.7, 4, 25.0, 512, "CYCLES", "lit", "nibu/hands") + b = turntable.recipe("b.blend", "out", "b", 0.7, 4, 25.0, 512, "CYCLES", "lit", "nibu/hands") + moves = lambda r: [i for i in r["intents"] if i["action"] in ("setObjectTransform", "setCamera")] + self.assertEqual(moves(a), moves(b)) + + +if __name__ == "__main__": + unittest.main() From 0921bec89babe7ebb75e10ebf3235130b890a05b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 01:08:05 +0100 Subject: [PATCH 059/223] docs: mesh polish actions, the headless intent runner and the turntable recipe Co-Authored-By: Claude Fable 5.2 --- README.md | 3 + surfaces/blender/docs/install.md | 3 + surfaces/blender/docs/mesh-polish.md | 172 +++++++++++++++++++++++++++ 3 files changed, 178 insertions(+) create mode 100644 surfaces/blender/docs/mesh-polish.md diff --git a/README.md b/README.md index e0be8d0..90f7c57 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,9 @@ broker. - `surfaces/blender/brokkr_bridge`: Blender add-on target backed by CultLib's Python CultMesh node/server, with an optional debug export probes. +- `surfaces/blender/brokkr_mesh_polish`: Blender host add-on that measures and polishes generated meshes + (audit, repair, orient, delight, scrub markings, cut parts), agent-callable through Brokkr's host actions; + `surfaces/blender/tools` runs intent recipes in a background Blender (`surfaces/blender/docs/mesh-polish.md`). - `brokkr-command`: .NET CLI that writes one Unity command intent through the project's directory store and reports the editor's receipt (`docs/provider-contract.md`). - `brokkr-daemon`: Rust CLI that emits Brokkr's provider advertisement and diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 9ef449e..2659f4d 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -290,6 +290,9 @@ with nothing pushed; an argument Blender will not convert, or an `ERROR` report agent turn clears that WindowManager property before the call and copies it, up to 16000 characters and then `[truncated]`, into the receipt's `hostResult` (empty for every other action). +`surfaces/blender/brokkr_mesh_polish` is a host add-on that ships with Brokkr (`mesh-polish.md`), and +`surfaces/blender/tools/run_intents.py` runs a list of intents, host rows included, in a background Blender. + The admitted rows are published in the host snapshot as `hostActions` (each with its `host` module). `brokkr-ctl blender send --help --store ` lists them after the built-ins, `send` refuses an intent they refuse before writing anything, and the add-on still decides. Human-only is absence: an operator only a diff --git a/surfaces/blender/docs/mesh-polish.md b/surfaces/blender/docs/mesh-polish.md new file mode 100644 index 0000000..93b8fac --- /dev/null +++ b/surfaces/blender/docs/mesh-polish.md @@ -0,0 +1,172 @@ +# Mesh polish for generated meshes + +`surfaces/blender/brokkr_mesh_polish` is a Blender add-on that measures and polishes meshes made by image-to-3D +generators (Tripo and its kin): one fused or many-shelled skin, vertices split at every UV seam, an arbitrary +orientation, a unit-cube scale, and a base colour texture with the concept render's lighting and lettering baked in. + +It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"): it imports nothing from Brokkr, and +`brokkr_actions.json` beside its `__init__.py` lists the operators agents may run. Every field, type, bound and +default is in that file; `brokkr-ctl blender send --help --store ` prints it for a live session. The +arithmetic is `core.py` (numpy only) and is tested without Blender. + +Every action writes a JSON report, returned in the receipt's `hostResult`. Actions that change the scene are one +undo step each. Lengths are in scene units; points and directions are world-space. + +## Running it + +In a person's Blender: enable the add-on beside Brokkr and press `Reload Host Actions` in the Brokkr panel; the +actions then arrive as intents like any other. + +With no Blender open, `surfaces/blender/tools/run_intents.py` runs a recipe (a JSON list of intents) in a +background Blender through the same agent turn, and writes the receipts to a file: + +```text +blender --background --factory-startup --python surfaces/blender/tools/run_intents.py -- polish.json +``` + +```json +{"requestedBy": "nibu/hands", "importDir": "work", "outputDir": "work", "hostAddons": ["brokkr_mesh_polish"], + "saveBlend": "work/ship.blend", + "intents": [ + {"action": "importGltf", "filepath": "ship_tripo.glb"}, + {"action": "brokkr_mesh_polish.audit"}, + {"action": "brokkr_mesh_polish.orient", "roll_quarter_turns": 2}, + {"action": "brokkr_mesh_polish.repair", "object_name": "tripo_ab12"}, + {"action": "brokkr_mesh_polish.delight", "object_name": "tripo_ab12", "clusters": 2}, + {"action": "brokkr_mesh_polish.audit"}, + {"action": "exportGltf", "filepath": "ship_polished.glb"}]} +``` + +The runner opens no CultMesh node: receipts go to `.receipts.json` only. It is the human of its own +Blender (it enables the host add-ons, reloads host actions once, opens and saves the `.blend`), and it refuses to +start without private `BLENDER_USER_CONFIG`, `BLENDER_USER_EXTENSIONS` and `BLENDER_USER_SCRIPTS`. Its exit status is +0 when every intent was accepted, 3 when one was not, 2 when the recipe could not run. + +`surfaces/blender/tools/turntable_recipe.py` writes a recipe of Brokkr's own scene actions (`setWorld`, +`createObject`, `setCamera`, `setObjectTransform`, `renderStill`) for an orthographic turntable of a `.blend` whose +subject is centred on the origin. Two recipes with the same numbers frame two files identically, so a before and +an after compare view by view. `--look flat` lights with a uniform white world alone and shows the texture as +stored, baked shadows included; `--look lit` adds a sun. + +A polish pass that works, in order: `audit`, `orient` (render a flat turntable and pick `roll_quarter_turns` and +`flip_forward` by eye), `repair`, `delight`, then `pick` and `scrub_markings` for each patch of lettering, then +`pick` and `cut_parts` when parts must move, `audit` again, `exportGltf`. + +## Actions + +### audit + +Measures one mesh object, or every mesh in the scene. Changes nothing. Topology is counted after welding positions +within 1e-5 of the bounding diagonal, because an imported mesh is split at every UV seam and would otherwise read +as all open edges. + +- `triangles`, `vertices`, `weldedVertices`, `extent`, `surfaceArea`, `degenerateTriangles`. +- `boundaryEdges` (one triangle on the edge: an open rim), `nonManifoldEdges` (three or more), `shells` and + the triangle count of the largest twelve. +- `uvIslands`, `uvFlippedTriangles` (mirrored in UV space), `uvZeroAreaTriangles`, `uvOutsideUnitTriangles`, + `uvCoverage` (share of the texture some triangle covers) and `uvOverlap` (share of covered texels that more + than one triangle covers), both counted at texel centres on a `raster` x `raster` grid. +- `texelDensityMedian`, `P5`, `P95` (texels per unit length for the base colour texture's size, area-weighted) and + `texelDensitySpread` (P95 / P5; 1 is uniform). +- `baseColorImage`, `baseColorSize`, `customNormals`. + +### repair + +Welds coincident vertices (UVs live on face corners, so seams keep their UVs), removes degenerate faces and loose +edges and vertices, optionally deletes shells below `min_shell_area` of the surface, optionally closes holes of up +to `fill_holes_sides` edges, and makes face normals consistent. With `sharp_angle` above 0 the generator's custom +normals are dropped and shading is recomputed: smooth, hard across edges sharper than the angle. + +A filled hole has no place in the UV map: each new face takes one UV point from the old face beside it, so it shows +that texel's colour and adds no UV overlap (it counts in `uvZeroAreaTriangles`). Making normals consistent flips the +winding of shells that faced inward, which mirrors their UVs; `uvFlippedTriangles` can rise. + +Welding does not join shells that merely touch or intersect. A mesh assembled from open, interpenetrating shells +stays one: its open edges and non-manifold edges are reported, not repaired. Closing such a mesh means remeshing it +and rebaking its texture, which this add-on does not do. + +### orient + +Turns every mesh in the scene, as one rigid body, onto its area-weighted principal axes: longest on Y, shortest on +Z, centred on the origin, the longest side scaled to `length` when given. The transform is baked into the mesh data +and the objects are left unparented at identity. Principal axes do not know bow from stern or up from down: +`flip_forward` and `roll_quarter_turns` choose, and `mirrorError` in the report (per axis, 0 is a perfect mirror) +says which plane the body is symmetric across. `principal: false` keeps the current axes and applies only the +turns, the centring and the scale. + +### delight + +Undoes lighting baked into the base colour texture, as far as the surface's own shape explains it. + +For each texel the add-on knows the surface normal and the ambient occlusion there (cosine-weighted rays against +the mesh, per vertex). It fits log luminance as an intercept per hue cluster (`clusters`: how many distinct paints +the texture holds) plus a light term: the order-2 spherical harmonics of the normal and the log of occlusion. The +fit follows the upper envelope of luminance (an expectile regression at 0.85), because within one hue the +brightest paint at a given normal and occlusion shows how much light the bake put there, while darker paint in the +same place, machinery in a crevice of a pale hull, is paint. Texels darker than 4% of the texture's white point are +left out of the fit: they are fill the generator never saw. Each texel is then multiplied by the factor that undoes +the fitted light, relative to the surface the light favoured (the 90th percentile), limited to `max_gain` either +way. The result is a new packed image (`.delit`) swapped into the material; nothing is written to disk. + +The report: `explainedByLight` (share of within-hue luminance variance the light term explains, before and +after), and two model-free readings before and after, over the texels that were judged: +`upDownLuminanceRatio` (up-facing over down-facing surface, 1 is none) and `occlusionCorrelation`. `gain.clamped` +is the share of texels that hit `max_gain`. + +What it cannot do. It removes smooth, shape-following light: sky-over-ground gradients and occlusion darkening. +It does not remove cast shadows, specular highlights, or light the shape does not explain. It cannot tell dark +paint from shadow where a hue has no bright paint at all in some range of occlusion. Texels the generator filled +with black stay black: there is no colour there to recover. It raises shaded paint by gain, so 8-bit noise and +JPEG blocks in dark areas are raised with it. + +### pick + +The surface point seen at `(u, v)` of a camera's frame (`u` across, `v` up, both 0 to 1), with the object and +normal there. `resolution_x` and `resolution_y` are the size of the picture the place was read from, since the +frame's shape follows the picture's. Changes nothing. It turns "the lettering at this place in this render" into a +point that `scrub_markings` or `cut_parts` can take. + +### scrub_markings + +Paints out markings on the base colour texture inside a world-space sphere. Texels of the object's surface inside +the sphere whose colour is further than `tolerance` from the sphere's median colour are the marking; the mask is +widened by `grow` texels, filled with a smooth blend of the unmasked texels of the same region (push-pull), and +given the surrounding texture's grain. The result is a new packed image (`.scrubbed`); successive scrubs +keep one image, not a chain. + +The median colour must be the panel, not the marking: keep the sphere wide enough that lettering is the minority. +Panel lines, rivets and rust inside the sphere that differ from the panel by more than `tolerance` go with the +lettering. The fill is a blend, not a reconstruction: a faint ghost of the removed strokes can remain where the +unmasked source was thin. + +### cut_parts + +Cuts one fused skin into named parts and makes each a separate object that can move. + +`seeds` is `name=x,y,z; name=x,y,z; ...`: points on the surface, several per name allowed; the first name is the +body. Every triangle joins the seed it is cheapest to walk to, where a step costs its length (as a share of the +bounding diagonal) plus `crease_cost` times the square of how concave the fold it crosses is. Parts therefore stop +at sharp concave creases, where one part of a fused skin meets another, and split by distance where there is no +crease. `through` above 0 also seeds the far face of each part off the body, found by a ray inward from each seed +no longer than that share of the diagonal: a thin shell (a petal, a fin) is then held from both faces. + +The mesh is welded and triangulated first. Each part becomes an object `.`; both sides of every cut +are capped with faces of a dark `Polish Cap` material (pinned to one UV point each, as in `repair`); each part off +the body gets its origin at the centre of its cut and is parented to the body without moving; custom properties +`polish_cut_normal` and `polish_cut_radius` record the cut's plane and mean radius. `joint_scale` above 0 adds a +ball of that share of the cut radius at each root, parented to the body. The original object is removed. + +The report gives each part's `triangles`, `capTriangles`, `cutEdges`, `root`, `cutNormal` and `cutRadius`. + +What it cannot do. Seeds decide the parts; a seed on the wrong surface gives a wrong part. Place them from a +render with `pick`, then check where they landed before cutting (a small cube at each seed, rendered, is enough). +Cuts follow triangle edges, so on a coarse mesh they are ragged. Caps are fans across the cut and can fold over on a +cut that is far from planar; they are meant to be hidden by the neighbouring part, not shown. The root is the +centre of the cut, not a designed hinge: it is a sensible pivot to start from. + +## Tests + +- `tests/test_mesh_polish.py`: the arithmetic on hand-built meshes and textures, `brokkr_actions.json` against + Brokkr's own host-file checker, and the turntable recipe against the action table. No Blender; needs numpy. +- `tests/live/mesh_polish.py`: every action through `run_intent` in a background Blender against real bpy + (`mesh_polish.result.json` is the last run, Blender 5.3.0). From 64ffc14e0abe72c039ba99e57738a1bc06a4e0f1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 02:17:45 +0100 Subject: [PATCH 060/223] run_intents: refuse Blender user directories that are a person's own, or that Blender is not using The guard only checked that the three variables were non-empty. tools/private_dirs.py now refuses a variable set inside %APPDATA%/Blender Foundation, ~/.config/blender or the macOS folder, and a Blender whose own answer for CONFIG, EXTENSIONS or SCRIPTS is not under the variable. (Soul finding run-intents-guard-checks-non-empty, PR 22.) Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tools/private_dirs.py | 44 ++++++++++++++++++++++++++ surfaces/blender/tools/run_intents.py | 12 ++++--- 2 files changed, 51 insertions(+), 5 deletions(-) create mode 100644 surfaces/blender/tools/private_dirs.py diff --git a/surfaces/blender/tools/private_dirs.py b/surfaces/blender/tools/private_dirs.py new file mode 100644 index 0000000..014ef78 --- /dev/null +++ b/surfaces/blender/tools/private_dirs.py @@ -0,0 +1,44 @@ +"""Whether a Blender about to be driven by a script has user directories of its own. Stdlib only. + +A script that enables add-ons or saves preferences in a person's own Blender folders changes her Blender. The +three variables below point Blender at other folders; BLENDER_USER_RESOURCE_PATH does not (Blender 5.3 ignores it). +""" +from __future__ import annotations + +import os +from pathlib import Path +from typing import Callable, Mapping + +VARIABLES = {"BLENDER_USER_CONFIG": "CONFIG", "BLENDER_USER_EXTENSIONS": "EXTENSIONS", "BLENDER_USER_SCRIPTS": "SCRIPTS"} + + +def own_blender_roots(environ: Mapping[str, str], home: str) -> list[Path]: + """Where a person's own Blender keeps its folders on Windows, Linux and macOS, for this environment.""" + roots = [Path(home) / ".config" / "blender", Path(home) / "Library" / "Application Support" / "Blender"] + for variable in ("APPDATA", "XDG_CONFIG_HOME"): + if environ.get(variable): + roots.append(Path(environ[variable]) / ("Blender Foundation" if variable == "APPDATA" else "blender")) + return roots + + +def _inside(path: Path, root: Path) -> bool: + a, b = os.path.normcase(os.path.abspath(path)), os.path.normcase(os.path.abspath(root)) + return a == b or a.startswith(b + os.sep) + + +def refusal(environ: Mapping[str, str], home: str, resource: Callable[[str], str] | None = None) -> str | None: + """None when the three variables are set to folders outside every own-Blender root, and, given Blender's + own answer (resource('CONFIG') and so on, bpy.utils.user_resource), Blender is really using them; otherwise + the sentence to refuse with.""" + for variable, kind in VARIABLES.items(): + value = environ.get(variable) + if not value: + return f"{variable} is not set: run in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories" + for root in own_blender_roots(environ, home): + if _inside(Path(value), root): + return f"{variable} is {value}, inside a person's own Blender folder ({root}): point it at a scratch directory" + if resource is not None: + used = resource(kind) + if not used or not _inside(Path(used), Path(value)): + return f"Blender uses {used or 'no folder'} for {kind}, not {variable} ({value}): refusing to touch it" + return None diff --git a/surfaces/blender/tools/run_intents.py b/surfaces/blender/tools/run_intents.py index 9c06c01..eb09a64 100644 --- a/surfaces/blender/tools/run_intents.py +++ b/surfaces/blender/tools/run_intents.py @@ -8,8 +8,8 @@ rows are checked as in a live session, and each gets a receipt. No CultMesh node written to (default: the recipe's name with .receipts.json) and nowhere else, so nothing here shows in a person's Agents panel. This script is the human of its own Blender: it enables the host add-ons the recipe names, reloads host actions once, and opens and saves the .blend. It refuses to start unless -BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are set, so it never reads or writes a -person's own Blender folders (docs/install.md). +BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are set to folders outside a person's own +Blender folders and Blender is really using them (tools/private_dirs.py), so it never reads or writes hers. The recipe: @@ -41,9 +41,11 @@ def fail(message: str) -> None: def main() -> int: - for name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): - if not os.environ.get(name): - fail(f"{name} is not set: run in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") + sys.path.insert(0, str(Path(__file__).resolve().parent)) + import private_dirs + refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) + if refused: + fail(refused) arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] if not arguments: fail("usage: blender --background --factory-startup --python run_intents.py -- []") From 7de1e25e609f2ad41fae577cae33cdb7f229c93b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 02:17:45 +0100 Subject: [PATCH 061/223] brokkr_mesh_polish: repair and cut_parts turn no face; orient keeps the hierarchy; the tests pin the operators Soul falsified PR 22: repair's unconditional recalc_face_normals reversed 4,565 of 23,341 and 15,735 of 28,426 triangles on two further Tripo hulls, which a single-sided material culls. repair now leaves every winding alone; recalc_normals is opt-in and reports windingFlipped. cut_parts no longer recalculates either. Custom shading normals are carried through weld, fill and cut as plain directions and set back, new faces are shaded by their own direction, and delight reads those shading normals instead of winding-derived ones. audit: windingAgainstNormals, and uvMirroredTriangles (texture parity against the shading normals) in place of uvFlippedTriangles, which changed whenever a winding did. orient: object_name scopes it to a root and its descendants; parents and pivots are kept. cut_parts: a mesh with no material keeps a bare first slot, so only caps take the cap material. Tests: 13 more unit tests and 18 more live checks (43 with BROKKR_POLISH_HULLS). The live sphere is now torn, half inside out under outward custom normals. Soul's 26 mutants and 11 of this batch's own all die. Co-Authored-By: Claude Fable 5.2 --- .../blender/brokkr_mesh_polish/__init__.py | 148 ++++- .../brokkr_mesh_polish/brokkr_actions.json | 6 +- surfaces/blender/brokkr_mesh_polish/core.py | 20 +- surfaces/blender/tests/live/mesh_polish.py | 259 +++++++- .../tests/live/mesh_polish.result.json | 585 ++++++++++++++++-- surfaces/blender/tests/test_mesh_polish.py | 115 +++- 6 files changed, 1017 insertions(+), 116 deletions(-) diff --git a/surfaces/blender/brokkr_mesh_polish/__init__.py b/surfaces/blender/brokkr_mesh_polish/__init__.py index af1916c..473550d 100644 --- a/surfaces/blender/brokkr_mesh_polish/__init__.py +++ b/surfaces/blender/brokkr_mesh_polish/__init__.py @@ -45,15 +45,17 @@ def mesh_objects(name: str) -> list: def arrays(obj) -> dict: - """World-space triangle arrays of a mesh object: V, T, UV (per corner, or None), N (vertex normals), - polygon (the polygon each triangle came from).""" + """World-space triangle arrays of a mesh object: V, T, UV (per corner, or None), CN (per corner, the + normals the mesh is shaded with: its custom normals when it has them), N (per vertex, the mean of its + corners' CN) and polygon (the polygon each triangle came from). The normals never come from the winding + alone when the mesh carries custom normals, so a shell wound inside out still reads as it is drawn.""" mesh = obj.data mesh.calc_loop_triangles() count = len(mesh.loop_triangles) V = np.empty(len(mesh.vertices) * 3, dtype=np.float32) mesh.vertices.foreach_get("co", V) - N = np.empty(len(mesh.vertices) * 3, dtype=np.float32) - mesh.vertex_normals.foreach_get("vector", N) + corner = np.empty(len(mesh.loops) * 3, dtype=np.float32) + mesh.corner_normals.foreach_get("vector", corner) T = np.empty(count * 3, dtype=np.int32) mesh.loop_triangles.foreach_get("vertices", T) L = np.empty(count * 3, dtype=np.int32) @@ -62,14 +64,18 @@ def arrays(obj) -> dict: mesh.loop_triangles.foreach_get("polygon_index", P) world = np.array(obj.matrix_world, dtype=np.float64) V = V.reshape(-1, 3).astype(np.float64) @ world[:3, :3].T + world[:3, 3] - N = N.reshape(-1, 3).astype(np.float64) @ np.linalg.inv(world[:3, :3]) + corner = corner.reshape(-1, 3).astype(np.float64) @ np.linalg.inv(world[:3, :3]) + corner /= np.maximum(np.linalg.norm(corner, axis=1, keepdims=True), 1e-30) + CN = corner[L.reshape(-1, 3)] + N = np.zeros((len(V), 3)) + np.add.at(N, T.reshape(-1), CN.reshape(-1, 3)) N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-30) UV = None if mesh.uv_layers.active is not None: flat = np.empty(len(mesh.loops) * 2, dtype=np.float32) mesh.uv_layers.active.uv.foreach_get("vector", flat) UV = flat.reshape(-1, 2).astype(np.float64)[L.reshape(-1, 3)] - return {"V": V, "T": T.reshape(-1, 3).astype(np.int64), "UV": UV, "N": N, "polygon": P} + return {"V": V, "T": T.reshape(-1, 3).astype(np.int64), "UV": UV, "N": N, "CN": CN, "polygon": P} def merged(objects: list) -> dict: @@ -78,6 +84,7 @@ def merged(objects: list) -> dict: offsets = np.cumsum([0] + [len(p["V"]) for p in parts[:-1]]) uv = None if any(p["UV"] is None for p in parts) else np.concatenate([p["UV"] for p in parts]) return {"V": np.concatenate([p["V"] for p in parts]), "N": np.concatenate([p["N"] for p in parts]), + "CN": np.concatenate([p["CN"] for p in parts]), "T": np.concatenate([p["T"] + o for p, o in zip(parts, offsets)]), "UV": uv} @@ -198,7 +205,14 @@ def upsample(field: np.ndarray, height: int, width: int) -> np.ndarray: def pin_uvs(bm, faces) -> None: """Give each new face (a filled hole, a cap) one UV point, taken from an old face beside it, so it shows that texel's colour and takes no area of the texture: a face made by filling has no place in the UV map, - and corners copied from several islands would smear the atlas across it and overlap everything.""" + and corners copied from several islands would smear the atlas across it and overlap everything. The fill + also copies its neighbours' stashed shading normals onto the new corners; those are cleared, so the new + face is shaded by its own direction.""" + kept = bm.loops.layers.float_vector.get(KEPT_NORMAL) + if kept is not None: + for face in faces: + for loop in face.loops: + loop[kept] = (0.0, 0.0, 0.0) layer = bm.loops.layers.uv.active if layer is None: return @@ -218,6 +232,41 @@ def pin_uvs(bm, faces) -> None: loop[layer].uv = anchor +KEPT_NORMAL = "polish_kept_normal" + + +def stash_normals(mesh, bm) -> bool: + """Copy the mesh's custom shading normals onto the bmesh's face corners, as plain vectors, so they survive + edits. Blender stores a custom normal against the automatic normal of its corner; welding or cutting + changes the automatic normals, and the stored ones would then be read as different directions.""" + if "custom_normal" not in mesh.attributes: + return False + flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) + mesh.corner_normals.foreach_get("vector", flat) + normals = flat.reshape(-1, 3) + layer = bm.loops.layers.float_vector.new(KEPT_NORMAL) + for face in bm.faces: + for loop in face.loops: + loop[layer] = normals[loop.index] + return True + + +def restore_normals(mesh, keep: bool = True) -> None: + """Set the stashed vectors back as the mesh's custom normals (a new face's zero vector means automatic), + or with keep False only drop the stash.""" + attribute = mesh.attributes.get(KEPT_NORMAL) + if attribute is None: + return + flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) + attribute.data.foreach_get("vector", flat) + mesh.attributes.remove(attribute) + if keep: + stale = mesh.attributes.get("custom_normal") + if stale is not None: # else a zero vector would keep the stale value instead of meaning automatic + mesh.attributes.remove(stale) + mesh.normals_split_custom_set(flat.reshape(-1, 3).tolist()) + + def cap_surface(): """The dark, rough material of cut faces and joints: what shows in the gap when a part swings away.""" material = bpy.data.materials.get(CAP_MATERIAL) @@ -261,7 +310,7 @@ class BROKKR_MESH_POLISH_OT_audit(PolishOperator): data = arrays(obj) nodes = base_color_nodes(obj) size = max(nodes[0].image.size) if nodes else 0 - entry = core.audit(data["V"], data["T"], data["UV"], size, raster=self.raster) + entry = core.audit(data["V"], data["T"], data["UV"], size, raster=self.raster, CN=data["CN"]) entry["baseColorImage"] = nodes[0].image.name if nodes else "" entry["baseColorSize"] = list(nodes[0].image.size) if nodes else [0, 0] entry["customNormals"] = "custom_normal" in obj.data.attributes @@ -271,7 +320,7 @@ class BROKKR_MESH_POLISH_OT_audit(PolishOperator): class BROKKR_MESH_POLISH_OT_repair(PolishOperator): """Weld coincident vertices (UV seams keep their UVs), drop degenerate and loose geometry, drop shells - below an area share, close small holes, make normals consistent and recompute shading from a sharp angle""" + below an area share, close small holes; on request rewind faces outward or recompute shading from a sharp angle""" bl_idname = "brokkr_mesh_polish.repair" bl_label = "Repair Mesh" object_name: bpy.props.StringProperty(name="Object") @@ -281,20 +330,26 @@ class BROKKR_MESH_POLISH_OT_repair(PolishOperator): description="Delete shells holding less than this share of the surface; 0 keeps all") fill_holes_sides: bpy.props.IntProperty(name="Fill Holes", default=0, min=0, max=1000, description="Close holes of up to this many edges; 0 leaves holes") + recalc_normals: bpy.props.BoolProperty(name="Recalculate Normals", default=False, + description="Rewind each shell so Blender judges it to face outward. Off leaves every face's winding as it is. On an open or intersecting shell the judgement can be wrong, and a face it turns is culled by a single-sided material: read windingFlipped in the report") sharp_angle: bpy.props.FloatProperty(name="Sharp Angle", default=0.0, min=0.0, max=180.0, description="Degrees; above 0, generated custom normals are dropped and edges sharper than this shade hard") def work(self, context): obj = mesh_object(self.object_name) mesh = obj.data - before = core.audit(arrays(obj)["V"], arrays(obj)["T"], None) + start = arrays(obj) + before = core.audit(start["V"], start["T"], None, CN=start["CN"]) bm = bmesh.new() bm.from_mesh(mesh) + stash_normals(mesh, bm) diagonal = (Vector(obj.bound_box[6]) - Vector(obj.bound_box[0])).length counts = {"vertices": len(bm.verts)} + faces = len(bm.faces) if self.weld_fraction > 0: bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=diagonal * self.weld_fraction) counts["welded"] = counts.pop("vertices") - len(bm.verts) + counts["facesCollapsedByWeld"] = faces - len(bm.faces) faces = len(bm.faces) bmesh.ops.dissolve_degenerate(bm, edges=bm.edges[:], dist=diagonal * 1e-7) counts["degenerateFacesRemoved"] = faces - len(bm.faces) @@ -323,26 +378,39 @@ class BROKKR_MESH_POLISH_OT_repair(PolishOperator): counts["holesFilled"] = len(filled["faces"]) pin_uvs(bm, filled["faces"]) bmesh.ops.triangulate(bm, faces=[f for f in filled["faces"] if len(f.verts) > 3]) - bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + counts["windingFlipped"] = 0 + if self.recalc_normals: + was = [face.normal.copy() for face in bm.faces] + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + bm.normal_update() + counts["windingFlipped"] = sum(1 for face, normal in zip(bm.faces, was) if face.normal.dot(normal) < 0) bm.to_mesh(mesh) bm.free() + # Custom normals are stored against each face's own normal: a face that was turned would carry its + # custom normal turned with it, so they cannot outlive a rewind. + drop_custom = self.sharp_angle > 0 or counts["windingFlipped"] > 0 + counts["customNormalsDropped"] = bool(drop_custom and "custom_normal" in mesh.attributes) + if drop_custom and "custom_normal" in mesh.attributes: + mesh.attributes.remove(mesh.attributes["custom_normal"]) + restore_normals(mesh, keep=not drop_custom) if self.sharp_angle > 0: - if "custom_normal" in mesh.attributes: - mesh.attributes.remove(mesh.attributes["custom_normal"]) mesh.polygons.foreach_set("use_smooth", [True] * len(mesh.polygons)) mesh.set_sharp_from_angle(angle=math.radians(self.sharp_angle)) mesh.update() - after = core.audit(arrays(obj)["V"], arrays(obj)["T"], None) + end = arrays(obj) + after = core.audit(end["V"], end["T"], None, CN=end["CN"]) + keys = ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells", "windingAgainstNormals") return {"object": obj.name, "changes": counts, - "before": {k: before[k] for k in ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells")}, - "after": {k: after[k] for k in ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells")}} + "before": {k: before[k] for k in keys}, "after": {k: after[k] for k in keys}} class BROKKR_MESH_POLISH_OT_orient(PolishOperator): - """Turn every mesh in the scene, as one rigid body, onto its principal axes (longest on Y, shortest on Z), - centre it at the origin, scale its longest side to a length, and bake that into the mesh data""" + """Turn an object and everything parented under it (or the whole scene), as one rigid body, onto its + principal axes (longest on Y, shortest on Z), centre it at the origin and scale its longest side to a length. + Rotation and scale are baked into the mesh data; every object keeps its parent and its pivot point""" bl_idname = "brokkr_mesh_polish.orient" bl_label = "Orient Meshes" + object_name: bpy.props.StringProperty(name="Object", description="The root of what to turn: it and its descendants; every object in the scene when empty") length: bpy.props.FloatProperty(name="Length", default=0.0, min=0.0, max=1e6, description="Longest side after scaling, in scene units; 0 keeps the size") flip_forward: bpy.props.BoolProperty(name="Flip Forward", description="Turn half a turn about Z: swap bow and stern") @@ -352,7 +420,17 @@ class BROKKR_MESH_POLISH_OT_orient(PolishOperator): description="Off keeps the current axes and only applies the turns, centre and scale") def work(self, context): - objects = mesh_objects("") + if self.object_name: + top = bpy.data.objects.get(self.object_name) + if top is None: + raise Refused(f"No object named {self.object_name!r}.") + members = [top] + list(top.children_recursive) + else: + members = list(context.scene.objects) + objects = [o for o in members if o.type == "MESH"] + if not objects: + raise Refused("There is no mesh to orient.") + context.view_layer.update() data = merged(objects) centre, rotation = core.principal_frame(data["V"], data["T"]) if self.principal: @@ -371,15 +449,20 @@ class BROKKR_MESH_POLISH_OT_orient(PolishOperator): middle = (low + high) / 2.0 frame = Matrix.Translation(Vector(-middle * scale)) @ Matrix.Diagonal((scale, scale, scale, 1.0)) \ @ Matrix([list(row) + [0.0] for row in rotation] + [[0, 0, 0, 1]]) @ Matrix.Translation(Vector(-centre)) - originals = {o.name: frame @ o.matrix_world for o in objects} - for obj in objects: - if obj.data.users > 1: - obj.data = obj.data.copy() - obj.data.transform(originals[obj.name]) - obj.data.update() - for obj in objects: - obj.parent = None - obj.matrix_world = Matrix.Identity(4) + def depth(obj): + return 0 if obj.parent is None else 1 + depth(obj.parent) + + world = {o.name: o.matrix_world.copy() for o in members} + for obj in sorted(members, key=depth): # parents first: a child's new place is set against its parent's + target = frame @ world[obj.name] + pivot = Matrix.Translation(target.translation) + if obj.type == "MESH": + if obj.data.users > 1: + obj.data = obj.data.copy() + obj.data.transform(pivot.inverted() @ target) + obj.data.update() + obj.matrix_world = pivot if obj.type in ("MESH", "EMPTY") else target + context.view_layer.update() final = (local - middle) * scale return {"objects": [o.name for o in objects], "scale": scale, "extent": [round(float(x), 6) for x in (high - low) * scale], @@ -413,7 +496,7 @@ class BROKKR_MESH_POLISH_OT_delight(PolishOperator): covered = owner >= 0 if covered.sum() < 64: raise Refused("The UV map covers too little of the texture to fit lighting.") - normals = core.interpolate(owner, bary, N[T])[covered] + normals = core.interpolate(owner, bary, data["CN"])[covered] normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-30) sky = core.interpolate(owner, bary, occlusion[T][..., None])[covered][:, 0] pixels = read_pixels(image) @@ -536,6 +619,7 @@ class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): world = obj.matrix_world.copy() bm = bmesh.new() bm.from_mesh(mesh) + stash_normals(mesh, bm) diagonal = (Vector(obj.bound_box[6]) - Vector(obj.bound_box[0])).length bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=diagonal * 1e-5) bmesh.ops.triangulate(bm, faces=[f for f in bm.faces if len(f.verts) > 3]) @@ -568,8 +652,8 @@ class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): for edge in bm.edges: edge[was_open] = int(edge.is_boundary) cap_material = cap_surface() - cap_slot = len(mesh.materials) - materials = list(mesh.materials) + [cap_material] + materials = (list(mesh.materials) or [None]) + [cap_material] # a bare mesh keeps a bare first slot: only caps are dark + cap_slot = len(materials) - 1 collection = obj.users_collection[0] if obj.users_collection else context.scene.collection made, report = [], [] for index, name in enumerate(names): @@ -593,11 +677,11 @@ class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): for face in caps: face.material_index = cap_slot face.smooth = False - bmesh.ops.recalc_face_normals(piece, faces=piece.faces[:]) new_mesh = bpy.data.meshes.new(f"{obj.name}.{name}") root_world = world @ Vector(root_local) if index else world.translation.copy() piece.to_mesh(new_mesh) piece.free() + restore_normals(new_mesh) for material in materials: new_mesh.materials.append(material) new_obj = bpy.data.objects.new(f"{obj.name}.{name}", new_mesh) diff --git a/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json b/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json index d2950b7..c161dcd 100644 --- a/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json +++ b/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json @@ -14,7 +14,7 @@ }, { "name": "brokkr_mesh_polish.repair", - "doc": "Weld coincident vertices, drop degenerate and loose geometry and small shells, close small holes, fix normals.", + "doc": "Weld coincident vertices, drop degenerate and loose geometry and small shells, close small holes; windings are left alone unless recalc_normals.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -23,16 +23,18 @@ {"name": "weld_fraction", "type": "number", "minimum": 0, "maximum": 0.01, "default": 0.0001, "doc": "weld distance as a share of the bounding diagonal"}, {"name": "min_shell_area", "type": "number", "minimum": 0, "maximum": 0.5, "default": 0, "doc": "delete shells below this share of the surface; 0 keeps all"}, {"name": "fill_holes_sides", "type": "integer", "minimum": 0, "maximum": 1000, "default": 0, "doc": "close holes of up to this many edges"}, + {"name": "recalc_normals", "type": "boolean", "default": false, "doc": "rewind each shell to face outward as Blender judges it; off leaves every winding as it is. Can turn faces wrongly on open shells: read windingFlipped"}, {"name": "sharp_angle", "type": "number", "minimum": 0, "maximum": 180, "default": 0, "doc": "degrees; above 0 drops generated custom normals and shades edges sharper than this hard"} ] }, { "name": "brokkr_mesh_polish.orient", - "doc": "Turn all meshes as one body onto their principal axes (long on Y, short on Z), centre, scale, and bake it in.", + "doc": "Turn an object and its descendants (or the scene) as one body onto its principal axes (long on Y, short on Z), centre, scale; parents and pivots are kept.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", "fields": [ + {"name": "object_name", "type": "string", "maxLength": 63, "doc": "the root of what to turn, with its descendants; every object in the scene when absent"}, {"name": "length", "type": "number", "minimum": 0, "maximum": 1000000, "default": 0, "doc": "longest side after scaling; 0 keeps the size"}, {"name": "flip_forward", "type": "boolean", "default": false, "doc": "half a turn about Z"}, {"name": "roll_quarter_turns", "type": "integer", "minimum": 0, "maximum": 3, "default": 0, "doc": "quarter turns about the long axis"}, diff --git a/surfaces/blender/brokkr_mesh_polish/core.py b/surfaces/blender/brokkr_mesh_polish/core.py index 0ae197a..9031425 100644 --- a/surfaces/blender/brokkr_mesh_polish/core.py +++ b/surfaces/blender/brokkr_mesh_polish/core.py @@ -111,13 +111,24 @@ def weighted_quantile(values: np.ndarray, weights: np.ndarray, q: float) -> floa return float(values[order][min(np.searchsorted(cumulative, q * cumulative[-1]), len(values) - 1)]) +def winding_against(V: np.ndarray, T: np.ndarray, CN: np.ndarray) -> np.ndarray: + """True for each triangle whose corner order faces away from its own shading normals CN (m,3,3): the + triangle is drawn from behind, and a single-sided material culls it.""" + a, b, c = V[T[:, 0]], V[T[:, 1]], V[T[:, 2]] + return (np.cross(b - a, c - a) * CN.sum(axis=1)).sum(axis=1) < 0 + + def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int = 0, - weld_fraction: float = 1e-5, raster: int = 1024) -> dict: + weld_fraction: float = 1e-5, raster: int = 1024, CN: np.ndarray | None = None) -> dict: """The measurements a polish pass is judged by. Lengths are in the mesh's own units. Topology is counted after welding positions within weld_fraction of the bounding diagonal. UV overlap is the share of covered texels (on a raster x raster grid) that more than one triangle covers. Texel density is - texels per unit length for a texture_size texture, area-weighted over triangles; its spread is p95 / p5.""" + texels per unit length for a texture_size texture, area-weighted over triangles; its spread is p95 / p5. + With CN, the per-corner shading normals, windingAgainstNormals counts triangles wound away from them, and + uvMirroredTriangles counts triangles whose texture reads mirrored on the surface as shaded: negative UV + area on a triangle wound with its normals, or positive on one wound against them. Without CN the winding is + taken as right, so uvMirroredTriangles is the triangles of negative UV area.""" V = np.asarray(V, dtype=np.float64) T = np.asarray(T, dtype=np.int64) extent = V.max(axis=0) - V.min(axis=0) if len(V) else np.zeros(3) @@ -128,6 +139,9 @@ def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int "extent": [round(float(x), 6) for x in extent], "surfaceArea": float(areas.sum()), "degenerateTriangles": int((areas <= 1e-14 * diagonal * diagonal).sum())} report.update(edge_census(TW)) + against = winding_against(V, T, np.asarray(CN, dtype=np.float64)) & (areas > 0) if CN is not None else np.zeros(len(T), dtype=bool) + if CN is not None: + report["windingAgainstNormals"] = int(against.sum()) shells = triangle_components(TW) _, shell_sizes = np.unique(shells, return_counts=True) report["shells"] = int(len(shell_sizes)) @@ -141,7 +155,7 @@ def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int covered = int((cover > 0).sum()) report.update({ "uvIslands": uv_islands(TW, UV), - "uvFlippedTriangles": int((signed < 0).sum()), + "uvMirroredTriangles": int(((signed < 0) ^ against)[np.abs(signed) >= 1e-12].sum()), "uvZeroAreaTriangles": int((np.abs(signed) < 1e-12).sum()), "uvOutsideUnitTriangles": int(((UV < -1e-6) | (UV > 1 + 1e-6)).any(axis=(1, 2)).sum()), "uvCoverage": covered / float(raster * raster), diff --git a/surfaces/blender/tests/live/mesh_polish.py b/surfaces/blender/tests/live/mesh_polish.py index 4284585..5659698 100644 --- a/surfaces/blender/tests/live/mesh_polish.py +++ b/surfaces/blender/tests/live/mesh_polish.py @@ -5,7 +5,8 @@ and does what its doc says to real bpy meshes and images. Not part of the unitte Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses without them). Every action is sent through BrokkrBlenderTarget.run_intent, as tools/run_intents.py sends it. -Writes .result.json and exits 1 when a check failed. +With BROKKR_POLISH_HULLS= it also repairs each and checks that no face was +turned. Writes .result.json and exits 1 when a check failed. """ import json import math @@ -17,13 +18,15 @@ from pathlib import Path import bmesh import bpy import numpy as np -from mathutils import Matrix - -for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): - if not os.environ.get(_name): - raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +from mathutils import Matrix, Vector 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] package = types.ModuleType("brokkr_bridge") package.__path__ = [str(SURFACE / "brokkr_bridge")] @@ -40,6 +43,7 @@ target.reload_host_actions() R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "hostRows": [row["name"] for row in target.host_actions()[0]]} COUNT = [0] +RATIO_BOUND, DEFICIT_BOUND, SHADE_BOUND = 1.906, 0.136, 0.684 # each derived where it is used def check(name, ok, detail=None): @@ -92,58 +96,184 @@ def pixels_of(obj): check("host file admitted", not R["hostErrors"] and len(R["hostRows"]) == 7, R["hostErrors"] or R["hostRows"]) -# --- audit and repair: a sphere torn into loose faces is welded back into one closed shell ----------------------- +# --- audit and repair: a generator's sphere, torn at every edge, half its faces wound inside out under outward +# --- custom normals, is welded back into one closed shell with no face turned and its shading normals intact ------ size = 256 -rows = (np.arange(size) + 0.5) / size # v: 0 at the south pole, 1 at the north pole of Blender's UV sphere +rows = np.clip(((np.arange(size) + 0.5) / size - 0.1) / 0.8, 0.0, 1.0) # latitude: 0 at the south pole, 1 at the north baked = np.repeat((0.8 * (0.2 + 0.8 * rows))[:, None, None], size, axis=1) * np.ones((1, 1, 3)) -sphere = new_object("Ball", lambda bm: bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True), - new_image("ball_bake", baked.astype(np.float32))) + + +def ball(bm): + bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True) + layer = bm.loops.layers.uv.active + for face in bm.faces: # the island sits inside the texture with a margin, as a generator's atlas does + for loop in face.loops: + loop[layer].uv = loop[layer].uv * 0.8 + Vector((0.1, 0.1)) + + +sphere = new_object("Ball", ball, new_image("ball_bake", baked.astype(np.float32))) sphere.data.polygons.foreach_set("use_smooth", [True] * len(sphere.data.polygons)) torn = bmesh.new() torn.from_mesh(sphere.data) bmesh.ops.split_edges(torn, edges=torn.edges[:]) +inside_out = [f for f in torn.faces if f.calc_center_median().x > 0] +reversed_faces, reversed_triangles = len(inside_out), sum(len(f.verts) - 2 for f in inside_out) +bmesh.ops.reverse_faces(torn, faces=inside_out) torn.to_mesh(sphere.data) torn.free() +sphere.data.normals_split_custom_set([tuple(sphere.data.vertices[loop.vertex_index].co.normalized()) for loop in sphere.data.loops]) + + +def polygon_normals(mesh): + flat = np.empty(len(mesh.polygons) * 3, dtype=np.float32) + mesh.polygons.foreach_get("normal", flat) + return flat.reshape(-1, 3) + + +def shading_error(mesh): + """The worst angle, in degrees, between a corner's shading normal and the sphere's own outward direction.""" + flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) + mesh.corner_normals.foreach_get("vector", flat) + outward = np.array([mesh.vertices[loop.vertex_index].co.normalized() for loop in mesh.loops]) + return float(np.degrees(np.arccos(np.clip((flat.reshape(-1, 3) * outward).sum(axis=1), -1, 1))).max()) + + receipt, before = send("brokkr_mesh_polish.audit", object_name="Ball") check("audit: accepted, no undo step", receipt["status"] == "accepted" and not receipt.get("undoLabel"), receipt["message"]) check("audit: welded topology sees one closed shell in the torn sphere", before["Ball"]["shells"] == 1 and before["Ball"]["boundaryEdges"] == 0 and before["Ball"]["nonManifoldEdges"] == 0, before["Ball"]) check("audit: texture and UV facts", before["Ball"]["baseColorSize"] == [size, size] and before["Ball"]["uvOverlap"] < 0.02 - and before["Ball"]["texelDensityMedian"] > 0, before["Ball"]) -torn_vertices = len(sphere.data.vertices) -receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball", sharp_angle=30) + and before["Ball"]["texelDensityMedian"] > 0 and 0.55 < before["Ball"]["uvCoverage"] < 0.64, before["Ball"]) # an 0.8 x 0.8 island less the pole gaps +check("audit: counts the triangles wound against their shading normals, and none of them as a mirrored texture", + reversed_triangles > 1000 and before["Ball"]["windingAgainstNormals"] == reversed_triangles + and before["Ball"]["uvMirroredTriangles"] == 0, [reversed_triangles, before["Ball"].get("windingAgainstNormals"), before["Ball"].get("uvMirroredTriangles")]) +torn_vertices, normals_before = len(sphere.data.vertices), polygon_normals(sphere.data) +receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball") check("repair: accepted as one undo step", receipt["status"] == "accepted" and "repair" in receipt.get("undoLabel", ""), receipt) check("repair: welds the torn vertices", repaired["changes"]["welded"] == torn_vertices - len(sphere.data.vertices) and len(sphere.data.vertices) == 48 * 23 + 2, repaired) -edges = [e for e in sphere.data.edges] -check("repair: every edge has two faces again", sum(1 for _ in edges) == 48 * 23 + 48 * 24, len(edges)) +check("repair: every edge has two faces again", len(sphere.data.edges) == 48 * 23 + 48 * 24, len(sphere.data.edges)) +normals_after = polygon_normals(sphere.data) +turned = int(((normals_before * normals_after).sum(axis=1) < 0).sum()) if len(normals_before) == len(normals_after) else -1 +R["winding"] = {"reversedTriangles": reversed_triangles, "turnedByDefaultRepair": turned, "shadingErrorDegrees": shading_error(sphere.data)} +check("repair: by default turns no face (a single-sided material would cull a turned one)", + turned == 0 and repaired["changes"]["windingFlipped"] == 0 + and repaired["after"]["windingAgainstNormals"] == repaired["before"]["windingAgainstNormals"] == reversed_triangles, [turned, repaired]) +check("repair: the shading normals survive the weld", "custom_normal" in sphere.data.attributes and R["winding"]["shadingErrorDegrees"] < 0.5 + and not repaired["changes"]["customNormalsDropped"], R["winding"]) -# --- delight: a bake that darkens with latitude is levelled ------------------------------------------------------ -receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=256, occlusion_rays=8) +# --- delight: a bake that darkens with latitude is levelled, reading the shading normals, not the windings -------- +receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=128, occlusion_rays=8, max_gain=8) after_pixels, after_image = pixels_of(sphere) column = after_pixels[:, size // 2, 0] -# top/bottom brightness of the stored texture, rows at v = 0.9 and v = 0.1 -ratio_before = float(baked[int(size * 0.9), 0, 0] / baked[int(size * 0.1), 0, 0]) -ratio_after = float(column[int(size * 0.9)] / column[int(size * 0.1)]) -R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after} -check("delight: accepted, new packed image on the material", receipt["status"] == "accepted" and after_image.name == "ball_bake.delit" - and after_image.packed_file is not None, receipt["message"]) +north, south = int(size * (0.1 + 0.8 * 0.9)), int(size * (0.1 + 0.8 * 0.1)) # rows at latitude 0.9 and 0.1 +ratio_before = float(baked[north, 0, 0] / baked[south, 0, 0]) +ratio_after = float(column[north] / column[south]) +# On the island's left border the gain field meets texels no triangle covers. With the field filled outward the +# border reads as the middle of the row does; left unfilled, the neutral gain of the uncovered texels bleeds in. +border = int(math.ceil(size * 0.1)) +deficit = float(np.median(1.0 - after_pixels[south - 8:south + 8, border, 0] / after_pixels[south - 8:south + 8, size // 2, 0])) +R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after, "borderDeficit": deficit} +check("delight: accepted, new packed image on the material, in the old image's colour space", receipt["status"] == "accepted" + and after_image.name == "ball_bake.delit" and after_image.packed_file is not None + and after_image.colorspace_settings.name == "Non-Color", [receipt["message"], after_image.colorspace_settings.name]) check("delight: finds the baked light", lit["explainedByLight"]["before"] > 0.5 and lit["before"]["upDownLuminanceRatio"] > 2.0, lit) -# bound: shipped ratioAfter 1.12, the no-op mutant leaves 3.29: sqrt(1.12 * 3.29) = 1.92 -check("delight: levels top against bottom", ratio_before > 1.92 * 1.2 and ratio_after < 1.92 / 1.2, [ratio_before, ratio_after]) +# bound: shipped ratioAfter 1.114; a no-op leaves 3.261 and so do normals taken from the windings (the inside-out half +# cancels the light the fit could find): sqrt(1.114 * 3.261) = 1.906 +check("delight: levels top against bottom", ratio_before > RATIO_BOUND * 1.2 and ratio_after < RATIO_BOUND / 1.2, [ratio_before, ratio_after]) +# bound: shipped deficit 0.000, an unfilled gain field leaves 0.164; the shipped reading being zero, the bound sits 1.2 under the mutant: 0.136 +check("delight: the gain reaches the island's border unweakened", abs(deficit) < DEFICIT_BOUND, deficit) -# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled ------------------------------------------ +receipt, rewound = send("brokkr_mesh_polish.repair", object_name="Ball", recalc_normals=True, sharp_angle=30) +check("repair: recalc_normals rewinds the inside-out half and says how many faces it turned", + receipt["status"] == "accepted" and rewound["changes"]["windingFlipped"] == reversed_faces + and rewound["changes"]["customNormalsDropped"] and "custom_normal" not in sphere.data.attributes + and rewound["after"]["windingAgainstNormals"] == 0, rewound) + +# --- repair: only holes up to the size asked are filled, and only shells below the share asked are dropped ----- +def holey(bm): + bmesh.ops.create_grid(bm, x_segments=6, y_segments=6, size=3.0, calc_uvs=True) # 36 quads, each 1 x 1 + at = lambda face: (round(face.calc_center_median().x, 1), round(face.calc_center_median().y, 1)) + small = [f for f in bm.faces if at(f) == (1.5, 1.5)] # one quad inside: a 4-edge hole + large = [f for f in bm.faces if at(f)[0] in (-1.5, -0.5) and at(f)[1] in (-1.5, -0.5)] # a 2 x 2 block: an 8-edge hole + bmesh.ops.delete(bm, geom=small + large, context="FACES") + bm.faces.new([bm.verts.new(co) for co in ((9.0, 9.0, 0.0), (9.2, 9.0, 0.0), (9.0, 9.2, 0.0))]) # a far chip: 0.02 of area against 31 + + +sheet = new_object("Sheet", holey) +flipped_sheet = bmesh.new() # the generator's sheet faces down: a fill must follow it, whichever way Blender would guess +flipped_sheet.from_mesh(sheet.data) +bmesh.ops.reverse_faces(flipped_sheet, faces=flipped_sheet.faces[:]) +flipped_sheet.to_mesh(sheet.data) +flipped_sheet.free() +TILT = (0.6, 0.0, -0.8) # the generator's shading normals lean: the old faces must keep them, a fill must not borrow them +sheet.data.normals_split_custom_set([TILT] * len(sheet.data.loops)) +receipt, mended = send("brokkr_mesh_polish.repair", object_name="Sheet", fill_holes_sides=4, min_shell_area=0.01) +R["mend"] = mended +check("repair: fills the 4-edge hole, leaves the 8-edge hole and the rim, drops the chip", + receipt["status"] == "accepted" and mended["changes"]["holesFilled"] == 1 and mended["changes"]["shellsRemoved"] == 1 + and mended["after"]["shells"] == 1 and mended["after"]["boundaryEdges"] == 24 + 8, mended) +facing = polygon_normals(sheet.data)[:, 2] +check("repair: a filled hole is wound as the faces around it", len(facing) == 31 * 1 + 2 and bool((facing < -0.9).all()), [len(facing), float(facing.max())]) +shading = np.empty(len(sheet.data.loops) * 3, dtype=np.float32) +sheet.data.corner_normals.foreach_get("vector", shading) +shading = shading.reshape(-1, 3) +fill_loops = [i for polygon in sheet.data.polygons if abs(polygon.center.x - 1.5) < 0.4 and abs(polygon.center.y - 1.5) < 0.4 for i in polygon.loop_indices] +old_loops = [i for i in range(len(shading)) if i not in set(fill_loops)] +check("repair: old faces keep their shading normals through the weld and the fill; the fill is shaded by its own direction", + len(fill_loops) == 6 and np.allclose(shading[old_loops], TILT, atol=1e-3) and np.allclose(shading[fill_loops], (0.0, 0.0, -1.0), atol=1e-3), + [len(fill_loops), shading[fill_loops].tolist()[:2], shading[old_loops[0]].tolist()]) +bpy.data.objects.remove(sheet) + +# --- delight: darkness that follows occlusion is levelled --------------------------------------------------------- +def pair(bm): + layer = bm.loops.layers.uv.active + for side in (-1.0, 1.0): # two unit spheres 0.1 apart: their facing sides occlude each other + made = bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16, radius=1.0, calc_uvs=True, matrix=Matrix.Translation((side * 1.05, 0, 0))) + for face in {f for v in made["verts"] for f in v.link_faces}: + for loop in face.loops: + loop[layer].uv = Vector((loop[layer].uv.x * 0.5 + (0.0 if side < 0 else 0.5), loop[layer].uv.y)) + + +import brokkr_mesh_polish as polish # noqa: E402 the fixture's bake uses the add-on's own occlusion, so the light is exactly what it can explain + +twins = new_object("Twins", pair, new_image("twins_bake", np.ones((size, size, 3), dtype=np.float32))) +twins.data.polygons.foreach_set("use_smooth", [True] * len(twins.data.polygons)) +twin = polish.arrays(twins) +twin_sky = polish.ambient_occlusion(twin["V"], twin["T"], twin["N"], 64, 0.35 * float(np.linalg.norm(twin["V"].max(axis=0) - twin["V"].min(axis=0)))) +owner, bary, _ = polish.core.rasterize(twin["UV"], size) +sky_map = polish.core.interpolate(owner, bary, twin_sky[twin["T"]][..., None])[..., 0] +occluded, open_sky = (owner >= 0) & (sky_map < 0.6), (owner >= 0) & (sky_map > 0.95) +twin_bake = np.where((owner >= 0)[..., None], 0.8 * np.clip(sky_map, 0.05, 1.0)[..., None], 0.5) * np.ones((1, 1, 3)) +flat = np.ones((size, size, 4), dtype=np.float32) +flat[..., :3] = twin_bake +bpy.data.images["twins_bake"].pixels.foreach_set(flat.reshape(-1)) +receipt, unshadowed = send("brokkr_mesh_polish.delight", object_name="Twins", clusters=1, fit_size=256, occlusion_rays=64, max_gain=8) +twin_after, _ = pixels_of(twins) +shade_before = float(np.median(twin_bake[..., 0][occluded]) / np.median(twin_bake[..., 0][open_sky])) +shade_after = float(np.median(twin_after[..., 0][occluded]) / np.median(twin_after[..., 0][open_sky])) +R["occlusion"] = {"report": unshadowed, "occludedTexels": int(occluded.sum()), "shadeBefore": shade_before, "shadeAfter": shade_after} +# bound: shipped shadeAfter 1.000; with occlusion ignored (a sky of 1 everywhere) it stays 0.468: sqrt(1.000 * 0.468) = 0.684 +check("delight: lifts occluded surface to the level of open surface", receipt["status"] == "accepted" and occluded.sum() > 500 + and shade_before < SHADE_BOUND / 1.2 and shade_after > SHADE_BOUND * 1.2, R["occlusion"]) +bpy.data.objects.remove(twins) + +# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled; nothing outside it moves ----------------- slab = new_object("Slab", lambda bm: bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Diagonal((3.0, 1.0, 0.5, 1.0)))) slab.matrix_world = Matrix.Translation((4, 5, 6)) @ Matrix.Rotation(math.radians(37), 4, (0.3, 0.5, 0.8)) -sphere.hide_viewport = True -bpy.context.scene.collection.objects.unlink(sphere) # orient turns every mesh in the scene as one body -receipt, oriented = send("brokkr_mesh_polish.orient", length=12.0) +sphere.location = (20, 0, 0) +bpy.context.view_layer.update() +receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Slab", length=12.0) corners = np.array([slab.matrix_world @ v.co for v in slab.data.vertices]) extent = corners.max(axis=0) - corners.min(axis=0) check("orient: long on Y, thin on Z, scaled to the length, centred", receipt["status"] == "accepted" and np.allclose(extent, [4.0, 12.0, 2.0], atol=1e-3) and np.allclose((corners.max(axis=0) + corners.min(axis=0)) / 2, 0, atol=1e-4), [list(map(float, extent)), oriented]) check("orient: reports the mirror error of a symmetric body as small", max(oriented["mirrorError"].values()) < 0.05, oriented["mirrorError"]) +check("orient: an object outside the named root is not touched", oriented["objects"] == ["Slab"] + and np.allclose(sphere.matrix_world.translation, [20, 0, 0]) and abs(max(v.co.length for v in sphere.data.vertices) - 1.0) < 1e-5, oriented["objects"]) +receipt, _ = send("brokkr_mesh_polish.orient", object_name="Nobody") +check("orient: an unknown root is refused", receipt["status"] == "failed", receipt["message"]) bpy.data.objects.remove(slab) # --- cut_parts: a knob fused to a block is cut off at the crease, capped, and rooted at its cut ----------------- @@ -177,11 +307,54 @@ if receipt["status"] == "accepted": check("cut_parts: both sides of the cut are capped (closed shells)", all(closed[name]["boundaryEdges"] == 0 and closed[name]["shells"] == 1 for name in ("Block.body", "Block.knob")), {name: [closed[name]["boundaryEdges"], closed[name]["shells"]] for name in ("Block.body", "Block.knob")}) - check("cut_parts: caps carry the cap material and a joint sits at the root", "Polish Cap" in [m.name for m in knob.data.materials] + capped = {o.name: sum(1 for polygon in o.data.polygons if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap") for o in (body, knob)} + check("cut_parts: exactly the cap faces carry the cap material", capped["Block.knob"] == part["Block.knob"]["capTriangles"] > 0 + and capped["Block.body"] == part["Block.body"]["capTriangles"] > 0, capped) + cap_normals = {o.name: [polygon.normal.z for polygon in o.data.polygons + if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap"] for o in (body, knob)} + check("cut_parts: each cap faces out of its own part, and no old face was turned", + all(z < -0.9 for z in cap_normals["Block.knob"]) and all(z > 0.9 for z in cap_normals["Block.body"]) + and closed["Block.body"]["windingAgainstNormals"] == 0 and closed["Block.knob"]["windingAgainstNormals"] == 0, cap_normals) + check("cut_parts: a joint sits at the root", "Polish Cap" in [getattr(m, "name", "") for m in knob.data.materials] and np.allclose(bpy.data.objects[part["Block.knob"]["joint"]].matrix_world.translation, [0, 0, 1], atol=1e-5), part["Block.knob"].get("joint")) + # orient after the cut: the body and what hangs from it turn as one; the knob keeps its parent and its pivot + receipt, turned_parts = send("brokkr_mesh_polish.orient", object_name="Block.body", length=6.0) + pivot = knob.matrix_world.translation + reach = max(abs((knob.matrix_world @ v.co).y) for v in knob.data.vertices) + R["orientParts"] = {"report": turned_parts, "knobPivot": list(pivot), "knobReach": reach, "parent": knob.parent.name if knob.parent else None} + # the 2 x 2 x 3 body-and-knob is laid along Y and doubled: the cut centre (0, 0, 1), half a unit above the middle, lands 1 along Y + check("orient: after a cut the parts keep their parent and their pivot at the cut", receipt["status"] == "accepted" and knob.parent == body + and abs(abs(pivot.y) - 1.0) < 1e-4 and abs(pivot.x) < 1e-4 and abs(pivot.z) < 1e-4 and abs(reach - 3.0) < 1e-4 + and np.allclose(np.array(knob.matrix_world.to_3x3()), np.eye(3), atol=1e-6), R["orientParts"]) receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Block.body", seeds="only=0,0,-1") check("cut_parts: one part is refused with nothing changed", receipt["status"] == "failed" and "Block.body" in bpy.data.objects, receipt["message"]) + +# --- cut_parts through: a seed on one face of a thin plate also holds the face behind it ----------------------- +def plate_body(bm): + bmesh.ops.create_cube(bm, size=2.0, matrix=Matrix.Diagonal((1.0, 1.0, 0.05, 1.0))) # 2 x 2 x 0.1 + bmesh.ops.subdivide_edges(bm, edges=bm.edges[:], cuts=7, use_grid_fill=True) + bmesh.ops.triangulate(bm, faces=bm.faces[:]) + + +def underside(name): + """Triangles of the part that face down and are surface, not cap.""" + part_object = bpy.data.objects[name] + return sum(1 for polygon in part_object.data.polygons + if polygon.normal.z < -0.9 and getattr(part_object.data.materials[polygon.material_index], "name", "") != "Polish Cap") + + +R["through"] = {} +for label, through in (("without", 0.0), ("with", 0.1)): + new_object("Plate", plate_body) + # by distance alone (no crease cost) the underside's middle is nearer the body's seed, at an underside corner, + # than the lid's seed on top, which must go round the rim; a ray inward from the lid's seed finds it at once + receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Plate", seeds="body=-0.9,-0.9,-0.05; lid=0,0,0.05", crease_cost=0, through=through) + R["through"][label] = underside("Plate.lid") if receipt["status"] == "accepted" else None + for leftover in [o for o in bpy.data.objects if o.name.startswith("Plate")]: + bpy.data.objects.remove(leftover) +check("cut_parts: through seeds the far face of a thin part", R["through"]["without"] == 0 and (R["through"]["with"] or 0) >= 8, R["through"]) + # --- pick and scrub_markings: lettering on one panel is found from a camera and painted out ---------------------- panel = np.full((128, 128, 3), [0.1, 0.35, 0.4], dtype=np.float32) panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32) @@ -194,16 +367,16 @@ def plate(bm): sign = new_object("Sign", plate, new_image("sign_paint", panel)) # 4 x 2, flat on z = 0, u along x -sign.location = (0, 0, 5) +sign.location = (40, 0, 5) # clear of the block bpy.context.view_layer.update() camera = bpy.data.objects.new("Eye", bpy.data.cameras.new("Eye")) bpy.context.scene.collection.objects.link(camera) camera.data.type = "ORTHO" camera.data.ortho_scale = 4.0 -camera.location = (0, 0, 9) +camera.location = (40, 0, 9) receipt, picked = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.25, v=0.5, resolution_x=400, resolution_y=200) check("pick: names the surface point under (u, v) of a picture of that shape", receipt["status"] == "accepted" and picked["hit"] - and picked["object"] == "Sign" and np.allclose(picked["point"], [-1.0, 0.0, 5.0], atol=1e-4), picked) + and picked["object"] == "Sign" and np.allclose(picked["point"], [39.0, 0.0, 5.0], atol=1e-4), picked) receipt, missed = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.5, v=0.99, resolution_x=200, resolution_y=400) check("pick: off the surface is a miss, not an error", receipt["status"] == "accepted" and missed == {"hit": False}, missed) @@ -227,6 +400,26 @@ check("scrub_markings: a sphere off the surface is refused", receipt["status"] = receipt, _ = send("brokkr_mesh_polish.delight", object_name="Sign", max_gain=9) check("a bound miss is denied by Brokkr's table before the operator runs", receipt["status"] == "denied", receipt["message"]) +# --- real generated hulls, when a directory of .glb files is given: repair must turn none of their faces --------- +HULLS = os.environ.get("BROKKR_POLISH_HULLS", "") +R["hulls"] = {} +for path in sorted(Path(HULLS).glob("*.glb")) if HULLS else []: + known = set(bpy.data.objects.keys()) + bpy.ops.import_scene.gltf(filepath=str(path)) + for hull in [o for o in bpy.data.objects if o.name not in known and o.type == "MESH"]: + was = polygon_normals(hull.data) + _, raw = send("brokkr_mesh_polish.audit", object_name=hull.name) + against = raw[hull.name]["windingAgainstNormals"] + receipt, mended = send("brokkr_mesh_polish.repair", object_name=hull.name) + now = polygon_normals(hull.data) + turned = int(((was * now).sum(axis=1) < 0).sum()) if len(was) == len(now) else None + R["hulls"][path.name] = {"polygons": len(was), "polygonsAfter": len(now), "turned": turned, "againstBefore": against, + "againstAfter": mended["after"]["windingAgainstNormals"], "changes": mended["changes"]} + check(f"hull {path.name}: repair turns no face and keeps the shading normals' sides", receipt["status"] == "accepted" + and mended["changes"]["windingFlipped"] == 0 and turned in (0, None) # None: faces were removed, so indices no longer pair + and 0 <= against - mended["after"]["windingAgainstNormals"] <= len(was) - len(now), R["hulls"][path.name]) + bpy.data.objects.remove(hull) + R["ok"] = all(c["ok"] for c in R["checks"]) Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: diff --git a/surfaces/blender/tests/live/mesh_polish.result.json b/surfaces/blender/tests/live/mesh_polish.result.json index 9f3bae1..afe1e82 100644 --- a/surfaces/blender/tests/live/mesh_polish.result.json +++ b/surfaces/blender/tests/live/mesh_polish.result.json @@ -37,26 +37,27 @@ "boundaryEdges": 0, "nonManifoldEdges": 0, "collapsedTriangles": 0, + "windingAgainstNormals": 1104, "shells": 1, "shellTriangles": [ 2208 ], "uvIslands": 1, - "uvFlippedTriangles": 0, + "uvMirroredTriangles": 0, "uvZeroAreaTriangles": 0, "uvOutsideUnitTriangles": 0, - "uvCoverage": 0.95831298828125, + "uvCoverage": 0.6139068603515625, "uvOverlap": 0.0, - "texelDensityMedian": 61.97425923665604, - "texelDensityP5": 57.66165269744736, - "texelDensityP95": 113.44982327717632, - "texelDensitySpread": 1.9675090457856172, + "texelDensityMedian": 49.579448658498315, + "texelDensityP5": 46.12933107377486, + "texelDensityP95": 90.75985098993894, + "texelDensitySpread": 1.9675085000644446, "baseColorImage": "ball_bake", "baseColorSize": [ 256, 256 ], - "customNormals": false + "customNormals": true } }, { @@ -77,28 +78,38 @@ "boundaryEdges": 0, "nonManifoldEdges": 0, "collapsedTriangles": 0, + "windingAgainstNormals": 1104, "shells": 1, "shellTriangles": [ 2208 ], "uvIslands": 1, - "uvFlippedTriangles": 0, + "uvMirroredTriangles": 0, "uvZeroAreaTriangles": 0, "uvOutsideUnitTriangles": 0, - "uvCoverage": 0.95831298828125, + "uvCoverage": 0.6139068603515625, "uvOverlap": 0.0, - "texelDensityMedian": 61.97425923665604, - "texelDensityP5": 57.66165269744736, - "texelDensityP95": 113.44982327717632, - "texelDensitySpread": 1.9675090457856172, + "texelDensityMedian": 49.579448658498315, + "texelDensityP5": 46.12933107377486, + "texelDensityP95": 90.75985098993894, + "texelDensitySpread": 1.9675085000644446, "baseColorImage": "ball_bake", "baseColorSize": [ 256, 256 ], - "customNormals": false + "customNormals": true } }, + { + "name": "audit: counts the triangles wound against their shading normals, and none of them as a mirrored texture", + "ok": true, + "detail": [ + 1104, + 1104, + 0 + ] + }, { "name": "repair: accepted as one undo step", "ok": true, @@ -113,8 +124,8 @@ "note": "", "undoLabel": "Brokkr test/driver: brokkr_mesh_polish.repair live-2", "lookPath": "", - "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1}}", - "observedAt": "2026-12-01T00:06:45.524772+00:00" + "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"facesCollapsedByWeld\":0,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0,\"windingFlipped\":0,\"customNormalsDropped\":false},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104}}", + "observedAt": "2026-12-01T01:10:29.202522+00:00" } }, { @@ -124,25 +135,30 @@ "object": "Ball", "changes": { "welded": 3406, + "facesCollapsedByWeld": 0, "degenerateFacesRemoved": 0, "looseEdgesRemoved": 0, "looseVertsRemoved": 0, "shellsRemoved": 0, - "holesFilled": 0 + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false }, "before": { "triangles": 2208, "vertices": 4512, "boundaryEdges": 0, "nonManifoldEdges": 0, - "shells": 1 + "shells": 1, + "windingAgainstNormals": 1104 }, "after": { "triangles": 2208, "vertices": 1106, "boundaryEdges": 0, "nonManifoldEdges": 0, - "shells": 1 + "shells": 1, + "windingAgainstNormals": 1104 } } }, @@ -152,9 +168,58 @@ "detail": 2256 }, { - "name": "delight: accepted, new packed image on the material", + "name": "repair: by default turns no face (a single-sided material would cull a turned one)", "ok": true, - "detail": "Operator brokkr_mesh_polish.delight finished." + "detail": [ + 0, + { + "object": "Ball", + "changes": { + "welded": 3406, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + }, + "before": { + "triangles": 2208, + "vertices": 4512, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 1104 + }, + "after": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 1104 + } + } + ] + }, + { + "name": "repair: the shading normals survive the weld", + "ok": true, + "detail": { + "reversedTriangles": 1104, + "turnedByDefaultRepair": 0, + "shadingErrorDegrees": 0.03426402062177658 + } + }, + { + "name": "delight: accepted, new packed image on the material, in the old image's colour space", + "ok": true, + "detail": [ + "Operator brokkr_mesh_polish.delight finished.", + "Non-Color" + ] }, { "name": "delight: finds the baked light", @@ -166,22 +231,22 @@ "Ball" ], "explainedByLight": { - "before": 0.9722586649734903, - "after": 0.005096664890544278 + "before": 0.9718638595466577, + "after": 0.0005166823179215685 }, "before": { - "upDownLuminanceRatio": 2.5686425388668988, + "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0190418174045521, + "upDownLuminanceRatio": 1.0166067038538378, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9849698054726783, - "median": 1.454503966956526, - "max": 3.0, - "clamped": 0.05147808358817533 + "min": 0.9857558709602762, + "median": 1.457103285957073, + "max": 3.0649151172981792, + "clamped": 0.0 } } }, @@ -189,10 +254,149 @@ "name": "delight: levels top against bottom", "ok": true, "detail": [ - 3.2905027932960893, - 1.119760513305664 + 3.2607489597780868, + 1.1137723922729492 ] }, + { + "name": "delight: the gain reaches the island's border unweakened", + "ok": true, + "detail": 0.0 + }, + { + "name": "repair: recalc_normals rewinds the inside-out half and says how many faces it turned", + "ok": true, + "detail": { + "object": "Ball", + "changes": { + "welded": 0, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 576, + "customNormalsDropped": true + }, + "before": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 1104 + }, + "after": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 0 + } + } + }, + { + "name": "repair: fills the 4-edge hole, leaves the 8-edge hole and the rim, drops the chip", + "ok": true, + "detail": { + "object": "Sheet", + "changes": { + "welded": 0, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 1, + "holesFilled": 1, + "windingFlipped": 0, + "customNormalsDropped": false + }, + "before": { + "triangles": 63, + "vertices": 51, + "boundaryEdges": 39, + "nonManifoldEdges": 0, + "shells": 2, + "windingAgainstNormals": 0 + }, + "after": { + "triangles": 64, + "vertices": 48, + "boundaryEdges": 32, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 0 + } + } + }, + { + "name": "repair: a filled hole is wound as the faces around it", + "ok": true, + "detail": [ + 33, + -1.0 + ] + }, + { + "name": "repair: old faces keep their shading normals through the weld and the fill; the fill is shaded by its own direction", + "ok": true, + "detail": [ + 6, + [ + [ + 0.0, + 0.0, + -1.0 + ], + [ + 0.0, + 0.0, + -1.0 + ] + ], + [ + 0.6000571846961975, + 7.155610326492479e-09, + -0.7999570965766907 + ] + ] + }, + { + "name": "delight: lifts occluded surface to the level of open surface", + "ok": true, + "detail": { + "report": { + "image": "twins_bake", + "newImage": "twins_bake.delit", + "objects": [ + "Twins" + ], + "explainedByLight": { + "before": 0.9999597575085393, + "after": 0.028075104342772272 + }, + "before": { + "upDownLuminanceRatio": 1.0000084632254227, + "occlusionCorrelation": 0.983967648279407 + }, + "after": { + "upDownLuminanceRatio": 0.9999964767503613, + "occlusionCorrelation": 0.40471079036691976 + }, + "gain": { + "min": 0.9999809983875252, + "median": 1.0000990920451596, + "max": 5.493916964800697, + "clamped": 0.0 + } + }, + "occludedTexels": 2209, + "shadeBefore": 0.42187492665834836, + "shadeAfter": 1.0 + } + }, { "name": "orient: long on Y, thin on Z, scaled to the length, centred", "ok": true, @@ -229,6 +433,18 @@ "Z": 1.962464589014781e-09 } }, + { + "name": "orient: an object outside the named root is not touched", + "ok": true, + "detail": [ + "Slab" + ] + }, + { + "name": "orient: an unknown root is refused", + "ok": true, + "detail": "Error: No object named 'Nobody'." + }, { "name": "cut fixture is one closed skin", "ok": true, @@ -247,12 +463,13 @@ "boundaryEdges": 0, "nonManifoldEdges": 0, "collapsedTriangles": 0, + "windingAgainstNormals": 0, "shells": 1, "shellTriangles": [ 28 ], "uvIslands": 1, - "uvFlippedTriangles": 0, + "uvMirroredTriangles": 0, "uvZeroAreaTriangles": 28, "uvOutsideUnitTriangles": 0, "uvCoverage": 0.0, @@ -312,15 +529,76 @@ } }, { - "name": "cut_parts: caps carry the cap material and a joint sits at the root", + "name": "cut_parts: exactly the cap faces carry the cap material", + "ok": true, + "detail": { + "Block.body": 2, + "Block.knob": 2 + } + }, + { + "name": "cut_parts: each cap faces out of its own part, and no old face was turned", + "ok": true, + "detail": { + "Block.body": [ + 1.0, + 1.0 + ], + "Block.knob": [ + -1.0, + -1.0 + ] + } + }, + { + "name": "cut_parts: a joint sits at the root", "ok": true, "detail": "Block.knob.joint" }, + { + "name": "orient: after a cut the parts keep their parent and their pivot at the cut", + "ok": true, + "detail": { + "report": { + "objects": [ + "Block.body", + "Block.knob", + "Block.knob.joint" + ], + "scale": 1.9999999986467376, + "extent": [ + 5.656854, + 6.0, + 5.656854 + ], + "mirrorError": { + "X": 1.8120748396336225e-08, + "Y": 0.1508370330678463, + "Z": 1.8363068583553207e-08 + } + }, + "knobPivot": [ + 1.407290284305418e-09, + 1.0, + -1.8218171415895767e-09 + ], + "knobReach": 3.0, + "parent": "Block.body" + } + }, { "name": "cut_parts: one part is refused with nothing changed", "ok": true, "detail": "Error: Cutting needs seeds for at least two parts." }, + { + "name": "cut_parts: through seeds the far face of a thin part", + "ok": true, + "detail": { + "without": 0, + "with": 93 + } + }, { "name": "pick: names the surface point under (u, v) of a picture of that shape", "ok": true, @@ -328,7 +606,7 @@ "hit": true, "object": "Sign", "point": [ - -1.0, + 39.0, 0.0, 5.0 ], @@ -375,6 +653,72 @@ "name": "a bound miss is denied by Brokkr's table before the operator runs", "ok": true, "detail": "max_gain must be between 1 and 8." + }, + { + "name": "hull fourth.glb: repair turns no face and keeps the shading normals' sides", + "ok": true, + "detail": { + "polygons": 28426, + "polygonsAfter": 28420, + "turned": null, + "againstBefore": 388, + "againstAfter": 387, + "changes": { + "welded": 6437, + "facesCollapsedByWeld": 2, + "degenerateFacesRemoved": 4, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } + }, + { + "name": "hull sub.glb: repair turns no face and keeps the shading normals' sides", + "ok": true, + "detail": { + "polygons": 10406, + "polygonsAfter": 10406, + "turned": 0, + "againstBefore": 64, + "againstAfter": 64, + "changes": { + "welded": 2454, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } + }, + { + "name": "hull third.glb: repair turns no face and keeps the shading normals' sides", + "ok": true, + "detail": { + "polygons": 23341, + "polygonsAfter": 23340, + "turned": null, + "againstBefore": 189, + "againstAfter": 189, + "changes": { + "welded": 3810, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 1, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } } ], "hostErrors": [], @@ -387,6 +731,11 @@ "brokkr_mesh_polish.cut_parts", "brokkr_mesh_polish.pick" ], + "winding": { + "reversedTriangles": 1104, + "turnedByDefaultRepair": 0, + "shadingErrorDegrees": 0.03426402062177658 + }, "delight": { "report": { "image": "ball_bake", @@ -395,26 +744,87 @@ "Ball" ], "explainedByLight": { - "before": 0.9722586649734903, - "after": 0.005096664890544278 + "before": 0.9718638595466577, + "after": 0.0005166823179215685 }, "before": { - "upDownLuminanceRatio": 2.5686425388668988, + "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0190418174045521, + "upDownLuminanceRatio": 1.0166067038538378, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9849698054726783, - "median": 1.454503966956526, - "max": 3.0, - "clamped": 0.05147808358817533 + "min": 0.9857558709602762, + "median": 1.457103285957073, + "max": 3.0649151172981792, + "clamped": 0.0 } }, - "ratioBefore": 3.2905027932960893, - "ratioAfter": 1.119760513305664 + "ratioBefore": 3.2607489597780868, + "ratioAfter": 1.1137723922729492, + "borderDeficit": 0.0 + }, + "mend": { + "object": "Sheet", + "changes": { + "welded": 0, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 1, + "holesFilled": 1, + "windingFlipped": 0, + "customNormalsDropped": false + }, + "before": { + "triangles": 63, + "vertices": 51, + "boundaryEdges": 39, + "nonManifoldEdges": 0, + "shells": 2, + "windingAgainstNormals": 0 + }, + "after": { + "triangles": 64, + "vertices": 48, + "boundaryEdges": 32, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 0 + } + }, + "occlusion": { + "report": { + "image": "twins_bake", + "newImage": "twins_bake.delit", + "objects": [ + "Twins" + ], + "explainedByLight": { + "before": 0.9999597575085393, + "after": 0.028075104342772272 + }, + "before": { + "upDownLuminanceRatio": 1.0000084632254227, + "occlusionCorrelation": 0.983967648279407 + }, + "after": { + "upDownLuminanceRatio": 0.9999964767503613, + "occlusionCorrelation": 0.40471079036691976 + }, + "gain": { + "min": 0.9999809983875252, + "median": 1.0000990920451596, + "max": 5.493916964800697, + "clamped": 0.0 + } + }, + "occludedTexels": 2209, + "shadeBefore": 0.42187492665834836, + "shadeAfter": 1.0 }, "cut": { "body": "Block.body", @@ -456,6 +866,37 @@ } ] }, + "orientParts": { + "report": { + "objects": [ + "Block.body", + "Block.knob", + "Block.knob.joint" + ], + "scale": 1.9999999986467376, + "extent": [ + 5.656854, + 6.0, + 5.656854 + ], + "mirrorError": { + "X": 1.8120748396336225e-08, + "Y": 0.1508370330678463, + "Z": 1.8363068583553207e-08 + } + }, + "knobPivot": [ + 1.407290284305418e-09, + 1.0, + -1.8218171415895767e-09 + ], + "knobReach": 3.0, + "parent": "Block.body" + }, + "through": { + "without": 0, + "with": 93 + }, "scrub": { "report": { "object": "Sign", @@ -467,5 +908,61 @@ "inkInsideBefore": 192, "inkInsideAfter": 0 }, + "hulls": { + "fourth.glb": { + "polygons": 28426, + "polygonsAfter": 28420, + "turned": null, + "againstBefore": 388, + "againstAfter": 387, + "changes": { + "welded": 6437, + "facesCollapsedByWeld": 2, + "degenerateFacesRemoved": 4, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + }, + "sub.glb": { + "polygons": 10406, + "polygonsAfter": 10406, + "turned": 0, + "againstBefore": 64, + "againstAfter": 64, + "changes": { + "welded": 2454, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + }, + "third.glb": { + "polygons": 23341, + "polygonsAfter": 23340, + "turned": null, + "againstBefore": 189, + "againstAfter": 189, + "changes": { + "welded": 3810, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 1, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } + }, "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/test_mesh_polish.py b/surfaces/blender/tests/test_mesh_polish.py index 7205f81..9f0b4ef 100644 --- a/surfaces/blender/tests/test_mesh_polish.py +++ b/surfaces/blender/tests/test_mesh_polish.py @@ -37,6 +37,7 @@ def load(name: str, path: Path): turntable = load("turntable_recipe", SURFACE / "tools" / "turntable_recipe.py") +private_dirs = load("private_dirs", SURFACE / "tools" / "private_dirs.py") core = load("brokkr_mesh_polish_core", SURFACE / "brokkr_mesh_polish" / "core.py") if np is not None else None @@ -83,6 +84,23 @@ class TopologyTests(unittest.TestCase): self.assertEqual(report["shells"], 2) self.assertEqual(report["shellTriangles"], [4, 4]) + def test_a_triangle_the_weld_collapses_adds_no_edges(self): + V, T = quad_strip(3) + sliver = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 1.0, 0.0]]) # two corners weld into one + _, TW = core.weld(np.concatenate([V, sliver]), np.concatenate([T, [[len(V), len(V) + 1, len(V) + 2]]]), 1e-6) + census = core.edge_census(TW) + self.assertEqual((census["collapsedTriangles"], census["boundaryEdges"], census["nonManifoldEdges"]), (1, 8, 0)) + + def test_winding_against_shading_normals_is_counted_per_triangle(self): + V, T = quad_strip(3) # every triangle faces +z + up = np.tile([0.0, 0.0, 1.0], (len(T), 3, 1)) + self.assertEqual(int(core.winding_against(V, T, up).sum()), 0) + mixed = T.copy() + mixed[:2] = mixed[:2, ::-1] # two triangles wound the other way, their shading normals still up + self.assertEqual(core.winding_against(V, mixed, up).tolist(), [True, True, False, False, False, False]) + self.assertEqual(core.audit(V, mixed, None, CN=up)["windingAgainstNormals"], 2) + self.assertNotIn("windingAgainstNormals", core.audit(V, mixed, None)) + def test_components_follow_long_chains(self): pairs = np.array([[i, i + 1] for i in range(999)]) self.assertEqual(len(np.unique(core.components(1000, pairs[::-1]))), 1) @@ -101,7 +119,34 @@ class UvTests(unittest.TestCase): self.assertLess(report["uvOverlap"], 0.02) # only texel centres exactly on the shared diagonal self.assertAlmostEqual(report["texelDensityMedian"], 1024.0, places=3) self.assertAlmostEqual(report["texelDensitySpread"], 1.0, places=6) - self.assertEqual((report["uvIslands"], report["uvFlippedTriangles"]), (1, 0)) + self.assertEqual((report["uvIslands"], report["uvMirroredTriangles"]), (1, 0)) + + def test_a_seam_in_uv_space_makes_two_islands_of_one_surface(self): + apart = self.SQUARE_UV * 0.4 + apart[1] += 0.5 # the second triangle's UVs moved away: the 3D edge is shared, the UV edge is not + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, apart, 1024, raster=64)["uvIslands"], 2) + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, self.SQUARE_UV * 0.4, 1024, raster=64)["uvIslands"], 1) + + def test_texel_density_is_weighted_by_surface_area(self): + # one large triangle at 1024 texels per unit and four tiny ones at 4096: by count the median is 4096, by area 1024 + tiny = np.array([[0, 0, 0], [0.01, 0, 0], [0, 0.01, 0]], dtype=float) + V = np.concatenate([self.SQUARE_V[[0, 1, 2]] * 0.5] + [tiny + [2 + i, 0, 0] for i in range(4)]) + T = np.arange(15).reshape(5, 3) + UV = np.concatenate([self.SQUARE_UV[:1] * 0.5] + [tiny[None, :, :2] * 4 + [0.6 + 0.05 * i, 0.6] for i in range(4)]) + report = core.audit(V, T, UV, texture_size=1024, raster=64) + self.assertAlmostEqual(report["texelDensityMedian"], 1024.0, places=3) + self.assertAlmostEqual(report["texelDensityP95"], 1024.0, places=3) + + def test_mirrored_texture_is_judged_against_the_shading_normals_not_the_winding(self): + up = np.tile([0.0, 0.0, 1.0], (2, 3, 1)) + wound_back = self.SQUARE_T[:, ::-1] + uv_back = self.SQUARE_UV[:, ::-1] # the same texel at each vertex, listed in the reversed corner order + report = core.audit(self.SQUARE_V, wound_back, uv_back, 1024, raster=64, CN=up) + self.assertEqual((report["windingAgainstNormals"], report["uvMirroredTriangles"]), (2, 0)) # culled, but not mirrored + mirrored = self.SQUARE_UV.copy() + mirrored[..., 0] = 1 - mirrored[..., 0] + report = core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64, CN=up) + self.assertEqual((report["windingAgainstNormals"], report["uvMirroredTriangles"]), (0, 2)) # drawn, and mirrored def test_two_triangles_on_the_same_texels_overlap(self): stacked = np.array([self.SQUARE_UV[0], self.SQUARE_UV[0]]) @@ -111,7 +156,7 @@ class UvTests(unittest.TestCase): def test_a_mirrored_island_counts_as_flipped_and_half_the_area_doubles_nothing_but_density(self): mirrored = self.SQUARE_UV.copy() mirrored[..., 0] = 1 - mirrored[..., 0] - self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64)["uvFlippedTriangles"], 2) + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64)["uvMirroredTriangles"], 2) half = core.audit(self.SQUARE_V, self.SQUARE_T, self.SQUARE_UV * 0.5, 1024, raster=64) self.assertAlmostEqual(half["texelDensityMedian"], 512.0, places=3) self.assertAlmostEqual(half["uvCoverage"], 0.25, places=2) @@ -138,6 +183,22 @@ class OrientTests(unittest.TestCase): self.assertLess(extent[2], 1e-9) self.assertAlmostEqual(float(np.linalg.det(R)), 1.0, places=9) + def test_principal_frame_is_a_rotation_for_a_shape_and_for_its_mirror_image(self): + rng = np.random.default_rng(4) + V = rng.random((60, 3)) * [5.0, 2.0, 1.0] + T = rng.integers(0, 60, size=(40, 3)) + T = T[(T[:, 0] != T[:, 1]) & (T[:, 1] != T[:, 2]) & (T[:, 0] != T[:, 2])] + determinants = [float(np.linalg.det(core.principal_frame(V * flip, T)[1])) for flip in ([1, 1, 1], [-1, 1, 1], [1, -1, 1], [1, 1, -1])] + self.assertTrue(np.allclose(determinants, 1.0), determinants) # never a reflection: it would turn the mesh inside out + + def test_mirror_error_is_about_the_axis_asked(self): + rng = np.random.default_rng(1) + half = rng.random((400, 3)) + about_y = np.concatenate([half, half * [1, -1, 1]]) + [0.7, 0.0, 0.3] # a mirror across y = 0 only + self.assertEqual(core.mirror_error(about_y, 1), 0.0) + self.assertGreater(core.mirror_error(about_y, 0), 0.05) + self.assertGreater(core.mirror_error(about_y, 2), 0.05) + def test_mirror_error_tells_a_symmetric_cloud_from_a_lopsided_one(self): rng = np.random.default_rng(1) half = rng.random((400, 3)) @@ -321,6 +382,16 @@ class TextureFillTests(unittest.TestCase): outside = np.zeros((40, 40), dtype=bool) self.assertFalse(core.marking_mask(panel, outside, 0.25, 1).any()) + def test_marking_mask_judges_against_the_median_so_heavy_lettering_does_not_move_the_panel_colour(self): + panel = np.full((40, 40, 3), [0.1, 0.35, 0.4], dtype=np.float32) + panel[:, ::3] = [0.95, 0.9, 0.3] # a third of the region is lettering: the mean colour is 0.3 from the panel + region = np.ones((40, 40), dtype=bool) + mask = core.marking_mask(panel, region, 0.25, 0) + self.assertTrue(np.array_equal(mask, np.repeat((np.arange(40) % 3 == 0)[None, :], 40, axis=0))) + + def test_srgb_known_values(self): + self.assertTrue(np.allclose(core.srgb_to_linear(np.array([0.0, 0.04045, 0.5, 1.0])), [0.0, 0.0031308, 0.21404, 1.0], atol=2e-5)) + def test_box_blur_keeps_a_flat_field_and_spreads_a_point(self): flat = np.full((9, 9), 0.5) self.assertTrue(np.allclose(core.box_blur(flat, 2), 0.5)) @@ -360,6 +431,46 @@ class HostFileTests(unittest.TestCase): at.validate({**envelope, "action": "brokkr_mesh_polish.cut_parts", "object_name": "Hull"}, host) # seeds required +class PrivateDirsTests(unittest.TestCase): + """The guard a driver script runs before it touches Blender's user folders.""" + HOME = str(Path("/home/her")) + APPDATA = str(Path("/users/her/AppData/Roaming")) + + def environ(self, **changes): + base = {"BLENDER_USER_CONFIG": "/scratch/bl/cfg", "BLENDER_USER_EXTENSIONS": "/scratch/bl/ext", + "BLENDER_USER_SCRIPTS": "/scratch/bl/scripts", "APPDATA": self.APPDATA} + base.update(changes) + return {k: v for k, v in base.items() if v is not None} + + def test_scratch_directories_pass(self): + self.assertIsNone(private_dirs.refusal(self.environ(), self.HOME)) + used = {"CONFIG": "/scratch/bl/cfg", "EXTENSIONS": "/scratch/bl/ext", "SCRIPTS": "/scratch/bl/scripts"} + self.assertIsNone(private_dirs.refusal(self.environ(), self.HOME, lambda kind: used[kind])) + + def test_an_unset_or_empty_variable_is_refused(self): + for name in private_dirs.VARIABLES: + for value in (None, ""): + self.assertIn(name, private_dirs.refusal(self.environ(**{name: value}), self.HOME)) + + def test_a_variable_pointing_into_her_own_blender_folders_is_refused(self): + own = [str(Path(self.APPDATA) / "Blender Foundation" / "Blender" / "5.3" / "extensions"), + str(Path(self.APPDATA) / "Blender Foundation"), + str(Path(self.HOME) / ".config" / "blender" / "5.3" / "scripts"), + str(Path(self.HOME) / "Library" / "Application Support" / "Blender" / "5.3" / "config")] + for folder in own: + for name in private_dirs.VARIABLES: + refused = private_dirs.refusal(self.environ(**{name: folder}), self.HOME) + self.assertIsNotNone(refused, folder) + self.assertIn("own Blender folder", refused) + beside = str(Path(self.APPDATA) / "Blender Foundation Scratch") # a sibling that only shares a prefix + self.assertIsNone(private_dirs.refusal(self.environ(BLENDER_USER_EXTENSIONS=beside), self.HOME)) + + def test_a_blender_that_is_not_using_the_variables_is_refused(self): + hers = str(Path(self.APPDATA) / "Blender Foundation" / "Blender" / "5.3") + self.assertIn("refusing to touch it", private_dirs.refusal(self.environ(), self.HOME, lambda kind: hers)) + self.assertIn("refusing", private_dirs.refusal(self.environ(), self.HOME, lambda kind: "")) + + class TurntableRecipeTests(unittest.TestCase): def test_every_pose_looks_at_the_origin_with_z_up(self): for azimuth in (0, 45, 90, 200, 315): From 2e3ac798eab717d30e6b245049970735cebf4930 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 02:17:46 +0100 Subject: [PATCH 062/223] docs: mesh polish after Soul's pass: windings, shading normals, orient scope, delight's gradient limit, the guard Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/mesh-polish.md | 68 ++++++++++++++++++++-------- 1 file changed, 49 insertions(+), 19 deletions(-) diff --git a/surfaces/blender/docs/mesh-polish.md b/surfaces/blender/docs/mesh-polish.md index 93b8fac..914ed6a 100644 --- a/surfaces/blender/docs/mesh-polish.md +++ b/surfaces/blender/docs/mesh-polish.md @@ -38,9 +38,11 @@ blender --background --factory-startup --python surfaces/blender/tools/run_inten ``` The runner opens no CultMesh node: receipts go to `.receipts.json` only. It is the human of its own -Blender (it enables the host add-ons, reloads host actions once, opens and saves the `.blend`), and it refuses to -start without private `BLENDER_USER_CONFIG`, `BLENDER_USER_EXTENSIONS` and `BLENDER_USER_SCRIPTS`. Its exit status is -0 when every intent was accepted, 3 when one was not, 2 when the recipe could not run. +Blender (it enables the host add-ons, reloads host actions once, opens and saves the `.blend`). It refuses to +start unless `BLENDER_USER_CONFIG`, `BLENDER_USER_EXTENSIONS` and `BLENDER_USER_SCRIPTS` are each set to a folder +outside a person's own Blender folders (`%APPDATA%\Blender Foundation`, `~/.config/blender`, +`~/Library/Application Support/Blender`) and Blender reports that it is using them (`tools/private_dirs.py`). Its +exit status is 0 when every intent was accepted, 3 when one was not, 2 when the recipe could not run. `surfaces/blender/tools/turntable_recipe.py` writes a recipe of Brokkr's own scene actions (`setWorld`, `createObject`, `setCamera`, `setObjectTransform`, `renderStill`) for an orthographic turntable of a `.blend` whose @@ -49,7 +51,7 @@ an after compare view by view. `--look flat` lights with a uniform white world a stored, baked shadows included; `--look lit` adds a sun. A polish pass that works, in order: `audit`, `orient` (render a flat turntable and pick `roll_quarter_turns` and -`flip_forward` by eye), `repair`, `delight`, then `pick` and `scrub_markings` for each patch of lettering, then +`flip_forward` by eye; give `principal: false` on any later call, or the axes are found again), `repair`, `delight`, then `pick` and `scrub_markings` for each patch of lettering, then `pick` and `cut_parts` when parts must move, `audit` again, `exportGltf`. ## Actions @@ -63,7 +65,13 @@ as all open edges. - `triangles`, `vertices`, `weldedVertices`, `extent`, `surfaceArea`, `degenerateTriangles`. - `boundaryEdges` (one triangle on the edge: an open rim), `nonManifoldEdges` (three or more), `shells` and the triangle count of the largest twelve. -- `uvIslands`, `uvFlippedTriangles` (mirrored in UV space), `uvZeroAreaTriangles`, `uvOutsideUnitTriangles`, +- `windingAgainstNormals`: triangles whose corner order faces away from their own shading normals (the custom + normals a generated mesh carries). A single-sided material culls them. A mesh without custom normals is shaded + from its windings, so this reads 0 whatever its windings are. +- `uvMirroredTriangles`: triangles whose texture reads mirrored on the surface as shaded, that is negative UV area + on a triangle wound with its normals, or positive UV area on one wound against them. A triangle that is merely + wound backwards is not counted here. +- `uvIslands`, `uvZeroAreaTriangles`, `uvOutsideUnitTriangles`, `uvCoverage` (share of the texture some triangle covers) and `uvOverlap` (share of covered texels that more than one triangle covers), both counted at texel centres on a `raster` x `raster` grid. - `texelDensityMedian`, `P5`, `P95` (texels per unit length for the base colour texture's size, area-weighted) and @@ -73,13 +81,24 @@ as all open edges. ### repair Welds coincident vertices (UVs live on face corners, so seams keep their UVs), removes degenerate faces and loose -edges and vertices, optionally deletes shells below `min_shell_area` of the surface, optionally closes holes of up -to `fill_holes_sides` edges, and makes face normals consistent. With `sharp_angle` above 0 the generator's custom -normals are dropped and shading is recomputed: smooth, hard across edges sharper than the angle. +edges and vertices, optionally deletes shells below `min_shell_area` of the surface, and optionally closes holes of +up to `fill_holes_sides` edges. + +It turns no face. The winding of every face is left as the generator made it, and the mesh's custom shading normals +are carried through the weld as plain directions and set back afterwards (Blender stores a custom normal against +its corner's automatic normal, which welding changes). `windingFlipped` in the report is 0 and +`windingAgainstNormals` is the same before and after, less any triangle that was removed. + +`recalc_normals: true` asks Blender to rewind each shell to face outward. On a closed shell that is right. On the +open, intersecting shells generators make it is a guess: on three Tripo hulls it turned 83 of 10,406, 4,564 of +23,341 and 15,734 of 28,426 triangles, and a single-sided material then culls whatever was turned the wrong way. +The report says how many faces it turned (`windingFlipped`); the custom normals cannot outlive a rewind and are +dropped (`customNormalsDropped`). With `sharp_angle` above 0 the custom normals are also dropped and shading is +recomputed: smooth, hard across edges sharper than the angle. A filled hole has no place in the UV map: each new face takes one UV point from the old face beside it, so it shows -that texel's colour and adds no UV overlap (it counts in `uvZeroAreaTriangles`). Making normals consistent flips the -winding of shells that faced inward, which mirrors their UVs; `uvFlippedTriangles` can rise. +that texel's colour and adds no UV overlap (it counts in `uvZeroAreaTriangles`); it is shaded by its own direction, +not by its neighbours' custom normals. Welding does not join shells that merely touch or intersect. A mesh assembled from open, interpenetrating shells stays one: its open edges and non-manifold edges are reported, not repaired. Closing such a mesh means remeshing it @@ -87,9 +106,11 @@ and rebaking its texture, which this add-on does not do. ### orient -Turns every mesh in the scene, as one rigid body, onto its area-weighted principal axes: longest on Y, shortest on -Z, centred on the origin, the longest side scaled to `length` when given. The transform is baked into the mesh data -and the objects are left unparented at identity. Principal axes do not know bow from stern or up from down: +Turns `object_name` and everything parented under it (every object in the scene when absent), as one rigid body, +onto its area-weighted principal axes: longest on Y, shortest on Z, centred on the origin, the longest side scaled +to `length` when given. Objects outside that root are not touched. Rotation and scale are baked into the mesh data; +every object keeps its parent and its pivot point (a cut part's origin stays at the centre of its cut), and meshes +and empties end unrotated and unscaled. Principal axes do not know bow from stern or up from down: `flip_forward` and `roll_quarter_turns` choose, and `mirrorError` in the report (per axis, 0 is a perfect mirror) says which plane the body is symmetric across. `principal: false` keeps the current axes and applies only the turns, the centring and the scale. @@ -98,8 +119,9 @@ turns, the centring and the scale. Undoes lighting baked into the base colour texture, as far as the surface's own shape explains it. -For each texel the add-on knows the surface normal and the ambient occlusion there (cosine-weighted rays against -the mesh, per vertex). It fits log luminance as an intercept per hue cluster (`clusters`: how many distinct paints +For each texel the add-on knows the shading normal (the mesh's custom normals when it has them, so a shell wound +inside out is still read as it is drawn) and the ambient occlusion there (cosine-weighted rays against the mesh, +per vertex). It fits log luminance as an intercept per hue cluster (`clusters`: how many distinct paints the texture holds) plus a light term: the order-2 spherical harmonics of the normal and the log of occlusion. The fit follows the upper envelope of luminance (an expectile regression at 0.85), because within one hue the brightest paint at a given normal and occlusion shows how much light the bake put there, while darker paint in the @@ -115,7 +137,11 @@ is the share of texels that hit `max_gain`. What it cannot do. It removes smooth, shape-following light: sky-over-ground gradients and occlusion darkening. It does not remove cast shadows, specular highlights, or light the shape does not explain. It cannot tell dark -paint from shadow where a hue has no bright paint at all in some range of occlusion. Texels the generator filled +paint from shadow where a hue has no bright paint at all in some range of occlusion. It cannot tell paint from light +when the paint itself follows the shape: a smooth fade of one hue that runs with the normal (a hull painted lighter +above than below) is read as sky-over-ground light and flattened; in a probe such a fade kept 0.35 of its slope. +Paint in panels, bands or patches keeps its contrast (slope 1.00 in the same probe). On a mesh without custom +normals whose shells are wound inside out, the normals it reads are wrong; `audit` cannot see that case. Texels the generator filled with black stay black: there is no colour there to recover. It raises shaded paint by gain, so 8-bit noise and JPEG blocks in dark areas are raised with it. @@ -151,7 +177,8 @@ crease. `through` above 0 also seeds the far face of each part off the body, fou no longer than that share of the diagonal: a thin shell (a petal, a fin) is then held from both faces. The mesh is welded and triangulated first. Each part becomes an object `.`; both sides of every cut -are capped with faces of a dark `Polish Cap` material (pinned to one UV point each, as in `repair`); each part off +are capped with faces of a dark `Polish Cap` material (pinned to one UV point each, as in `repair`); no existing +face is turned and the custom shading normals are carried through, as in `repair`; each part off the body gets its origin at the centre of its cut and is parented to the body without moving; custom properties `polish_cut_normal` and `polish_cut_radius` record the cut's plane and mean radius. `joint_scale` above 0 adds a ball of that share of the cut radius at each root, parented to the body. The original object is removed. @@ -167,6 +194,9 @@ centre of the cut, not a designed hinge: it is a sensible pivot to start from. ## Tests - `tests/test_mesh_polish.py`: the arithmetic on hand-built meshes and textures, `brokkr_actions.json` against - Brokkr's own host-file checker, and the turntable recipe against the action table. No Blender; needs numpy. + Brokkr's own host-file checker, the private-directory guard, and the turntable recipe against the action table. + No Blender; needs numpy. - `tests/live/mesh_polish.py`: every action through `run_intent` in a background Blender against real bpy - (`mesh_polish.result.json` is the last run, Blender 5.3.0). + (`mesh_polish.result.json` is the last run, Blender 5.3.0). Its sphere is a generator's in miniature: torn at + every edge, half its faces wound inside out under outward custom normals. With `BROKKR_POLISH_HULLS` set to a + directory of generated `.glb` hulls it also repairs each and checks that no face was turned. From e141782a608f807fca5b2925d409adebda98476d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 06:46:50 +0100 Subject: [PATCH 063/223] mesh polish: boundary_root, the cut-root formula cut_parts shared with the rig Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_mesh_polish/__init__.py | 2 +- surfaces/blender/brokkr_mesh_polish/core.py | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/brokkr_mesh_polish/__init__.py b/surfaces/blender/brokkr_mesh_polish/__init__.py index 473550d..915ab5d 100644 --- a/surfaces/blender/brokkr_mesh_polish/__init__.py +++ b/surfaces/blender/brokkr_mesh_polish/__init__.py @@ -667,7 +667,7 @@ class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): raise Refused(f"Part {name!r} came out empty: move its seed onto the surface.") lengths = np.array([e.calc_length() for e in cut]) mids = np.array([((e.verts[0].co + e.verts[1].co) / 2)[:] for e in cut]).reshape(-1, 3) - root_local = (mids * lengths[:, None]).sum(axis=0) / lengths.sum() if len(cut) else np.zeros(3) + root_local = core.boundary_root(mids, lengths) spread = mids - root_local normal_local = np.linalg.eigh((spread * lengths[:, None]).T @ spread)[1][:, 0] if len(cut) >= 3 else np.array([0.0, 0.0, 1.0]) mean_radius = float((np.linalg.norm(spread, axis=1) * lengths).sum() / lengths.sum()) if len(cut) else 0.0 diff --git a/surfaces/blender/brokkr_mesh_polish/core.py b/surfaces/blender/brokkr_mesh_polish/core.py index 9031425..179efb0 100644 --- a/surfaces/blender/brokkr_mesh_polish/core.py +++ b/surfaces/blender/brokkr_mesh_polish/core.py @@ -259,6 +259,12 @@ def grow_parts(count: int, pairs: np.ndarray, costs: np.ndarray, seeds: list[tup return np.asarray(part, dtype=np.int64), np.asarray(best) +def boundary_root(mids: np.ndarray, lengths: np.ndarray) -> np.ndarray: + """Where a part is rooted: the length-weighted mean of the midpoints of the edges along its cut (zeros when + it has no cut).""" + return (mids * lengths[:, None]).sum(axis=0) / lengths.sum() if len(lengths) else np.zeros(3) + + def parse_seeds(text: str) -> list[tuple[str, tuple[float, float, float]]]: """'hull=0,0,0; pod1=1,0,0.5; pod1=1.2,0,0.4' as [(name, (x, y, z))]; ValueError names the bad entry.""" seeds = [] From 62e7897f156132cd8114557886b84ddfe5e488db Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 06:49:57 +0100 Subject: [PATCH 064/223] brokkr_rig: body, tendrils and colliders host actions and the VRMC_springBone export hook Rigs a fused generated mesh for the spring-bone runtime: spine and seed-part bones with weights, tendril chains grown from shape diameter and geodesic bands, body colliders shrunk to clear every spring joint, and VRMC_springBone written by Blender's own glTF exporter through a user extension. Imports brokkr_mesh_polish instead of copying it; acceptance is Aetheria's SpringRigVerify.VerifyGlb. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_rig/__init__.py | 519 ++++++++++++++++++ .../blender/brokkr_rig/brokkr_actions.json | 207 +++++++ surfaces/blender/brokkr_rig/core.py | 349 ++++++++++++ surfaces/blender/docs/rig.md | 123 +++++ surfaces/blender/tests/live/rig.py | 272 +++++++++ surfaces/blender/tests/live/rig.result.json | 390 +++++++++++++ surfaces/blender/tests/test_rig.py | 266 +++++++++ 7 files changed, 2126 insertions(+) create mode 100644 surfaces/blender/brokkr_rig/__init__.py create mode 100644 surfaces/blender/brokkr_rig/brokkr_actions.json create mode 100644 surfaces/blender/brokkr_rig/core.py create mode 100644 surfaces/blender/docs/rig.md create mode 100644 surfaces/blender/tests/live/rig.py create mode 100644 surfaces/blender/tests/live/rig.result.json create mode 100644 surfaces/blender/tests/test_rig.py diff --git a/surfaces/blender/brokkr_rig/__init__.py b/surfaces/blender/brokkr_rig/__init__.py new file mode 100644 index 0000000..1302b3d --- /dev/null +++ b/surfaces/blender/brokkr_rig/__init__.py @@ -0,0 +1,519 @@ +"""Rig a fused generated mesh for the spring-bone runtime: body bones and weights, tendril chains grown from the +mesh's own thickness, body colliders, and VRMC_springBone written by Blender's own glTF exporter. + +A host add-on for Brokkr beside brokkr_mesh_polish (it imports that package's operator base and arithmetic, and +nothing from Brokkr): brokkr_actions.json beside this file lists the operators agents may run (docs/rig.md). +The arithmetic is core.py (numpy, tested without Blender); this file is the bpy around it. Every operator writes +a JSON report to WindowManager.brokkr_mesh_polish_result, as the polish operators do. + +The rig lives in the scene as bones, vertex groups and bone ID properties. glTF2ExportUserExtension below reads +those properties when anything exports (Brokkr's exportGltf or File > Export) and writes VRMC_springBone into +the GLB; whether the result is acceptable is the runtime's own parse (SpringRigData.FromGlbJson), which this +add-on does not copy. +""" +bl_info = {"name": "Brokkr Rig", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), + "category": "Rigging", "description": "Rig generated creatures for spring-bone tendrils; agent-callable through Brokkr."} + +import json +from types import SimpleNamespace + +import bpy +import numpy as np +from mathutils import Matrix, Vector +from mathutils.bvhtree import BVHTree + +try: + from brokkr_mesh_polish import RESULT, PolishOperator, Refused, arrays, mesh_object + from brokkr_mesh_polish import core as polish + MISSING = None +except ImportError as error: # register() says so; the classes below only need something to subclass + RESULT, PolishOperator, Refused, polish, MISSING = "brokkr_mesh_polish_result", bpy.types.Operator, RuntimeError, None, error + +from . import core + +CHAIN, INDEX, STIFFNESS, DRAG, GRAVITY, HIT, COLLIDERS = ("rig_chain", "rig_index", "rig_stiffness", "rig_drag", "rig_gravity", + "rig_hit_radius", "rig_colliders") +GRAVITY_DOWN = (0.0, 0.0, -1.0) # Blender world; the exporter hook turns it into glTF world + + +# --- the scene around the arithmetic --------------------------------------------------------------------- + +def armature_of(obj, name: str): + if name: + arm = bpy.data.objects.get(name) + if arm is None or arm.type != "ARMATURE": + raise Refused(f"No armature object named {name!r}.") + return arm + for modifier in obj.modifiers: + if modifier.type == "ARMATURE" and modifier.object is not None: + return modifier.object + raise Refused(f"Object {obj.name!r} has no Armature modifier: run brokkr_rig.body first or give armature_name.") + + +def welded(obj) -> SimpleNamespace: + """The mesh as the rig sees it: world positions and triangles welded over UV seams (ids maps each mesh vertex to its + welded vertex), the welded edge graph and per-vertex normals.""" + data = arrays(obj) + V, T = data["V"], data["T"] + diagonal = float(np.linalg.norm(V.max(axis=0) - V.min(axis=0))) + ids, TW = polish.weld(V, T, diagonal * 1e-5) + count = int(ids.max()) + 1 + Vw, N = np.zeros((count, 3)), np.zeros((count, 3)) + Vw[ids] = V + np.add.at(N, ids, data["N"]) + N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-30) + return SimpleNamespace(V=V, ids=ids, Vw=Vw, TW=TW, N=N, E=core.welded_edges(TW), count=count, + diagonal=diagonal, length=float((V.max(axis=0) - V.min(axis=0)).max())) + + +class edit_mode: + """Edit Mode on an armature object for the length of the block; yields its edit bones.""" + + def __init__(self, context, arm): + self.context, self.arm = context, arm + + def __enter__(self): + self.context.view_layer.objects.active = self.arm + bpy.ops.object.mode_set(mode="EDIT") + return self.arm.data.edit_bones + + def __exit__(self, *_): + bpy.ops.object.mode_set(mode="OBJECT") + + +def spine_of(arm) -> list: + """The spine of an armature as the runtime finds it: from the first root, the child with the most descendants at + each step. Bones that belong to tendril chains are not part of the body.""" + bones = [b for b in arm.data.bones if CHAIN not in b] + kids = {b.name: [c for c in b.children if CHAIN not in c] for b in bones} + weight = {} + + def count(bone): + weight[bone.name] = 1 + sum(count(c) for c in kids[bone.name]) + return weight[bone.name] + + roots = [b for b in bones if b.parent is None or CHAIN in b.parent] + if not roots: + raise Refused(f"Armature {arm.name!r} has no body bones.") + for root in roots: + count(root) + spine, bone = [], roots[0] + while bone is not None: + spine.append(bone) + bone = max(kids[bone.name], key=lambda c: weight[c.name], default=None) + return spine + + +def write_weights(obj, names: list, ids: np.ndarray, idx: np.ndarray, w: np.ndarray): + """Replace the mesh's vertex groups with one per bone name; idx indexes names, (idx, w) per welded vertex.""" + obj.vertex_groups.clear() + groups = [obj.vertex_groups.new(name=name) for name in names] + wi, ww = idx[ids].tolist(), w[ids].tolist() + for vertex in range(len(ids)): + for b, weight in zip(wi[vertex], ww[vertex]): + if weight > 0: + groups[b].add([vertex], weight, "REPLACE") + + +def read_weights(obj, names: list, ids: np.ndarray, count: int) -> np.ndarray: + """Dense weights (welded vertices, names) of the mesh's vertex groups called names.""" + column = {obj.vertex_groups[n].index: i for i, n in enumerate(names) if n in obj.vertex_groups} + out = np.zeros((len(obj.data.vertices), len(names))) + for vertex in obj.data.vertices: + for entry in vertex.groups: + if entry.group in column: + out[vertex.index, column[entry.group]] = entry.weight + dense = np.zeros((count, len(names))) + dense[ids] = out + return dense + + +def shape_diameter(w: SimpleNamespace) -> np.ndarray: + """Per welded vertex, the median of five rays going inward (one along the reversed normal, four jittered inside a + cone, fixed seed) to the far side of the surface; a vertex whose rays find no back face (an open sheet) reads 0.""" + live = (w.TW[:, 0] != w.TW[:, 1]) & (w.TW[:, 1] != w.TW[:, 2]) & (w.TW[:, 0] != w.TW[:, 2]) + tree = BVHTree.FromPolygons([tuple(p) for p in w.Vw], [tuple(int(i) for i in t) for t in w.TW[live]]) + jitter = np.random.default_rng(0).normal(0.0, 0.35, (w.count, 4, 3)) + reach, lift = 0.5 * w.length, 1e-5 * w.length + out = np.zeros(w.count) + for i in range(w.count): + inward = -w.N[i] + hits = [] + for k in range(5): + way = inward if k == 0 else inward + jitter[i, k - 1] + way = way / max(float(np.linalg.norm(way)), 1e-30) + if way @ inward < 0.5: + continue + hit = tree.ray_cast(Vector(w.Vw[i] + way * lift), Vector(way), reach) + if hit[0] is not None: + hits.append(hit[3]) + out[i] = np.median(hits) if hits else 0.0 + return out + + +def rounded(values) -> list: + return [round(float(x), 6) for x in values] + + +# --- operators ------------------------------------------------------------------------------------------- + +class BROKKR_RIG_OT_body(PolishOperator): + """Give a mesh its body skeleton and weights: a spine along the long axis (root at the head end) and a bone + for each named seed region, or the weights alone against an armature that is already authored""" + bl_idname = "brokkr_rig.body" + bl_label = "Rig Body" + object_name: bpy.props.StringProperty(name="Object") + armature_name: bpy.props.StringProperty(name="Armature", description="An authored armature to weight against; empty makes .rig") + spine_bones: bpy.props.IntProperty(name="Spine Bones", default=8, min=2, max=32, description="Bones along the long axis of a new armature") + head: bpy.props.EnumProperty(name="Head", items=[("+y", "+Y", "The head is at the +Y end"), ("-y", "-Y", "The head is at the -Y end")], + default="+y", description="Which end of the long axis is the head: the spine's root, where the swim wave starts") + seeds: bpy.props.StringProperty(name="Seeds", maxlen=4000, + description="name=x,y,z; name=x,y,z ... world-space surface points: each name is a part with its own bone (a jaw, a fin); the spine takes the rest") + crease_cost: bpy.props.FloatProperty(name="Crease Cost", default=40.0, min=0.0, max=1000.0, + description="How strongly parts stop at concave creases; 0 splits by distance alone") + smooth_rounds: bpy.props.IntProperty(name="Smooth Rounds", default=3, min=0, max=64, description="Laplacian rounds over the weights") + + def work(self, context): + obj = mesh_object(self.object_name) + try: + seeds = polish.parse_seeds(self.seeds) if self.seeds.strip() else [] + except ValueError as error: + raise Refused(str(error)) from None + w = welded(obj) + _, frame = polish.principal_frame(w.Vw, w.TW) + axis = frame[0] / np.linalg.norm(frame[0]) + existing = bpy.data.objects.get(self.armature_name) if self.armature_name else None + if self.armature_name and (existing is None or existing.type != "ARMATURE"): + raise Refused(f"No armature object named {self.armature_name!r}.") + if existing is None: + if bpy.data.objects.get(f"{obj.name}.rig") is not None: + raise Refused(f"{obj.name}.rig exists: give armature_name={obj.name}.rig to weight against it.") + if (axis[1] < 0) == (self.head == "+y"): + axis = -axis + joints, u, length = core.spine_points(w.Vw, axis, self.spine_bones) + names = [f"spine_{i:02d}" for i in range(self.spine_bones)] + spine = [(joints[i], joints[i + 1]) for i in range(self.spine_bones)] + knots = np.arange(self.spine_bones) * (length / self.spine_bones) + others = [] # (name, head, tail) of bones the armature does not have yet; filled from the regions + wanted = [name for name, _ in seeds] + else: + matrix = np.array(existing.matrix_world) + body = spine_of(existing) + names = [b.name for b in body] + spine = [(matrix[:3, :3] @ np.array(b.head_local) + matrix[:3, 3], matrix[:3, :3] @ np.array(b.tail_local) + matrix[:3, 3]) for b in body] + if len(names) < 2: + raise Refused(f"Armature {existing.name!r} has a spine of {len(names)} bone: a spine needs 2 or more.") + if spine[0][0] @ axis < spine[-1][0] @ axis: + axis = -axis + top = w.Vw @ axis + u = top.max() - top + knots = top.max() - np.array([head @ axis for head, _ in spine]) + if np.any(np.diff(knots) <= 0): + raise Refused("The spine's bones do not run from the head end to the tail end of the mesh's long axis.") + others = [b for b in existing.data.bones if b.name not in names and CHAIN not in b] + known = {b.name for b in others} + for name, _ in seeds: + if name not in known: + raise Refused(f"Seed {name!r} names no bone of {existing.name!r} outside its spine.") + wanted = [b.name for b in others] + tails = {b.name: matrix[:3, :3] @ np.array(b.tail_local) + matrix[:3, 3] for b in others} + seeds = seeds + [(name, tail) for name, tail in tails.items()] + parts = ["spine"] + [n for n in dict.fromkeys(wanted) if n != "spine"] + pairs = polish.face_adjacency(w.TW) + centroid = w.Vw[w.TW].mean(axis=1) + nearest = lambda point: int(np.argmin(((centroid - np.asarray(point)) ** 2).sum(axis=1))) # noqa: E731 + placed = [(nearest(point), 0) for point in ([a for a, _ in spine] + [spine[-1][1]])] + placed += [(nearest(point), parts.index(name) if name in parts else 0) for name, point in seeds] + part, _ = polish.grow_parts(len(w.TW), pairs, polish.crease_costs(w.Vw, w.TW, pairs, self.crease_cost), placed) + part[part < 0] = 0 + areas = polish.triangle_areas(w.Vw, w.TW) + pa, pb, mids, lengths = core.cut_edges(w.Vw, w.TW, part) + region = [] + for p in range(1, len(parts)): + mine = part == p + if not mine.any(): + raise Refused(f"Part {parts[p]!r} came out empty: move its seed onto the surface.") + tail = (centroid[mine] * areas[mine][:, None]).sum(axis=0) / max(float(areas[mine].sum()), 1e-30) + cut = (pa == p) | (pb == p) + region.append((parts[p], polish.boundary_root(mids[cut], lengths[cut]), tail)) + if existing is None: + for name, head, tail in region: + if np.linalg.norm(tail - head) < 1e-4 * w.diagonal: + raise Refused(f"Part {name!r} has no length from its root to its centre: move its seed.") + # weights: spine bones along the axis, a region 1 on its bone, then the rounds + bones = names + [n for n in parts[1:]] + W = np.zeros((w.count, len(bones))) + W[:, :len(names)] = core.axial_weights(u, knots) + for p in range(1, len(parts)): + verts = np.unique(w.TW[part == p]) + W[verts] = 0.0 + W[verts, len(names) + p - 1] = 1.0 + idx, weight = core.top4(core.smooth(W, w.E, self.smooth_rounds)) + # the scene: bake the object's transform, make or keep the armature, skin + mesh = obj.data + mesh.transform(obj.matrix_world) + obj.parent = None + obj.matrix_world = Matrix.Identity(4) + collection = obj.users_collection[0] if obj.users_collection else context.scene.collection + if existing is None: + arm = bpy.data.objects.new(f"{obj.name}.rig", bpy.data.armatures.new(f"{obj.name}.rig")) + collection.objects.link(arm) + with edit_mode(context, arm) as edits: + for i, (head, tail) in enumerate(spine): + bone = edits.new(names[i]) + bone.head, bone.tail = Vector(head), Vector(tail) + bone.parent = edits[names[i - 1]] if i else None + for name, head, tail in region: + bone = edits.new(name) + bone.head, bone.tail = Vector(head), Vector(tail) + bone.parent = edits[names[int(np.argmin([core.segment_distance(head[None], a, b)[0] for a, b in spine]))]] + else: + arm = existing + write_weights(obj, bones, w.ids, idx, weight) + for modifier in [m for m in obj.modifiers if m.type == "ARMATURE"]: + obj.modifiers.remove(modifier) + obj.modifiers.new("Armature", "ARMATURE").object = arm + obj.parent = arm + obj.matrix_parent_inverse = arm.matrix_world.inverted() + return {"object": obj.name, "armature": arm.name, "created": existing is None, "spine": names, + "parts": [{"name": n, "root": rounded(h), "tail": rounded(t), "triangles": int((part == i + 1).sum())} + for i, (n, h, t) in enumerate(region)], + "head": rounded(spine[0][0]), "tail": rounded(spine[-1][1]), "axis": rounded(axis), + "vertices": int(len(mesh.vertices)), "weldedVertices": w.count} + + +class BROKKR_RIG_OT_tendrils(PolishOperator): + """Grow spring chains from the mesh's thin parts: skin each tendril to a chain of bones hung from the body and + mark the chains' stiffness, drag, gravity and hit radii for the exporter""" + bl_idname = "brokkr_rig.tendrils" + bl_label = "Rig Tendrils" + object_name: bpy.props.StringProperty(name="Object") + armature_name: bpy.props.StringProperty(name="Armature", description="Empty: the object's Armature modifier") + tau: bpy.props.FloatProperty(name="Tau", default=0.04, min=0.0, max=0.5, description="Shape diameter below which the surface is thin, as a share of the longest side") + band: bpy.props.FloatProperty(name="Band", default=0.04, min=0.0, max=0.5, description="Distance from the body one joint ring spans, as a share of the longest side") + dilate: bpy.props.FloatProperty(name="Dilate", default=0.04, min=0.0, max=0.5, description="How far the thick body is grown over its roots, as a share of the longest side") + fold_bands: bpy.props.FloatProperty(name="Fold Bands", default=1.5, min=0.0, max=10.0, description="A chain whose every vertex lies within this many bands of the body is a vein and folds into it") + min_joints: bpy.props.IntProperty(name="Min Joints", default=2, min=1, max=64, description="A chain with fewer rings than this folds into the body") + blend: bpy.props.FloatProperty(name="Blend", default=0.5, min=0.0, max=4.0, description="Bands over which weights blend between neighbouring bones and into the body") + stiffness: bpy.props.FloatProperty(name="Stiffness", default=3.0, min=0.0, max=1000.0, description="Rate (1 per second) a joint closes on its rest pose, at the root") + stiffness_tip_ratio: bpy.props.FloatProperty(name="Tip Ratio", default=0.5, min=0.0, max=10.0, description="Stiffness at the tip as a multiple of the root's") + drag: bpy.props.FloatProperty(name="Drag", default=0.3, min=0.0, max=1.0, description="Share of velocity a joint loses per substep") + gravity_power: bpy.props.FloatProperty(name="Gravity", default=0.0, min=0.0, max=100.0, description="Displacement per second along the world's down, in scene units") + hit_scale: bpy.props.FloatProperty(name="Hit Scale", default=1.0, min=0.0, max=10.0, description="Joint hit radius as a multiple of half the ring's median shape diameter") + + def work(self, context): + obj = mesh_object(self.object_name) + arm = armature_of(obj, self.armature_name) + w = welded(obj) + body_bones = [b for b in arm.data.bones if CHAIN not in b] + if not body_bones: + raise Refused(f"Armature {arm.name!r} has no body bones.") + body_names = [b.name for b in body_bones] + Wb = read_weights(obj, body_names, w.ids, w.count) + known = Wb.sum(axis=1) > 0 # a vertex a past run skinned to a chain has none: it takes the nearest one's + if not known.any(): + raise Refused("No vertex has weight on a body bone: run brokkr_rig.body first.") + if not known.all(): + near = core.dijkstra(core.graph(w.Vw, w.E), np.flatnonzero(known))[2] + Wb = Wb[np.where(known, np.arange(w.count), np.where(near >= 0, near, 0))] + bidx, bw = core.top4(Wb) + scale, band = w.length, self.band * w.length + sd = shape_diameter(w) + try: + found = core.extract(w.Vw, w.E, sd, self.tau * scale, band, self.dilate * scale, self.fold_bands, self.min_joints) + except ValueError as error: + raise Refused(str(error)) from None + springs = core.plan(w.Vw, sd, found, band) + for spring in springs: + spring.bone = body_names[int(np.argmax(Wb[spring.anchor].sum(axis=0)))] + idx, weight, start = core.tendril_weights(w.Vw, w.E, found, springs, bidx, bw, len(body_names), band, self.blend) + names = list(body_names) + for c, spring in enumerate(springs): + spring.names = [f"tendril_{c:03d}_{k:02d}" for k in range(len(spring.pos))] + names += spring.names + matrix = np.array(arm.matrix_world) + inverse = np.linalg.inv(matrix) + to_arm = lambda p: inverse[:3, :3] @ np.asarray(p) + inverse[:3, 3] # noqa: E731 + with edit_mode(context, arm) as edits: + for old in [e for e in edits if CHAIN in e]: + edits.remove(old) + for spring in springs: + for k, name in enumerate(spring.names): + head = spring.pos[k] + tail = spring.pos[k + 1] if k + 1 < len(spring.pos) else head + (head - spring.pos[k - 1]) * 0.5 + bone = edits.new(name) + bone.head, bone.tail = Vector(to_arm(head)), Vector(to_arm(tail)) + bone.parent = edits[spring.names[k - 1]] if k else edits[spring.bone] + for c, spring in enumerate(springs): + last = len(spring.names) - 1 + for k, name in enumerate(spring.names): + bone = arm.data.bones[name] + bone[CHAIN], bone[INDEX] = f"tendril_{c:03d}", k + bone[STIFFNESS] = self.stiffness * (1.0 + (self.stiffness_tip_ratio - 1.0) * k / last) + bone[DRAG], bone[GRAVITY] = self.drag, self.gravity_power + bone[HIT] = float(0.5 * spring.sd[k] * self.hit_scale) + arm.data["rig_gravity_dir"] = list(GRAVITY_DOWN) + write_weights(obj, names, w.ids, idx, weight) + kept = [c for c in found.chains if not c.folded] + lost = ~found.body & ~np.isfinite(found.d) + shells = len(np.unique(polish.components(w.count, w.E[lost[w.E[:, 0]] & lost[w.E[:, 1]]])[lost])) if lost.any() else 0 + branches = int(sum(1 for r in range(len(found.parent)) if not found.on_main[r] and found.parent[r] >= 0 + and found.on_main[found.parent[r]] and found.tree[r] in {c.tree for c in kept})) + return {"object": obj.name, "armature": arm.name, "bodyVertices": int(found.body.sum()), "chains": len(springs), + "springBones": int(sum(len(s.pos) for s in springs)), "branchesRigid": branches, + "veinsFolded": len(found.chains) - len(kept), "shellsAttached": shells, + "unreachedVertices": int(lost.sum()), "rings": int(len(found.parent)), + "shapeDiameterMedian": float(np.median(sd)), "tau": self.tau * scale, "band": band} + + +class BROKKR_RIG_OT_colliders(PolishOperator): + """Size body colliders for the spring chains: a capsule on each spine bone, a sphere on each other body bone, + shrunk until every spring joint past the first stands outside its hit radius at rest""" + bl_idname = "brokkr_rig.colliders" + bl_label = "Rig Colliders" + object_name: bpy.props.StringProperty(name="Object") + armature_name: bpy.props.StringProperty(name="Armature", description="Empty: the object's Armature modifier") + scale: bpy.props.FloatProperty(name="Scale", default=0.8, min=0.0, max=2.0, description="Collider radius as a multiple of the median radius of the body around it") + + def work(self, context): + obj = mesh_object(self.object_name) + arm = armature_of(obj, self.armature_name) + w = welded(obj) + matrix = np.array(arm.matrix_world) + world = lambda p: matrix[:3, :3] @ np.array(p) + matrix[:3, 3] # noqa: E731 + body = [b for b in arm.data.bones if CHAIN not in b] + spine = {b.name for b in spine_of(arm)} + Wb = read_weights(obj, [b.name for b in body], w.ids, w.count) + solid = Wb.sum(axis=1) >= 0.5 + heaviest = Wb.argmax(axis=1) + chain = [b for b in arm.data.bones if CHAIN in b and b[INDEX] >= 1] + joints = np.array([world(b.head_local) for b in chain]).reshape(-1, 3) + hit = np.array([b[HIT] for b in chain]) + made = {"capsules": 0, "spheres": 0, "shrunk": 0, "dropped": 0, "skipped": 0} + for bone in body: + if COLLIDERS in bone: + del bone[COLLIDERS] + for column, bone in enumerate(body): + head, tail = world(bone.head_local), world(bone.tail_local) + if bone.name in spine: + radius = core.capsule_radius(w.Vw[solid], head, tail, self.scale) + shape, offset, end = "capsule", head, tail + else: + mine = solid & (heaviest == column) + if not mine.any(): + made["skipped"] += 1 + continue + offset, radius = core.sphere_fit(w.Vw[mine], self.scale) + shape, end = "sphere", offset + cleared = core.clear_radius(radius, joints, hit, offset, end) + if cleared < radius: + made["shrunk"] += 1 + if cleared <= 0: + made["dropped"] += 1 + continue + entry = {"shape": shape, "offset": rounded(offset), "radius": float(cleared)} + if shape == "capsule": + entry["tail"] = rounded(end) + bone[COLLIDERS] = [entry] + made["capsules" if shape == "capsule" else "spheres"] += 1 + made.update({"object": obj.name, "armature": arm.name, "springJoints": len(chain)}) + return made + + +# --- the export hook: VRMC_springBone ---------------------------------------------------------------------- + +def _node_matrix(node) -> np.ndarray: + if getattr(node, "matrix", None): + return np.array(node.matrix, dtype=np.float64).reshape(4, 4).T + x, y, z, s = node.rotation if getattr(node, "rotation", None) else (0.0, 0.0, 0.0, 1.0) + rotation = np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * s), 2 * (x * z + y * s)], + [2 * (x * y + z * s), 1 - 2 * (x * x + z * z), 2 * (y * z - x * s)], + [2 * (x * z - y * s), 2 * (y * z + x * s), 1 - 2 * (x * x + y * y)]]) + scale = np.array(node.scale) if getattr(node, "scale", None) else np.ones(3) + local = np.eye(4) + local[:3, :3] = rotation * scale + local[:3, 3] = node.translation if getattr(node, "translation", None) else (0.0, 0.0, 0.0) + return local + + +def _spring_bone(gltf, export_settings) -> dict | None: + """The VRMC_springBone object for the armatures this export carries (those with brokkr_rig chains whose bones all + became nodes), or None when there are none.""" + nodes = gltf.nodes or [] + node_of = {node.name: i for i, node in enumerate(nodes)} + parent = {} + for i, node in enumerate(nodes): + for child in node.children or []: + parent[child if isinstance(child, int) else next(j for j, n in enumerate(nodes) if n is child)] = i + world = {} + + def matrix_of(i): + if i not in world: + world[i] = (matrix_of(parent[i]) if i in parent else np.eye(4)) @ _node_matrix(nodes[i]) + return world[i] + + yup = bool(export_settings.get("gltf_yup", True)) + swing = np.array([[1.0, 0, 0], [0, 0, 1.0], [0, -1.0, 0]]) if yup else np.eye(3) + local = lambda i, p: (np.linalg.inv(matrix_of(i)) @ np.append(swing @ np.asarray(p, dtype=np.float64), 1.0))[:3].tolist() # noqa: E731 + springs, colliders = [], [] + for arm in sorted((o for o in bpy.data.objects if o.type == "ARMATURE"), key=lambda o: o.name): + by_chain = {} + for bone in arm.data.bones: + if CHAIN in bone: + by_chain.setdefault(bone[CHAIN], []).append(bone) + gravity = (swing @ np.asarray(list(arm.data.get("rig_gravity_dir", GRAVITY_DOWN)), dtype=np.float64)).tolist() + for name in sorted(by_chain): + chain = sorted(by_chain[name], key=lambda b: b[INDEX]) + if not all(b.name in node_of for b in chain): + continue + springs.append({"name": name, "colliderGroups": [0], "joints": [ + {"node": node_of[b.name], "hitRadius": float(b[HIT]), "stiffness": float(b[STIFFNESS]), "gravityPower": float(b[GRAVITY]), + "gravityDir": gravity, "dragForce": float(b[DRAG])} for b in chain]}) + for bone in arm.data.bones: + if COLLIDERS in bone and bone.name in node_of: + for entry in bone[COLLIDERS]: + entry = entry.to_dict() if hasattr(entry, "to_dict") else entry + at = node_of[bone.name] + shape = {"offset": local(at, entry["offset"]), "radius": float(entry["radius"])} + if entry["shape"] == "capsule": + shape["tail"] = local(at, entry["tail"]) + colliders.append({"node": at, "shape": {entry["shape"]: shape}}) + if not springs: + return None + if not colliders: + springs = [{k: v for k, v in s.items() if k != "colliderGroups"} for s in springs] + return {"specVersion": "1.0", "colliders": colliders, + "colliderGroups": [{"name": "body", "colliders": list(range(len(colliders)))}] if colliders else [], "springs": springs} + + +class glTF2ExportUserExtension: + """Blender's glTF exporter finds this class on every enabled add-on and calls its hook once the nodes are final.""" + + def __init__(self): + from io_scene_gltf2.io.com.gltf2_io_extensions import Extension + self.Extension = Extension + + def gather_gltf_extensions_hook(self, gltf, export_settings): + spring = _spring_bone(gltf, export_settings) + if spring is None: + return + gltf.extensions = gltf.extensions or {} + gltf.extensions["VRMC_springBone"] = self.Extension(name="VRMC_springBone", extension=spring, required=False) + gltf.extensions_used = gltf.extensions_used or [] + if "VRMC_springBone" not in gltf.extensions_used: + gltf.extensions_used.append("VRMC_springBone") + + +classes = (BROKKR_RIG_OT_body, BROKKR_RIG_OT_tendrils, BROKKR_RIG_OT_colliders) + + +def register(): + if MISSING is not None or not hasattr(bpy.types.WindowManager, RESULT): + raise RuntimeError(f"brokkr_rig needs brokkr_mesh_polish enabled first ({MISSING or 'its result property is not registered'}).") + for cls in classes: + bpy.utils.register_class(cls) + + +def unregister(): + for cls in reversed(classes): + bpy.utils.unregister_class(cls) diff --git a/surfaces/blender/brokkr_rig/brokkr_actions.json b/surfaces/blender/brokkr_rig/brokkr_actions.json new file mode 100644 index 0000000..d258802 --- /dev/null +++ b/surfaces/blender/brokkr_rig/brokkr_actions.json @@ -0,0 +1,207 @@ +{ + "schema": "brokkr.blender.host_actions.v0", + "actions": [ + { + "name": "brokkr_rig.body", + "doc": "Skin a mesh to its body: a new spine along the long axis (root at the head end) with a bone per seed part, or an authored armature, weighted. Bakes the object's transform.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + }, + { + "name": "armature_name", + "type": "string", + "maxLength": 63, + "doc": "an authored armature to weight against, kept as it is; empty makes .rig" + }, + { + "name": "spine_bones", + "type": "integer", + "minimum": 2, + "maximum": 32, + "default": 8, + "doc": "bones along the long axis of a new armature" + }, + { + "name": "head", + "type": "string", + "enum": [ + "+y", + "-y" + ], + "default": "+y", + "doc": "which end of the long axis is the head, the spine's root" + }, + { + "name": "seeds", + "type": "string", + "maxLength": 4000, + "doc": "name=x,y,z; name=x,y,z ... world-space surface points; each name is a part with its own bone, the spine takes the rest" + }, + { + "name": "crease_cost", + "type": "number", + "minimum": 0, + "maximum": 1000, + "default": 40, + "doc": "how strongly parts stop at concave creases" + }, + { + "name": "smooth_rounds", + "type": "integer", + "minimum": 0, + "maximum": 64, + "default": 3, + "doc": "Laplacian rounds over the weights" + } + ] + }, + { + "name": "brokkr_rig.tendrils", + "doc": "Grow spring chains from the thin parts of a skinned mesh: one bone chain per tendril hung from a body bone, weights, and spring parameters for the exporter.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + }, + { + "name": "armature_name", + "type": "string", + "maxLength": 63, + "doc": "an armature object; the object's Armature modifier when absent" + }, + { + "name": "tau", + "type": "number", + "minimum": 0.001, + "maximum": 0.5, + "default": 0.04, + "doc": "shape diameter below which the surface is thin, as a share of the longest side" + }, + { + "name": "band", + "type": "number", + "minimum": 0.002, + "maximum": 0.5, + "default": 0.04, + "doc": "distance from the body one joint ring spans, as a share of the longest side" + }, + { + "name": "dilate", + "type": "number", + "minimum": 0, + "maximum": 0.5, + "default": 0.04, + "doc": "how far the thick body is grown over its roots, as a share of the longest side" + }, + { + "name": "fold_bands", + "type": "number", + "minimum": 0, + "maximum": 10, + "default": 1.5, + "doc": "a chain whose every vertex lies within this many bands of the body is a vein and folds into it" + }, + { + "name": "min_joints", + "type": "integer", + "minimum": 1, + "maximum": 64, + "default": 2, + "doc": "a chain with fewer rings than this folds into the body" + }, + { + "name": "blend", + "type": "number", + "minimum": 0, + "maximum": 4, + "default": 0.5, + "doc": "bands over which weights blend between neighbouring bones and into the body" + }, + { + "name": "stiffness", + "type": "number", + "minimum": 0.01, + "maximum": 1000, + "default": 3, + "doc": "rate (1 per second) a joint closes on its rest pose, at the root" + }, + { + "name": "stiffness_tip_ratio", + "type": "number", + "minimum": 0.01, + "maximum": 10, + "default": 0.5, + "doc": "stiffness at the tip as a multiple of the root's" + }, + { + "name": "drag", + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 0.3, + "doc": "share of velocity a joint loses per substep" + }, + { + "name": "gravity_power", + "type": "number", + "minimum": 0, + "maximum": 100, + "default": 0, + "doc": "displacement per second along the world's down, in scene units" + }, + { + "name": "hit_scale", + "type": "number", + "minimum": 0, + "maximum": 10, + "default": 1, + "doc": "joint hit radius as a multiple of half the ring's median shape diameter" + } + ] + }, + { + "name": "brokkr_rig.colliders", + "doc": "Size body colliders for the spring chains: a capsule per spine bone, a sphere per other body bone, shrunk to clear every spring joint past the first.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + }, + { + "name": "armature_name", + "type": "string", + "maxLength": 63, + "doc": "an armature object; the object's Armature modifier when absent" + }, + { + "name": "scale", + "type": "number", + "minimum": 0.05, + "maximum": 2, + "default": 0.8, + "doc": "collider radius as a multiple of the median radius of the body around it" + } + ] + } + ] +} \ No newline at end of file diff --git a/surfaces/blender/brokkr_rig/core.py b/surfaces/blender/brokkr_rig/core.py new file mode 100644 index 0000000..5dde1d9 --- /dev/null +++ b/surfaces/blender/brokkr_rig/core.py @@ -0,0 +1,349 @@ +"""The arithmetic of the rig builder: numpy only, no bpy, so every rule here is tested without Blender. + +A mesh is welded positions V (n,3) and unique edges E (k,2) of the welded graph (mesh polish's weld, so a vertex +split at a UV seam is one vertex here). Skin weights are (idx, w): four bone indices and four weights per vertex. + +Tendril extraction is a level-set walk from a thick body: every vertex gets a geodesic distance from the body, +the distance is cut into bands, each band into connected rings, and a ring is one joint at its centroid whose +parent is the ring one band nearer. Each tree's root-to-deepest-leaf path is one spring; the rest of the tree +rides the path rigidly. +""" +from __future__ import annotations + +import heapq +from types import SimpleNamespace + +import numpy as np +from brokkr_mesh_polish.core import components + + +# --- graph ----------------------------------------------------------------------------------------------- + +def welded_edges(TW: np.ndarray) -> np.ndarray: + """Unique edges (k,2), low id first, of the welded triangles; triangles that collapsed in the weld add none.""" + live = (TW[:, 0] != TW[:, 1]) & (TW[:, 1] != TW[:, 2]) & (TW[:, 0] != TW[:, 2]) + tw = TW[live] + return np.unique(np.sort(np.concatenate([tw[:, [0, 1]], tw[:, [1, 2]], tw[:, [2, 0]]]), axis=1), axis=0) + + +def graph(V: np.ndarray, E: np.ndarray) -> tuple[list, list, list]: + """Adjacency in compressed rows: (start, target, length); the neighbours of v are target[start[v]:start[v + 1]].""" + length = np.linalg.norm(V[E[:, 0]] - V[E[:, 1]], axis=1) + source = np.concatenate([E[:, 0], E[:, 1]]) + order = np.argsort(source, kind="stable") + return (np.searchsorted(source[order], np.arange(len(V) + 1)).tolist(), + np.concatenate([E[:, 1], E[:, 0]])[order].tolist(), np.concatenate([length, length])[order].tolist()) + + +def dijkstra(g: tuple, sources: np.ndarray, limit: float = float("inf")) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """(distance, predecessor, origin) over the edge graph from several sources; distance is inf, predecessor + and origin -1, where no source reaches within limit.""" + start, target, length = g + n = len(start) - 1 + best = [float("inf")] * n + pred = [-1] * n + origin = [-1] * n + heap = [] + for s in sources.tolist(): + best[s], origin[s] = 0.0, s + heap.append((0.0, s)) + heapq.heapify(heap) + while heap: + cost, u = heapq.heappop(heap) + if cost > best[u]: + continue + for k in range(start[u], start[u + 1]): + w, reach = target[k], cost + length[k] + if reach < best[w] and reach <= limit: + best[w], pred[w], origin[w] = reach, u, origin[u] + heapq.heappush(heap, (reach, w)) + return np.asarray(best), np.asarray(pred, dtype=np.int64), np.asarray(origin, dtype=np.int64) + + +# --- weights --------------------------------------------------------------------------------------------- + +def top4(W: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """(idx, w) of a dense weight matrix (n,bones): the four heaviest per vertex, normalised to sum 1.""" + keep = min(4, W.shape[1]) + idx = np.argsort(-W, axis=1, kind="stable")[:, :keep] + w = np.take_along_axis(W, idx, axis=1) + total = w.sum(axis=1, keepdims=True) + w = np.where(total > 0, w / np.maximum(total, 1e-30), 0.0) + if keep < 4: + idx, w = np.pad(idx, ((0, 0), (0, 4 - keep))), np.pad(w, ((0, 0), (0, 4 - keep))) + return idx, w + + +def axial_weights(u: np.ndarray, knots: np.ndarray) -> np.ndarray: + """(n, len(knots)): bone i weighs 1 at knot i and falls linearly to 0 at knot i + 1, where bone i + 1 takes over; + before the first knot and past the last, one bone. knots increase.""" + count = len(knots) + W = np.zeros((len(u), count)) + at = np.clip(np.searchsorted(knots, u, side="right") - 1, 0, count - 1) + nxt = np.minimum(at + 1, count - 1) + span = knots[nxt] - knots[at] + t = np.where(span > 0, np.clip((u - knots[at]) / np.where(span > 0, span, 1.0), 0.0, 1.0), 0.0) + rows = np.arange(len(u)) + W[rows, at] += 1.0 - t + W[rows, nxt] += t + return W + + +def smooth(W: np.ndarray, E: np.ndarray, rounds: int) -> np.ndarray: + """Laplacian rounds over the vertex graph: each vertex takes half its own weights and half its neighbours' mean.""" + degree = np.maximum(np.bincount(E.reshape(-1), minlength=len(W)), 1)[:, None] + for _ in range(rounds): + near = np.zeros_like(W) + np.add.at(near, E[:, 0], W[E[:, 1]]) + np.add.at(near, E[:, 1], W[E[:, 0]]) + W = 0.5 * W + 0.5 * near / degree + return W + + +def spine_points(V: np.ndarray, axis: np.ndarray, count: int) -> tuple[np.ndarray, np.ndarray, float]: + """(joints (count + 1,3), u, length): count equal bones from the head end (the far end along axis) to the tail + end, each joint centred on the median of the vertices around it; u is every vertex's distance from the head + end along axis, length the extent.""" + a = V @ axis + head, tail = float(a.max()), float(a.min()) + u = head - a + length = head - tail + step = length / count + side = V - np.outer(a, axis) + joints = np.empty((count + 1, 3)) + for i in range(count + 1): + near = np.abs(u - i * step) <= step + joints[i] = axis * (head - i * step) + (np.median(side[near], axis=0) if near.any() else 0.0) + return joints, u, length + + +def cut_edges(V: np.ndarray, TW: np.ndarray, part: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """The welded edges whose two triangles lie in different parts: (part a, part b, midpoint, length).""" + count = len(TW) + edges = np.sort(np.concatenate([TW[:, [0, 1]], TW[:, [1, 2]], TW[:, [2, 0]]]), axis=1) + face = np.tile(np.arange(count), 3) + order = np.lexsort((edges[:, 1], edges[:, 0])) + edges, face = edges[order], face[order] + same = (edges[1:] == edges[:-1]).all(axis=1) + i, j, e = face[:-1][same], face[1:][same], edges[:-1][same] + cut = part[i] != part[j] + e = e[cut] + return part[i][cut], part[j][cut], (V[e[:, 0]] + V[e[:, 1]]) / 2.0, np.linalg.norm(V[e[:, 0]] - V[e[:, 1]], axis=1) + + +# --- tendril extraction ---------------------------------------------------------------------------------- + +def body_region(g: tuple, E: np.ndarray, sd: np.ndarray, tau: float, dilate: float) -> np.ndarray: + """The body: the largest connected set of vertices whose shape diameter is at least tau (a vertex in an open + sheet reads 0 and is thin), grown geodesically by dilate.""" + n = len(sd) + thick = sd >= tau + if not thick.any(): + raise ValueError("no vertex is thicker than tau: lower tau") + label = components(n, E[thick[E[:, 0]] & thick[E[:, 1]]]) + body = thick & (label == np.bincount(label[thick], minlength=n).argmax()) + if dilate > 0: + body = np.isfinite(dijkstra(g, np.flatnonzero(body), dilate)[0]) + return body + + +def extract(V: np.ndarray, E: np.ndarray, sd: np.ndarray, tau: float, band: float, dilate: float, + fold_bands: float, min_joints: int) -> SimpleNamespace: + """Rings, the joint tree and the chains. tau, band and dilate are lengths. + + Returns: body, d (distance from the body), origin (nearest body vertex), ring (per vertex, -1 off the rings), + and per ring: parent (-1 touches the body), band, centroid, dist (mean distance), size, tree, on_main, fork + (the main-path ring a branch ring rides), index (position on its main path). chains is a list of + SimpleNamespace(tree, rings, folded): rings is the main path, root first; a tree whose farthest vertex is + within fold_bands bands of the body, or whose main path has fewer than min_joints rings, is folded + (a vein lying on the body).""" + n = len(V) + g = graph(V, E) + body = body_region(g, E, sd, tau, dilate) + d, pred, origin = dijkstra(g, np.flatnonzero(body)) + free = ~body & np.isfinite(d) + band_of = np.where(free, np.floor(d / band), -1).astype(np.int64) + same = free[E[:, 0]] & free[E[:, 1]] & (band_of[E[:, 0]] == band_of[E[:, 1]]) + label = components(n, E[same]) + ids = np.unique(label[free]) + ring = np.full(n, -1, dtype=np.int64) + ring[free] = np.searchsorted(ids, label[free]) + R = len(ids) + r = ring[free] + size = np.bincount(r, minlength=R) + centroid = np.stack([np.bincount(r, weights=V[free][:, k], minlength=R) for k in range(3)], axis=1) / np.maximum(size, 1)[:, None] + dist = np.bincount(r, weights=d[free], minlength=R) / np.maximum(size, 1) + ring_band = np.zeros(R, dtype=np.int64) + ring_band[r] = band_of[free] + far = np.zeros(R) + np.maximum.at(far, r, d[free]) + # a ring hangs from the ring its nearest vertex was reached through: one band nearer, or the body + near = np.flatnonzero(free) + near = near[np.lexsort((near, d[near], ring[near]))] + first = near[np.unique(ring[near], return_index=True)[1]] + up = pred[first] + parent = np.where(body[up], -1, ring[up]) + # the main path of each tree: at each ring the child with the tallest subtree (then the most vertices, then the lowest id) + order = np.argsort(-ring_band, kind="stable") + height = np.ones(R, dtype=np.int64) + main = np.full(R, -1, dtype=np.int64) + for c in order.tolist(): + if main[c] >= 0: + height[c] = 1 + height[main[c]] + p = parent[c] + if p >= 0 and (main[p] < 0 or (height[c], size[c], -c) > (height[main[p]], size[main[p]], -main[p])): + main[p] = c + tree = np.arange(R) + on_main = np.zeros(R, dtype=bool) + fork = np.arange(R) + index = np.zeros(R, dtype=np.int64) + for c in order[::-1].tolist(): + p = parent[c] + if p < 0: + on_main[c] = True + continue + tree[c] = tree[p] + on_main[c] = on_main[p] and main[p] == c + fork[c] = c if on_main[c] else fork[p] + index[c] = index[p] + 1 if on_main[c] else 0 + reach = np.zeros(R) + np.maximum.at(reach, tree, far) + chains = [] + for root in np.flatnonzero(parent < 0).tolist(): + path = [root] + while main[path[-1]] >= 0: + path.append(int(main[path[-1]])) + chains.append(SimpleNamespace(tree=root, rings=path, folded=bool(reach[root] <= fold_bands * band or len(path) < min_joints))) + return SimpleNamespace(body=body, d=d, pred=pred, origin=origin, ring=ring, parent=parent, band=ring_band, centroid=centroid, + dist=dist, size=size, tree=tree, on_main=on_main, fork=fork, index=index, chains=chains) + + +def plan(V: np.ndarray, sd: np.ndarray, found: SimpleNamespace, band: float) -> list[SimpleNamespace]: + """The springs: for each kept chain its joints (a ring's centroid each, then the tip at the leaf ring's + farthest vertex), the distance of each from the body, the median shape diameter of each ring, and the + vertex of the body the chain's first ring leaves from. The tip stands at least a quarter band from the last + ring's centroid.""" + out = [] + for chain in found.chains: + if chain.folded: + continue + rings = chain.rings + pos = [found.centroid[r] for r in rings] + dist = [float(found.dist[r]) for r in rings] + leaf = np.flatnonzero(found.ring == rings[-1]) + tip = leaf[np.argmax(found.d[leaf])] + tip_pos, tip_dist = V[tip].copy(), float(found.d[tip]) + gap = 0.25 * band + if np.linalg.norm(tip_pos - pos[-1]) < gap: + way = pos[-1] - (pos[-2] if len(pos) > 1 else V[found.origin[leaf[0]]]) + way = way / np.linalg.norm(way) if np.linalg.norm(way) > 0 else np.array([0.0, 0.0, 1.0]) + tip_pos, tip_dist = pos[-1] + way * gap, max(tip_dist, dist[-1] + gap) + hit = [float(np.median(sd[found.ring == r])) for r in rings] + [float(np.median(sd[leaf]))] + out.append(SimpleNamespace(tree=chain.tree, rings=rings, pos=np.array(pos + [tip_pos]), dist=np.array(dist + [tip_dist]), + sd=np.array(hit), anchor=np.unique(found.origin[found.ring == rings[0]]))) + return out + + +def tendril_weights(V: np.ndarray, E: np.ndarray, found: SimpleNamespace, springs: list, body_idx: np.ndarray, + body_w: np.ndarray, bodies: int, band: float, blend: float) -> tuple[np.ndarray, np.ndarray, list]: + """(idx, w, start): skin weights over bodies body bones then every spring's bones, spring c owning bones + start[c] .. start[c] + len(pos) - 1 (its rings, then the tip). + + A vertex on a spring's main path, at distance x from the body, takes bone k, the last joint at or before x, + blending linearly from bone k - 1 over blend bands from joint k (a joint's distance is its ring's mean); + a branch ring rides the main-path bone at its fork; a vertex within blend bands of the body takes the body + weights of its nearest body vertex in the complement; a folded vein takes those body weights; a vertex the + distance never reaches takes, per shell, the nearest spring bone.""" + n = len(V) + start, at = [], bodies + for s in springs: + start.append(at) + at += len(s.pos) + chain_of = {s.tree: c for c, s in enumerate(springs)} + ring_joint = {} # ring -> (spring, joint index) on the main path + for c, s in enumerate(springs): + for k, r in enumerate(s.rings): + ring_joint[r] = (c, k) + reach = blend * band + out = [None] * n + for v in range(n): + if found.body[v]: + out[v] = {int(b): float(w) for b, w in zip(body_idx[v], body_w[v]) if w > 0} + continue + r = found.ring[v] + if r < 0: + continue + near = int(found.origin[v]) + c = chain_of.get(int(found.tree[r])) + if c is None: + out[v] = {int(b): float(w) for b, w in zip(body_idx[near], body_w[near]) if w > 0} + continue + s = springs[c] + if found.on_main[r]: + k = int(np.searchsorted(s.dist, found.d[v], side="right")) - 1 + if k <= 0: + mix = {start[c]: 1.0} + else: + t = min((found.d[v] - s.dist[k]) / reach, 1.0) if reach > 0 else 1.0 + mix = {start[c] + k: t, **({start[c] + k - 1: 1.0 - t} if k > 0 and t < 1.0 else {})} + else: + mix = {start[c] + ring_joint[int(found.fork[r])][1]: 1.0} + share = min(found.d[v] / reach, 1.0) if reach > 0 else 1.0 + row = {b: w * share for b, w in mix.items()} + if share < 1.0: + for b, w in zip(body_idx[near], body_w[near]): + row[int(b)] = row.get(int(b), 0.0) + float(w) * (1.0 - share) + out[v] = row + lost = [v for v in range(n) if out[v] is None] + if lost: + lost = np.asarray(lost) + bone_pos = np.concatenate([s.pos for s in springs]) if springs else np.zeros((0, 3)) + bone_id = np.concatenate([start[c] + np.arange(len(s.pos)) for c, s in enumerate(springs)]) if springs else np.zeros(0, dtype=int) + pairs = E[np.isin(E[:, 0], lost) & np.isin(E[:, 1], lost)] + shell = components(n, pairs) + for label in np.unique(shell[lost]): + members = lost[shell[lost] == label] + if len(bone_pos): + bone = int(bone_id[np.argmin(np.linalg.norm(bone_pos - V[members].mean(axis=0), axis=1))]) + for v in members.tolist(): + out[v] = {bone: 1.0} + else: + for v in members.tolist(): + out[v] = {int(b): float(w) for b, w in zip(body_idx[v], body_w[v]) if w > 0} + idx, w = np.zeros((n, 4), dtype=np.int64), np.zeros((n, 4)) + for v, row in enumerate(out): + top = sorted(row.items(), key=lambda item: (-item[1], item[0]))[:4] + total = sum(x for _, x in top) + for slot, (b, x) in enumerate(top): + idx[v, slot], w[v, slot] = b, x / total + return idx, w, start + + +# --- colliders ------------------------------------------------------------------------------------------- + +def segment_distance(P: np.ndarray, a: np.ndarray, b: np.ndarray) -> np.ndarray: + """Distance from each point of P (k,3) to the segment a-b (a point when a == b).""" + ab = b - a + along = np.clip(((P - a) @ ab) / max(float(ab @ ab), 1e-30), 0.0, 1.0) + return np.linalg.norm(P - (a + along[:, None] * ab), axis=1) + + +def capsule_radius(V: np.ndarray, head: np.ndarray, tail: np.ndarray, scale: float) -> float: + """The median distance from the axis head-tail of the vertices that project onto it, times scale (0 if none).""" + ab = tail - head + t = ((V - head) @ ab) / max(float(ab @ ab), 1e-30) + on = (t >= 0.0) & (t <= 1.0) + return float(np.median(segment_distance(V[on], head, tail)) * scale) if on.any() else 0.0 + + +def sphere_fit(V: np.ndarray, scale: float) -> tuple[np.ndarray, float]: + """(centre, radius): the centroid of the vertices and the median distance from it, times scale.""" + centre = V.mean(axis=0) + return centre, float(np.median(np.linalg.norm(V - centre, axis=1)) * scale) + + +def clear_radius(radius: float, joints: np.ndarray, hit: np.ndarray, a: np.ndarray, b: np.ndarray) -> float: + """radius shrunk until every joint (k,3) stands at least its hit radius outside the capsule a-b (a sphere when a == b).""" + if not len(joints): + return radius + return min(radius, float((segment_distance(joints, a, b) - hit).min())) diff --git a/surfaces/blender/docs/rig.md b/surfaces/blender/docs/rig.md new file mode 100644 index 0000000..1b3a0b9 --- /dev/null +++ b/surfaces/blender/docs/rig.md @@ -0,0 +1,123 @@ +# Rigging generated creatures for spring-bone tendrils + +`surfaces/blender/brokkr_rig` is a Blender add-on that rigs a fused generated mesh (Tripo and its kin: one skin, +body and tendrils welded together) for a spring-bone runtime. It is a host add-on in Brokkr's sense +(`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish`: it imports that package's operator base, +`Refused`, `mesh_object`, `arrays` and arithmetic (weld, components, face adjacency, crease costs, seed growing, +`principal_frame`, `boundary_root`) instead of copying them, and nothing from `brokkr_bridge`. Enable +`brokkr_mesh_polish` first; `brokkr_rig` refuses to register without it. `brokkr_actions.json` beside its +`__init__.py` lists the three operators agents may run; the arithmetic is `core.py` (numpy only, tested without +Blender). Every action writes a JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. + +## The contract it produces, and who owns it + +The GLB the exporter writes has one skin over every bone, every node with translation and rotation at unit scale +and no matrix, mesh primitives with exactly `POSITION`, `NORMAL`, `TEXCOORD_0`, `JOINTS_0`, `WEIGHTS_0` (at most 4 +influences, weights summing to 1), and `VRMC_springBone` 1.0: each spring a linear chain whose first joint hangs +from a body bone, colliders only on body bones in one group `body` named by every spring. Stiffness is a rate in +1 per second, not VRM's unit. + +Whether a GLB is acceptable is **Aetheria's** `SpringRigData.FromGlbJson`, not this add-on, which ships no copy of +its refusals. Run the owner's code on the output with `SpringRigVerify.VerifyGlb` (Aetheria, batch mode): + +```text +SPRINGRIG_GLB= Unity -batchmode -projectPath \ + -executeMethod Aetheria.EditorTools.SpringRigVerify.VerifyGlb -logFile +``` + +(no `-nographics`, no `-quit`; one Unity batch instance at a time). It logs the rig's bone, body, chain, joint and +collider counts and exits 0 on PASS. + +## Export + +There is no export action of its own: Brokkr's `exportGltf` (or File > Export > glTF) writes the GLB, and the +add-on's `glTF2ExportUserExtension` hook writes `VRMC_springBone` into it, mapping bone names to node indices from +the exporter's final node list. It acts only when an exported armature carries `brokkr_rig` chains, so any other +export is untouched. Collider offsets and capsule tails are stored in Blender world space on the body bones and +composed into each collider node's local glTF frame at export from the exported nodes' translation, rotation and +scale; the gravity direction goes into glTF world. Both follow `export_yup`. + +## Actions + +### body + +`brokkr_rig.body` (`object_name`, `armature_name`, `spine_bones` 2-32, `head` `+y`/`-y`, `seeds`, `crease_cost`, +`smooth_rounds`). Bakes the object's transform into its mesh and parents it to the armature at identity, so no +node carries a scale. + +With no `armature_name` it makes `.rig`: a spine of equal bones along the principal axis, the root at the +head end (`head` names which end of world Y; the swim wave runs head to tail), and one bone per seed name. `seeds` +reads as in `cut_parts` (`name=x,y,z; ...`, several points may name one part). The spine is an implicit part named +`spine` seeded at the surface nearest each spine joint; a seed named `spine` adds to it. Each named part is grown +from its seeds along concave creases (`grow_parts`); its bone runs from the root of the part's cut +(`boundary_root`) to its centroid and hangs from the nearest spine bone. + +With an existing `armature_name` the armature is kept as it is: its spine is the first root's heaviest-child chain +(as the runtime derives it), every other body bone is seeded at the surface nearest its tail (`seeds` may add +points for a bone by name). The spine's bones must run from the head end to the tail end along the long axis. + +Weights: spine bones by axial projection, linear between neighbouring joints; a part's region 1 on its bone; then +`smooth_rounds` Laplacian rounds over the welded vertex graph, the top 4 kept and normalised. + +### tendrils + +`brokkr_rig.tendrils` (`object_name`, `armature_name`, `tau`, `band`, `dilate` as shares of the longest side, +`fold_bands`, `min_joints`, `blend`, `stiffness`, `stiffness_tip_ratio`, `drag`, `gravity_power`, `hit_scale`). +Needs `body` first. The mesh is welded; each vertex gets a shape diameter (median of five inward rays, fixed +seed; an open sheet with no back face reads 0). The body is the largest component thicker than `tau`, dilated by +`dilate`. Edge distance from the body is cut into bands of `band`; each band splits into connected rings, one +joint per ring at its centroid, its parent the ring it touches one band nearer. + +- A tree (everything hanging from one root ring) whose farthest vertex lies within `fold_bands` bands of the body + is a surface vein and folds into the body; so does a tree whose main path has fewer than `min_joints` rings. +- Each remaining tree's root-to-deepest-leaf path is one spring, ending in a tip joint at the leaf ring's farthest + vertex (the runtime gives a chain's last joint its parent's aimed rotation). Side branches cannot be springs of + their own (a spring's first joint must hang from a body bone), so their vertices weight rigidly to the main-path + bone at their fork. +- Vertices the distance never reaches (detached shells) weight rigidly, per shell, to the nearest spring bone. +- Weights: a vertex between joints k and k+1 goes to bone k, blending linearly from bone k-1 over `blend` bands + from joint k, and with the body weights of its nearest body vertex within `blend` bands of the body. +- Bones `tendril__`; joint 0 hangs from the body bone with most weight at its ring's body boundary. Bone + ID properties: `rig_chain`, `rig_index`, `rig_stiffness` (tapered from the root to the tip by + `stiffness_tip_ratio`), `rig_drag`, `rig_gravity`, `rig_hit_radius` (half the ring's median shape diameter times + `hit_scale`). Running it again replaces every earlier chain. + +The report counts chains, spring bones, rigid branches, veins folded, shells attached and unreached vertices. + +### colliders + +`brokkr_rig.colliders` (`object_name`, `armature_name`, `scale`). A capsule per spine bone from head to tail, +radius the median radial distance of the body vertices projecting onto it times `scale`; a sphere per other body +bone at the centroid of its heaviest vertices, radius the median distance times `scale`. Each radius is then +shrunk until every spring joint past the first stands at least its hit radius outside it at rest (`shrunk` counts +them). Stored as the bone's `rig_colliders` property list. + +## What it cannot do + +It does not judge a rig: acceptance is the runtime's parse. It does not simulate the springs (the report's +chain, joint and collider counts are what was built, not how it moves). It reads thickness from rays against the +mesh, so a mesh whose windings face inward needs `repair` and `recalc_normals` first. A vein the dilation reaches +is absorbed before the fold rule sees it. Seeds on a smooth surface split by distance alone. + +## A recipe + +```json +{"requestedBy": "nibu/hands", "importDir": "work", "outputDir": "work", + "hostAddons": ["brokkr_mesh_polish", "brokkr_rig"], "saveBlend": "work/whale.blend", + "intents": [ + {"action": "importGltf", "filepath": "whale.glb"}, + {"action": "brokkr_mesh_polish.audit"}, + {"action": "brokkr_mesh_polish.repair", "object_name": "whale_mesh"}, + {"action": "brokkr_mesh_polish.orient", "object_name": "whale_root", "length": 1.0}, + {"action": "brokkr_rig.body", "object_name": "whale_mesh", "spine_bones": 8, "head": "+y", "seeds": "jaw=0.2,0.4,0"}, + {"action": "brokkr_rig.tendrils", "object_name": "whale_mesh", "tau": 0.04, "band": 0.04, "dilate": 0.04}, + {"action": "brokkr_rig.colliders", "object_name": "whale_mesh"}, + {"action": "exportGltf", "filepath": "whale_rigged.glb"}]} +``` + +Pick seed points from a flat turntable with `brokkr_mesh_polish.pick`, and pick `head` by eye from a render. Run +the recipe with `tools/run_intents.py` under private `BLENDER_USER_*` directories (`mesh-polish.md`), then +`VerifyGlb` on `whale_rigged.glb`. + +The live proof is `tests/live/rig.py` (a synthetic whale through the same intents; `rig.result.json` is its last +run). diff --git a/surfaces/blender/tests/live/rig.py b/surfaces/blender/tests/live/rig.py new file mode 100644 index 0000000..54bc1a4 --- /dev/null +++ b/surfaces/blender/tests/live/rig.py @@ -0,0 +1,272 @@ +"""Live proof, in a background Blender, that the brokkr_rig rows are admitted by Brokkr as host actions and that a +synthetic whale (a capsule body, six tendrils of which one forks and one is a vein lying on the body, a detached +bead and a jaw seed) goes through run_intent: repair, orient, body, tendrils, colliders, exportGltf, and comes out +as a GLB the exporter hook has given VRMC_springBone. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/rig.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). Writes .result.json and .glb (the synthetic whale's rig, for the runtime's own parse, +Aetheria SpringRigVerify.VerifyGlb) and exits 1 when a check failed. The acceptance is the runtime's parse, not +anything here: the structure checks below are what this builder promised, not the runtime's rules. +""" +import json +import math +import os +import struct +import sys +import tempfile +import time +import types +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix, Vector + +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] +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 + +sys.path.append(str(SURFACE)) +T0 = time.time() +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_rig"): + addon_utils.enable(module, default_set=True) +target = bt.BrokkrBlenderTarget(bpy) +WORK = Path(tempfile.mkdtemp(prefix="brokkr-rig-live-")) +target.configure_action_dirs("", str(WORK)) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], + "hostRows": [row["name"] for row in target.host_actions()[0]]} +COUNT = [0] +T0 = time.time() + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +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 = json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None + print("SEND", f"{time.time() - T0:.1f}s", action, receipt["status"], str(receipt["message"])[:300], flush=True) + return receipt, result + + +def tube(start, end, radius=0.006, segments=6): + start, end = Vector(start), Vector(end) + along = end - start + matrix = Matrix.Translation((start + end) / 2) @ along.to_track_quat("Z", "Y").to_matrix().to_4x4() + return matrix, along.length, radius, segments + + +def make_whale(): + """Body: an ellipsoid 0.24 x 1.0 x 0.24. Tendrils are tubes whose first 0.03 lies inside the body, joined by an + exact union so the skin is fused as a generated mesh is; the bead is a separate shell.""" + body = bmesh.new() + bmesh.ops.create_uvsphere(body, u_segments=32, v_segments=24, radius=1.0, calc_uvs=True) + bmesh.ops.scale(body, vec=(0.12, 0.5, 0.12), verts=body.verts) + bm = bmesh.new() + inside = 0.03 + specs = [] + for y, tilt, length in ((-0.3, -0.4, 0.34), (-0.1, 0.4, 0.3), (0.1, -0.2, 0.36), (0.3, 0.3, 0.28)): + d = Vector((tilt, 0.0, -1.0)).normalized() + surface = Vector((0.0, y, -0.12 * math.sqrt(max(1.0 - (y / 0.5) ** 2, 0.0)))) + specs.append((surface - d * inside, surface + d * length)) + d = Vector((0.5, 0.2, -1.0)).normalized() # the forked one: a trunk with a side branch near its middle + surface = Vector((0.0, 0.0, -0.12)) + trunk = (surface - d * inside, surface + d * 0.4) + specs.append(trunk) + mid = surface + d * 0.2 + specs.append((mid - Vector((0.0, 0.01, 0.0)), mid + Vector((0.0, 0.18, -0.05)))) + specs.append((Vector((-0.02, -0.12, 0.125)), Vector((-0.02, 0.12, 0.125)))) # the vein lies along the top + for start, end in specs: + matrix, depth, radius, segments = tube(start, end, 0.015 if end.z > 0.1 else 0.006) + bmesh.ops.create_cone(bm, cap_ends=True, segments=segments, radius1=radius, radius2=radius, depth=depth, matrix=matrix) + bmesh.ops.subdivide_edges(bm, edges=[e for e in bm.edges if e.calc_length() > 0.05], cuts=15, use_grid_fill=True) + mesh = bpy.data.meshes.new("Whale") + body.to_mesh(mesh) + body.free() + mesh.uv_layers.new(name="UVMap") + tubes = bpy.data.meshes.new("WhaleTubes") + bm.to_mesh(tubes) + bm.free() + obj = bpy.data.objects.new("Whale", mesh) + other = bpy.data.objects.new("WhaleTubes", tubes) + for o in (obj, other): + bpy.context.scene.collection.objects.link(o) + mod = obj.modifiers.new("Union", "BOOLEAN") + mod.operation, mod.operand_type, mod.solver, mod.object, mod.use_self = "UNION", "OBJECT", "EXACT", other, True + bpy.context.view_layer.objects.active = obj + bpy.ops.object.modifier_apply(modifier="Union") + bpy.data.objects.remove(other) + bead = bmesh.new() + bmesh.ops.create_uvsphere(bead, u_segments=8, v_segments=6, radius=0.02, matrix=Matrix.Translation((0.3, 0.1, -0.3))) + mesh2 = bpy.data.meshes.new("Bead") + bead.to_mesh(mesh2) + bead.free() + both = bmesh.new() + both.from_mesh(obj.data) + both.from_mesh(mesh2) + both.to_mesh(obj.data) + both.free() + obj.data.uv_layers.new(name="UVMap") if not obj.data.uv_layers else None + bpy.data.meshes.remove(mesh2) + return obj + + +def glb_json(path): + blob = Path(path).read_bytes() + length = struct.unpack_from(" 0 + and arm.data.bones["jaw"].parent.name in body["spine"], body["parts"]) + head, tail = np.array(body["head"]), np.array(body["tail"]) + check("body: the root bone is at the +y end and the object's transform is baked", head[1] > tail[1] + and np.allclose(np.array(whale.matrix_world), np.eye(4), atol=1e-9) and arm.data.bones["spine_00"].parent is None, [head, tail]) +receipt, tendrils = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) +check("tendrils accepted", receipt["status"] == "accepted", receipt["message"]) +R["tendrils"] = tendrils +if tendrils: + check("tendrils: five chains (the vein folded), the fork made one chain with a rigid branch, the bead attached", + tendrils["chains"] == 5 and tendrils["veinsFolded"] >= 1 and tendrils["branchesRigid"] >= 1 and tendrils["shellsAttached"] >= 1, tendrils) +receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") +check("colliders accepted", receipt["status"] == "accepted", receipt["message"]) +R["colliders"] = colliders +receipt, again = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) +check("tendrils run again on the same rig gives the same chains", again and tendrils and again["chains"] == tendrils["chains"] + and again["springBones"] == tendrils["springBones"], [again, tendrils]) +receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") +R["colliders"] = colliders + +# --- export: the five attributes, weights, extension, structure ---------------------------------------------------- +receipt, _ = send("exportGltf", filepath="whale.glb", extras=False, yUp=True, applyModifiers=True) +check("exportGltf accepted", receipt["status"] == "accepted", receipt["message"]) +gltf, blob, bin_at = glb_json(WORK / "whale.glb") +ext = gltf.get("extensions", {}).get("VRMC_springBone") +check("VRMC_springBone is in extensions and extensionsUsed", ext is not None and "VRMC_springBone" in gltf.get("extensionsUsed", []), list(gltf.get("extensions", {}))) +if ext and tendrils and colliders: + check("the springs, joints and colliders are the built ones", len(ext["springs"]) == tendrils["chains"] + and sum(len(s["joints"]) for s in ext["springs"]) == tendrils["springBones"] + and len(ext["colliders"]) == colliders["capsules"] + colliders["spheres"] + and all(s["colliderGroups"] == [0] for s in ext["springs"]) and [g["name"] for g in ext["colliderGroups"]] == ["body"], + [len(ext["springs"]), len(ext["colliders"])]) +prims = [p for m in gltf["meshes"] for p in m["primitives"]] +check("mesh primitives carry exactly the five attributes", all(set(p["attributes"]) == {"POSITION", "NORMAL", "TEXCOORD_0", "JOINTS_0", "WEIGHTS_0"} for p in prims), + [sorted(p["attributes"]) for p in prims]) +worst_sum, worst_count = 0.0, 0 +for p in prims: + if "WEIGHTS_0" not in p["attributes"]: + check("every primitive is skinned", False, sorted(p["attributes"])) + continue + acc = gltf["accessors"][p["attributes"]["WEIGHTS_0"]] + view = gltf["bufferViews"][acc["bufferView"]] + W = np.frombuffer(blob, np.float32, acc["count"] * 4, bin_at + view.get("byteOffset", 0) + acc.get("byteOffset", 0)).reshape(-1, 4) + worst_sum = max(worst_sum, float(np.abs(W.sum(axis=1) - 1).max())) + worst_count = max(worst_count, int((W > 0).sum(axis=1).max())) +check("weights sum to 1 with at most four influences", worst_sum < 1e-5 and worst_count <= 4, [worst_sum, worst_count]) +nodes = gltf["nodes"] +parent = {c: i for i, n in enumerate(nodes) for c in n.get("children", [])} +check("no node carries a matrix and every scale is 1", all("matrix" not in n and all(abs(s - 1) < 1e-4 for s in n.get("scale", (1, 1, 1))) for n in nodes), None) +joints = gltf["skins"][0]["joints"] +check("one skin over every bone", len(gltf["skins"]) == 1 and len(joints) == len(arm.data.bones), [len(joints), len(arm.data.bones)]) +if ext: + in_spring = {j["node"] for s in ext["springs"] for j in s["joints"]} + linear = all(parent.get(s["joints"][0]["node"]) in set(joints) - in_spring and all(parent[s["joints"][k]["node"]] == s["joints"][k - 1]["node"] for k in range(1, len(s["joints"]))) + for s in ext["springs"]) + check("each spring is a linear chain, its first joint hung from a body bone, no bone in two springs", linear + and len(in_spring) == sum(len(s["joints"]) for s in ext["springs"]), None) + check("every segment has length", all(np.linalg.norm(nodes[j["node"]].get("translation", (0, 0, 0))) > 1e-6 for s in ext["springs"] for j in s["joints"][1:]), None) + check("colliders sit on body bones", all(c["node"] in set(joints) - in_spring for c in ext["colliders"]), None) + swing = np.array([[1.0, 0, 0], [0, 0, 1.0], [0, -1.0, 0]]) + where = [world_of(nodes, parent, j["node"])[:3, 3] for s in ext["springs"] for j in s["joints"]] + expect = [swing @ np.array(arm.matrix_world @ arm.data.bones[nodes[j["node"]]["name"]].head_local) for s in ext["springs"] for j in s["joints"]] + check("every joint's node stands where its bone's head is in the scene", np.allclose(where, expect, atol=1e-4), float(np.abs(np.array(where) - np.array(expect)).max())) +R["glb"] = {"nodes": len(nodes), "joints": len(joints), "springs": len(ext["springs"]) if ext else 0, "colliders": len(ext["colliders"]) if ext else 0} +Path(OUT + ".glb").write_bytes((WORK / "whale.glb").read_bytes()) + +# --- determinism, yUp, and a scene with no rig ------------------------------------------------------------------------ +send("exportGltf", filepath="again.glb", extras=False, yUp=True, applyModifiers=True) +a, b = glb_json(WORK / "whale.glb")[0], glb_json(WORK / "again.glb")[0] +check("two exports have identical JSON chunks", json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True), None) +send("exportGltf", filepath="flat.glb", extras=False, yUp=False, applyModifiers=True) +flat, _, _ = glb_json(WORK / "flat.glb") +fext = flat.get("extensions", {}).get("VRMC_springBone") +if ext and fext: + nodes_f = flat["nodes"] + parent_f = {c: i for i, n in enumerate(nodes_f) for c in n.get("children", [])} + names = {n["name"]: i for i, n in enumerate(nodes)} + + def collider_world(gl, nd, par, c, key): + return (world_of(nd, par, c["node"]) @ np.append(c["shape"][list(c["shape"])[0]][key], 1.0))[:3] + + pairs = [(collider_world(gltf, nodes, parent, c, "offset"), collider_world(flat, nodes_f, parent_f, f, "offset")) + for c, f in zip(ext["colliders"], fext["colliders"])] + check("yUp false: a collider's node-local offset composes to the same scene point (up to the axis swing)", + bool(pairs) and all(np.allclose(up, swing @ flat_point, atol=1e-4) for up, flat_point in pairs), pairs[:1]) +bpy.ops.mesh.primitive_cube_add() +cube = bpy.context.active_object +cube.name = "Cube" +send("exportGltf", filepath="cube.glb", extras=False, yUp=True, applyModifiers=True, selection=["Cube"]) +cube_json, _, _ = glb_json(WORK / "cube.glb") +check("a scene with no rig springs exports no VRMC_springBone", "VRMC_springBone" not in cube_json.get("extensions", {}) + and "VRMC_springBone" not in cube_json.get("extensionsUsed", []), list(cube_json.get("extensions", {}))) + +R["ok"] = all(c["ok"] for c in R["checks"]) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") +for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/rig.result.json b/surfaces/blender/tests/live/rig.result.json new file mode 100644 index 0000000..3cbaafd --- /dev/null +++ b/surfaces/blender/tests/live/rig.result.json @@ -0,0 +1,390 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "host file admitted", + "ok": true, + "detail": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick", + "brokkr_rig.body", + "brokkr_rig.tendrils", + "brokkr_rig.colliders" + ] + }, + { + "name": "fixture: one fused shell and a detached bead", + "ok": true, + "detail": { + "Whale": { + "triangles": 3094, + "vertices": 1551, + "weldedVertices": 1549, + "extent": [ + 1.0, + 0.451844, + 0.615025 + ], + "surfaceArea": 0.6858676781563833, + "degenerateTriangles": 0, + "edges": 4635, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 4, + "windingAgainstNormals": 1, + "shells": 2, + "shellTriangles": [ + 3014, + 80 + ], + "uvIslands": 721, + "uvMirroredTriangles": 1, + "uvZeroAreaTriangles": 1508, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 1.0, + "uvOverlap": 1.0, + "baseColorImage": "", + "baseColorSize": [ + 0, + 0 + ], + "customNormals": false + } + } + }, + { + "name": "repair accepted", + "ok": true, + "detail": "Operator brokkr_mesh_polish.repair finished." + }, + { + "name": "orient accepted", + "ok": true, + "detail": "Operator brokkr_mesh_polish.orient finished." + }, + { + "name": "body accepted", + "ok": true, + "detail": "Operator brokkr_rig.body finished." + }, + { + "name": "body: a spine of six, a jaw bone parented to a spine bone", + "ok": true, + "detail": [ + { + "name": "jaw", + "root": [ + -0.157115, + 0.175099, + 0.032488 + ], + "tail": [ + -0.15589, + 0.217733, + 0.04605 + ], + "triangles": 91 + } + ] + }, + { + "name": "body: the root bone is at the +y end and the object's transform is baked", + "ok": true, + "detail": [ + "[-0.183123 0.5 -0.039007]", + "[-0.16983 -0.5 -0.027336]" + ] + }, + { + "name": "tendrils accepted", + "ok": true, + "detail": "Operator brokkr_rig.tendrils finished." + }, + { + "name": "tendrils: five chains (the vein folded), the fork made one chain with a rigid branch, the bead attached", + "ok": true, + "detail": { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + } + }, + { + "name": "colliders accepted", + "ok": true, + "detail": "Operator brokkr_rig.colliders finished." + }, + { + "name": "tendrils run again on the same rig gives the same chains", + "ok": true, + "detail": [ + { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + }, + { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + } + ] + }, + { + "name": "exportGltf accepted", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-hx2wf__p\\whale.glb (301168 bytes)." + }, + { + "name": "VRMC_springBone is in extensions and extensionsUsed", + "ok": true, + "detail": [ + "VRMC_springBone" + ] + }, + { + "name": "the springs, joints and colliders are the built ones", + "ok": true, + "detail": [ + 5, + 7 + ] + }, + { + "name": "mesh primitives carry exactly the five attributes", + "ok": true, + "detail": [ + [ + "JOINTS_0", + "NORMAL", + "POSITION", + "TEXCOORD_0", + "WEIGHTS_0" + ] + ] + }, + { + "name": "weights sum to 1 with at most four influences", + "ok": true, + "detail": [ + 1.1920928955078125e-07, + 4 + ] + }, + { + "name": "no node carries a matrix and every scale is 1", + "ok": true, + "detail": null + }, + { + "name": "one skin over every bone", + "ok": true, + "detail": [ + 57, + 57 + ] + }, + { + "name": "each spring is a linear chain, its first joint hung from a body bone, no bone in two springs", + "ok": true, + "detail": null + }, + { + "name": "every segment has length", + "ok": true, + "detail": null + }, + { + "name": "colliders sit on body bones", + "ok": true, + "detail": null + }, + { + "name": "every joint's node stands where its bone's head is in the scene", + "ok": true, + "detail": 7.357579227540434e-07 + }, + { + "name": "two exports have identical JSON chunks", + "ok": true, + "detail": null + }, + { + "name": "yUp false: a collider's node-local offset composes to the same scene point (up to the axis swing)", + "ok": true, + "detail": [ + [ + "[-0.183123 -0.039007 -0.5 ]", + "[-0.183123 0.5 -0.039007]" + ] + ] + }, + { + "name": "a scene with no rig springs exports no VRMC_springBone", + "ok": true, + "detail": [] + } + ], + "hostErrors": [], + "hostRows": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick", + "brokkr_rig.body", + "brokkr_rig.tendrils", + "brokkr_rig.colliders" + ], + "audit": { + "Whale": { + "triangles": 3094, + "vertices": 1551, + "weldedVertices": 1549, + "extent": [ + 1.0, + 0.451844, + 0.615025 + ], + "surfaceArea": 0.6858676781563833, + "degenerateTriangles": 0, + "edges": 4635, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 4, + "windingAgainstNormals": 1, + "shells": 2, + "shellTriangles": [ + 3014, + 80 + ], + "uvIslands": 721, + "uvMirroredTriangles": 1, + "uvZeroAreaTriangles": 1508, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 1.0, + "uvOverlap": 1.0, + "baseColorImage": "", + "baseColorSize": [ + 0, + 0 + ], + "customNormals": false + } + }, + "body": { + "object": "Whale", + "armature": "Whale.rig", + "created": true, + "spine": [ + "spine_00", + "spine_01", + "spine_02", + "spine_03", + "spine_04", + "spine_05" + ], + "parts": [ + { + "name": "jaw", + "root": [ + -0.157115, + 0.175099, + 0.032488 + ], + "tail": [ + -0.15589, + 0.217733, + 0.04605 + ], + "triangles": 91 + } + ], + "head": [ + -0.183123, + 0.5, + -0.039007 + ], + "tail": [ + -0.16983, + -0.5, + -0.027336 + ], + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "vertices": 1546, + "weldedVertices": 1546 + }, + "tendrils": { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + }, + "colliders": { + "capsules": 6, + "spheres": 1, + "shrunk": 4, + "dropped": 0, + "skipped": 0, + "object": "Whale", + "armature": "Whale.rig", + "springJoints": 45 + }, + "glb": { + "nodes": 59, + "joints": 57, + "springs": 5, + "colliders": 7 + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_rig.py b/surfaces/blender/tests/test_rig.py new file mode 100644 index 0000000..35bcf2b --- /dev/null +++ b/surfaces/blender/tests/test_rig.py @@ -0,0 +1,266 @@ +"""Rig builder tests. No Blender: the arithmetic in brokkr_rig/core.py on a hand-built tube graph with one fork, the +host action file against Brokkr's own checker, and the shared cut-root formula. + +Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) +The operators and the exporter hook are exercised in a real Blender by tests/live/rig.py; the runtime's own parse +of the GLB is Aetheria's SpringRigVerify.VerifyGlb. + +Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is +the built value, and each names the mutant it kills. +""" +from __future__ import annotations + +import importlib +import importlib.util +import json +import re +import sys +import types +import unittest +from pathlib import Path + +SURFACE = Path(__file__).resolve().parents[1] +for name in ("brokkr_bridge", "brokkr_mesh_polish"): + package = types.ModuleType(name) + package.__path__ = [str(SURFACE / name)] + sys.modules.setdefault(name, package) +from brokkr_bridge import action_table as at # noqa: E402 + +try: + import numpy as np +except ImportError: # pragma: no cover + np = None + +if np is not None: + polish = importlib.import_module("brokkr_mesh_polish.core") + spec = importlib.util.spec_from_file_location("brokkr_rig_core", SURFACE / "brokkr_rig" / "core.py") + core = importlib.util.module_from_spec(spec) + spec.loader.exec_module(core) + +BAND, TAU = 0.25, 0.1 + + +def tube_graph(vein: bool = True): + """A body of three stations (thick), a trunk of nine stations along x that forks at station 5 into a branch of + three along y, and a short vein of two stations off the body. Every station is two vertices 0.01 apart, so a + ring is a handful of vertices. Distances from the body run .11 per trunk station: bands 0,0,1,1,2,2,3,3,3.""" + V, E, sd = [], [], [] + + def station(x, y, thick=False): + a = len(V) + V.extend([(x, y, 0.0), (x, y, 0.01)]) + sd.extend([1.0 if thick else 0.01] * 2) + E.append((a, a + 1)) + return a + + def join(a, b): + E.extend([(a, b), (a + 1, b + 1), (a, b + 1), (a + 1, b)]) + + body = [station(-0.2 + 0.1 * i, 0.0, True) for i in range(3)] + for a, b in zip(body, body[1:]): + join(a, b) + trunk, last = [], body[-1] + for k in range(1, 10): + trunk.append(station(0.11 * k, 0.0)) + join(last, trunk[-1]) + last = trunk[-1] + branch, last = [], trunk[4] + for k in range(1, 4): + branch.append(station(0.55, 0.11 * k)) + join(last, branch[-1]) + last = branch[-1] + veins, last = [], body[0] + for k in range(1, 3) if vein else (): + veins.append(station(-0.2, 0.11 * k)) + join(last, veins[-1]) + last = veins[-1] + return np.array(V), np.array(E), np.array(sd), {"body": body, "trunk": trunk, "branch": branch, "vein": veins} + + +def extract(fold_bands=1.5, min_joints=1, vein=True): + V, E, sd, at_ = tube_graph(vein) + return V, E, sd, at_, core.extract(V, E, sd, TAU, BAND, 0.0, fold_bands, min_joints) + + +class RingTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_rings_make_the_tree(self): + """Dies if a ring's parent is taken from its own band.""" + V, E, sd, s, f = extract(vein=False) + self.assertEqual(int(f.body.sum()), 6) + trunk_rings = [int(f.ring[s["trunk"][i]]) for i in (0, 2, 4, 6)] + self.assertEqual([int(f.band[r]) for r in trunk_rings], [0, 1, 2, 3]) + self.assertEqual(len(f.parent), 5) + self.assertEqual([int(f.parent[r]) for r in trunk_rings], [-1, trunk_rings[0], trunk_rings[1], trunk_rings[2]]) + branch_ring = int(f.ring[s["branch"][2]]) + self.assertNotEqual(branch_ring, trunk_rings[3]) + self.assertEqual(int(f.parent[branch_ring]), trunk_rings[2]) + self.assertEqual(int(f.band[branch_ring]), 3) + self.assertEqual([int(r) for r in np.flatnonzero(f.parent < 0)], [trunk_rings[0]]) + for r in range(5): + self.assertNotEqual(int(f.band[f.parent[r]]) if f.parent[r] >= 0 else -1, int(f.band[r])) + + @unittest.skipIf(np is None, "numpy") + def test_main_path_and_tip(self): + """Dies without the tip or with the branch as a second spring.""" + V, E, sd, s, f = extract(vein=False) + self.assertEqual(len(f.chains), 1) + chain = f.chains[0] + trunk_rings = [int(f.ring[s["trunk"][i]]) for i in (0, 2, 4, 6)] + self.assertEqual(chain.rings, trunk_rings) + self.assertFalse(chain.folded) + branch_ring = int(f.ring[s["branch"][2]]) + self.assertFalse(bool(f.on_main[branch_ring])) + self.assertEqual(int(f.fork[branch_ring]), trunk_rings[2]) + springs = core.plan(V, sd, f, BAND) + self.assertEqual(len(springs), 1) + spring = springs[0] + self.assertEqual(len(spring.pos), 5) # four rings and the tip + tip = s["trunk"][8] + farthest = tip + int(np.argmax(f.d[[tip, tip + 1]])) + self.assertTrue(np.allclose(spring.pos[-1], V[farthest])) + self.assertGreater(float(np.linalg.norm(spring.pos[-1] - spring.pos[-2])), 0.0) + # the side branch's vertices weight 1 to the fork's bone + body_idx, body_w = np.zeros((len(V), 4), dtype=np.int64), np.zeros((len(V), 4)) + body_w[:, 0] = 1.0 + idx, w, start = core.tendril_weights(V, E, f, springs, body_idx, body_w, 1, BAND, 0.5) + for v in (s["branch"][1], s["branch"][2]): + self.assertEqual((int(idx[v, 0]), float(w[v, 0])), (start[0] + 2, 1.0)) + + @unittest.skipIf(np is None, "numpy") + def test_vein_folds(self): + """Dies with fold off or fold always on.""" + for bands, folded in ((0.0, [False, False]), (1.5, [True, False]), (4.0, [True, True])): + *_, f = extract(fold_bands=bands) + self.assertEqual(sorted(c.folded for c in f.chains), sorted(folded), bands) + *_, f = extract(min_joints=3) + self.assertEqual(sorted(c.folded for c in f.chains), [False, True]) # the vein has two rings + + +class WeightTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_weights_partition(self): + """Dies if weights go to bone k + 1 (the joint the segment ends at).""" + V, E, sd, s, f = extract(vein=False) + springs = core.plan(V, sd, f, BAND) + body_idx, body_w = np.zeros((len(V), 4), dtype=np.int64), np.zeros((len(V), 4)) + body_w[:, 0] = 1.0 + idx, w, start = core.tendril_weights(V, E, f, springs, body_idx, body_w, 1, BAND, 0.5) + self.assertTrue(np.allclose(w.sum(axis=1), 1.0, atol=1e-6)) + self.assertLessEqual(int((w > 0).sum(axis=1).max()), 4) + self.assertTrue((idx[w > 0] < start[0] + len(springs[0].pos)).all()) + reach = 0.5 * BAND + D = springs[0].dist + for v in (s["trunk"][2], s["trunk"][3]): # outside the blend: bone k alone; inside: linear from bone k - 1 + d = f.d[v] + k = int(np.searchsorted(D, d, side="right")) - 1 + t = min((d - D[k]) / reach, 1.0) + got = {int(b): float(x) for b, x in zip(idx[v], w[v]) if x > 0} + if t >= 1.0: + self.assertEqual(got, {start[0] + k: 1.0}) + else: + self.assertAlmostEqual(got[start[0] + k], t, places=9) + self.assertAlmostEqual(got[start[0] + k - 1], 1.0 - t, places=9) + outside = [v for v in s["trunk"] if (lambda k: k >= 0 and (f.d[v] - D[k]) / reach >= 1.0)(int(np.searchsorted(D, f.d[v], side="right")) - 1)] + self.assertTrue(outside) + # a vertex at the body is the body's; one in the blend is part body + near = s["trunk"][0] + self.assertGreater(float(w[near][idx[near] == 0].sum()) if (idx[near] == 0).any() else 0.0, 0.0) + + @unittest.skipIf(np is None, "numpy") + def test_axial_weights_are_linear_between_knots_and_sum_to_one(self): + knots = np.array([0.0, 1.0, 3.0]) + W = core.axial_weights(np.array([-1.0, 0.0, 0.5, 1.0, 2.0, 3.0, 9.0]), knots) + self.assertTrue(np.allclose(W.sum(axis=1), 1.0)) + self.assertTrue(np.allclose(W[[0, 1, 3, 5, 6]], np.eye(3)[[0, 0, 1, 2, 2]])) + self.assertTrue(np.allclose(W[2], [0.5, 0.5, 0.0]) and np.allclose(W[4], [0.0, 0.5, 0.5])) + + @unittest.skipIf(np is None, "numpy") + def test_top4_keeps_the_heaviest_and_normalises(self): + idx, w = core.top4(np.array([[0.1, 0.5, 0.2, 0.15, 0.05]])) + self.assertEqual(sorted(idx[0].tolist()), [0, 1, 2, 3]) + self.assertAlmostEqual(float(w.sum()), 1.0, places=12) + self.assertAlmostEqual(float(w[0, 0]), 0.5 / 0.95, places=12) + + +class ColliderTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_colliders_clear_rest(self): + """Dies without the shrink.""" + a, b = np.array([0.0, 0.0, 0.0]), np.array([1.0, 0.0, 0.0]) + joints = np.array([[0.5, 0.4, 0.0], [2.0, 0.0, 0.0]]) + hit = np.array([0.05, 0.05]) + radius = core.clear_radius(0.5, joints, hit, a, b) + self.assertAlmostEqual(radius, 0.35, places=12) + self.assertTrue((core.segment_distance(joints, a, b) - hit >= radius - 1e-12).all()) + self.assertFalse((core.segment_distance(joints, a, b) - hit >= 0.5).all()) + self.assertEqual(core.clear_radius(0.2, joints, hit, a, b), 0.2) # already clear: unchanged + self.assertAlmostEqual(core.clear_radius(1.0, joints[:1], hit[:1], a, a), float(np.linalg.norm([0.5, 0.4])) - 0.05, places=12) # a sphere + + @unittest.skipIf(np is None, "numpy") + def test_capsule_and_sphere_sizes(self): + ring = np.array([[np.cos(t), np.sin(t), z] for z in (0.2, 0.5, 0.8) for t in np.linspace(0, 6.2, 12)]) + self.assertAlmostEqual(core.capsule_radius(ring, np.array([0.0, 0.0, 0.0]), np.array([0.0, 0.0, 1.0]), 0.8), 0.8, places=9) + centre, radius = core.sphere_fit(ring[:12], 0.5) + self.assertTrue(np.allclose(centre[:2], ring[:12, :2].mean(axis=0))) + self.assertAlmostEqual(radius, 0.5 * float(np.median(np.linalg.norm(ring[:12] - centre, axis=1))), places=12) + + +class SharedRootTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_boundary_root_equals_the_former_inline_formula(self): + mids = np.array([[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [2.0, 4.0, 0.0]]) + lengths = np.array([1.0, 1.0, 2.0]) + inline = (mids * lengths[:, None]).sum(axis=0) / lengths.sum() + self.assertTrue(np.array_equal(polish.boundary_root(mids, lengths), inline)) + self.assertTrue(np.array_equal(polish.boundary_root(np.zeros((0, 3)), np.zeros(0)), np.zeros(3))) + source = (SURFACE / "brokkr_mesh_polish" / "__init__.py").read_text(encoding="utf-8") + self.assertIn("core.boundary_root(mids, lengths)", source) + self.assertNotIn("(mids * lengths[:, None]).sum(axis=0) / lengths.sum() if len(cut)", source) + + +class HostFileTests(unittest.TestCase): + def setUp(self): + self.document = json.loads((SURFACE / "brokkr_rig" / "brokkr_actions.json").read_text(encoding="utf-8")) + + def test_brokkr_admits_the_file(self): + """rows-check: Brokkr's own host-file checker.""" + at.check_host(self.document, at.table()["charsets"]) + + def test_every_row_names_an_operator_and_property_the_add_on_defines(self): + source = (SURFACE / "brokkr_rig" / "__init__.py").read_text(encoding="utf-8") + for row in self.document["actions"]: + self.assertIn(f'bl_idname = "{row["name"]}"', source) + self.assertEqual(row.get("result"), "brokkr_mesh_polish_result") + body = source.split(f'bl_idname = "{row["name"]}"')[1].split("def work")[0] + for field in row["fields"]: + self.assertIn(f" {field['name']}: bpy.props.", body, f"{row['name']}.{field['name']}") + + def test_a_valid_intent_is_admitted_and_a_bound_miss_is_refused(self): + host = [{**row, "host": "brokkr_rig"} for row in self.document["actions"]] + envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver"} + admitted = at.validate({**envelope, "action": "brokkr_rig.tendrils", "object_name": "Hull"}, host) + self.assertEqual(admitted["tau"], 0.04) + with self.assertRaises(at.IntentInvalid): + at.validate({**envelope, "action": "brokkr_rig.tendrils", "object_name": "Hull", "tau": 0.9}, host) + + +class OwnershipTests(unittest.TestCase): + """The negative patterns of the cut: the contract's refusals, a second exporter and the bridge stay out of brokkr_rig.""" + PATTERNS = (r"non-unit scale|first joint|named twice|not a skin joint", r"brokkr_bridge", r"export_scene\.gltf|struct\.pack") + + def sources(self): + return {p.name: p.read_text(encoding="utf-8") for p in (SURFACE / "brokkr_rig").glob("*.py")} + + def test_no_pattern_matches_the_package(self): + for pattern in self.PATTERNS: + for name, text in self.sources().items(): + self.assertIsNone(re.search(pattern, text), f"{pattern} in {name}") + + def test_the_patterns_bite(self): + for pattern, planted in zip(self.PATTERNS, ("Node 3 has a non-unit scale", "from brokkr_bridge import x", "struct.pack(' Date: Tue, 1 Dec 2026 07:53:21 +0100 Subject: [PATCH 065/223] brokkr_rig: reruns depend only on their inputs; body clears chains it would orphan; reports and tests (Soul s1 fix batch) tendrils starts from the body weights kept on the mesh instead of the vertex groups a past run rewrote; body on an existing armature removes the chain bones; the spine seed stays off tendrils; tendrils reports the biggest chain's share, fused contacts and a warning; colliders report each shrink; mutants of stiffness taper, hit radius, shell bone, main path and fold rule are killed. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_rig/__init__.py | 88 +++++- surfaces/blender/brokkr_rig/core.py | 9 + surfaces/blender/docs/rig.md | 29 +- surfaces/blender/tests/live/rig.py | 45 ++- surfaces/blender/tests/live/rig.result.json | 291 +++++++++++++++++--- surfaces/blender/tests/test_rig.py | 69 ++++- 6 files changed, 468 insertions(+), 63 deletions(-) diff --git a/surfaces/blender/brokkr_rig/__init__.py b/surfaces/blender/brokkr_rig/__init__.py index 1302b3d..b153ccd 100644 --- a/surfaces/blender/brokkr_rig/__init__.py +++ b/surfaces/blender/brokkr_rig/__init__.py @@ -33,6 +33,8 @@ from . import core CHAIN, INDEX, STIFFNESS, DRAG, GRAVITY, HIT, COLLIDERS = ("rig_chain", "rig_index", "rig_stiffness", "rig_drag", "rig_gravity", "rig_hit_radius", "rig_colliders") +OPEN_SHEET_WARN = 0.042 # the share of the mesh one chain may hold before tendrils warns: the geometric mean of the lace leviathan (0.0227) and the skeletal hull (0.0774), docs/rig.md +SPINE_THICK = 0.04 # shape diameter, as a share of the longest side, a triangle needs to take a spine seed GRAVITY_DOWN = (0.0, 0.0, -1.0) # Blender world; the exporter hook turns it into glTF world @@ -115,6 +117,44 @@ def write_weights(obj, names: list, ids: np.ndarray, idx: np.ndarray, w: np.ndar groups[b].add([vertex], weight, "REPLACE") +SOURCE = ("rig_src_i0", "rig_src_i1", "rig_src_i2", "rig_src_i3", "rig_src_w0", "rig_src_w1", "rig_src_w2", "rig_src_w3") + + +def write_source(obj, names: list, ids: np.ndarray, idx: np.ndarray, w: np.ndarray): + """Keep the body's own weights on the mesh (eight point attributes and the bone names they index), so tendrils, + which rewrite the vertex groups, always start again from them: a rerun is a function of its inputs.""" + for name in SOURCE: + if name in obj.data.attributes: + obj.data.attributes.remove(obj.data.attributes[name]) + for slot in range(4): + for prefix, column in (("rig_src_i", idx[ids, slot]), ("rig_src_w", w[ids, slot])): + attribute = obj.data.attributes.new(f"{prefix}{slot}", "FLOAT", "POINT") + attribute.data.foreach_set("value", column.astype(np.float32)) + obj["rig_src_bones"] = json.dumps(names) + + +def read_source(obj, names: list, ids: np.ndarray, count: int) -> np.ndarray: + """Dense body weights (welded vertices, names) from write_source; Refused when body has not run or a bone it + named is gone.""" + if "rig_src_bones" not in obj or SOURCE[0] not in obj.data.attributes: + raise Refused(f"Object {obj.name!r} has no body weights: run brokkr_rig.body first.") + kept = json.loads(obj["rig_src_bones"]) + missing = [n for n in kept if n not in names] + if missing: + raise Refused(f"Body bone {missing[0]!r} is gone from the armature: run brokkr_rig.body again.") + column = [names.index(n) for n in kept] + n = len(obj.data.vertices) + own = np.zeros((n, len(names))) + for slot in range(4): + i, v = np.empty(n, dtype=np.float32), np.empty(n, dtype=np.float32) + obj.data.attributes[f"rig_src_i{slot}"].data.foreach_get("value", i) + obj.data.attributes[f"rig_src_w{slot}"].data.foreach_get("value", v) + np.add.at(own, (np.arange(n), np.array(column)[i.astype(np.int64)]), v.astype(np.float64)) + out = np.zeros((count, len(names))) + out[ids] = own + return out + + def read_weights(obj, names: list, ids: np.ndarray, count: int) -> np.ndarray: """Dense weights (welded vertices, names) of the mesh's vertex groups called names.""" column = {obj.vertex_groups[n].index: i for i, n in enumerate(names) if n in obj.vertex_groups} @@ -222,7 +262,11 @@ class BROKKR_RIG_OT_body(PolishOperator): pairs = polish.face_adjacency(w.TW) centroid = w.Vw[w.TW].mean(axis=1) nearest = lambda point: int(np.argmin(((centroid - np.asarray(point)) ** 2).sum(axis=1))) # noqa: E731 - placed = [(nearest(point), 0) for point in ([a for a, _ in spine] + [spine[-1][1]])] + sd = shape_diameter(w) # the spine's seeds take body surface: a triangle with a thin vertex is a tendril or a sheet + solid = (sd[w.TW] >= SPINE_THICK * w.length).all(axis=1) + pool = np.flatnonzero(solid) if solid.any() else np.arange(len(w.TW)) + nearest_solid = lambda point: int(pool[np.argmin(((centroid[pool] - np.asarray(point)) ** 2).sum(axis=1))]) # noqa: E731 + placed = [(nearest_solid(point), 0) for point in ([a for a, _ in spine] + [spine[-1][1]])] placed += [(nearest(point), parts.index(name) if name in parts else 0) for name, point in seeds] part, _ = polish.grow_parts(len(w.TW), pairs, polish.crease_costs(w.Vw, w.TW, pairs, self.crease_cost), placed) part[part < 0] = 0 @@ -269,13 +313,23 @@ class BROKKR_RIG_OT_body(PolishOperator): bone.parent = edits[names[int(np.argmin([core.segment_distance(head[None], a, b)[0] for a, b in spine]))]] else: arm = existing + cleared = 0 + if existing is not None: # chains hang on the old weights: they go, and tendrils runs again + with edit_mode(context, arm) as edits: + for old in [e for e in edits if CHAIN in e]: + edits.remove(old) + cleared += 1 + for bone in arm.data.bones: + if COLLIDERS in bone: + del bone[COLLIDERS] write_weights(obj, bones, w.ids, idx, weight) + write_source(obj, bones, w.ids, idx, weight) for modifier in [m for m in obj.modifiers if m.type == "ARMATURE"]: obj.modifiers.remove(modifier) obj.modifiers.new("Armature", "ARMATURE").object = arm obj.parent = arm obj.matrix_parent_inverse = arm.matrix_world.inverted() - return {"object": obj.name, "armature": arm.name, "created": existing is None, "spine": names, + return {"object": obj.name, "armature": arm.name, "created": existing is None, "chainBonesCleared": cleared, "spine": names, "parts": [{"name": n, "root": rounded(h), "tail": rounded(t), "triangles": int((part == i + 1).sum())} for i, (n, h, t) in enumerate(region)], "head": rounded(spine[0][0]), "tail": rounded(spine[-1][1]), "axis": rounded(axis), @@ -309,13 +363,7 @@ class BROKKR_RIG_OT_tendrils(PolishOperator): if not body_bones: raise Refused(f"Armature {arm.name!r} has no body bones.") body_names = [b.name for b in body_bones] - Wb = read_weights(obj, body_names, w.ids, w.count) - known = Wb.sum(axis=1) > 0 # a vertex a past run skinned to a chain has none: it takes the nearest one's - if not known.any(): - raise Refused("No vertex has weight on a body bone: run brokkr_rig.body first.") - if not known.all(): - near = core.dijkstra(core.graph(w.Vw, w.E), np.flatnonzero(known))[2] - Wb = Wb[np.where(known, np.arange(w.count), np.where(near >= 0, near, 0))] + Wb = read_source(obj, body_names, w.ids, w.count) bidx, bw = core.top4(Wb) scale, band = w.length, self.band * w.length sd = shape_diameter(w) @@ -345,13 +393,13 @@ class BROKKR_RIG_OT_tendrils(PolishOperator): bone.head, bone.tail = Vector(to_arm(head)), Vector(to_arm(tail)) bone.parent = edits[spring.names[k - 1]] if k else edits[spring.bone] for c, spring in enumerate(springs): - last = len(spring.names) - 1 + stiffness, hit = core.joint_params(spring.sd, self.stiffness, self.stiffness_tip_ratio, self.hit_scale) for k, name in enumerate(spring.names): bone = arm.data.bones[name] bone[CHAIN], bone[INDEX] = f"tendril_{c:03d}", k - bone[STIFFNESS] = self.stiffness * (1.0 + (self.stiffness_tip_ratio - 1.0) * k / last) + bone[STIFFNESS] = float(stiffness[k]) bone[DRAG], bone[GRAVITY] = self.drag, self.gravity_power - bone[HIT] = float(0.5 * spring.sd[k] * self.hit_scale) + bone[HIT] = float(hit[k]) arm.data["rig_gravity_dir"] = list(GRAVITY_DOWN) write_weights(obj, names, w.ids, idx, weight) kept = [c for c in found.chains if not c.folded] @@ -359,7 +407,19 @@ class BROKKR_RIG_OT_tendrils(PolishOperator): shells = len(np.unique(polish.components(w.count, w.E[lost[w.E[:, 0]] & lost[w.E[:, 1]]])[lost])) if lost.any() else 0 branches = int(sum(1 for r in range(len(found.parent)) if not found.on_main[r] and found.parent[r] >= 0 and found.on_main[found.parent[r]] and found.tree[r] in {c.tree for c in kept})) + on_chain = (found.ring >= 0) & np.isin(found.tree[np.maximum(found.ring, 0)], [c.tree for c in kept]) + kept_trees = [c.tree for c in kept] + trees = found.tree[found.ring[on_chain]] + open_share = float(np.bincount(trees).max() / w.count) if on_chain.any() else 0.0 # the biggest chain's share of the mesh + ring_of = np.where(found.ring >= 0, found.tree[np.maximum(found.ring, 0)], -1) + a, b = ring_of[w.E[:, 0]], ring_of[w.E[:, 1]] + fused = int(((a >= 0) & (b >= 0) & (a != b) & np.isin(a, [c.tree for c in kept]) & np.isin(b, [c.tree for c in kept])).sum()) + warnings = [] + if open_share >= OPEN_SHEET_WARN: + warnings.append(f"one chain holds {open_share:.0%} of the mesh: a plate of a hull may have become a chain; " + "raise tau or fold_bands, or rig a mesh whose tendrils are tubes") return {"object": obj.name, "armature": arm.name, "bodyVertices": int(found.body.sum()), "chains": len(springs), + "chainVertexShare": float(on_chain.mean()), "largestChainShare": open_share, "fusedContacts": fused, "warnings": warnings, "springBones": int(sum(len(s.pos) for s in springs)), "branchesRigid": branches, "veinsFolded": len(found.chains) - len(kept), "shellsAttached": shells, "unreachedVertices": int(lost.sum()), "rings": int(len(found.parent)), @@ -389,7 +449,7 @@ class BROKKR_RIG_OT_colliders(PolishOperator): chain = [b for b in arm.data.bones if CHAIN in b and b[INDEX] >= 1] joints = np.array([world(b.head_local) for b in chain]).reshape(-1, 3) hit = np.array([b[HIT] for b in chain]) - made = {"capsules": 0, "spheres": 0, "shrunk": 0, "dropped": 0, "skipped": 0} + made = {"capsules": 0, "spheres": 0, "shrunk": 0, "dropped": 0, "skipped": 0, "shrinks": [], "shrunkMax": 0.0} for bone in body: if COLLIDERS in bone: del bone[COLLIDERS] @@ -408,6 +468,8 @@ class BROKKR_RIG_OT_colliders(PolishOperator): cleared = core.clear_radius(radius, joints, hit, offset, end) if cleared < radius: made["shrunk"] += 1 + made["shrinks"].append({"bone": bone.name, "before": round(float(radius), 6), "after": round(float(max(cleared, 0.0)), 6)}) + made["shrunkMax"] = round(max(made["shrunkMax"], float(1.0 - max(cleared, 0.0) / radius)), 4) if cleared <= 0: made["dropped"] += 1 continue diff --git a/surfaces/blender/brokkr_rig/core.py b/surfaces/blender/brokkr_rig/core.py index 5dde1d9..35c8ba9 100644 --- a/surfaces/blender/brokkr_rig/core.py +++ b/surfaces/blender/brokkr_rig/core.py @@ -347,3 +347,12 @@ def clear_radius(radius: float, joints: np.ndarray, hit: np.ndarray, a: np.ndarr if not len(joints): return radius return min(radius, float((segment_distance(joints, a, b) - hit).min())) + + +# --- spring parameters ----------------------------------------------------------------------------------- + +def joint_params(sd: np.ndarray, stiffness: float, tip_ratio: float, hit_scale: float) -> tuple[np.ndarray, np.ndarray]: + """(stiffness, hit radius) per joint of a spring whose joints' median shape diameters are sd: stiffness tapers + linearly from the root's value to tip_ratio times it at the tip; the hit radius is half the diameter times hit_scale.""" + last = len(sd) - 1 + return stiffness * (1.0 + (tip_ratio - 1.0) * np.arange(last + 1) / last), 0.5 * np.asarray(sd) * hit_scale diff --git a/surfaces/blender/docs/rig.md b/surfaces/blender/docs/rig.md index 1b3a0b9..cf85323 100644 --- a/surfaces/blender/docs/rig.md +++ b/surfaces/blender/docs/rig.md @@ -48,22 +48,29 @@ node carries a scale. With no `armature_name` it makes `.rig`: a spine of equal bones along the principal axis, the root at the head end (`head` names which end of world Y; the swim wave runs head to tail), and one bone per seed name. `seeds` reads as in `cut_parts` (`name=x,y,z; ...`, several points may name one part). The spine is an implicit part named -`spine` seeded at the surface nearest each spine joint; a seed named `spine` adds to it. Each named part is grown +`spine` seeded at the surface nearest each spine joint and the tail point, among triangles whose three vertices have +a shape diameter of at least 0.04 of the longest side (a tendril or a sheet never takes a spine seed); a seed named +`spine` adds to it. Each named part is grown from its seeds along concave creases (`grow_parts`); its bone runs from the root of the part's cut (`boundary_root`) to its centroid and hangs from the nearest spine bone. With an existing `armature_name` the armature is kept as it is: its spine is the first root's heaviest-child chain (as the runtime derives it), every other body bone is seeded at the surface nearest its tail (`seeds` may add points for a bone by name). The spine's bones must run from the head end to the tail end along the long axis. +Chain bones an earlier `tendrils` left on that armature are removed (the report says how many: `chainBonesCleared`), +because they hang on the old weights; run `tendrils` again. Weights: spine bones by axial projection, linear between neighbouring joints; a part's region 1 on its bone; then -`smooth_rounds` Laplacian rounds over the welded vertex graph, the top 4 kept and normalised. +`smooth_rounds` Laplacian rounds over the welded vertex graph, the top 4 kept and normalised. They are also kept on +the mesh (point attributes `rig_src_*` and the object property `rig_src_bones`), because `tendrils` rewrites the +vertex groups. ### tendrils `brokkr_rig.tendrils` (`object_name`, `armature_name`, `tau`, `band`, `dilate` as shares of the longest side, `fold_bands`, `min_joints`, `blend`, `stiffness`, `stiffness_tip_ratio`, `drag`, `gravity_power`, `hit_scale`). -Needs `body` first. The mesh is welded; each vertex gets a shape diameter (median of five inward rays, fixed +Needs `body` first, and starts from the body's weights kept on the mesh, so a run depends only on the mesh and its +knobs, never on earlier runs. The mesh is welded; each vertex gets a shape diameter (median of five inward rays, fixed seed; an open sheet with no back face reads 0). The body is the largest component thicker than `tau`, dilated by `dilate`. Edge distance from the body is cut into bands of `band`; each band splits into connected rings, one joint per ring at its centroid, its parent the ring it touches one band nearer. @@ -82,22 +89,30 @@ joint per ring at its centroid, its parent the ring it touches one band nearer. `stiffness_tip_ratio`), `rig_drag`, `rig_gravity`, `rig_hit_radius` (half the ring's median shape diameter times `hit_scale`). Running it again replaces every earlier chain. -The report counts chains, spring bones, rigid branches, veins folded, shells attached and unreached vertices. +The report counts chains, spring bones, rigid branches, veins folded, shells attached and unreached vertices, and +gauges the rig: `chainVertexShare`, `largestChainShare` (the biggest chain's share of the mesh) and `fusedContacts` +(mesh edges joining two different chains). `warnings` says when one chain holds 4.2% of the mesh or more, which +is what a hull plate that became a chain looks like (the lace leviathan reads 2.3%, the skeletal and mantle hulls +7.7% and 11.2%; the bound is the geometric mean of the first two). An open sheet reads shape diameter 0, so on a +hull the builder succeeds; read the warning. ### colliders `brokkr_rig.colliders` (`object_name`, `armature_name`, `scale`). A capsule per spine bone from head to tail, radius the median radial distance of the body vertices projecting onto it times `scale`; a sphere per other body bone at the centroid of its heaviest vertices, radius the median distance times `scale`. Each radius is then -shrunk until every spring joint past the first stands at least its hit radius outside it at rest (`shrunk` counts -them). Stored as the bone's `rig_colliders` property list. +shrunk until every spring joint past the first stands at least its hit radius outside it at rest. The report lists +each shrink (`shrinks`: bone, before, after) and the largest fraction (`shrunkMax`): where tendrils lie on the +body at rest the rule fits colliders to the gaps between them (the leviathan's spine_07 shrinks by 91%). Stored as the bone's `rig_colliders` property list. ## What it cannot do It does not judge a rig: acceptance is the runtime's parse. It does not simulate the springs (the report's chain, joint and collider counts are what was built, not how it moves). It reads thickness from rays against the mesh, so a mesh whose windings face inward needs `repair` and `recalc_normals` first. A vein the dilation reaches -is absorbed before the fold rule sees it. Seeds on a smooth surface split by distance alone. +is absorbed before the fold rule sees it. Seeds on a smooth surface split by distance alone. A fused generated +mesh joins tendrils that touch: the edges between two chains stretch when the chains move apart (the leviathan has +132 such edges; `fusedContacts` counts them). ## A recipe diff --git a/surfaces/blender/tests/live/rig.py b/surfaces/blender/tests/live/rig.py index 54bc1a4..26de79f 100644 --- a/surfaces/blender/tests/live/rig.py +++ b/surfaces/blender/tests/live/rig.py @@ -186,10 +186,28 @@ if tendrils: receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") check("colliders accepted", receipt["status"] == "accepted", receipt["message"]) R["colliders"] = colliders + + +def skin_state(): + """Every vertex's (group name, weight) pairs and every chain bone's properties, exactly as stored.""" + groups = [g.name for g in whale.vertex_groups] + weights = [sorted((groups[e.group], e.weight) for e in v.groups) for v in whale.data.vertices] + props = {b.name: [b[k] for k in ("rig_chain", "rig_index", "rig_stiffness", "rig_drag", "rig_gravity", "rig_hit_radius")] + for b in arm.data.bones if "rig_chain" in b} + return weights, props + + +first = skin_state() +send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.06, dilate=0.02) +other = skin_state() receipt, again = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) -check("tendrils run again on the same rig gives the same chains", again and tendrils and again["chains"] == tendrils["chains"] - and again["springBones"] == tendrils["springBones"], [again, tendrils]) +check("tendrils with other knobs changes the skin", other != first, None) +check("tendrils, other knobs, then the first knobs again restores the weights and bone properties exactly", skin_state() == first, None) +check("the tendrils report says what it sees", tendrils and {"warnings", "largestChainShare", "chainVertexShare", "fusedContacts"} <= set(tendrils) + and len(tendrils["warnings"]) == 1 and "one chain holds" in tendrils["warnings"][0], tendrils) # five chains hold 13% each at most: hull-like by the gauge receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") +check("the colliders report lists each shrink", colliders and len(colliders["shrinks"]) == colliders["shrunk"] + and all(x["after"] < x["before"] for x in colliders["shrinks"]), colliders) R["colliders"] = colliders # --- export: the five attributes, weights, extension, structure ---------------------------------------------------- @@ -204,6 +222,12 @@ if ext and tendrils and colliders: and len(ext["colliders"]) == colliders["capsules"] + colliders["spheres"] and all(s["colliderGroups"] == [0] for s in ext["springs"]) and [g["name"] for g in ext["colliderGroups"]] == ["body"], [len(ext["springs"]), len(ext["colliders"])]) +check("the extension is not required", "VRMC_springBone" not in gltf.get("extensionsRequired", []), gltf.get("extensionsRequired")) +if ext: + check("stiffness tapers from the root's 3 to the tip's 1.5 and hit radii are half a tube's diameter or less", + all(abs(s["joints"][0]["stiffness"] - 3.0) < 1e-6 and abs(s["joints"][-1]["stiffness"] - 1.5) < 1e-6 + and all(0 <= j["hitRadius"] <= 0.016 for j in s["joints"]) for s in ext["springs"]), + [[j["stiffness"] for j in ext["springs"][0]["joints"]], [j["hitRadius"] for j in ext["springs"][0]["joints"]]]) prims = [p for m in gltf["meshes"] for p in m["primitives"]] check("mesh primitives carry exactly the five attributes", all(set(p["attributes"]) == {"POSITION", "NORMAL", "TEXCOORD_0", "JOINTS_0", "WEIGHTS_0"} for p in prims), [sorted(p["attributes"]) for p in prims]) @@ -265,6 +289,23 @@ cube_json, _, _ = glb_json(WORK / "cube.glb") check("a scene with no rig springs exports no VRMC_springBone", "VRMC_springBone" not in cube_json.get("extensions", {}) and "VRMC_springBone" not in cube_json.get("extensionsUsed", []), list(cube_json.get("extensions", {}))) +# --- body again on its own armature: the chains go, nothing is left weighing nothing; colliders alone export no springs +chain_bones = sum(1 for b in arm.data.bones if "rig_chain" in b) +receipt, rebody = send("brokkr_rig.body", object_name="Whale", armature_name=arm.name, seeds="jaw=0,0.45,0.05") +check("body again clears the chain bones it would orphan", + rebody and rebody["chainBonesCleared"] == chain_bones > 0 and not any("rig_chain" in b for b in arm.data.bones), rebody) +send("exportGltf", filepath="cleared.glb", extras=False, yUp=True, applyModifiers=True) +cleared_json, _, _ = glb_json(WORK / "cleared.glb") +check("an armature with no chains exports no springs", "VRMC_springBone" not in cleared_json.get("extensions", {}), None) +receipt, lone = send("brokkr_rig.colliders", object_name="Whale") +send("exportGltf", filepath="colliders_only.glb", extras=False, yUp=True, applyModifiers=True) +only_json, _, _ = glb_json(WORK / "colliders_only.glb") +check("colliders without chains export no VRMC_springBone", lone and lone["capsules"] > 0 and "VRMC_springBone" not in only_json.get("extensions", {}) + and "VRMC_springBone" not in only_json.get("extensionsUsed", []), lone) +receipt, rerun = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) +check("tendrils after the second body rebuilds the same chains", rerun and tendrils and rerun["chains"] == tendrils["chains"] + and rerun["springBones"] == tendrils["springBones"], [rerun, tendrils]) + R["ok"] = all(c["ok"] for c in R["checks"]) Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: diff --git a/surfaces/blender/tests/live/rig.result.json b/surfaces/blender/tests/live/rig.result.json index 3cbaafd..e00bb76 100644 --- a/surfaces/blender/tests/live/rig.result.json +++ b/surfaces/blender/tests/live/rig.result.json @@ -113,6 +113,12 @@ "armature": "Whale.rig", "bodyVertices": 913, "chains": 5, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], "springBones": 50, "branchesRigid": 1, "veinsFolded": 10, @@ -130,45 +136,81 @@ "detail": "Operator brokkr_rig.colliders finished." }, { - "name": "tendrils run again on the same rig gives the same chains", + "name": "tendrils with other knobs changes the skin", "ok": true, - "detail": [ - { - "object": "Whale", - "armature": "Whale.rig", - "bodyVertices": 913, - "chains": 5, - "springBones": 50, - "branchesRigid": 1, - "veinsFolded": 10, - "shellsAttached": 1, - "unreachedVertices": 42, - "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, - "tau": 0.05000000074505806, - "band": 0.03999999910593033 - }, - { - "object": "Whale", - "armature": "Whale.rig", - "bodyVertices": 913, - "chains": 5, - "springBones": 50, - "branchesRigid": 1, - "veinsFolded": 10, - "shellsAttached": 1, - "unreachedVertices": 42, - "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, - "tau": 0.05000000074505806, - "band": 0.03999999910593033 - } - ] + "detail": null + }, + { + "name": "tendrils, other knobs, then the first knobs again restores the weights and bone properties exactly", + "ok": true, + "detail": null + }, + { + "name": "the tendrils report says what it sees", + "ok": true, + "detail": { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + } + }, + { + "name": "the colliders report lists each shrink", + "ok": true, + "detail": { + "capsules": 6, + "spheres": 1, + "shrunk": 4, + "dropped": 0, + "skipped": 0, + "shrinks": [ + { + "bone": "spine_01", + "before": 0.155853, + "after": 0.070036 + }, + { + "bone": "spine_02", + "before": 0.148599, + "after": 0.053107 + }, + { + "bone": "spine_03", + "before": 0.166193, + "after": 0.056984 + }, + { + "bone": "spine_04", + "before": 0.106817, + "after": 0.074496 + } + ], + "shrunkMax": 0.6571, + "object": "Whale", + "armature": "Whale.rig", + "springJoints": 45 + } }, { "name": "exportGltf accepted", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-hx2wf__p\\whale.glb (301168 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-237ky4n3\\whale.glb (301188 bytes)." }, { "name": "VRMC_springBone is in extensions and extensionsUsed", @@ -185,6 +227,37 @@ 7 ] }, + { + "name": "the extension is not required", + "ok": true, + "detail": null + }, + { + "name": "stiffness tapers from the root's 3 to the tip's 1.5 and hit radii are half a tube's diameter or less", + "ok": true, + "detail": [ + [ + 3, + 2.7857142857142856, + 2.5714285714285716, + 2.357142857142857, + 2.142857142857143, + 1.9285714285714284, + 1.7142857142857142, + 1.5 + ], + [ + 0.0059821512550115585, + 0.005849682260304689, + 0.005868155509233475, + 0.005716879619285464, + 0.00568680465221405, + 0.005836397642269731, + 0.005983717972412705, + 0.005983717972412705 + ] + ] + }, { "name": "mesh primitives carry exactly the five attributes", "ok": true, @@ -258,6 +331,126 @@ "name": "a scene with no rig springs exports no VRMC_springBone", "ok": true, "detail": [] + }, + { + "name": "body again clears the chain bones it would orphan", + "ok": true, + "detail": { + "object": "Whale", + "armature": "Whale.rig", + "created": false, + "chainBonesCleared": 50, + "spine": [ + "spine_00", + "spine_01", + "spine_02", + "spine_03", + "spine_04", + "spine_05" + ], + "parts": [ + { + "name": "jaw", + "root": [ + -0.160415, + 0.128395, + 0.030328 + ], + "tail": [ + -0.170113, + 0.140889, + 0.055153 + ], + "triangles": 140 + } + ], + "head": [ + -0.183123, + 0.5, + -0.039007 + ], + "tail": [ + -0.16983, + -0.5, + -0.027336 + ], + "axis": [ + 0.0, + 1.0, + -0.0 + ], + "vertices": 1546, + "weldedVertices": 1546 + } + }, + { + "name": "an armature with no chains exports no springs", + "ok": true, + "detail": null + }, + { + "name": "colliders without chains export no VRMC_springBone", + "ok": true, + "detail": { + "capsules": 6, + "spheres": 1, + "shrunk": 0, + "dropped": 0, + "skipped": 0, + "shrinks": [], + "shrunkMax": 0.0, + "object": "Whale", + "armature": "Whale.rig", + "springJoints": 0 + } + }, + { + "name": "tendrils after the second body rebuilds the same chains", + "ok": true, + "detail": [ + { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + }, + { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + } + ] } ], "hostErrors": [], @@ -313,6 +506,7 @@ "object": "Whale", "armature": "Whale.rig", "created": true, + "chainBonesCleared": 0, "spine": [ "spine_00", "spine_01", @@ -360,6 +554,12 @@ "armature": "Whale.rig", "bodyVertices": 913, "chains": 5, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], "springBones": 50, "branchesRigid": 1, "veinsFolded": 10, @@ -376,6 +576,29 @@ "shrunk": 4, "dropped": 0, "skipped": 0, + "shrinks": [ + { + "bone": "spine_01", + "before": 0.155853, + "after": 0.070036 + }, + { + "bone": "spine_02", + "before": 0.148599, + "after": 0.053107 + }, + { + "bone": "spine_03", + "before": 0.166193, + "after": 0.056984 + }, + { + "bone": "spine_04", + "before": 0.106817, + "after": 0.074496 + } + ], + "shrunkMax": 0.6571, "object": "Whale", "armature": "Whale.rig", "springJoints": 45 diff --git a/surfaces/blender/tests/test_rig.py b/surfaces/blender/tests/test_rig.py index 35bcf2b..21755b0 100644 --- a/surfaces/blender/tests/test_rig.py +++ b/surfaces/blender/tests/test_rig.py @@ -40,9 +40,10 @@ if np is not None: BAND, TAU = 0.25, 0.1 -def tube_graph(vein: bool = True): +def tube_graph(vein: bool = True, perm=None): """A body of three stations (thick), a trunk of nine stations along x that forks at station 5 into a branch of - three along y, and a short vein of two stations off the body. Every station is two vertices 0.01 apart, so a + three along y, a short vein of two stations off the body (vein=True also adds a lone far + ring joined by one long edge and a detached shell). Every station is two vertices 0.01 apart, so a ring is a handful of vertices. Distances from the body run .11 per trunk station: bands 0,0,1,1,2,2,3,3,3.""" V, E, sd = [], [], [] @@ -74,11 +75,28 @@ def tube_graph(vein: bool = True): veins.append(station(-0.2, 0.11 * k)) join(last, veins[-1]) last = veins[-1] - return np.array(V), np.array(E), np.array(sd), {"body": body, "trunk": trunk, "branch": branch, "vein": veins} + lone, shell = [], [] + if vein: + a = len(V) + V.extend([(-0.1, 0.9, 0.0), (-0.1, 0.9, 0.01)]) + sd.extend([0.01, 0.01]) + E.extend([(a, a + 1), (body[1], a), (body[1] + 1, a + 1)]) + lone = [a] + b = len(V) + V.extend([(0.3, 0.0, 0.6), (0.3, 0.0, 0.61)]) + sd.extend([0.01, 0.01]) + E.append((b, b + 1)) + shell = [b] + V, E, sd = np.array(V), np.array(E), np.array(sd) + if perm is not None: # the same graph with its vertices numbered another way + V2, sd2 = np.empty_like(V), np.empty_like(sd) + V2[perm], sd2[perm] = V, sd + V, E, sd = V2, perm[E], sd2 + return V, E, sd, {"body": body, "trunk": trunk, "branch": branch, "vein": veins, "lone": lone, "shell": shell} -def extract(fold_bands=1.5, min_joints=1, vein=True): - V, E, sd, at_ = tube_graph(vein) +def extract(fold_bands=1.5, min_joints=1, vein=True, perm=None): + V, E, sd, at_ = tube_graph(vein, perm) return V, E, sd, at_, core.extract(V, E, sd, TAU, BAND, 0.0, fold_bands, min_joints) @@ -130,14 +148,51 @@ class RingTests(unittest.TestCase): @unittest.skipIf(np is None, "numpy") def test_vein_folds(self): """Dies with fold off or fold always on.""" - for bands, folded in ((0.0, [False, False]), (1.5, [True, False]), (4.0, [True, True])): + for bands, folded in ((0.0, [False] * 3), (1.5, [False, False, True]), (4.0, [True] * 3)): # trunk, a far lone ring, a vein *_, f = extract(fold_bands=bands) self.assertEqual(sorted(c.folded for c in f.chains), sorted(folded), bands) *_, f = extract(min_joints=3) - self.assertEqual(sorted(c.folded for c in f.chains), [False, True]) # the vein has two rings + self.assertEqual(sorted(c.folded for c in f.chains), [False, True, True]) # the vein has two rings, the lone ring one + + + @unittest.skipIf(np is None, "numpy") + def test_the_main_path_is_the_tallest_subtree_however_the_vertices_are_numbered(self): + """Dies if the main path is the shortest subtree, or the lowest ring id.""" + for seed in range(8): + perm = np.random.default_rng(seed).permutation(len(tube_graph(False)[0])) + V, E, sd, s, f = extract(vein=False, perm=perm) + leaf = f.chains[0].rings[-1] + self.assertIn(int(perm[s["trunk"][8]]), np.flatnonzero(f.ring == leaf).tolist(), seed) class WeightTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_a_detached_shell_rides_the_nearest_spring_bone(self): + """Dies if the shell takes the farthest bone, or any other than the nearest.""" + V, E, sd, s, f = extract() + springs = core.plan(V, sd, f, BAND) + trunk = [sp for sp in springs if np.linalg.norm(sp.pos[0] - V[s["trunk"][0]]) < 0.2][0] + body_idx, body_w = np.zeros((len(V), 4), dtype=np.int64), np.zeros((len(V), 4)) + body_w[:, 0] = 1.0 + idx, w, start = core.tendril_weights(V, E, f, springs, body_idx, body_w, 1, BAND, 0.5) + every = np.concatenate([sp.pos for sp in springs]) + owner = np.concatenate([start[c] + np.arange(len(sp.pos)) for c, sp in enumerate(springs)]) + centre = V[s["shell"][0]:s["shell"][0] + 2].mean(axis=0) + near = int(owner[np.argmin(np.linalg.norm(every - centre, axis=1))]) + far = int(owner[np.argmax(np.linalg.norm(every - centre, axis=1))]) + self.assertNotEqual(near, far) + for v in (s["shell"][0], s["shell"][0] + 1): + self.assertEqual((int(idx[v, 0]), float(w[v, 0])), (near, 1.0)) + self.assertIn(near, range(start[springs.index(trunk)], start[springs.index(trunk)] + len(trunk.pos))) + + @unittest.skipIf(np is None, "numpy") + def test_stiffness_tapers_to_the_tip_ratio_and_the_hit_radius_is_half_the_diameter(self): + """Dies if the taper runs tip to root, or the hit radius is a diameter.""" + stiffness, hit = core.joint_params(np.array([0.02, 0.04, 0.06, 0.0]), 3.0, 0.5, 1.0) + self.assertTrue(np.allclose(stiffness, [3.0, 2.5, 2.0, 1.5])) + self.assertTrue(np.allclose(hit, [0.01, 0.02, 0.03, 0.0])) + self.assertTrue(np.allclose(core.joint_params(np.array([0.02, 0.04]), 3.0, 0.5, 2.0)[1], [0.02, 0.04])) + @unittest.skipIf(np is None, "numpy") def test_weights_partition(self): """Dies if weights go to bone k + 1 (the joint the segment ends at).""" From 804863ccc92518bb335d2d3a63352922bd918e0a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 08:38:05 +0100 Subject: [PATCH 066/223] brokkr_rig: no thin part is a reported outcome; shape rays reach the longest side; gauges, seeds and shrink pinned in core (Soul s2 fix batch) tendrils on a mesh with no rings reports zero chains instead of raising. The shape-diameter ray reach was half the longest side, so a body wider than that read thin; it is the longest side now. chain_gauges, seed_triangle and shrink_fraction move into core with tests; the live test pins stale colliders and the no-thin-part mesh. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_rig/__init__.py | 19 +++---- surfaces/blender/brokkr_rig/core.py | 25 +++++++++ surfaces/blender/docs/rig.md | 9 +++- surfaces/blender/tests/live/rig.py | 29 ++++++++++- surfaces/blender/tests/live/rig.result.json | 50 +++++++++++++++--- surfaces/blender/tests/test_rig.py | 56 ++++++++++++++++++--- 6 files changed, 157 insertions(+), 31 deletions(-) diff --git a/surfaces/blender/brokkr_rig/__init__.py b/surfaces/blender/brokkr_rig/__init__.py index b153ccd..39dbecb 100644 --- a/surfaces/blender/brokkr_rig/__init__.py +++ b/surfaces/blender/brokkr_rig/__init__.py @@ -174,7 +174,7 @@ def shape_diameter(w: SimpleNamespace) -> np.ndarray: live = (w.TW[:, 0] != w.TW[:, 1]) & (w.TW[:, 1] != w.TW[:, 2]) & (w.TW[:, 0] != w.TW[:, 2]) tree = BVHTree.FromPolygons([tuple(p) for p in w.Vw], [tuple(int(i) for i in t) for t in w.TW[live]]) jitter = np.random.default_rng(0).normal(0.0, 0.35, (w.count, 4, 3)) - reach, lift = 0.5 * w.length, 1e-5 * w.length + reach, lift = w.length, 1e-5 * w.length out = np.zeros(w.count) for i in range(w.count): inward = -w.N[i] @@ -264,9 +264,7 @@ class BROKKR_RIG_OT_body(PolishOperator): nearest = lambda point: int(np.argmin(((centroid - np.asarray(point)) ** 2).sum(axis=1))) # noqa: E731 sd = shape_diameter(w) # the spine's seeds take body surface: a triangle with a thin vertex is a tendril or a sheet solid = (sd[w.TW] >= SPINE_THICK * w.length).all(axis=1) - pool = np.flatnonzero(solid) if solid.any() else np.arange(len(w.TW)) - nearest_solid = lambda point: int(pool[np.argmin(((centroid[pool] - np.asarray(point)) ** 2).sum(axis=1))]) # noqa: E731 - placed = [(nearest_solid(point), 0) for point in ([a for a, _ in spine] + [spine[-1][1]])] + placed = [(core.seed_triangle(centroid, solid, point), 0) for point in ([a for a, _ in spine] + [spine[-1][1]])] placed += [(nearest(point), parts.index(name) if name in parts else 0) for name, point in seeds] part, _ = polish.grow_parts(len(w.TW), pairs, polish.crease_costs(w.Vw, w.TW, pairs, self.crease_cost), placed) part[part < 0] = 0 @@ -407,19 +405,14 @@ class BROKKR_RIG_OT_tendrils(PolishOperator): shells = len(np.unique(polish.components(w.count, w.E[lost[w.E[:, 0]] & lost[w.E[:, 1]]])[lost])) if lost.any() else 0 branches = int(sum(1 for r in range(len(found.parent)) if not found.on_main[r] and found.parent[r] >= 0 and found.on_main[found.parent[r]] and found.tree[r] in {c.tree for c in kept})) - on_chain = (found.ring >= 0) & np.isin(found.tree[np.maximum(found.ring, 0)], [c.tree for c in kept]) - kept_trees = [c.tree for c in kept] - trees = found.tree[found.ring[on_chain]] - open_share = float(np.bincount(trees).max() / w.count) if on_chain.any() else 0.0 # the biggest chain's share of the mesh - ring_of = np.where(found.ring >= 0, found.tree[np.maximum(found.ring, 0)], -1) - a, b = ring_of[w.E[:, 0]], ring_of[w.E[:, 1]] - fused = int(((a >= 0) & (b >= 0) & (a != b) & np.isin(a, [c.tree for c in kept]) & np.isin(b, [c.tree for c in kept])).sum()) + gauges = core.chain_gauges(found, w.E, [c.tree for c in kept], w.count) + open_share = gauges["largestChainShare"] warnings = [] if open_share >= OPEN_SHEET_WARN: warnings.append(f"one chain holds {open_share:.0%} of the mesh: a plate of a hull may have become a chain; " "raise tau or fold_bands, or rig a mesh whose tendrils are tubes") return {"object": obj.name, "armature": arm.name, "bodyVertices": int(found.body.sum()), "chains": len(springs), - "chainVertexShare": float(on_chain.mean()), "largestChainShare": open_share, "fusedContacts": fused, "warnings": warnings, + **gauges, "warnings": warnings, "springBones": int(sum(len(s.pos) for s in springs)), "branchesRigid": branches, "veinsFolded": len(found.chains) - len(kept), "shellsAttached": shells, "unreachedVertices": int(lost.sum()), "rings": int(len(found.parent)), @@ -469,7 +462,7 @@ class BROKKR_RIG_OT_colliders(PolishOperator): if cleared < radius: made["shrunk"] += 1 made["shrinks"].append({"bone": bone.name, "before": round(float(radius), 6), "after": round(float(max(cleared, 0.0)), 6)}) - made["shrunkMax"] = round(max(made["shrunkMax"], float(1.0 - max(cleared, 0.0) / radius)), 4) + made["shrunkMax"] = round(max(made["shrunkMax"], core.shrink_fraction(radius, cleared)), 4) if cleared <= 0: made["dropped"] += 1 continue diff --git a/surfaces/blender/brokkr_rig/core.py b/surfaces/blender/brokkr_rig/core.py index 35c8ba9..2638c2f 100644 --- a/surfaces/blender/brokkr_rig/core.py +++ b/surfaces/blender/brokkr_rig/core.py @@ -356,3 +356,28 @@ def joint_params(sd: np.ndarray, stiffness: float, tip_ratio: float, hit_scale: linearly from the root's value to tip_ratio times it at the tip; the hit radius is half the diameter times hit_scale.""" last = len(sd) - 1 return stiffness * (1.0 + (tip_ratio - 1.0) * np.arange(last + 1) / last), 0.5 * np.asarray(sd) * hit_scale + + +# --- seeds and gauges ------------------------------------------------------------------------------------ + +def seed_triangle(centroid: np.ndarray, solid: np.ndarray, point: np.ndarray) -> int: + """The triangle nearest point among the solid ones (all of them when none is solid).""" + pool = np.flatnonzero(solid) if solid.any() else np.arange(len(centroid)) + return int(pool[np.argmin(((centroid[pool] - np.asarray(point)) ** 2).sum(axis=1))]) + + +def chain_gauges(found: SimpleNamespace, E: np.ndarray, kept: list, count: int) -> dict: + """What a rig looks like from outside: the share of the mesh on kept chains, the biggest chain's share, and the + mesh edges joining two different kept chains. kept are the trees of the chains that are not folded.""" + ring = np.maximum(found.ring, 0) + tree = np.where(found.ring >= 0, found.tree[ring] if len(found.tree) else -1, -1) + mine = np.isin(tree, kept) & (found.ring >= 0) + a, b = tree[E[:, 0]], tree[E[:, 1]] + return {"chainVertexShare": float(mine.sum() / max(count, 1)), + "largestChainShare": float(np.bincount(tree[mine]).max() / max(count, 1)) if mine.any() else 0.0, + "fusedContacts": int((np.isin(a, kept) & np.isin(b, kept) & (a != b)).sum())} + + +def shrink_fraction(before: float, after: float) -> float: + """How much of a collider's radius a shrink took: 0 none, 1 all.""" + return 1.0 - max(after, 0.0) / before diff --git a/surfaces/blender/docs/rig.md b/surfaces/blender/docs/rig.md index cf85323..379dd96 100644 --- a/surfaces/blender/docs/rig.md +++ b/surfaces/blender/docs/rig.md @@ -94,7 +94,14 @@ gauges the rig: `chainVertexShare`, `largestChainShare` (the biggest chain's sha (mesh edges joining two different chains). `warnings` says when one chain holds 4.2% of the mesh or more, which is what a hull plate that became a chain looks like (the lace leviathan reads 2.3%, the skeletal and mantle hulls 7.7% and 11.2%; the bound is the geometric mean of the first two). An open sheet reads shape diameter 0, so on a -hull the builder succeeds; read the warning. +hull the builder succeeds; read the warning. The gauge is fitted to four meshes and catches a hull whose plates +merge into a few big chains. It does not catch one that fragments into many small plate chains: the submarine +reads 2.7% largest (9 chains, 11% of the mesh on chains) and gets no warning, and no second signal tried +(open-sheet share, ring width in shape diameters, share of the mesh on chains) separated it from the leviathan. +Look at the chains in a render before trusting a hull's rig. + +A mesh with no thin part (the crystal emblem) has no rings: `tendrils` is accepted, reports `chains` 0, removes +any chains from an earlier run, and leaves the skin as `body` made it. ### colliders diff --git a/surfaces/blender/tests/live/rig.py b/surfaces/blender/tests/live/rig.py index 26de79f..09c4396 100644 --- a/surfaces/blender/tests/live/rig.py +++ b/surfaces/blender/tests/live/rig.py @@ -206,8 +206,9 @@ check("tendrils, other knobs, then the first knobs again restores the weights an check("the tendrils report says what it sees", tendrils and {"warnings", "largestChainShare", "chainVertexShare", "fusedContacts"} <= set(tendrils) and len(tendrils["warnings"]) == 1 and "one chain holds" in tendrils["warnings"][0], tendrils) # five chains hold 13% each at most: hull-like by the gauge receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") -check("the colliders report lists each shrink", colliders and len(colliders["shrinks"]) == colliders["shrunk"] - and all(x["after"] < x["before"] for x in colliders["shrinks"]), colliders) +check("the colliders report lists each shrink and the largest share taken", colliders and colliders["shrunk"] > 0 + and len(colliders["shrinks"]) == colliders["shrunk"] and all(x["after"] < x["before"] for x in colliders["shrinks"]) + and abs(colliders["shrunkMax"] - max(1 - x["after"] / x["before"] for x in colliders["shrinks"])) < 1e-3, colliders) R["colliders"] = colliders # --- export: the five attributes, weights, extension, structure ---------------------------------------------------- @@ -294,6 +295,7 @@ chain_bones = sum(1 for b in arm.data.bones if "rig_chain" in b) receipt, rebody = send("brokkr_rig.body", object_name="Whale", armature_name=arm.name, seeds="jaw=0,0.45,0.05") check("body again clears the chain bones it would orphan", rebody and rebody["chainBonesCleared"] == chain_bones > 0 and not any("rig_chain" in b for b in arm.data.bones), rebody) +check("body again leaves no collider from the old body", not any("rig_colliders" in b for b in arm.data.bones), None) send("exportGltf", filepath="cleared.glb", extras=False, yUp=True, applyModifiers=True) cleared_json, _, _ = glb_json(WORK / "cleared.glb") check("an armature with no chains exports no springs", "VRMC_springBone" not in cleared_json.get("extensions", {}), None) @@ -306,6 +308,29 @@ receipt, rerun = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band check("tendrils after the second body rebuilds the same chains", rerun and tendrils and rerun["chains"] == tendrils["chains"] and rerun["springBones"] == tendrils["springBones"], [rerun, tendrils]) +# --- a mesh with no thin part: no chains is an outcome, not a crash, and the skin stays the body's -------------------------- +ball = bmesh.new() +bmesh.ops.create_uvsphere(ball, u_segments=24, v_segments=12, radius=0.3, calc_uvs=True) +ball_mesh = bpy.data.meshes.new("Ball") +ball.to_mesh(ball_mesh) +ball.free() +ball_obj = bpy.data.objects.new("Ball", ball_mesh) +bpy.context.scene.collection.objects.link(ball_obj) +send("brokkr_rig.body", object_name="Ball", spine_bones=4) + + +def ball_weights(): + names = [g.name for g in ball_obj.vertex_groups] + return [sorted((names[e.group], e.weight) for e in v.groups) for v in ball_obj.data.vertices] + + +before = ball_weights() +receipt, bald = send("brokkr_rig.tendrils", object_name="Ball", tau=0.05, band=0.04, dilate=0.01) +check("tendrils on a mesh with no thin part is accepted and reports no chains", receipt["status"] == "accepted" and bald and bald["chains"] == 0 + and bald["springBones"] == 0 and bald["rings"] == 0 and bald["fusedContacts"] == 0, [receipt["message"], bald]) +check("and leaves the skin as body made it, with no chain bones", ball_weights() == before + and not any("rig_chain" in b for b in bpy.data.objects["Ball.rig"].data.bones), None) + R["ok"] = all(c["ok"] for c in R["checks"]) Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: diff --git a/surfaces/blender/tests/live/rig.result.json b/surfaces/blender/tests/live/rig.result.json index e00bb76..9cc1424 100644 --- a/surfaces/blender/tests/live/rig.result.json +++ b/surfaces/blender/tests/live/rig.result.json @@ -125,7 +125,7 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 } @@ -165,13 +165,13 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 } }, { - "name": "the colliders report lists each shrink", + "name": "the colliders report lists each shrink and the largest share taken", "ok": true, "detail": { "capsules": 6, @@ -210,7 +210,7 @@ { "name": "exportGltf accepted", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-237ky4n3\\whale.glb (301188 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-l9ustbpi\\whale.glb (301188 bytes)." }, { "name": "VRMC_springBone is in extensions and extensionsUsed", @@ -383,6 +383,11 @@ "weldedVertices": 1546 } }, + { + "name": "body again leaves no collider from the old body", + "ok": true, + "detail": null + }, { "name": "an armature with no chains exports no springs", "ok": true, @@ -425,7 +430,7 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 }, @@ -446,11 +451,42 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 } ] + }, + { + "name": "tendrils on a mesh with no thin part is accepted and reports no chains", + "ok": true, + "detail": [ + "Operator brokkr_rig.tendrils finished.", + { + "object": "Ball", + "armature": "Ball.rig", + "bodyVertices": 266, + "chains": 0, + "chainVertexShare": 0.0, + "largestChainShare": 0.0, + "fusedContacts": 0, + "warnings": [], + "springBones": 0, + "branchesRigid": 0, + "veinsFolded": 0, + "shellsAttached": 0, + "unreachedVertices": 0, + "rings": 0, + "shapeDiameterMedian": 0.5665553510189056, + "tau": 0.03000000163912775, + "band": 0.024000000417232492 + } + ] + }, + { + "name": "and leaves the skin as body made it, with no chain bones", + "ok": true, + "detail": null } ], "hostErrors": [], @@ -566,7 +602,7 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 }, diff --git a/surfaces/blender/tests/test_rig.py b/surfaces/blender/tests/test_rig.py index 21755b0..e25cae1 100644 --- a/surfaces/blender/tests/test_rig.py +++ b/surfaces/blender/tests/test_rig.py @@ -40,7 +40,7 @@ if np is not None: BAND, TAU = 0.25, 0.1 -def tube_graph(vein: bool = True, perm=None): +def tube_graph(vein: bool = True, perm=None, trunk_stations: int = 9): """A body of three stations (thick), a trunk of nine stations along x that forks at station 5 into a branch of three along y, a short vein of two stations off the body (vein=True also adds a lone far ring joined by one long edge and a detached shell). Every station is two vertices 0.01 apart, so a @@ -61,7 +61,7 @@ def tube_graph(vein: bool = True, perm=None): for a, b in zip(body, body[1:]): join(a, b) trunk, last = [], body[-1] - for k in range(1, 10): + for k in range(1, trunk_stations + 1): trunk.append(station(0.11 * k, 0.0)) join(last, trunk[-1]) last = trunk[-1] @@ -95,8 +95,8 @@ def tube_graph(vein: bool = True, perm=None): return V, E, sd, {"body": body, "trunk": trunk, "branch": branch, "vein": veins, "lone": lone, "shell": shell} -def extract(fold_bands=1.5, min_joints=1, vein=True, perm=None): - V, E, sd, at_ = tube_graph(vein, perm) +def extract(fold_bands=1.5, min_joints=1, vein=True, perm=None, trunk_stations=9): + V, E, sd, at_ = tube_graph(vein, perm, trunk_stations) return V, E, sd, at_, core.extract(V, E, sd, TAU, BAND, 0.0, fold_bands, min_joints) @@ -157,12 +157,52 @@ class RingTests(unittest.TestCase): @unittest.skipIf(np is None, "numpy") def test_the_main_path_is_the_tallest_subtree_however_the_vertices_are_numbered(self): - """Dies if the main path is the shortest subtree, or the lowest ring id.""" + """Dies if the main path is the shortest subtree, or the lowest ring id. The long trunk (12 stations, six rings + past the fork) is taller than the branch (one ring), so the height alone decides, never the size tie-break.""" for seed in range(8): - perm = np.random.default_rng(seed).permutation(len(tube_graph(False)[0])) - V, E, sd, s, f = extract(vein=False, perm=perm) + perm = np.random.default_rng(seed).permutation(len(tube_graph(False, trunk_stations=12)[0])) + V, E, sd, s, f = extract(vein=False, perm=perm, trunk_stations=12) leaf = f.chains[0].rings[-1] - self.assertIn(int(perm[s["trunk"][8]]), np.flatnonzero(f.ring == leaf).tolist(), seed) + self.assertIn(int(perm[s["trunk"][11]]), np.flatnonzero(f.ring == leaf).tolist(), seed) + self.assertEqual(len(f.chains[0].rings), 6) + + @unittest.skipIf(np is None, "numpy") + def test_a_mesh_with_no_thin_part_has_no_rings_and_no_chains(self): + V, E, sd, s = tube_graph(False) + f = core.extract(V, E, np.ones(len(V)), TAU, BAND, 0.0, 1.5, 1) + self.assertEqual((len(f.parent), f.chains, int(f.body.sum())), (0, [], len(V))) + self.assertEqual(core.plan(V, np.ones(len(V)), f, BAND), []) + self.assertEqual(core.chain_gauges(f, E, [], len(V)), {"chainVertexShare": 0.0, "largestChainShare": 0.0, "fusedContacts": 0}) + idx, w, start = core.tendril_weights(V, E, f, [], np.zeros((len(V), 4), dtype=np.int64), np.eye(4)[[0] * len(V)], 1, BAND, 0.5) + self.assertTrue((w[:, 0] == 1.0).all() and start == []) + + @unittest.skipIf(np is None, "numpy") + def test_gauges_count_the_biggest_chain_the_total_and_only_edges_between_chains(self): + """Dies if the largest share is the total, or fused contacts count edges inside one chain.""" + V, E, sd, s, f = extract() + kept = [c.tree for c in f.chains if not c.folded] + self.assertEqual(len(kept), 2) # the trunk and the lone ring + n = len(V) + own = core.chain_gauges(f, E, kept, n) + self.assertAlmostEqual(own["largestChainShare"], 24 / n) # the trunk's 9 stations and the branch's 3, two vertices each + self.assertAlmostEqual(own["chainVertexShare"], 26 / n) + self.assertEqual(own["fusedContacts"], 0) # trunk-branch edges are one chain + crossed = np.vstack([E, [s["trunk"][2], s["lone"][0]], [s["trunk"][3], s["lone"][0]]]) + self.assertEqual(core.chain_gauges(f, crossed, kept, n)["fusedContacts"], 2) + + @unittest.skipIf(np is None, "numpy") + def test_a_spine_seed_takes_the_nearest_solid_triangle_not_the_nearest_triangle(self): + """Dies if the seed is the nearest triangle whatever its thickness, or if no solid triangle leaves it nowhere.""" + centre = np.array([[0.0, 0, 0], [1.0, 0, 0], [3.0, 0, 0]]) + solid = np.array([False, True, True]) + self.assertEqual(core.seed_triangle(centre, solid, np.array([0.1, 0, 0])), 1) + self.assertEqual(core.seed_triangle(centre, np.array([False] * 3), np.array([0.1, 0, 0])), 0) # nothing solid: the nearest + + @unittest.skipIf(np is None, "numpy") + def test_shrink_fraction_is_the_share_of_the_radius_taken(self): + self.assertAlmostEqual(core.shrink_fraction(0.1, 0.0079), 0.921) + self.assertEqual(core.shrink_fraction(0.2, 0.2), 0.0) + self.assertEqual(core.shrink_fraction(0.2, -0.1), 1.0) class WeightTests(unittest.TestCase): From 9a8b72a2138fec4a7f6e733750fd7224f07563ed Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 14:48:03 +0100 Subject: [PATCH 067/223] brokkr_kitbash: a part kit as data, the mechanical kit, and four host actions core.py (numpy and stdlib, no bpy) owns brokkr.kit.v0: check_kit, load_kit by name only, resolve_params and parse_params, and build, which turns a part's tube, box and repeat shapes into closed outward-wound shells with socket frames. Expressions are parsed with ast and walked against a whitelist; nothing is run. kits/mechanical.v0.json holds nine parts. __init__.py is a host add-on beside brokkr_mesh_polish and brokkr_rig with place_part, set_params, describe and report. A placed part is its kit_kit, kit_part and kit_params ID properties; the mesh is derived from them and set_params rebuilds it in the same datablock, so transform, parent, modifiers and materials stay. Socket frames are derived at each report. test_kitbash.py runs without Blender; tests/live/kitbash.py proves the rows through run_intent in a background Blender 5.3, its result committed. Cut aetheria-release:cut_spec:cut-chassis-kit-format.r1. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 184 +++++++ .../brokkr_kitbash/brokkr_actions.json | 111 ++++ surfaces/blender/brokkr_kitbash/core.py | 478 ++++++++++++++++++ .../brokkr_kitbash/kits/mechanical.v0.json | 295 +++++++++++ surfaces/blender/tests/live/kitbash.py | 210 ++++++++ .../blender/tests/live/kitbash.result.json | 362 +++++++++++++ surfaces/blender/tests/test_kitbash.py | 413 +++++++++++++++ 7 files changed, 2053 insertions(+) create mode 100644 surfaces/blender/brokkr_kitbash/__init__.py create mode 100644 surfaces/blender/brokkr_kitbash/brokkr_actions.json create mode 100644 surfaces/blender/brokkr_kitbash/core.py create mode 100644 surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json create mode 100644 surfaces/blender/tests/live/kitbash.py create mode 100644 surfaces/blender/tests/live/kitbash.result.json create mode 100644 surfaces/blender/tests/test_kitbash.py diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py new file mode 100644 index 0000000..ea1c2fd --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -0,0 +1,184 @@ +"""Kitbash parts: place a parametric machine part from a kit, re-parameterise it, and report where its sockets are. + +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 +may run (docs/kitbash.md). The kit format, its checks and the geometry are core.py (numpy, tested without +Blender); this file is the bpy around it. Every operator writes a JSON report to +WindowManager.brokkr_mesh_polish_result, as the polish operators do. + +What a placed part is lives on its object as three ID properties: kit_kit, kit_part and kit_params. The mesh is +derived from them (set_params rebuilds it), and socket frames are derived again at every report: nothing else in +the scene stores them. Placement, materials and export are Brokkr's own rows (setObjectTransform, assignMaterial, +exportGltf). +""" +bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), + "category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."} + +import json +import math + +import bpy +import numpy as np + +try: + from brokkr_mesh_polish import RESULT, PolishOperator, Refused, mesh_object + MISSING = None +except ImportError as error: # register() says so; the classes below only need something to subclass + RESULT, PolishOperator, Refused, mesh_object, MISSING = "brokkr_mesh_polish_result", bpy.types.Operator, RuntimeError, None, error + +from . import core + +KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" +BEVEL = "Kit Bevel" +BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0) +REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates + + +def kit_work(work): + """A KitError from core is this request's refusal.""" + def wrapped(self, context): + try: + return work(self, context) + except core.KitError as error: + raise Refused(str(error)) from None + return wrapped + + +def write_mesh(mesh, built) -> None: + """The built part into an empty mesh datablock: vertices, n-gon faces, and flat shading on every face not marked smooth.""" + mesh.vertices.add(len(built.V)) + mesh.vertices.foreach_set("co", built.V.astype(np.float32).ravel()) + mesh.loops.add(len(built.faces)) + mesh.loops.foreach_set("vertex_index", built.faces) + mesh.polygons.add(len(built.counts)) + mesh.polygons.foreach_set("loop_start", (np.cumsum(built.counts) - built.counts).astype(np.int32)) + sharp = mesh.attributes.get("sharp_face") or mesh.attributes.new("sharp_face", "BOOLEAN", "FACE") + sharp.data.foreach_set("value", ~built.smooth) + mesh.update(calc_edges=True) + + +def sync_bevel(obj, width: float) -> None: + modifier = obj.modifiers.get(BEVEL) + if modifier is None and width > 0: + modifier = obj.modifiers.new(BEVEL, "BEVEL") + modifier.segments, modifier.limit_method, modifier.angle_limit = BEVEL_SEGMENTS, "ANGLE", BEVEL_ANGLE + if modifier is not None: + modifier.width = width + + +def kit_part_of(obj): + """(part, stored params) of a placed part, read from its ID properties.""" + if PART not in obj: + raise Refused(f"{obj.name!r} is not a kit part (it has no {PART} property); place_part makes one.") + try: + stored = json.loads(obj.get(PARAMS, "{}")) + except ValueError: + stored = None + if not isinstance(stored, dict): + raise Refused(f"{obj.name!r} has a {PARAMS} property that is not a JSON object.") + return core.part(core.load_kit(str(obj.get(KIT, ""))), str(obj[PART])), stored + + +def part_report(obj, part, built) -> dict: + return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, + "faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), + "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world))} + + +def bounded(report: dict, advice: str) -> dict: + size = len(json.dumps(report, separators=(",", ":"))) + if size > REPORT_LIMIT: + raise Refused(f"The report is {size} characters, over the {REPORT_LIMIT} a receipt carries: {advice}.") + return report + + +class BROKKR_KITBASH_OT_place_part(PolishOperator): + """Place a kit part at the origin as a new mesh object: its geometry from the kit and params, a Bevel modifier + when the part has a bevel, and the kit, part and params stored on the object""" + bl_idname = "brokkr_kitbash.place_part" + bl_label = "Place Kit Part" + kit: bpy.props.StringProperty(name="Kit", default="mechanical") + part: bpy.props.StringProperty(name="Part") + object_name: bpy.props.StringProperty(name="Object") + params: bpy.props.StringProperty(name="Params", description="name=value; name=value ... the rest take the part's defaults") + + @kit_work + def work(self, context): + part = core.part(core.load_kit(self.kit), self.part) + if self.object_name in bpy.data.objects: + raise Refused(f"An object named {self.object_name!r} exists; nothing changed.") + built = core.build(part, core.parse_params(self.params)) + mesh = bpy.data.meshes.new(self.object_name) + write_mesh(mesh, built) + obj = bpy.data.objects.new(self.object_name, mesh) + context.scene.collection.objects.link(obj) + sync_bevel(obj, built.bevel) + obj[KIT], obj[PART], obj[PARAMS] = part["kit"], part["name"], json.dumps(built.params) + return part_report(obj, part, built) + + +class BROKKR_KITBASH_OT_set_params(PolishOperator): + """Change params of a placed kit part and rebuild its mesh in place: its transform, parent, modifiers and + material slots stay, and the Bevel width follows""" + bl_idname = "brokkr_kitbash.set_params" + bl_label = "Set Kit Part Params" + object_name: bpy.props.StringProperty(name="Object") + params: bpy.props.StringProperty(name="Params", description="name=value; name=value ... the rest keep their stored values") + + @kit_work + def work(self, context): + obj = mesh_object(self.object_name) + part, stored = kit_part_of(obj) + built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored)) + obj.data.clear_geometry() + write_mesh(obj.data, built) + sync_bevel(obj, built.bevel) + obj[PARAMS] = json.dumps(built.params) + return part_report(obj, part, built) + + +class BROKKR_KITBASH_OT_describe(PolishOperator): + """List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame + at default params""" + bl_idname = "brokkr_kitbash.describe" + bl_label = "Describe Kit" + bl_options = {"REGISTER"} + kit: bpy.props.StringProperty(name="Kit", default="mechanical") + part: bpy.props.StringProperty(name="Part", description="Empty: every part of the kit") + + @kit_work + def work(self, context): + return bounded(core.describe(core.load_kit(self.kit), self.part), "name a part to describe it alone") + + +class BROKKR_KITBASH_OT_report(PolishOperator): + """Report placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world frame""" + bl_idname = "brokkr_kitbash.report" + bl_label = "Report Kit Parts" + bl_options = {"REGISTER"} + object_name: bpy.props.StringProperty(name="Object", description="Empty: every object that is a kit part") + + @kit_work + def work(self, context): + chosen = [mesh_object(self.object_name)] if self.object_name else sorted( + (o for o in context.scene.objects if o.type == "MESH" and PART in o), key=lambda o: o.name) + parts = [] + for obj in chosen: + part, stored = kit_part_of(obj) + parts.append(part_report(obj, part, core.build(part, stored))) + return bounded({"parts": parts}, "name an object to report it alone") + + +classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report) + + +def register(): + if MISSING is not None or not hasattr(bpy.types.WindowManager, RESULT): + raise RuntimeError(f"brokkr_kitbash needs brokkr_mesh_polish enabled first ({MISSING or 'its result property is not registered'}).") + for cls in classes: + bpy.utils.register_class(cls) + + +def unregister(): + for cls in reversed(classes): + bpy.utils.unregister_class(cls) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json new file mode 100644 index 0000000..41e010a --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -0,0 +1,111 @@ +{ + "schema": "brokkr.blender.host_actions.v0", + "actions": [ + { + "name": "brokkr_kitbash.place_part", + "doc": "Place a kit part at the origin as a new mesh object (move it with setObjectTransform). Reports its params, faces, shells and each socket's world 4x4 (rows; column 2 is the outward normal, column 3 the origin).", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "kit", + "type": "string", + "chars": "id", + "minLength": 1, + "maxLength": 32, + "default": "mechanical", + "doc": "a kit shipped with the add-on (a-z, 0-9, _)" + }, + { + "name": "part", + "type": "string", + "required": true, + "chars": "id", + "minLength": 1, + "maxLength": 32, + "doc": "a part of the kit; brokkr_kitbash.describe lists them" + }, + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the new object's name; refused when an object has it" + }, + { + "name": "params", + "type": "string", + "maxLength": 4000, + "default": "", + "doc": "name=value; name=value ... inside each param's bounds; the rest take the part's defaults" + } + ] + }, + { + "name": "brokkr_kitbash.set_params", + "doc": "Change params of a placed kit part and rebuild its mesh in place; transform, parent, modifiers and materials stay. Reports as place_part.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + }, + { + "name": "params", + "type": "string", + "required": true, + "maxLength": 4000, + "doc": "name=value; name=value ... the rest keep their stored values" + } + ] + }, + { + "name": "brokkr_kitbash.describe", + "doc": "A kit's parts, or one part: params (type, min, max, default, doc) and sockets in the part's frame at default params.", + "changesScene": false, + "editModeSafe": true, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "kit", + "type": "string", + "chars": "id", + "minLength": 1, + "maxLength": 32, + "default": "mechanical" + }, + { + "name": "part", + "type": "string", + "chars": "id", + "maxLength": 32, + "default": "", + "doc": "empty: every part of the kit" + } + ] + }, + { + "name": "brokkr_kitbash.report", + "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world 4x4.", + "changesScene": false, + "editModeSafe": true, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "maxLength": 63, + "default": "", + "doc": "empty: every object that is a kit part" + } + ] + } + ] +} diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py new file mode 100644 index 0000000..0d6b0c8 --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -0,0 +1,478 @@ +"""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, repeat) 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. An +expression is parsed with ast.parse and walked against a whitelist; nothing in a kit is ever run as Python. + + kit = load_kit("mechanical") + built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, shell_count, sockets + +Every refusal is a KitError whose message names the kit, part and field. +""" +from __future__ import annotations + +import ast +import json +import math +import re +from pathlib import Path +from typing import Any, NamedTuple + +import numpy as np + +SCHEMA = "brokkr.kit.v0" +KITS = Path(__file__).with_name("kits") +KIT_NAME = r"[a-z0-9_]{1,32}" +NAME = r"[a-z][a-z0-9_]{0,31}" +CALLS = {"min": min, "max": max} +AXES = {"+x": (1.0, 0.0, 0.0), "-x": (-1.0, 0.0, 0.0), "+y": (0.0, 1.0, 0.0), "-y": (0.0, -1.0, 0.0), + "+z": (0.0, 0.0, 1.0), "-z": (0.0, 0.0, -1.0)} +PLACED = ("at", "rot") +SHAPES = {"tube": (("r0", "r1", "length", "segments"), ("inner0", "inner1", "smooth") + PLACED), + "box": (("size",), PLACED), + "repeat": (("count", "step", "of"), ())} +SEGMENTS = (3, 128) +COPIES = (1, 256) + + +class KitError(ValueError): + """The kit document, a param or a build breaks a rule of the format; the message names where.""" + + +# --- expressions --------------------------------------------------------------------------------------------- + +class Expr: + """A number, or an expression over a part's params that passed the whitelist. value(env) walks the tree.""" + __slots__ = ("source", "tree", "where") + + def __init__(self, source, tree, where): + self.source, self.tree, self.where = source, tree, where + + def value(self, env: dict[str, float]) -> float: + result = self.source if self.tree is None else _walk(self.tree, env, self) + if not math.isfinite(result): + raise KitError(f"{self.where}: {self.source!r} is not a finite number") + return float(result) + + +def parse(value: Any, names, where: str) -> Expr: + """The Expr for a numeric field: a finite number, or a string of + - * /, unary minus, parentheses, min(a,b), + max(a,b), numbers and the names given. Anything else is refused here, before any build.""" + if isinstance(value, (int, float)) and not isinstance(value, bool): + if not math.isfinite(value): + raise KitError(f"{where}: {value!r} is not a finite number") + return Expr(value, None, where) + if not isinstance(value, str): + raise KitError(f"{where} must be a number or an expression string, not {type(value).__name__}") + try: + tree = ast.parse(value, mode="eval").body + except (SyntaxError, ValueError, RecursionError, MemoryError): + raise KitError(f"{where}: {value!r} does not parse as an expression") from None + try: + _admit(tree, frozenset(names), where, value) + except RecursionError: + raise KitError(f"{where}: {value!r} nests too deeply") from None + return Expr(value, tree, where) + + +def _admit(node, names, where, source) -> None: + if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div)): + _admit(node.left, names, where, source) + _admit(node.right, names, where, source) + elif isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)): + _admit(node.operand, names, where, source) + elif isinstance(node, ast.Constant) and type(node.value) in (int, float): + pass + elif isinstance(node, ast.Name): + if node.id not in names: + raise KitError(f"{where}: {source!r} names {node.id!r}, which is not a param of this part ({', '.join(sorted(names)) or 'it has none'})") + elif isinstance(node, ast.Call): + if not isinstance(node.func, ast.Name) or node.func.id not in CALLS: + raise KitError(f"{where}: {source!r} calls something other than min or max") + if len(node.args) != 2 or node.keywords: + raise KitError(f"{where}: {source!r}: {node.func.id} takes exactly two positional arguments") + for argument in node.args: + _admit(argument, names, where, source) + else: + raise KitError(f"{where}: {source!r} uses {type(node).__name__}; an expression is + - * /, unary minus, " + "parentheses, min(a,b), max(a,b), numbers and param names") + + +def _walk(node, env, expr: Expr) -> float: + if isinstance(node, ast.Constant): + return node.value + if isinstance(node, ast.Name): + return env[node.id] + if isinstance(node, ast.UnaryOp): + operand = _walk(node.operand, env, expr) + return -operand if isinstance(node.op, ast.USub) else operand + if isinstance(node, ast.Call): + return CALLS[node.func.id](_walk(node.args[0], env, expr), _walk(node.args[1], env, expr)) + left, right = _walk(node.left, env, expr), _walk(node.right, env, expr) + if isinstance(node.op, ast.Add): + return left + right + if isinstance(node.op, ast.Sub): + return left - right + if isinstance(node.op, ast.Mult): + return left * right + if right == 0: + raise KitError(f"{expr.where}: division by zero in {expr.source!r}") + return left / right + + +# --- the kit document ---------------------------------------------------------------------------------------- + +def _keys(value: Any, where: str, required, optional=()) -> None: + if not isinstance(value, dict): + raise KitError(f"{where} must be an object") + for key in value: + if key not in required and key not in optional: + raise KitError(f"{where} has no key {key!r}; its keys: {', '.join((*required, *optional))}") + for key in required: + if key not in value: + raise KitError(f"{where} lacks {key!r}") + + +def _text(value: Any, where: str) -> str: + if not isinstance(value, str): + raise KitError(f"{where} must be a string") + return value + + +def _name(value: Any, where: str, seen: set) -> str: + if not isinstance(value, str) or not re.fullmatch(NAME, value) or value in CALLS: + raise KitError(f"{where}: {value!r} is not a name (a-z first, then a-z, 0-9 or _, at most 32, not min or max)") + if value in seen: + raise KitError(f"{where}: {value!r} is listed twice") + seen.add(value) + return value + + +def _number(value: Any, where: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise KitError(f"{where} must be a finite number") + return value + + +def _vector(value: Any, names, where: str) -> list[Expr]: + if not isinstance(value, list) or len(value) != 3: + raise KitError(f"{where} must be an array of three numbers or expressions") + return [parse(item, names, f"{where}[{i}]") for i, item in enumerate(value)] + + +ZERO = [Expr(0.0, None, "zero")] * 3 + + +def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict: + kind = shape.get("shape") if isinstance(shape, dict) else None + if kind not in SHAPES: + raise KitError(f"{where}: unknown shape {kind!r}; shapes are {', '.join(SHAPES)}") + where = f"{where} ({kind})" + required, optional = SHAPES[kind] + _keys(shape, where, ("shape", *required), optional) + if kind == "repeat": + if inside_repeat: + raise KitError(f"{where}: a repeat cannot hold a repeat") + return {"shape": kind, "count": parse(shape["count"], names, f"{where} count"), + "step": _vector(shape["step"], names, f"{where} step"), + "of": _shape(shape["of"], names, f"{where} of", inside_repeat=True)} + made = {"shape": kind, "where": where, + "at": _vector(shape["at"], names, f"{where} at") if "at" in shape else ZERO, + "rot": _vector(shape["rot"], names, f"{where} rot") if "rot" in shape else ZERO} + if kind == "box": + made["size"] = _vector(shape["size"], names, f"{where} size") + return made + for key in ("r0", "r1", "length", "segments"): + made[key] = parse(shape[key], names, f"{where} {key}") + for key in ("inner0", "inner1"): + made[key] = parse(shape.get(key, 0), names, f"{where} {key}") + if not isinstance(shape.get("smooth", False), bool): + raise KitError(f"{where} smooth must be true or false") + made["smooth"] = shape.get("smooth", False) + return made + + +def check_kit(document: Any) -> dict: + """The checked kit: {'kit', 'doc', 'socketTypes', 'parts': {name: part}} with every numeric field an Expr. + Refuses, naming kit, part and field, anything the format does not say (the module docstring and docs/kitbash.md).""" + if not isinstance(document, dict) or document.get("schema") != SCHEMA: + raise KitError(f"kit schema must be {SCHEMA}") + _keys(document, "kit", ("schema", "kit", "doc", "socketTypes", "parts")) + kit = document["kit"] + if not isinstance(kit, str) or not re.fullmatch(KIT_NAME, kit): + raise KitError(f"kit name {kit!r} must be 1 to 32 of a-z, 0-9 and _") + here = f"kit {kit!r}" + _text(document["doc"], f"{here} doc") + if not isinstance(document["socketTypes"], dict) or not isinstance(document["parts"], list): + raise KitError(f"{here}: socketTypes must be an object and parts an array") + types = {} + for name, entry in document["socketTypes"].items(): + where = f"{here} socket type {name!r}" + _name(name, where, set()) + _keys(entry, where, ("match", "doc")) + if entry["match"] not in ("equal", "fits"): + raise KitError(f"{where}: match must be 'equal' or 'fits'") + types[name] = {"match": entry["match"], "doc": _text(entry["doc"], f"{where} doc")} + parts, part_names = {}, set() + for index, part in enumerate(document["parts"]): + name = _name(part.get("name") if isinstance(part, dict) else None, f"{here} part {index}", part_names) + where = f"{here} part {name!r}" + _keys(part, where, ("name", "doc", "params", "shapes", "sockets"), ("bevel",)) + if not all(isinstance(part[key], list) for key in ("params", "shapes", "sockets")): + raise KitError(f"{where}: params, shapes and sockets must be arrays") + params, names = [], set() + for p_index, param in enumerate(part["params"]): + p_name = _name(param.get("name") if isinstance(param, dict) else None, f"{where} param {p_index}", names) + p_where = f"{where} param {p_name!r}" + _keys(param, p_where, ("name", "type", "min", "max", "default", "doc")) + if param["type"] not in ("number", "integer"): + raise KitError(f"{p_where}: type must be 'number' or 'integer'") + low, high, default = (_number(param[key], f"{p_where} {key}") for key in ("min", "max", "default")) + if low > high: + raise KitError(f"{p_where}: min {low} is above max {high}") + if not low <= default <= high: + raise KitError(f"{p_where}: default {default} is outside [{low}, {high}]") + if param["type"] == "integer": + for key, value in (("min", low), ("max", high), ("default", default)): + if value != int(value): + raise KitError(f"{p_where}: an integer param's {key} must be whole, not {value}") + low, high, default = int(low), int(high), int(default) + params.append({"name": p_name, "type": param["type"], "min": low, "max": high, "default": default, + "doc": _text(param["doc"], f"{p_where} doc")}) + shapes = [_shape(shape, names, f"{where} shape {i}") for i, shape in enumerate(part["shapes"])] + if not shapes: + raise KitError(f"{where} has no shapes") + sockets, socket_names = [], set() + for s_index, socket in enumerate(part["sockets"]): + s_name = _name(socket.get("name") if isinstance(socket, dict) else None, f"{where} socket {s_index}", socket_names) + s_where = f"{where} socket {s_name!r}" + _keys(socket, s_where, ("name", "type", "size", "at", "z", "y")) + if socket["type"] not in types: + raise KitError(f"{s_where}: type {socket['type']!r} is not one of the kit's socketTypes ({', '.join(types) or 'none'})") + for key in ("z", "y"): + if socket[key] not in AXES: + raise KitError(f"{s_where}: {key} must be one of {', '.join(AXES)}") + if socket["z"][1] == socket["y"][1]: + raise KitError(f"{s_where}: z ({socket['z']}) and y ({socket['y']}) lie on the same axis") + sockets.append({"name": s_name, "type": socket["type"], "size": parse(socket["size"], names, f"{s_where} size"), + "at": _vector(socket["at"], names, f"{s_where} at"), "z": socket["z"], "y": socket["y"]}) + parts[name] = {"kit": kit, "name": name, "doc": _text(part["doc"], f"{where} doc"), "params": params, + "bevel": parse(part["bevel"], names, f"{where} bevel") if "bevel" in part else None, + "shapes": shapes, "sockets": sockets} + return {"kit": kit, "doc": document["doc"], "socketTypes": types, "parts": parts} + + +def load_kit(name: str) -> dict: + """The checked kit kits/.v0.json. The name is the only thing a caller chooses: it cannot spell a path.""" + if not isinstance(name, str) or not re.fullmatch(KIT_NAME, name): + raise KitError(f"kit name {name!r} must be 1 to 32 of a-z, 0-9 and _") + path = KITS / f"{name}.v0.json" + if not path.is_file(): + raise KitError(f"no kit named {name!r}; kits: {', '.join(kit_names()) or 'none'}") + try: + document = json.loads(path.read_text(encoding="utf-8")) + except ValueError as error: + raise KitError(f"kit {name!r} is not JSON: {error}") from None + kit = check_kit(document) + if kit["kit"] != name: + raise KitError(f"kit file {path.name} says it is kit {kit['kit']!r}") + return kit + + +def kit_names() -> list[str]: + return sorted(p.name[:-len(".v0.json")] for p in KITS.glob("*.v0.json")) + + +def part(kit: dict, name: str) -> dict: + found = kit["parts"].get(name) + if found is None: + raise KitError(f"kit {kit['kit']!r} has no part {name!r}; its parts: {', '.join(kit['parts'])}") + return found + + +# --- params -------------------------------------------------------------------------------------------------- + +def parse_params(text: str) -> dict[str, float]: + """'k=v; k=v' as a dict of numbers. Refuses a repeated key and a value that is not a finite number.""" + given: dict[str, float] = {} + for item in text.split(";"): + if not item.strip(): + continue + key, equals, value = item.partition("=") + key = key.strip() + if not equals or not key: + raise KitError(f"params: {item.strip()!r} is not name=value") + if key in given: + raise KitError(f"params: {key!r} is given twice") + try: + number = float(value) + except ValueError: + number = math.nan + if not math.isfinite(number): + raise KitError(f"params: {key} = {value.strip()!r} is not a number") + given[key] = number + return given + + +def resolve_params(part: dict, given: dict, base: dict | None = None) -> dict: + """Every param of the part, in the part's order: base overlaid by given, defaults for the rest. Refuses an + unknown param, a value outside the inclusive [min, max], and a fraction for an integer param.""" + merged = {**(base or {}), **given} + here = f"kit {part['kit']!r} part {part['name']!r}" + known = [p["name"] for p in part["params"]] + for key in merged: + if key not in known: + raise KitError(f"{here} has no param {key!r}; its params: {', '.join(known) or 'none'}") + resolved = {} + for param in part["params"]: + name = param["name"] + value = merged.get(name, param["default"]) + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise KitError(f"{here} param {name!r} must be a finite number") + if not param["min"] <= value <= param["max"]: + raise KitError(f"{here} param {name!r} = {value} is outside [{param['min']}, {param['max']}] (bounds included)") + if param["type"] == "integer": + if value != int(value): + raise KitError(f"{here} param {name!r} is an integer; {value} is not whole") + value = int(value) + resolved[name] = value if param["type"] == "integer" else float(value) + return resolved + + +# --- geometry ------------------------------------------------------------------------------------------------ + +class Built(NamedTuple): + """A part at given params, in the part's frame, metres. Face i has counts[i] corners, listed in order in + faces (quads and n-gon caps, wound outward); smooth[i] marks tube sides to shade smooth. Each socket is + {'name', 'type', 'size', 'matrix'} with matrix the 4x4 frame: column 2 the outward normal, column 1 up, + column 0 = y cross z, column 3 the origin.""" + V: np.ndarray + faces: np.ndarray + counts: np.ndarray + smooth: np.ndarray + shell_count: int + sockets: list + bevel: float + params: dict + + +def _whole(expr: Expr, env, bounds) -> int: + value = expr.value(env) + if abs(value - round(value)) > 1e-9 or not bounds[0] <= round(value) <= bounds[1]: + raise KitError(f"{expr.where} is {value}: it must be a whole number from {bounds[0]} to {bounds[1]}") + return int(round(value)) + + +def _rotation(degrees) -> np.ndarray: + """XYZ Euler: about x, then y, then z, each about the fixed axes of the shape's own origin.""" + (cx, sx), (cy, sy), (cz, sz) = ((math.cos(math.radians(a)), math.sin(math.radians(a))) for a in degrees) + rx = np.array([[1.0, 0.0, 0.0], [0.0, cx, -sx], [0.0, sx, cx]]) + ry = np.array([[cy, 0.0, sy], [0.0, 1.0, 0.0], [-sy, 0.0, cy]]) + rz = np.array([[cz, -sz, 0.0], [sz, cz, 0.0], [0.0, 0.0, 1.0]]) + return rz @ ry @ rx + + +def _tube(shape: dict, env): + r0, r1, length = (shape[key].value(env) for key in ("r0", "r1", "length")) + i0, i1 = shape["inner0"].value(env), shape["inner1"].value(env) + n = _whole(shape["segments"], env, SEGMENTS) + where = shape["where"] + if length <= 0: + raise KitError(f"{where}: length {length} must be above 0") + if not (0 <= i0 < r0 and 0 <= i1 < r1): + raise KitError(f"{where}: needs 0 <= inner < outer at both ends, got inner {i0}, {i1} and outer {r0}, {r1}") + if (i0 > 0) != (i1 > 0): + raise KitError(f"{where}: inner0 and inner1 must both be above 0 (hollow) or both be 0 (solid), got {i0}, {i1}") + angle = 2.0 * math.pi * np.arange(n) / n + cos, sin = np.cos(angle), np.sin(angle) + ring = lambda r, z: np.column_stack([r * cos, r * sin, np.full(n, z)]) # noqa: E731 + k = np.arange(n) + j = (k + 1) % n + side = np.column_stack([k, j, n + j, n + k]) + if i0 > 0: + V = np.vstack([ring(r0, 0.0), ring(r1, length), ring(i0, 0.0), ring(i1, length)]) + inner = np.column_stack([2 * n + j, 2 * n + k, 3 * n + k, 3 * n + j]) + bottom = np.column_stack([k, 2 * n + k, 2 * n + j, j]) + top = np.column_stack([n + k, n + j, 3 * n + j, 3 * n + k]) + faces = np.concatenate([side, inner, bottom, top]).ravel() + counts = np.full(4 * n, 4) + smooth = np.repeat([shape["smooth"], shape["smooth"], False, False], n) + else: + V = np.vstack([ring(r0, 0.0), ring(r1, length)]) + faces = np.concatenate([side.ravel(), k[::-1], n + k]) + counts = np.concatenate([np.full(n, 4), [n, n]]) + smooth = np.concatenate([np.full(n, shape["smooth"]), [False, False]]) + return V, faces, counts, smooth + + +BOX_FACES = np.array([[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]) +BOX_SIGNS = np.array([[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]]) * 0.5 + + +def _box(shape: dict, env): + size = np.array([e.value(env) for e in shape["size"]]) + if not (size > 0).all(): + raise KitError(f"{shape['where']}: every size must be above 0, got {size.tolist()}") + return BOX_SIGNS * size, BOX_FACES.ravel(), np.full(6, 4), np.zeros(6, dtype=bool) + + +def _placed(shape: dict, env): + V, faces, counts, smooth = (_tube if shape["shape"] == "tube" else _box)(shape, env) + rotation = _rotation([e.value(env) for e in shape["rot"]]) + return V @ rotation.T + np.array([e.value(env) for e in shape["at"]]), faces, counts, smooth + + +def build(part: dict, params: dict | None = None) -> Built: + """The part at these params (resolve_params fills and checks them). The same part and params give + byte-identical arrays.""" + env = resolve_params(part, params or {}) + shells = [] + for shape in part["shapes"]: + if shape["shape"] == "repeat": + count = _whole(shape["count"], env, COPIES) + step = np.array([e.value(env) for e in shape["step"]]) + V, faces, counts, smooth = _placed(shape["of"], env) + shells += [(V + k * step, faces, counts, smooth) for k in range(count)] + else: + shells.append(_placed(shape, env)) + offsets = np.cumsum([0] + [len(s[0]) for s in shells[:-1]]) + sockets = [] + for socket in part["sockets"]: + z, y = np.array(AXES[socket["z"]]), np.array(AXES[socket["y"]]) + matrix = np.eye(4) + matrix[:3, 0], matrix[:3, 1], matrix[:3, 2] = np.cross(y, z), y, z + matrix[:3, 3] = [e.value(env) for e in socket["at"]] + size = socket["size"].value(env) + if size <= 0: + raise KitError(f"{socket['size'].where} is {size}: a socket's size must be above 0") + sockets.append({"name": socket["name"], "type": socket["type"], "size": size, "matrix": matrix}) + bevel = part["bevel"].value(env) if part["bevel"] is not None else 0.0 + if bevel < 0: + raise KitError(f"{part['bevel'].where} is {bevel}: a bevel is 0 or more") + return Built(V=np.vstack([s[0] for s in shells]).astype(np.float64), + faces=np.concatenate([s[1] + o for s, o in zip(shells, offsets)]).astype(np.int32), + counts=np.concatenate([s[2] for s in shells]).astype(np.int32), + smooth=np.concatenate([s[3] for s in shells]).astype(bool), + shell_count=len(shells), sockets=sockets, bevel=bevel, params=env) + + +# --- reports ------------------------------------------------------------------------------------------------- + +def rows(matrix) -> list[list[float]]: + """A 4x4 as rows of 6 decimals, for a report.""" + return [[round(float(value), 6) + 0.0 for value in row] for row in np.asarray(matrix)] + + +def socket_rows(sockets: list, frame=None) -> list[dict]: + """Sockets for a report, their frames carried into `frame` (a 4x4; the part's own frame when None).""" + frame = np.eye(4) if frame is None else np.asarray(frame, dtype=np.float64) + return [{"name": s["name"], "type": s["type"], "size": round(s["size"], 6), "matrix": rows(frame @ s["matrix"])} for s in sockets] + + +def describe(kit: dict, name: str = "") -> dict: + """The kit's parts (or the one named): params with their bounds, and sockets in the part frame at default params.""" + chosen = [part(kit, name)] if name else list(kit["parts"].values()) + return {"kit": kit["kit"], "doc": kit["doc"], "socketTypes": kit["socketTypes"], + "parts": [{"name": p["name"], "doc": p["doc"], "params": p["params"], + "sockets": socket_rows(build(p).sockets)} for p in chosen]} diff --git a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json new file mode 100644 index 0000000..41d2da7 --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json @@ -0,0 +1,295 @@ +{ + "schema": "brokkr.kit.v0", + "kit": "mechanical", + "doc": "Ship machinery: engines, tanks, structure, plumbing and cooling. Parts run along +z; metres.", + "socketTypes": { + "flange": {"match": "equal", "doc": "bolted pipe or duct face; size is the bore diameter"}, + "mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"}, + "pivot": {"match": "equal", "doc": "pin joint; size is the pin diameter"} + }, + "parts": [ + { + "name": "nozzle", + "doc": "Rocket engine: mount flange, chamber with gimbal lugs, throat collar and a hollow hooped bell opening along +z.", + "params": [ + {"name": "throat_r", "type": "number", "min": 0.04, "max": 0.12, "default": 0.07, "doc": "throat radius"}, + {"name": "exit_r", "type": "number", "min": 0.16, "max": 0.45, "default": 0.26, "doc": "bell exit radius"}, + {"name": "length", "type": "number", "min": 0.25, "max": 1.0, "default": 0.5, "doc": "bell length, throat to exit"}, + {"name": "wall", "type": "number", "min": 0.004, "max": 0.015, "default": 0.008, "doc": "bell wall thickness"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"} + ], + "bevel": "0.3*wall", + "shapes": [ + {"shape": "tube", "r0": "2.1*throat_r", "r1": "2.1*throat_r", "length": "0.3*throat_r", "segments": "segments", "smooth": true}, + {"shape": "repeat", "count": 2, "step": ["2.62*throat_r", 0, 0], "of": + {"shape": "tube", "r0": "0.14*throat_r", "r1": "0.14*throat_r", "length": "0.35*throat_r", "segments": 6, "at": ["-1.31*throat_r", "-1.31*throat_r", "0.1*throat_r"]}}, + {"shape": "repeat", "count": 2, "step": ["2.62*throat_r", 0, 0], "of": + {"shape": "tube", "r0": "0.14*throat_r", "r1": "0.14*throat_r", "length": "0.35*throat_r", "segments": 6, "at": ["-1.31*throat_r", "1.31*throat_r", "0.1*throat_r"]}}, + {"shape": "tube", "r0": "1.6*throat_r", "r1": "1.6*throat_r", "length": "1.75*throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "0.15*throat_r"]}, + {"shape": "tube", "r0": "1.6*throat_r", "r1": "throat_r+wall", "length": "throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.9*throat_r"]}, + {"shape": "tube", "r0": "1.78*throat_r", "r1": "1.78*throat_r", "length": "0.5*throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.6*throat_r"]}, + {"shape": "tube", "r0": "throat_r+wall", "r1": "throat_r+wall+0.226*(exit_r-throat_r-wall)", "inner0": "throat_r", "inner1": "throat_r+0.226*(exit_r-throat_r-wall)", + "length": "0.12*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r"]}, + {"shape": "tube", "r0": "throat_r+wall+0.226*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.482*(exit_r-throat_r-wall)", "inner0": "throat_r+0.226*(exit_r-throat_r-wall)", "inner1": "throat_r+0.482*(exit_r-throat_r-wall)", + "length": "0.16*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.12*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.482*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "inner0": "throat_r+0.482*(exit_r-throat_r-wall)", "inner1": "throat_r+0.75*(exit_r-throat_r-wall)", + "length": "0.22*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.28*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.9375*(exit_r-throat_r-wall)", "inner0": "throat_r+0.75*(exit_r-throat_r-wall)", "inner1": "throat_r+0.9375*(exit_r-throat_r-wall)", + "length": "0.25*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.5*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.9375*(exit_r-throat_r-wall)", "r1": "exit_r", "inner0": "throat_r+0.9375*(exit_r-throat_r-wall)", "inner1": "exit_r-wall", + "length": "0.25*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.75*length"]}, + {"shape": "tube", "r0": "throat_r+2.4*wall+0.5795*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.616*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.5795*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.616*(exit_r-throat_r-wall)", + "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.36*length"]}, + {"shape": "tube", "r0": "throat_r+2.4*wall+0.825*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.8475*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.825*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.8475*(exit_r-throat_r-wall)", + "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.6*length"]}, + {"shape": "tube", "r0": "throat_r+2.4*wall+0.965*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.9725*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.965*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.9725*(exit_r-throat_r-wall)", + "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.86*length"]}, + {"shape": "repeat", "count": 2, "step": ["3.4*throat_r", 0, 0], "of": + {"shape": "box", "size": ["0.5*throat_r", "0.35*throat_r", "0.6*throat_r"], "at": ["-1.7*throat_r", 0, "throat_r"]}}, + {"shape": "repeat", "count": 2, "step": [0, "3.4*throat_r", 0], "of": + {"shape": "box", "size": ["0.35*throat_r", "0.5*throat_r", "0.6*throat_r"], "at": [0, "-1.7*throat_r", "throat_r"]}}, + {"shape": "tube", "r0": "exit_r+1.6*wall", "r1": "exit_r+1.6*wall", "inner0": "exit_r-0.5*wall", "inner1": "exit_r-0.5*wall", + "length": "3*wall", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+length-2.5*wall"]} + ], + "sockets": [ + {"name": "mount", "type": "flange", "size": "2*throat_r", "at": [0, 0, 0], "z": "-z", "y": "+y"} + ] + }, + { + "name": "tank", + "doc": "Pressure tank: domed ends with flanged ports, weld bands, two straps on saddle cradles and a mounting pad.", + "params": [ + {"name": "radius", "type": "number", "min": 0.12, "max": 0.35, "default": 0.22, "doc": "shell radius"}, + {"name": "length", "type": "number", "min": 0.6, "max": 2.0, "default": 0.9, "doc": "port face to port face"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"} + ], + "bevel": "0.008*radius", + "shapes": [ + {"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.05*radius", "segments": "segments", "smooth": true}, + {"shape": "tube", "r0": "0.2*radius", "r1": "0.2*radius", "length": "0.18*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.02*radius"]}, + {"shape": "tube", "r0": "0.47*radius", "r1": "0.85*radius", "length": "0.15*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.12*radius"]}, + {"shape": "tube", "r0": "0.85*radius", "r1": "radius", "length": "0.22*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.27*radius"]}, + {"shape": "tube", "r0": "radius", "r1": "radius", "length": "length-0.98*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.49*radius"]}, + {"shape": "tube", "r0": "radius", "r1": "0.85*radius", "length": "0.22*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.49*radius"]}, + {"shape": "tube", "r0": "0.85*radius", "r1": "0.47*radius", "length": "0.15*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.27*radius"]}, + {"shape": "tube", "r0": "0.2*radius", "r1": "0.2*radius", "length": "0.18*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.2*radius"]}, + {"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.05*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.05*radius"]}, + {"shape": "repeat", "count": 2, "step": [0, 0, "length-0.98*radius"], "of": + {"shape": "tube", "r0": "1.012*radius", "r1": "1.012*radius", "inner0": "0.97*radius", "inner1": "0.97*radius", "length": "0.04*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.47*radius"]}}, + {"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of": + {"shape": "tube", "r0": "1.035*radius", "r1": "1.035*radius", "inner0": "0.97*radius", "inner1": "0.97*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.44*radius+0.22*(length-0.98*radius)"]}}, + {"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of": + {"shape": "box", "size": ["1.3*radius", "0.55*radius", "0.1*radius"], "at": [0, "-0.85*radius", "0.49*radius+0.22*(length-0.98*radius)"]}}, + {"shape": "box", "size": ["1.5*radius", "0.08*radius", "0.56*(length-0.98*radius)+0.3*radius"], "at": [0, "-1.14*radius", "length/2"]} + ], + "sockets": [ + {"name": "port_a", "type": "flange", "size": "0.4*radius", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "port_b", "type": "flange", "size": "0.4*radius", "at": [0, 0, "length"], "z": "+z", "y": "+y"}, + {"name": "saddle", "type": "mount", "size": "1.5*radius", "at": [0, "-1.18*radius", "length/2"], "z": "-y", "y": "+z"} + ] + }, + { + "name": "ribbed_cylinder", + "doc": "Finned housing (motor, exchanger, capacitor): a drum with cooling ribs, end flanges, four tie bolts and a cable raceway.", + "params": [ + {"name": "radius", "type": "number", "min": 0.08, "max": 0.3, "default": 0.15, "doc": "drum radius"}, + {"name": "length", "type": "number", "min": 0.3, "max": 1.5, "default": 0.6, "doc": "end face to end face"}, + {"name": "ribs", "type": "integer", "min": 2, "max": 24, "default": 10, "doc": "rib rings"}, + {"name": "rib_depth", "type": "number", "min": 0.01, "max": 0.05, "default": 0.03, "doc": "how far ribs stand off the drum"}, + {"name": "rib_width", "type": "number", "min": 0.008, "max": 0.03, "default": 0.015, "doc": "rib thickness along the axis (narrowed when ribs crowd)"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"} + ], + "bevel": "0.15*min(min(rib_width,rib_depth),0.6*(length-3*rib_width)/ribs)", + "shapes": [ + {"shape": "tube", "r0": "radius+1.6*rib_depth", "r1": "radius+1.6*rib_depth", "length": "1.5*rib_width", "segments": "segments", "smooth": true}, + {"shape": "tube", "r0": "radius", "r1": "radius", "length": "length-1.5*rib_width", "segments": "segments", "smooth": true, "at": [0, 0, "0.75*rib_width"]}, + {"shape": "tube", "r0": "radius+1.6*rib_depth", "r1": "radius+1.6*rib_depth", "length": "1.5*rib_width", "segments": "segments", "smooth": true, "at": [0, 0, "length-1.5*rib_width"]}, + {"shape": "repeat", "count": "ribs", "step": [0, 0, "(length-3*rib_width)/ribs"], "of": + {"shape": "tube", "r0": "radius+rib_depth", "r1": "radius+rib_depth", "length": "min(rib_width,0.6*(length-3*rib_width)/ribs)", "segments": "segments", "smooth": true, + "at": [0, 0, "1.5*rib_width+0.5*(length-3*rib_width)/ribs-0.5*min(rib_width,0.6*(length-3*rib_width)/ribs)"]}}, + {"shape": "repeat", "count": 2, "step": ["1.4142*(radius+0.5*rib_depth)", 0, 0], "of": + {"shape": "tube", "r0": "0.28*rib_depth", "r1": "0.28*rib_depth", "length": "length-1.5*rib_width", "segments": 6, "at": ["-0.7071*(radius+0.5*rib_depth)", "-0.7071*(radius+0.5*rib_depth)", "0.75*rib_width"]}}, + {"shape": "repeat", "count": 2, "step": ["1.4142*(radius+0.5*rib_depth)", 0, 0], "of": + {"shape": "tube", "r0": "0.28*rib_depth", "r1": "0.28*rib_depth", "length": "length-1.5*rib_width", "segments": 6, "at": ["-0.7071*(radius+0.5*rib_depth)", "0.7071*(radius+0.5*rib_depth)", "0.75*rib_width"]}}, + {"shape": "box", "size": ["0.45*radius", "0.15*radius+1.3*rib_depth", "length-3*rib_width"], "at": [0, "0.925*radius+0.65*rib_depth", "length/2"]} + ], + "sockets": [ + {"name": "end_a", "type": "flange", "size": "2*radius", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "end_b", "type": "flange", "size": "2*radius", "at": [0, 0, "length"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "strut", + "doc": "Structural strut: an I-beam with web stiffeners between two pinned end blocks.", + "params": [ + {"name": "length", "type": "number", "min": 0.3, "max": 2.0, "default": 0.8, "doc": "end face to end face"}, + {"name": "width", "type": "number", "min": 0.04, "max": 0.12, "default": 0.08, "doc": "flange width (x)"}, + {"name": "thickness", "type": "number", "min": 0.02, "max": 0.08, "default": 0.05, "doc": "beam depth (y)"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of the pins"} + ], + "bevel": "0.03*min(width,thickness)", + "shapes": [ + {"shape": "box", "size": ["1.3*width", "1.3*thickness", "0.9*width"], "at": [0, 0, "0.45*width"]}, + {"shape": "box", "size": ["1.3*width", "1.3*thickness", "0.9*width"], "at": [0, 0, "length-0.45*width"]}, + {"shape": "repeat", "count": 2, "step": [0, 0, "length-0.9*width"], "of": + {"shape": "tube", "r0": "0.3*width", "r1": "0.3*width", "length": "1.7*thickness", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.85*thickness", "0.45*width"]}}, + {"shape": "repeat", "count": 2, "step": [0, "0.78*thickness", 0], "of": + {"shape": "box", "size": ["width", "0.22*thickness", "length-0.9*width"], "at": [0, "-0.39*thickness", "length/2"]}}, + {"shape": "box", "size": ["0.18*width", "0.6*thickness", "length-0.9*width"], "at": [0, 0, "length/2"]}, + {"shape": "repeat", "count": 3, "step": [0, 0, "(length-1.8*width)/4"], "of": + {"shape": "box", "size": ["0.9*width", "0.7*thickness", "0.08*width"], "at": [0, 0, "0.9*width+(length-1.8*width)/4"]}} + ], + "sockets": [ + {"name": "end_a", "type": "pivot", "size": "0.6*width", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "end_b", "type": "pivot", "size": "0.6*width", "at": [0, 0, "length"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "actuator", + "doc": "Tie-rod hydraulic cylinder: pinned base eye, square caps, barrel, ports, and a rod with its eye; extension moves rod_end.", + "params": [ + {"name": "body_r", "type": "number", "min": 0.05, "max": 0.12, "default": 0.06, "doc": "barrel radius"}, + {"name": "body_len", "type": "number", "min": 0.2, "max": 1.0, "default": 0.4, "doc": "barrel length between caps"}, + {"name": "rod_r", "type": "number", "min": 0.01, "max": 0.02, "default": 0.018, "doc": "rod radius"}, + {"name": "extension", "type": "number", "min": 0.0, "max": 0.8, "default": 0.15, "doc": "rod travel out of the gland"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"} + ], + "bevel": "0.04*body_r", + "shapes": [ + {"shape": "box", "size": ["1.2*body_r", "0.9*body_r", "1.6*body_r"], "at": [0, 0, "0.8*body_r"]}, + {"shape": "tube", "r0": "0.45*body_r", "r1": "0.45*body_r", "length": "1.3*body_r", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.65*body_r", "0.8*body_r"]}, + {"shape": "box", "size": ["2.4*body_r", "2.4*body_r", "0.5*body_r"], "at": [0, 0, "1.75*body_r"]}, + {"shape": "tube", "r0": "body_r", "r1": "body_r", "length": "body_len+0.2*body_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.9*body_r"]}, + {"shape": "box", "size": ["2.4*body_r", "2.4*body_r", "0.5*body_r"], "at": [0, 0, "2.25*body_r+body_len"]}, + {"shape": "repeat", "count": 2, "step": ["1.9*body_r", 0, 0], "of": + {"shape": "tube", "r0": "0.12*body_r", "r1": "0.12*body_r", "length": "body_len+1.3*body_r", "segments": 6, "at": ["-0.95*body_r", "-0.95*body_r", "1.35*body_r"]}}, + {"shape": "repeat", "count": 2, "step": ["1.9*body_r", 0, 0], "of": + {"shape": "tube", "r0": "0.12*body_r", "r1": "0.12*body_r", "length": "body_len+1.3*body_r", "segments": 6, "at": ["-0.95*body_r", "0.95*body_r", "1.35*body_r"]}}, + {"shape": "repeat", "count": 2, "step": [0, 0, "body_len+0.5*body_r"], "of": + {"shape": "tube", "r0": "0.2*body_r", "r1": "0.2*body_r", "length": "0.45*body_r", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": ["body_r", 0, "1.75*body_r"]}}, + {"shape": "tube", "r0": "rod_r+0.25*body_r", "r1": "rod_r+0.25*body_r", "length": "0.4*body_r", "segments": "segments", "smooth": true, "at": [0, 0, "2.4*body_r+body_len"]}, + {"shape": "tube", "r0": "rod_r", "r1": "rod_r", "length": "extension+0.9*body_r", "segments": "segments", "smooth": true, "at": [0, 0, "2.4*body_r+body_len"]}, + {"shape": "box", "size": ["1.2*body_r", "0.9*body_r", "1.4*body_r"], "at": [0, 0, "3.8*body_r+body_len+extension"]}, + {"shape": "tube", "r0": "0.45*body_r", "r1": "0.45*body_r", "length": "1.3*body_r", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.65*body_r", "3.8*body_r+body_len+extension"]} + ], + "sockets": [ + {"name": "base", "type": "pivot", "size": "0.9*body_r", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "rod_end", "type": "pivot", "size": "0.9*body_r", "at": [0, 0, "4.5*body_r+body_len+extension"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "pipe_fitting", + "doc": "Flanged tee: a run along +z with a branch along +x at its middle, a reinforced hub and bolted flanges.", + "params": [ + {"name": "pipe_r", "type": "number", "min": 0.03, "max": 0.07, "default": 0.05, "doc": "pipe radius"}, + {"name": "run", "type": "number", "min": 0.4, "max": 1.0, "default": 0.5, "doc": "run length, face a to face b"}, + {"name": "branch", "type": "number", "min": 0.15, "max": 0.5, "default": 0.25, "doc": "branch length, run axis to face c"}, + {"name": "flange_r", "type": "number", "min": 0.09, "max": 0.14, "default": 0.095, "doc": "flange radius"}, + {"name": "flange_t", "type": "number", "min": 0.012, "max": 0.04, "default": 0.02, "doc": "flange thickness"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"} + ], + "bevel": "min(0.15*flange_t,0.06*(flange_r-pipe_r))", + "shapes": [ + {"shape": "tube", "r0": "pipe_r", "r1": "pipe_r", "length": "run-flange_t", "segments": "segments", "smooth": true, "at": [0, 0, "0.5*flange_t"]}, + {"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true}, + {"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true, "at": [0, 0, "run-flange_t"]}, + {"shape": "tube", "r0": "1.3*pipe_r", "r1": "1.3*pipe_r", "length": "min(3*pipe_r,run-4*flange_t)", "segments": "segments", "smooth": true, "at": [0, 0, "run/2-min(3*pipe_r,run-4*flange_t)/2"]}, + {"shape": "tube", "r0": "pipe_r", "r1": "pipe_r", "length": "branch-0.5*flange_t", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": [0, 0, "run/2"]}, + {"shape": "tube", "r0": "1.3*pipe_r", "r1": "1.3*pipe_r", "length": "min(2.2*pipe_r,branch-2*flange_t)", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": [0, 0, "run/2"]}, + {"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": ["branch-flange_t", 0, "run/2"]}, + {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "-0.3536*(flange_r+pipe_r)", "0.15*flange_t"]}}, + {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "0.3536*(flange_r+pipe_r)", "0.15*flange_t"]}}, + {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "-0.3536*(flange_r+pipe_r)", "run-1.5*flange_t"]}}, + {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "0.3536*(flange_r+pipe_r)", "run-1.5*flange_t"]}}, + {"shape": "repeat", "count": 2, "step": [0, 0, "0.7072*(flange_r+pipe_r)"], "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "rot": [0, 90, 0], "at": ["branch-1.5*flange_t", "-0.3536*(flange_r+pipe_r)", "run/2-0.3536*(flange_r+pipe_r)"]}}, + {"shape": "repeat", "count": 2, "step": [0, 0, "0.7072*(flange_r+pipe_r)"], "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "rot": [0, 90, 0], "at": ["branch-1.5*flange_t", "0.3536*(flange_r+pipe_r)", "run/2-0.3536*(flange_r+pipe_r)"]}} + ], + "sockets": [ + {"name": "a", "type": "flange", "size": "2*pipe_r", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "b", "type": "flange", "size": "2*pipe_r", "at": [0, 0, "run"], "z": "+z", "y": "+y"}, + {"name": "c", "type": "flange", "size": "2*pipe_r", "at": ["branch", 0, "run/2"], "z": "+x", "y": "+z"} + ] + }, + { + "name": "radiator_stack", + "doc": "Fin stack: plate fins on a spine and two heat pipes, between a base block and a header.", + "params": [ + {"name": "fins", "type": "integer", "min": 3, "max": 40, "default": 12, "doc": "fin plates"}, + {"name": "fin_w", "type": "number", "min": 0.15, "max": 0.6, "default": 0.3, "doc": "fin width (x)"}, + {"name": "fin_h", "type": "number", "min": 0.08, "max": 0.4, "default": 0.18, "doc": "fin height (y)"}, + {"name": "fin_t", "type": "number", "min": 0.003, "max": 0.012, "default": 0.005, "doc": "fin thickness"}, + {"name": "pitch", "type": "number", "min": 0.015, "max": 0.05, "default": 0.025, "doc": "fin spacing along +z"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of the heat pipes"} + ], + "bevel": "0.2*fin_t", + "shapes": [ + {"shape": "box", "size": ["0.5*fin_w", "0.85*fin_h", "0.12*fin_h"], "at": [0, 0, "0.06*fin_h"]}, + {"shape": "box", "size": ["0.1*fin_w", "0.55*fin_h", "fins*pitch+0.06*fin_h"], "at": [0, 0, "0.09*fin_h+0.5*fins*pitch"]}, + {"shape": "repeat", "count": "fins", "step": [0, 0, "pitch"], "of": + {"shape": "box", "size": ["fin_w", "fin_h", "fin_t"], "at": [0, 0, "0.12*fin_h+0.5*pitch"]}}, + {"shape": "repeat", "count": 2, "step": ["0.64*fin_w", 0, 0], "of": + {"shape": "tube", "r0": "0.07*fin_h", "r1": "0.07*fin_h", "length": "fins*pitch+0.1*fin_h", "segments": "segments", "smooth": true, "at": ["-0.32*fin_w", 0, "0.06*fin_h"]}}, + {"shape": "box", "size": ["0.8*fin_w", "0.3*fin_h", "0.1*fin_h"], "at": [0, 0, "0.17*fin_h+fins*pitch"]} + ], + "sockets": [ + {"name": "base", "type": "mount", "size": "min(0.5*fin_w,0.85*fin_h)", "at": [0, 0, 0], "z": "-z", "y": "+y"} + ] + }, + { + "name": "vent", + "doc": "Louvred vent: a framed box on a back plate with tilted slats; it breathes along +z.", + "params": [ + {"name": "width", "type": "number", "min": 0.2, "max": 0.8, "default": 0.4, "doc": "frame width (x)"}, + {"name": "height", "type": "number", "min": 0.15, "max": 0.6, "default": 0.3, "doc": "frame height (y)"}, + {"name": "depth", "type": "number", "min": 0.04, "max": 0.15, "default": 0.08, "doc": "frame depth (z)"}, + {"name": "slats", "type": "integer", "min": 2, "max": 16, "default": 6, "doc": "louvre slats"}, + {"name": "slat_t", "type": "number", "min": 0.003, "max": 0.01, "default": 0.005, "doc": "slat thickness"}, + {"name": "tilt", "type": "number", "min": 0.0, "max": 60.0, "default": 35.0, "doc": "slat tilt in degrees; 0 is edge-on, fully open"} + ], + "bevel": "0.25*slat_t", + "shapes": [ + {"shape": "box", "size": ["width-0.048*min(width,height)", "height-0.048*min(width,height)", "0.12*depth"], "at": [0, 0, "0.06*depth"]}, + {"shape": "repeat", "count": 2, "step": ["width-0.08*min(width,height)", 0, 0], "of": + {"shape": "box", "size": ["0.08*min(width,height)", "height", "0.95*depth"], "at": ["-(width-0.08*min(width,height))/2", 0, "0.525*depth"]}}, + {"shape": "repeat", "count": 2, "step": [0, "height-0.08*min(width,height)", 0], "of": + {"shape": "box", "size": ["width-0.16*min(width,height)", "0.08*min(width,height)", "0.95*depth"], "at": [0, "-(height-0.08*min(width,height))/2", "0.525*depth"]}}, + {"shape": "repeat", "count": "slats", "step": [0, "(height-0.16*min(width,height))/slats", 0], "of": + {"shape": "box", "size": ["width-0.12*min(width,height)", "slat_t", "min(0.62*depth,1.1*(height-0.16*min(width,height))/slats)"], "rot": ["tilt", 0, 0], + "at": [0, "-(height-0.16*min(width,height))/2+0.5*(height-0.16*min(width,height))/slats", "0.56*depth"]}} + ], + "sockets": [ + {"name": "back", "type": "mount", "size": "0.9*min(width,height)", "at": [0, 0, 0], "z": "-z", "y": "+y"} + ] + }, + { + "name": "plate", + "doc": "Cover plate: a bolted rim around a raised panel; mounts on its back and carries a part on its front.", + "params": [ + {"name": "width", "type": "number", "min": 0.1, "max": 1.0, "default": 0.4, "doc": "x size"}, + {"name": "height", "type": "number", "min": 0.1, "max": 1.0, "default": 0.3, "doc": "y size"}, + {"name": "thickness", "type": "number", "min": 0.005, "max": 0.05, "default": 0.015, "doc": "back face to panel face (z)"} + ], + "bevel": "0.1*thickness", + "shapes": [ + {"shape": "box", "size": ["width", "height", "0.7*thickness"], "at": [0, 0, "0.35*thickness"]}, + {"shape": "box", "size": ["width-0.24*min(width,height)", "height-0.24*min(width,height)", "0.7*thickness"], "at": [0, 0, "0.65*thickness"]}, + {"shape": "repeat", "count": 2, "step": ["width-0.12*min(width,height)", 0, 0], "of": + {"shape": "tube", "r0": "0.036*min(width,height)", "r1": "0.036*min(width,height)", "length": "0.6*thickness", "segments": 6, + "at": ["-(width-0.12*min(width,height))/2", "-(height-0.12*min(width,height))/2", "0.35*thickness"]}}, + {"shape": "repeat", "count": 2, "step": ["width-0.12*min(width,height)", 0, 0], "of": + {"shape": "tube", "r0": "0.036*min(width,height)", "r1": "0.036*min(width,height)", "length": "0.6*thickness", "segments": 6, + "at": ["-(width-0.12*min(width,height))/2", "(height-0.12*min(width,height))/2", "0.35*thickness"]}} + ], + "sockets": [ + {"name": "back", "type": "mount", "size": "min(width,height)", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "front", "type": "mount", "size": "0.76*min(width,height)", "at": [0, 0, "thickness"], "z": "+z", "y": "+y"} + ] + } + ] +} diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py new file mode 100644 index 0000000..7ab51e5 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash.py @@ -0,0 +1,210 @@ +"""Live proof, in a background Blender, that the brokkr_kitbash rows are admitted by Brokkr as host actions and that +the mechanical kit goes through run_intent: describe, place_part for all nine parts, setObjectTransform, +assignMaterial, set_params, report, the refusals, and exportGltf. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). Writes .result.json and exits 1 when a check failed. +""" +import importlib.util +import json +import math +import os +import sys +import tempfile +import types +from pathlib import Path + +import bpy +import numpy as np + +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] +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 tests load it: what each placed mesh is compared 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-live-")) +target.configure_action_dirs("", str(WORK)) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], + "hostRows": [row["name"] for row in target.host_actions()[0]]} +COUNT = [0] + + +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 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 extent(obj, axis=2): + co = np.array([v.co[:] for v in obj.data.vertices]) + return float(co[:, axis].max() - co[:, axis].min()) + + +check("the four kitbash rows load as host actions with no errors", not R["hostErrors"] + and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", + "brokkr_kitbash.describe", "brokkr_kitbash.report"], [R["hostErrors"], R["hostRows"]]) + +# --- describe --------------------------------------------------------------------------------------------------------- +kit = core.load_kit("mechanical") +receipt, described = send("brokkr_kitbash.describe") +names = [p["name"] for p in described["parts"]] if described else [] +check("describe lists nine parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 9 + and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")]) +receipt, one = send("brokkr_kitbash.describe", part="actuator") +check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"] + and [p["name"] for p in one["parts"][0]["params"]] == ["body_r", "body_len", "rod_r", "extension", "segments"] + and one["parts"][0]["sockets"] == core.socket_rows(core.build(kit["parts"]["actuator"]).sockets), one) +check("describe changes nothing", len(bpy.data.objects) == 0 and len(bpy.data.meshes) == 0, [len(bpy.data.objects), len(bpy.data.meshes)]) + +# --- place every part at default ----------------------------------------------------------------------------------------- +placed = {} +for index, name in enumerate(names): + receipt, report = send("brokkr_kitbash.place_part", part=name, object_name=f"P_{name}") + obj = bpy.data.objects.get(f"P_{name}") + reference = core.build(kit["parts"][name]) + faces = len(obj.data.polygons) if obj else -1 + clean = obj is not None and not obj.data.validate(verbose=False) + flat = np.zeros(max(faces, 0), dtype=bool) + if obj: + obj.data.attributes["sharp_face"].data.foreach_get("value", flat) + bevel = obj.modifiers.get("Kit Bevel") if obj else None + evaluated = len(obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) if obj else -1 + placed[name] = report + check(f"place_part {name}: core's faces, a valid mesh, core's flat faces, at the origin", receipt["status"] == "accepted" and report + and faces == len(reference.counts) == report["faces"] and clean and report["shells"] == reference.shell_count + and flat.tolist() == (~reference.smooth).tolist() and list(obj.location) == [0.0, 0.0, 0.0] + and np.allclose(np.array([v.co[:] for v in obj.data.vertices]), reference.V, atol=1e-6), + [receipt["message"], faces, len(reference.counts), clean]) + check(f"place_part {name}: a Bevel of the part's width, 2 segments, angle 30, that evaluates", bevel is not None + and abs(bevel.width - reference.bevel) < 1e-7 and bevel.segments == 2 and bevel.limit_method == "ANGLE" + and abs(bevel.angle_limit - math.radians(30)) < 1e-6 and evaluated > faces, [bevel and bevel.width, reference.bevel, evaluated, faces]) + check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None + and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"] + and report["sockets"] == core.socket_rows(reference.sockets), report) +check("nine parts are nine mesh objects", len(bpy.data.objects) == 9 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) + +# --- set_params keeps what is not derived -------------------------------------------------------------------------------- +tank = bpy.data.objects["P_tank"] +send("setObjectTransform", targetObjectName="P_tank", location=[1.0, 2.0, 3.0], rotationEuler=[0.3, -0.2, 0.5], scale=[1.0, 1.0, 1.0]) +send("assignMaterial", targetObjectName="P_tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) +send("setObjectParent", targetObjectName="P_tank", parentObjectName="P_plate") +before = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name, + "materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers], + "faces": len(tank.data.polygons)} +receipt, grown = send("brokkr_kitbash.set_params", object_name="P_tank", params="length=1.8") +after = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name, + "materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers], + "faces": len(tank.data.polygons)} +check("set_params doubling the tank's length doubles its z extent", receipt["status"] == "accepted" and abs(before["z"] - 0.9) < 1e-6 + and abs(after["z"] - 1.8) < 1e-6, [before["z"], after["z"]]) +check("set_params keeps the mesh datablock, transform, parent, Bevel and the assigned material", before["parent"] == "P_plate" + and before["materials"] == ["Tank Paint"] and before["modifiers"] == ["Kit Bevel"] + and {k: v for k, v in after.items() if k != "z"} == {k: v for k, v in before.items() if k != "z"} and not tank.data.validate(verbose=False), [before, after]) +check("set_params stores the merged params and reports them", grown and json.loads(tank["kit_params"]) == grown["params"] + == {"radius": 0.22, "length": 1.8, "segments": 24}, grown) +receipt, wide = send("brokkr_kitbash.set_params", object_name="P_tank", params="radius=0.3; segments=12") +check("set_params overlays the stored params, and the Bevel width follows the part's bevel", wide and wide["params"] == {"radius": 0.3, "length": 1.8, "segments": 12} + and abs(tank.modifiers["Kit Bevel"].width - 0.008 * 0.3) < 1e-7 and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], wide["params"]).counts), + [wide and wide["params"], tank.modifiers["Kit Bevel"].width]) + +# --- report: sockets in the world ------------------------------------------------------------------------------------------- +send("setObjectTransform", targetObjectName="P_pipe_fitting", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) +bpy.context.view_layer.update() +receipt, reported = send("brokkr_kitbash.report") +worst, listed = 0.0, [] +for entry in (reported or {}).get("parts", []): + obj = bpy.data.objects[entry["object"]] + listed.append(entry["object"]) + local = core.build(core.part(kit, entry["part"]), entry["params"]).sockets + world = np.array(obj.matrix_world) + for socket, mine in zip(entry["sockets"], local): + worst = max(worst, float(np.abs(np.array(socket["matrix"]) - world @ mine["matrix"]).max())) +check("report lists every kit part with socket frames equal to matrix_world times the local frame", receipt["status"] == "accepted" + and listed == sorted(f"P_{n}" for n in names) and worst < 1e-6, [listed, worst]) +receipt, single = send("brokkr_kitbash.report", object_name="P_tank") +tank_world = np.array(tank.matrix_world) +check("report of the parented, rotated tank carries its parent's and its own transform", single and len(single["parts"]) == 1 + and single["parts"][0]["params"] == wide["params"] and single["parts"][0]["faces"] == len(tank.data.polygons) + and np.abs(np.array(single["parts"][0]["sockets"][2]["matrix"]) - tank_world @ core.build(kit["parts"]["tank"], wide["params"]).sockets[2]["matrix"]).max() < 1e-6 + and np.abs(tank_world[:3, 3] - [1.0, 2.0, 3.0]).max() < 1e-6, single) + +# --- refusals leave the scene as it was -------------------------------------------------------------------------------------- +bpy.ops.mesh.primitive_cube_add() +bpy.context.active_object.name = "Plain" + + +def scene_state(): + return (sorted(o.name for o in bpy.data.objects), sorted(m.name for m in bpy.data.meshes), + {o.name: (len(o.data.polygons), o.get("kit_params")) for o in bpy.data.objects}) + + +state = scene_state() +refusals = [ + ("an unknown kit", "brokkr_kitbash.place_part", {"kit": "hydraulic", "part": "tank", "object_name": "X"}, "no kit named 'hydraulic'"), + ("a kit name that spells a path", "brokkr_kitbash.place_part", {"kit": "../x", "part": "tank", "object_name": "X"}, "kit"), + ("a kit name with a dot", "brokkr_kitbash.place_part", {"kit": "mechanical.v0", "part": "tank", "object_name": "X"}, "must be 1 to 32 of"), + ("an unknown part", "brokkr_kitbash.place_part", {"part": "wing", "object_name": "X"}, "has no part 'wing'"), + ("an out-of-range param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "radius=5"}, "param 'radius' = 5.0 is outside [0.12, 0.35]"), + ("a fraction for an integer param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "segments=12.5"}, "is an integer"), + ("an existing name", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "P_plate"}, "An object named 'P_plate' exists"), + ("set_params on a plain mesh", "brokkr_kitbash.set_params", {"object_name": "Plain", "params": "length=1"}, "is not a kit part"), + ("set_params with an unknown param", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "girth=1"}, "has no param 'girth'"), + ("set_params out of range", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=0.1"}, "is outside [0.6, 2.0]"), + ("set_params with a repeated key", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=1; length=1.2"}, "'length' is given twice"), + ("report of a plain mesh", "brokkr_kitbash.report", {"object_name": "Plain"}, "is not a kit part"), + ("describe of an unknown part", "brokkr_kitbash.describe", {"part": "wing"}, "has no part 'wing'"), +] +for label, action, fields, expected in refusals: + receipt, _ = send(action, **fields) + check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state, + [receipt["status"], receipt["message"]]) + +# --- export --------------------------------------------------------------------------------------------------------------- +receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names]) +glb = WORK / "kit.glb" +meshes = -1 +if glb.is_file(): + blob = glb.read_bytes() + meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", [])) +check("exportGltf of all nine parts succeeds", receipt["status"] == "accepted" and meshes == 9, [receipt["message"], meshes]) + +R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]} + for name, report in placed.items() if report} +R["ok"] = all(c["ok"] for c in R["checks"]) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") +for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json new file mode 100644 index 0000000..2097f87 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -0,0 +1,362 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "the four kitbash rows load as host actions with no errors", + "ok": true, + "detail": null + }, + { + "name": "describe lists nine parts, whole, inside a receipt", + "ok": true, + "detail": null + }, + { + "name": "describe of one part gives its params and its sockets at default params", + "ok": true, + "detail": null + }, + { + "name": "describe changes nothing", + "ok": true, + "detail": null + }, + { + "name": "place_part nozzle: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part nozzle: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part nozzle: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part tank: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part tank: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part tank: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part ribbed_cylinder: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part ribbed_cylinder: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part ribbed_cylinder: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part strut: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part strut: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part strut: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part actuator: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part actuator: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part actuator: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part pipe_fitting: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part pipe_fitting: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part pipe_fitting: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part radiator_stack: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part radiator_stack: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part radiator_stack: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part vent: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part vent: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part vent: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part plate: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part plate: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part plate: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "nine parts are nine mesh objects", + "ok": true, + "detail": null + }, + { + "name": "set_params doubling the tank's length doubles its z extent", + "ok": true, + "detail": null + }, + { + "name": "set_params keeps the mesh datablock, transform, parent, Bevel and the assigned material", + "ok": true, + "detail": null + }, + { + "name": "set_params stores the merged params and reports them", + "ok": true, + "detail": null + }, + { + "name": "set_params overlays the stored params, and the Bevel width follows the part's bevel", + "ok": true, + "detail": null + }, + { + "name": "report lists every kit part with socket frames equal to matrix_world times the local frame", + "ok": true, + "detail": null + }, + { + "name": "report of the parented, rotated tank carries its parent's and its own transform", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an unknown kit", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a kit name that spells a path", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a kit name with a dot", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an unknown part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an out-of-range param", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a fraction for an integer param", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an existing name", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a plain mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params with an unknown param", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params out of range", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params with a repeated key", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: report of a plain mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: describe of an unknown part", + "ok": true, + "detail": null + }, + { + "name": "exportGltf of all nine parts succeeds", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "hostRows": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick", + "brokkr_kitbash.place_part", + "brokkr_kitbash.set_params", + "brokkr_kitbash.describe", + "brokkr_kitbash.report" + ], + "placed": { + "nozzle": { + "faces": 1024, + "shells": 21, + "bevel": 0.0024, + "sockets": [ + "mount" + ] + }, + "tank": { + "faces": 636, + "shells": 16, + "bevel": 0.00176, + "sockets": [ + "port_a", + "port_b", + "saddle" + ] + }, + "ribbed_cylinder": { + "faces": 376, + "shells": 18, + "bevel": 0.00225, + "sockets": [ + "end_a", + "end_b" + ] + }, + "strut": { + "faces": 100, + "shells": 10, + "bevel": 0.0015, + "sockets": [ + "end_a", + "end_b" + ] + }, + "actuator": { + "faces": 238, + "shells": 15, + "bevel": 0.0024, + "sockets": [ + "base", + "rod_end" + ] + }, + "pipe_fitting": { + "faces": 278, + "shells": 19, + "bevel": 0.0027, + "sockets": [ + "a", + "b", + "c" + ] + }, + "radiator_stack": { + "faces": 142, + "shells": 17, + "bevel": 0.001, + "sockets": [ + "base" + ] + }, + "vent": { + "faces": 66, + "shells": 11, + "bevel": 0.00125, + "sockets": [ + "back" + ] + }, + "plate": { + "faces": 44, + "shells": 6, + "bevel": 0.0015, + "sockets": [ + "back", + "front" + ] + } + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py new file mode 100644 index 0000000..c0b0bcd --- /dev/null +++ b/surfaces/blender/tests/test_kitbash.py @@ -0,0 +1,413 @@ +"""Kitbash tests. No Blender: the kit format and geometry in brokkr_kitbash/core.py, the mechanical kit at every +corner of its params, and the host action file against Brokkr's own checker. + +Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) +The operators are exercised in a real Blender by tests/live/kitbash.py. + +Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is +the built value, and each names the mutant it kills. +""" +from __future__ import annotations + +import copy +import importlib.util +import json +import math +import random +import re +import sys +import types +import unittest +from collections import Counter +from pathlib import Path + +SURFACE = Path(__file__).resolve().parents[1] +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules.setdefault("brokkr_bridge", package) +from brokkr_bridge import action_table as at # noqa: E402 + +try: + import numpy as np +except ImportError: # pragma: no cover + np = None + +if np is not None: + spec = importlib.util.spec_from_file_location("brokkr_kitbash_core", SURFACE / "brokkr_kitbash" / "core.py") + core = importlib.util.module_from_spec(spec) + spec.loader.exec_module(core) + + +def param(name, low=0.0, high=10.0, default=1.0, kind="number"): + return {"name": name, "type": kind, "min": low, "max": high, "default": default, "doc": ""} + + +def document(shapes=None, params=(), sockets=(), **extra): + """A kit of one part 'p'.""" + part = {"name": "p", "doc": "", "params": list(params), "shapes": shapes or [{"shape": "box", "size": [1, 1, 1]}], + "sockets": list(sockets), **extra} + return {"schema": "brokkr.kit.v0", "kit": "t", "doc": "", "socketTypes": {"mount": {"match": "fits", "doc": ""}}, "parts": [part]} + + +def built(shapes, params=(), given=None): + return core.build(core.part(core.check_kit(document(shapes, params)), "p"), given or {}) + + +def faces_of(b): + start = 0 + for count in b.counts: + yield b.faces[start:start + count] + start += count + + +def closed_and_oriented(b) -> bool: + """Every directed edge exactly once, with its reverse exactly once.""" + edges = Counter() + for face in faces_of(b): + for i in range(len(face)): + edges[(int(face[i]), int(face[(i + 1) % len(face)]))] += 1 + return all(n == 1 and edges.get((v, u)) == 1 for (u, v), n in edges.items()) + + +def signed_volume(b) -> float: + total = 0.0 + for face in faces_of(b): + p = b.V[face] + for i in range(1, len(face) - 1): + total += float(np.dot(p[0], np.cross(p[i], p[i + 1]))) / 6.0 + return total + + +def frustum(r0, r1, h, n) -> float: + a0, a1 = (0.5 * n * r * r * math.sin(2 * math.pi / n) for r in (r0, r1)) + return h / 3.0 * (a0 + a1 + math.sqrt(a0 * a1)) + + +def point_triangle(p, a, b, c) -> float: + """Distance from p to triangle abc (Ericson, Real-Time Collision Detection 5.1.5).""" + ab, ac, ap = b - a, c - a, p - a + d1, d2 = ab @ ap, ac @ ap + if d1 <= 0 and d2 <= 0: + return float(np.linalg.norm(ap)) + bp = p - b + d3, d4 = ab @ bp, ac @ bp + if d3 >= 0 and d4 <= d3: + return float(np.linalg.norm(bp)) + vc = d1 * d4 - d3 * d2 + if vc <= 0 and d1 >= 0 and d3 <= 0: + return float(np.linalg.norm(ap - ab * (d1 / (d1 - d3)))) + cp = p - c + d5, d6 = ab @ cp, ac @ cp + if d6 >= 0 and d5 <= d6: + return float(np.linalg.norm(cp)) + vb = d5 * d2 - d1 * d6 + if vb <= 0 and d2 >= 0 and d6 <= 0: + return float(np.linalg.norm(ap - ac * (d2 / (d2 - d6)))) + va = d3 * d6 - d5 * d4 + if va <= 0 and d4 - d3 >= 0 and d5 - d6 >= 0: + return float(np.linalg.norm(bp - (c - b) * ((d4 - d3) / ((d4 - d3) + (d5 - d6))))) + normal = np.cross(ab, ac) + return float(abs(ap @ normal) / np.linalg.norm(normal)) + + +def socket_seat(b, socket) -> float: + """Distance from the socket's origin to the nearest face whose normal is the socket's z (inf when none faces it).""" + origin, z = socket["matrix"][:3, 3], socket["matrix"][:3, 2] + best = math.inf + for face in faces_of(b): + p = b.V[face] + normal = np.cross(p[1] - p[0], p[2] - p[0]) + normal /= np.linalg.norm(normal) + if np.abs(normal - z).max() > 1e-6: + continue + best = min([best] + [point_triangle(origin, p[0], p[i], p[i + 1]) for i in range(1, len(face) - 1)]) + return best + + +@unittest.skipIf(np is None, "numpy is not installed") +class ExpressionTests(unittest.TestCase): + def test_the_whitelist_evaluates_exactly_and_refuses_the_rest(self): + """expr-whitelist. Mutant M1 (drop the call-name check): pow(a,b) is admitted (abs(a) still dies on its one + argument, so the two-argument call is the witness).""" + env = {"a": 1.5, "b": 0.25} + self.assertEqual(core.parse("2*(a+b)-min(a,3)/4", env, "t").value(env), 2 * (1.5 + 0.25) - 1.5 / 4) + self.assertEqual(core.parse("-a+max(b,-2)", env, "t").value(env), -1.25) + self.assertEqual(core.parse("+a", env, "t").value(env), 1.5) + self.assertEqual(core.parse(3, env, "t").value(env), 3.0) + for text in ("a.real", "a[0]", "a**2", "a Date: Tue, 1 Dec 2026 14:48:03 +0100 Subject: [PATCH 068/223] docs: kitbash.md, the kit format by example, the four actions and a recipe Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 167 +++++++++++++++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 surfaces/blender/docs/kitbash.md diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md new file mode 100644 index 0000000..a893abf --- /dev/null +++ b/surfaces/blender/docs/kitbash.md @@ -0,0 +1,167 @@ +# Kitbash parts: machinery from kits + +`surfaces/blender/brokkr_kitbash` is a Blender add-on that places parametric machine parts from a **kit** and +reports where their **sockets** are. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks, +actuators, housings and plumbing an agent assembles offline under a hand-fit armor cage, baked once. It is a host +add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish` and `brokkr_rig`: +it imports the polish package's operator base, `Refused` and `mesh_object`, and nothing from `brokkr_bridge`. +Enable `brokkr_mesh_polish` first; `brokkr_kitbash` refuses to register without it. `brokkr_actions.json` beside +its `__init__.py` lists the four operators agents may run. Every action writes a JSON report to +`brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. + +Who owns what: + +- `brokkr_kitbash/core.py` (numpy and the standard library, no Blender) owns the kit format: what a kit document + may say (`check_kit`), what a part's params may be (`resolve_params`), and the geometry and socket frames a part + and its params produce (`build`). There is no other validator of the format. +- `brokkr_kitbash/kits/.v0.json` own kit content. A kit is chosen by name (`a-z`, `0-9`, `_`, at most 32); + the name is the only thing an intent contributes to the path. +- In the scene, an object's `kit_kit`, `kit_part` and `kit_params` ID properties own what that part is. Its mesh is + derived from them: `set_params` rebuilds it, and an edit made to the mesh by hand is lost at the next + `set_params`. Socket frames are derived at every report and stored nowhere. + +This add-on places and re-parameterises parts. Mating sockets, booleans and baking are not here. + +## A part, end to end + +A kit document is `{schema: "brokkr.kit.v0", kit, doc, socketTypes, parts}`. One part of a kit, whole: + +```json +{ + "name": "standoff", + "doc": "A post on a square foot.", + "params": [ + {"name": "height", "type": "number", "min": 0.05, "max": 0.5, "default": 0.2, "doc": "foot face to top face"}, + {"name": "radius", "type": "number", "min": 0.01, "max": 0.05, "default": 0.02, "doc": "post radius"}, + {"name": "bolts", "type": "integer", "min": 1, "max": 4, "default": 2, "doc": "bolts along x"} + ], + "bevel": "0.1*radius", + "shapes": [ + {"shape": "box", "size": ["6*radius", "3*radius", "radius"], "at": [0, 0, "0.5*radius"]}, + {"shape": "tube", "r0": "radius", "r1": "0.8*radius", "length": "height-0.5*radius", "segments": 24, "smooth": true, + "at": [0, 0, "0.5*radius"]}, + {"shape": "repeat", "count": "bolts", "step": ["4*radius/max(bolts-1,1)", 0, 0], "of": + {"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.4*radius", "segments": 6, + "at": ["-2*radius", 0, "0.9*radius"]}} + ], + "sockets": [ + {"name": "foot", "type": "mount", "size": "3*radius", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "top", "type": "mount", "size": "1.6*radius", "at": [0, 0, "height"], "z": "+z", "y": "+y"} + ] +} +``` + +Lengths are metres in the part's own frame. Unknown keys are refused at every level, and so is a repeated part, +param or socket name, a default outside `[min, max]`, and an integer param with a fractional bound or default. + +**Params** are `number` or `integer` with inclusive bounds. A param name is lower case (`a-z`, then `a-z`, `0-9`, +`_`) and is not `min` or `max`. + +**Shapes.** Each is one or more closed shells wound outward. `at` (metres) and `rot` (XYZ Euler degrees: about x, +then y, then z, about the shape's own origin) place it, rotation first; both default to zero. + +| shape | fields | what it is | +| --- | --- | --- | +| `tube` | `r0`, `r1`, `length`, `segments`, `inner0`?, `inner1`?, `smooth`? | A frustum on +z from radius `r0` at z=0 to `r1` at z=`length`, with n-gon caps. Inner radii above 0 make it hollow (an inner wall and two flat end rings); they are both above 0 or both 0, and below the outer radius. `segments` is 3 to 128. `smooth` shades the walls smooth; caps stay flat. | +| `box` | `size` | A box centred on its origin; every size above 0. | +| `repeat` | `count`, `step`, `of` | `count` copies (1 to 256) of one tube or box at `k * step`, k from 0. A repeat cannot hold a repeat. | + +Shells may overlap (a pad that runs into a tank), and a part is then not one solid: reports give the shell count. + +**`bevel`** is the width of a Bevel modifier `place_part` adds (2 segments, edges sharper than 30 degrees). Keep it +well under the part's thinnest feature at its smallest params. + +**Sockets** are frames. `at` is the origin; `z` is the outward normal (a mating socket faces it), `y` is up (the +roll reference), and x is y cross z; each is one of `+x -x +y -y +z -z` in the part's frame, on different axes. +`size` is a diameter in metres. `type` names one of the kit's `socketTypes`, whose `match` says how sizes are to +be compared when sockets are mated: `equal` (within 1 percent) or `fits` (the child at most the parent). A socket +sits on a flat face of the part whose normal is its `z`; `test_kitbash` checks this for every part of a shipped +kit at its default, smallest and largest params and at seeded draws between. + +## Expressions + +Every numeric field of a shape or socket, and `bevel`, is a number or a string over the part's params: + +```text ++ - * / unary minus ( ) min(a, b) max(a, b) numbers param names +``` + +An expression is parsed once and walked against that list when the kit is checked; an attribute, subscript, +power, comparison, any other call, a keyword argument, a lambda or a string is refused there, naming the part and +field. Nothing in a kit is run as Python. Division by zero and a `count` or `segments` that is not whole are +refused when the part is built, naming the expression. + +## The actions + +| action | fields | what it does | +| --- | --- | --- | +| `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | +| `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: transform, parent, modifiers and material slots stay, and the Bevel width follows. | +| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, and each socket's world frame. Changes nothing. | + +`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. + +A socket in a report is `{name, type, size, matrix}`: `matrix` is the 4x4 as four rows of 6 decimals, in world +space for `place_part`, `set_params` and `report`. Column 2 is the outward normal, column 1 up, column 3 the +origin. A report over 16000 characters (what a receipt carries) is refused with advice to name one part or +object. + +Placement, look and export are Brokkr's own rows: `setObjectTransform`, `assignMaterial`, `exportGltf`. +`place_part` has no location or colour fields. + +## A recipe + +`tools/run_intents.py` runs this in a background Blender (`install.md`, private user directories required): + +```json +{"requestedBy": "nibu/hands", "outputDir": "/work/out", "hostAddons": ["brokkr_mesh_polish", "brokkr_kitbash"], + "saveBlend": "/work/out/engine.blend", + "intents": [ + {"action": "brokkr_kitbash.describe", "part": "tank"}, + {"action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank", "params": "radius=0.3; length=1.4"}, + {"action": "setObjectTransform", "targetObjectName": "Tank", "location": [0, 0.6, 0], "rotationEuler": [1.5708, 0, 0]}, + {"action": "assignMaterial", "targetObjectName": "Tank", "materialName": "Machinery", "color": [0.35, 0.35, 0.35]}, + {"action": "brokkr_kitbash.place_part", "part": "nozzle", "object_name": "Nozzle"}, + {"action": "brokkr_kitbash.set_params", "object_name": "Nozzle", "params": "exit_r=0.32"}, + {"action": "brokkr_kitbash.report"}, + {"action": "exportGltf", "filepath": "engine.glb", "selection": ["Tank", "Nozzle"]} + ]} +``` + +The receipts file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the saved `.blend`. + +## The mechanical kit + +`kits/mechanical.v0.json`: nine parts, each along +z, with socket types `flange` (equal), `mount` (fits) and +`pivot` (equal). + +| part | params | sockets | +| --- | --- | --- | +| `nozzle` | `throat_r`, `exit_r`, `length`, `wall`, `segments` | `mount` (flange) | +| `tank` | `radius`, `length`, `segments` | `port_a`, `port_b` (flange), `saddle` (mount) | +| `ribbed_cylinder` | `radius`, `length`, `ribs`, `rib_depth`, `rib_width`, `segments` | `end_a`, `end_b` (flange) | +| `strut` | `length`, `width`, `thickness`, `segments` | `end_a`, `end_b` (pivot) | +| `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `rod_end` (pivot); `rod_end` moves with `extension` | +| `pipe_fitting` | `pipe_r`, `run`, `branch`, `flange_r`, `flange_t`, `segments` | `a`, `b`, `c` (flange) | +| `radiator_stack` | `fins`, `fin_w`, `fin_h`, `fin_t`, `pitch`, `segments` | `base` (mount) | +| `vent` | `width`, `height`, `depth`, `slats`, `slat_t`, `tilt` | `back` (mount) | +| `plate` | `width`, `height`, `thickness` | `back`, `front` (mount) | + +`describe` gives the bounds and docs. + +## Adding a part or a kit + +Edit the kit's JSON (or add `kits/.v0.json`, whose `kit` field is ``), then run the tests: + +```text +python -m unittest discover -s surfaces/blender/tests -p "test_kitbash.py" -v +``` + +`MechanicalKitTests` builds every part of `mechanical` at its default, all-minimum and all-maximum params and at +16 seeded draws, and checks that every shell is closed and wound outward, every socket frame is right-handed and +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_nine_parts_and_three_socket_types`. +The operators are exercised in a real Blender by `tests/live/kitbash.py`. From d952fb55e97ba3bd03b21f83e549aa35abfd039a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 15:21:36 +0100 Subject: [PATCH 069/223] brokkr_kitbash: one owner per part (shared mesh, scale), named refusals, materials by shape Fixes from verdict aetheria-release:verdict:cut-chassis-kit-format.s1. set_params refuses a mesh datablock another object uses: rebuilding it changed the linked duplicate while its kit_params stayed. set_params and report refuse a part whose world transform scales, mirrors or shears: a part's size is its params and a socket frame is a rotation and an origin. set_params carries per-face material_index by shape (Built.shape names each face's shape), so an assignment survives a change of segments or counts. Kit-side mistakes are KitErrors: an unhashable value where a name belongs, an integer no float holds, and vertices that overflow are refused by name. Tests pin the finite check, socket size, bevel sign and the hollow tube's inner radii (Soul's N4, N8, N9, N10). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 44 ++++++++++++- .../brokkr_kitbash/brokkr_actions.json | 4 +- surfaces/blender/brokkr_kitbash/core.py | 61 +++++++++++++------ surfaces/blender/docs/kitbash.md | 12 +++- surfaces/blender/tests/live/kitbash.py | 37 ++++++++++- .../blender/tests/live/kitbash.result.json | 53 ++++++++++++++-- surfaces/blender/tests/test_kitbash.py | 46 +++++++++++++- 7 files changed, 224 insertions(+), 33 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index ea1c2fd..eb004e0 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -8,7 +8,9 @@ WindowManager.brokkr_mesh_polish_result, as the polish operators do. What a placed part is lives on its object as three ID properties: kit_kit, kit_part and kit_params. The mesh is derived from them (set_params rebuilds it), and socket frames are derived again at every report: nothing else in -the scene stores them. Placement, materials and export are Brokkr's own rows (setObjectTransform, assignMaterial, +the scene stores them. Two things would give a part a second owner and are refused: a mesh datablock shared with +another object (set_params), and a world transform that scales, mirrors or shears (set_params and report: a +part's size is its params). Placement, materials and export are Brokkr's own rows (setObjectTransform, assignMaterial, exportGltf). """ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), @@ -66,10 +68,19 @@ def sync_bevel(obj, width: float) -> None: modifier.width = width +RIGID = 1e-5 # how far a world matrix's 3x3 may stand from a rotation + + def kit_part_of(obj): - """(part, stored params) of a placed part, read from its ID properties.""" + """(part, stored params) of a placed part, read from its ID properties. Refuses a part whose world transform is + not rigid: its socket frames would not be frames, and its size would have a second owner.""" if PART not in obj: raise Refused(f"{obj.name!r} is not a kit part (it has no {PART} property); place_part makes one.") + turn = np.array(obj.matrix_world)[:3, :3] + if np.abs(turn.T @ turn - np.eye(3)).max() > RIGID or np.linalg.det(turn) < 0: + scale = ", ".join(f"{s:.4g}" for s in obj.matrix_world.to_scale()) + raise Refused(f"{obj.name!r} is scaled, mirrored or sheared in the world (scale {scale}): a kit part's size is its params. " + "Set its scale, and its parents', to 1 (setObjectTransform) and resize it with set_params.") try: stored = json.loads(obj.get(PARAMS, "{}")) except ValueError: @@ -85,6 +96,22 @@ def part_report(obj, part, built) -> dict: "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world))} +def carried_materials(mesh, old, new): + """Per-face material indices for a rebuilt mesh, or None when there is nothing to carry: each shape of the part + keeps the index most of its faces had (the lowest on a tie), since faces do not survive a change of segments + or counts but shapes do. A mesh that is no longer the old build (edited by hand) carries nothing.""" + if old is None or len(mesh.polygons) != len(old.counts): + return None + index = np.zeros(len(old.counts), dtype=np.int32) + mesh.polygons.foreach_get("material_index", index) + if not index.any(): + return None + carried = np.zeros(len(new.counts), dtype=np.int32) + for shape in np.unique(old.shape): + carried[new.shape == shape] = np.bincount(index[old.shape == shape]).argmax() + return carried + + def bounded(report: dict, advice: str) -> dict: size = len(json.dumps(report, separators=(",", ":"))) if size > REPORT_LIMIT: @@ -119,7 +146,7 @@ class BROKKR_KITBASH_OT_place_part(PolishOperator): class BROKKR_KITBASH_OT_set_params(PolishOperator): """Change params of a placed kit part and rebuild its mesh in place: its transform, parent, modifiers and - material slots stay, and the Bevel width follows""" + material slots stay, each shape keeps its faces' material, and the Bevel width follows""" bl_idname = "brokkr_kitbash.set_params" bl_label = "Set Kit Part Params" object_name: bpy.props.StringProperty(name="Object") @@ -129,9 +156,20 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): def work(self, context): obj = mesh_object(self.object_name) part, stored = kit_part_of(obj) + if obj.data.users > 1: + raise Refused(f"{obj.name!r} shares its mesh {obj.data.name!r} with {obj.data.users - 1} other user(s): rebuilding it would change " + "them while their params stay. Give it its own mesh (place_part a new part) and set that; nothing changed.") built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored)) + try: + old = core.build(part, stored) + except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by + old = None + materials = carried_materials(obj.data, old, built) obj.data.clear_geometry() write_mesh(obj.data, built) + if materials is not None: + obj.data.polygons.foreach_set("material_index", materials) + obj.data.update() sync_bevel(obj, built.bevel) obj[PARAMS] = json.dumps(built.params) return part_report(obj, part, built) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 41e010a..b570c13 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -45,7 +45,7 @@ }, { "name": "brokkr_kitbash.set_params", - "doc": "Change params of a placed kit part and rebuild its mesh in place; transform, parent, modifiers and materials stay. Reports as place_part.", + "doc": "Change params of a placed kit part and rebuild its mesh in place; transform, parent, modifiers and materials stay. Refuses a mesh another object shares and a scaled part. Reports as place_part.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -93,7 +93,7 @@ }, { "name": "brokkr_kitbash.report", - "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world 4x4.", + "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world 4x4. Refuses a part scaled in the world: resize with set_params.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 0d6b0c8..a9b0c6b 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -40,6 +40,16 @@ class KitError(ValueError): """The kit document, a param or a build breaks a rule of the format; the message names where.""" +def finite(value: Any) -> bool: + """A number (not a bool) a float can hold: an integer too large for one is not finite.""" + if isinstance(value, bool) or not isinstance(value, (int, float)): + return False + try: + return math.isfinite(float(value)) + except OverflowError: + return False + + # --- expressions --------------------------------------------------------------------------------------------- class Expr: @@ -50,8 +60,11 @@ class Expr: self.source, self.tree, self.where = source, tree, where def value(self, env: dict[str, float]) -> float: - result = self.source if self.tree is None else _walk(self.tree, env, self) - if not math.isfinite(result): + try: + result = self.source if self.tree is None else _walk(self.tree, env, self) + except OverflowError: # an integer literal no float holds + result = math.inf + if not finite(result): raise KitError(f"{self.where}: {self.source!r} is not a finite number") return float(result) @@ -60,8 +73,8 @@ def parse(value: Any, names, where: str) -> Expr: """The Expr for a numeric field: a finite number, or a string of + - * /, unary minus, parentheses, min(a,b), max(a,b), numbers and the names given. Anything else is refused here, before any build.""" if isinstance(value, (int, float)) and not isinstance(value, bool): - if not math.isfinite(value): - raise KitError(f"{where}: {value!r} is not a finite number") + if not finite(value): + raise KitError(f"{where}: {str(value)[:40]} is not a finite number") return Expr(value, None, where) if not isinstance(value, str): raise KitError(f"{where} must be a number or an expression string, not {type(value).__name__}") @@ -150,7 +163,7 @@ def _name(value: Any, where: str, seen: set) -> str: def _number(value: Any, where: str) -> float: - if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + if not finite(value): raise KitError(f"{where} must be a finite number") return value @@ -166,7 +179,7 @@ ZERO = [Expr(0.0, None, "zero")] * 3 def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict: kind = shape.get("shape") if isinstance(shape, dict) else None - if kind not in SHAPES: + if not isinstance(kind, str) or kind not in SHAPES: raise KitError(f"{where}: unknown shape {kind!r}; shapes are {', '.join(SHAPES)}") where = f"{where} ({kind})" required, optional = SHAPES[kind] @@ -248,10 +261,10 @@ def check_kit(document: Any) -> dict: s_name = _name(socket.get("name") if isinstance(socket, dict) else None, f"{where} socket {s_index}", socket_names) s_where = f"{where} socket {s_name!r}" _keys(socket, s_where, ("name", "type", "size", "at", "z", "y")) - if socket["type"] not in types: + if not isinstance(socket["type"], str) or socket["type"] not in types: raise KitError(f"{s_where}: type {socket['type']!r} is not one of the kit's socketTypes ({', '.join(types) or 'none'})") for key in ("z", "y"): - if socket[key] not in AXES: + if not isinstance(socket[key], str) or socket[key] not in AXES: raise KitError(f"{s_where}: {key} must be one of {', '.join(AXES)}") if socket["z"][1] == socket["y"][1]: raise KitError(f"{s_where}: z ({socket['z']}) and y ({socket['y']}) lie on the same axis") @@ -328,7 +341,7 @@ def resolve_params(part: dict, given: dict, base: dict | None = None) -> dict: for param in part["params"]: name = param["name"] value = merged.get(name, param["default"]) - if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + if not finite(value): raise KitError(f"{here} param {name!r} must be a finite number") if not param["min"] <= value <= param["max"]: raise KitError(f"{here} param {name!r} = {value} is outside [{param['min']}, {param['max']}] (bounds included)") @@ -344,13 +357,15 @@ def resolve_params(part: dict, given: dict, base: dict | None = None) -> dict: class Built(NamedTuple): """A part at given params, in the part's frame, metres. Face i has counts[i] corners, listed in order in - faces (quads and n-gon caps, wound outward); smooth[i] marks tube sides to shade smooth. Each socket is + faces (quads and n-gon caps, wound outward); smooth[i] marks tube sides to shade smooth; shape[i] is the index, + in the part's shapes list, of the shape the face belongs to (every copy of a repeat shares one). Each socket is {'name', 'type', 'size', 'matrix'} with matrix the 4x4 frame: column 2 the outward normal, column 1 up, column 0 = y cross z, column 3 the origin.""" V: np.ndarray faces: np.ndarray counts: np.ndarray smooth: np.ndarray + shape: np.ndarray shell_count: int sockets: list bevel: float @@ -427,15 +442,22 @@ def build(part: dict, params: dict | None = None) -> Built: """The part at these params (resolve_params fills and checks them). The same part and params give byte-identical arrays.""" env = resolve_params(part, params or {}) - shells = [] - for shape in part["shapes"]: - if shape["shape"] == "repeat": - count = _whole(shape["count"], env, COPIES) - step = np.array([e.value(env) for e in shape["step"]]) - V, faces, counts, smooth = _placed(shape["of"], env) - shells += [(V + k * step, faces, counts, smooth) for k in range(count)] - else: - shells.append(_placed(shape, env)) + here = f"kit {part['kit']!r} part {part['name']!r}" + shells, owner = [], [] + with np.errstate(over="ignore", invalid="ignore"): # a huge value is refused below, not warned about + for index, shape in enumerate(part["shapes"]): + if shape["shape"] == "repeat": + count = _whole(shape["count"], env, COPIES) + step = np.array([e.value(env) for e in shape["step"]]) + V, faces, counts, smooth = _placed(shape["of"], env) + made = [(V + k * step, faces, counts, smooth) for k in range(count)] + else: + made = [_placed(shape, env)] + for shell in made: + if not np.isfinite(shell[0]).all(): + raise KitError(f"{here} shape {index} ({shape['shape']}): its vertices are not finite at these params") + shells += made + owner += [index] * len(made) offsets = np.cumsum([0] + [len(s[0]) for s in shells[:-1]]) sockets = [] for socket in part["sockets"]: @@ -454,6 +476,7 @@ def build(part: dict, params: dict | None = None) -> Built: faces=np.concatenate([s[1] + o for s, o in zip(shells, offsets)]).astype(np.int32), counts=np.concatenate([s[2] for s in shells]).astype(np.int32), smooth=np.concatenate([s[3] for s in shells]).astype(bool), + shape=np.concatenate([np.full(len(s[2]), o) for s, o in zip(shells, owner)]).astype(np.int32), shell_count=len(shells), sockets=sockets, bevel=bevel, params=env) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index a893abf..8ce9c2c 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -19,6 +19,11 @@ Who owns what: - In the scene, an object's `kit_kit`, `kit_part` and `kit_params` ID properties own what that part is. Its mesh is derived from them: `set_params` rebuilds it, and an edit made to the mesh by hand is lost at the next `set_params`. Socket frames are derived at every report and stored nowhere. +- Two things would give a part a second owner, and are refused. `set_params` refuses an object whose mesh + datablock another object uses (a linked duplicate): rebuilding it would change the other while its params stay. + `set_params` and `report` refuse a part whose world transform scales, mirrors or shears, its parents' + included: a part's size is its params, and a socket's frame is a rotation and an origin. Set scale to 1 and + resize with `set_params`. This add-on places and re-parameterises parts. Mating sockets, booleans and baking are not here. @@ -88,8 +93,9 @@ Every numeric field of a shape or socket, and `bevel`, is a number or a string o An expression is parsed once and walked against that list when the kit is checked; an attribute, subscript, power, comparison, any other call, a keyword argument, a lambda or a string is refused there, naming the part and -field. Nothing in a kit is run as Python. Division by zero and a `count` or `segments` that is not whole are -refused when the part is built, naming the expression. +field. Nothing in a kit is run as Python. Division by zero, a result that is not a finite number, and a `count` +or `segments` that is not whole are refused when the part is built, naming the expression; so is a shape whose +vertices overflow. ## The actions @@ -97,7 +103,7 @@ refused when the part is built, naming the expression. | --- | --- | --- | | `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | | `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: transform, parent, modifiers and material slots stay, and the Bevel width follows. | +| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: transform, parent, 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. | | `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, and each socket's world frame. Changes nothing. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 7ab51e5..410cab3 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -142,8 +142,8 @@ check("set_params overlays the stored params, and the Bevel width follows the pa # --- report: sockets in the world ------------------------------------------------------------------------------------------- send("setObjectTransform", targetObjectName="P_pipe_fitting", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) +receipt, reported = send("brokkr_kitbash.report") # straight after the move, before anything here updates the view layer: the frames are already the moved ones bpy.context.view_layer.update() -receipt, reported = send("brokkr_kitbash.report") worst, listed = 0.0, [] for entry in (reported or {}).get("parts", []): obj = bpy.data.objects[entry["object"]] @@ -161,9 +161,29 @@ check("report of the parented, rotated tank carries its parent's and its own tra and np.abs(np.array(single["parts"][0]["sockets"][2]["matrix"]) - tank_world @ core.build(kit["parts"]["tank"], wide["params"]).sockets[2]["matrix"]).max() < 1e-6 and np.abs(tank_world[:3, 3] - [1.0, 2.0, 3.0]).max() < 1e-6, single) +# --- per-face materials ride on the part's shapes ---------------------------------------------------------------------------- +strut = bpy.data.objects["P_strut"] +send("assignMaterial", targetObjectName="P_strut", materialName="Strut Paint", color=[0.35, 0.35, 0.35]) +strut.data.materials.append(bpy.data.materials.new("Pin Steel")) +PINS = 2 # the strut's third shape: the repeat of two pins +was = core.build(kit["parts"]["strut"]) +strut.data.polygons.foreach_set("material_index", np.where(was.shape == PINS, 1, 0).astype(np.int32)) +receipt, _ = send("brokkr_kitbash.set_params", object_name="P_strut", params="segments=12; length=1.2") +now = core.build(kit["parts"]["strut"], {"segments": 12, "length": 1.2}) +index = np.zeros(len(strut.data.polygons), dtype=np.int32) +strut.data.polygons.foreach_get("material_index", index) +check("set_params with other segments keeps each shape's material: the pins stay Pin Steel, the rest Strut Paint", receipt["status"] == "accepted" + and len(now.counts) != len(was.counts) and index.tolist() == np.where(now.shape == PINS, 1, 0).tolist() and int(index.sum()) == 2 * (12 + 2) + and [s.material.name for s in strut.material_slots] == ["Strut Paint", "Pin Steel"], [receipt["message"], int(index.sum()), len(index)]) + # --- refusals leave the scene as it was -------------------------------------------------------------------------------------- bpy.ops.mesh.primitive_cube_add() bpy.context.active_object.name = "Plain" +twin = bpy.data.objects["P_vent"].copy() # a linked duplicate: one mesh, two objects, each with its own kit_params +twin.name = "P_vent_twin" +bpy.context.scene.collection.objects.link(twin) +send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[2.0, 2.0, 2.0]) +send("setObjectTransform", targetObjectName="P_actuator", scale=[-1.0, 1.0, 1.0]) def scene_state(): @@ -185,6 +205,12 @@ refusals = [ ("set_params out of range", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=0.1"}, "is outside [0.6, 2.0]"), ("set_params with a repeated key", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=1; length=1.2"}, "'length' is given twice"), ("report of a plain mesh", "brokkr_kitbash.report", {"object_name": "Plain"}, "is not a kit part"), + ("set_params on a mesh a linked duplicate shares", "brokkr_kitbash.set_params", {"object_name": "P_vent", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"), + ("set_params on the linked duplicate", "brokkr_kitbash.set_params", {"object_name": "P_vent_twin", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"), + ("report of a scaled part", "brokkr_kitbash.report", {"object_name": "P_radiator_stack"}, "'P_radiator_stack' is scaled, mirrored or sheared in the world (scale 2, 2, 2)"), + ("set_params on a scaled part", "brokkr_kitbash.set_params", {"object_name": "P_radiator_stack", "params": "fins=5"}, "is scaled, mirrored or sheared"), + ("report of a mirrored part", "brokkr_kitbash.report", {"object_name": "P_actuator"}, "'P_actuator' is scaled, mirrored or sheared"), + ("report of every part while one is scaled", "brokkr_kitbash.report", {}, "is scaled, mirrored or sheared"), ("describe of an unknown part", "brokkr_kitbash.describe", {"part": "wing"}, "has no part 'wing'"), ] for label, action, fields, expected in refusals: @@ -192,6 +218,15 @@ for label, action, fields, expected in refusals: check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state, [receipt["status"], receipt["message"]]) +bpy.data.objects.remove(twin) +send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[1.0, 1.0, 1.0]) +send("setObjectTransform", targetObjectName="P_actuator", scale=[1.0, 1.0, 1.0]) +receipt, alone = send("brokkr_kitbash.set_params", object_name="P_vent", params="slats=9") +check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone + and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"]) +receipt, whole = send("brokkr_kitbash.report") +check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 9, receipt["message"]) + # --- export --------------------------------------------------------------------------------------------------------------- receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names]) glb = WORK / "kit.glb" diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 2097f87..ab893bc 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -191,6 +191,11 @@ "ok": true, "detail": null }, + { + "name": "set_params with other segments keeps each shape's material: the pins stay Pin Steel, the rest Strut Paint", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: an unknown kit", "ok": true, @@ -251,11 +256,51 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: set_params on a mesh a linked duplicate shares", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on the linked duplicate", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: report of a scaled part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a scaled part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: report of a mirrored part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: report of every part while one is scaled", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: describe of an unknown part", "ok": true, "detail": null }, + { + "name": "with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", + "ok": true, + "detail": null + }, + { + "name": "with scale back at 1 every part reports again", + "ok": true, + "detail": null + }, { "name": "exportGltf of all nine parts succeeds", "ok": true, @@ -278,16 +323,16 @@ ], "placed": { "nozzle": { - "faces": 1024, - "shells": 21, + "faces": 1312, + "shells": 24, "bevel": 0.0024, "sockets": [ "mount" ] }, "tank": { - "faces": 636, - "shells": 16, + "faces": 740, + "shells": 20, "bevel": 0.00176, "sockets": [ "port_a", diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index c0b0bcd..5481efd 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -150,6 +150,34 @@ class ExpressionTests(unittest.TestCase): core.build(core.part(kit, "p")) self.assertEqual(float(np.ptp(core.build(core.part(kit, "p"), {"a": 3}).V[:, 0])), 0.5) + def test_a_value_no_float_holds_is_refused_by_name(self): + """Mutant N4 (finite check dropped in Expr.value): 1e308*a at a=10 is inf and is no longer refused there.""" + part = core.part(core.check_kit(document([{"shape": "box", "size": ["1e308*a", 1, "a*" + "9" * 400]}], [param("a", 0, 10, 0)])), "p") + with self.assertRaisesRegex(core.KitError, r"part 'p' shape 0 \(box\) size\[0\]: '1e308\*a' is not a finite number"): + core.build(part, {"a": 10}) + with self.assertRaisesRegex(core.KitError, r"size\[2\]: 'a\*9+' is not a finite number"): # an integer literal no float holds + core.build(part, {"a": 1e-300}) + for doc, message in ((document([{"shape": "box", "size": [10 ** 400, 1, 1]}]), r"size\[0\]: 1000\d+ is not a finite number"), + (document(params=[param("a", 0, 10 ** 400, 1)]), r"param 'a' max must be a finite number")): + with self.assertRaisesRegex(core.KitError, message): + core.check_kit(doc) + with self.assertRaisesRegex(core.KitError, r"param 'a' must be a finite number"): + core.resolve_params(part, {"a": 10 ** 400}) + far = core.part(core.check_kit(document([{"shape": "box", "size": [1, 1, 1]}, {"shape": "box", "size": [1e308, 1, 1], "at": [1.5e308, 0, 0]}])), "p") + with self.assertRaisesRegex(core.KitError, r"part 'p' shape 1 \(box\): its vertices are not finite"): # each number finite, their sum not + core.build(far) + + def test_a_socket_size_is_above_zero_and_a_bevel_is_not_negative(self): + """Mutants N8 (socket size <= 0 allowed) and N9 (negative bevel allowed).""" + socket = {"name": "s", "type": "mount", "size": "a-1", "at": [0, 0, 0], "z": "+z", "y": "+y"} + part = core.part(core.check_kit(document(params=[param("a")], sockets=[socket], bevel="2-a")), "p") + self.assertEqual((core.build(part, {"a": 2}).sockets[0]["size"], core.build(part, {"a": 2}).bevel), (1.0, 0.0)) + for a in (1.0, 0.5): + with self.assertRaisesRegex(core.KitError, r"part 'p' socket 's' size is -?0\.\d: a socket's size must be above 0"): + core.build(part, {"a": a}) + with self.assertRaisesRegex(core.KitError, r"part 'p' bevel is -1\.0: a bevel is 0 or more"): + core.build(part, {"a": 3}) + @unittest.skipIf(np is None, "numpy is not installed") class CheckKitTests(unittest.TestCase): @@ -175,6 +203,10 @@ class CheckKitTests(unittest.TestCase): (document([{**box, "size": ["width", 1, 1]}], [param("a")]), r"part 'p' shape 0 \(box\) size\[0\]: 'width' names 'width'"), (document(params=[param("min")]), r"part 'p' param 0: 'min' is not a name"), (document(bevel="a.b"), r"part 'p' bevel: 'a\.b' uses Attribute"), + (document(sockets=[{**socket, "type": ["mount"]}]), r"part 'p' socket 's': type \['mount'\] is not one of"), # unhashable where a name belongs + (document(sockets=[{**socket, "z": {}}]), r"part 'p' socket 's': z must be one of"), + (document([{"shape": ["box"], "size": [1, 1, 1]}]), r"part 'p' shape 0: unknown shape \['box'\]"), + (document(sockets=[{**socket, "at": [0, 0, 10 ** 400]}]), r"part 'p' socket 's' at\[2\]: 1000\d+ is not a finite number"), ] for doc, message in cases: with self.assertRaisesRegex(core.KitError, message): @@ -199,7 +231,8 @@ class CheckKitTests(unittest.TestCase): class ShapeTests(unittest.TestCase): def test_tubes_are_closed_oriented_and_hold_their_volume(self): """tube-closed-oriented. Mutants M3 (inner wall not reversed) and M4 (solid tube without its top cap) break - the edge census; M5 (r0 and r1 swapped) puts the z=0 ring at r1.""" + the edge census; M5 (r0 and r1 swapped) puts the z=0 ring at r1; N10 (inner0 and inner1 swapped) puts the + z=0 inner ring at inner1, which volume and the census cannot see.""" for n in (3, 32): solid = built([{"shape": "tube", "r0": 0.5, "r1": 0.3, "length": 2.0, "segments": n}]) hollow = built([{"shape": "tube", "r0": 0.5, "r1": 0.3, "inner0": 0.2, "inner1": 0.1, "length": 2.0, "segments": n, "smooth": True}]) @@ -211,6 +244,9 @@ class ShapeTests(unittest.TestCase): low = b.V[np.abs(b.V[:, 2]) < 1e-12] self.assertTrue(np.allclose(np.linalg.norm(low[:n, :2], axis=1), 0.5, atol=1e-12)) self.assertEqual(float(b.V[:, 2].max()), 2.0) + for rows_, radius, z in ((slice(2 * n, 3 * n), 0.2, 0.0), (slice(3 * n, 4 * n), 0.1, 2.0)): + self.assertTrue(np.allclose(np.linalg.norm(hollow.V[rows_, :2], axis=1), radius, atol=1e-12)) + self.assertTrue((hollow.V[rows_, 2] == z).all()) self.assertEqual(solid.smooth.tolist(), [False] * (n + 2)) self.assertEqual(hollow.smooth.tolist(), [True] * (2 * n) + [False] * (2 * n)) # both walls smooth, both end rings flat tube = {"shape": "tube", "r0": 1, "r1": 1, "length": 1, "segments": 8} @@ -246,6 +282,14 @@ class ShapeTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, "count is .*whole number from 1 to 256"): built([shape], [param("n", 0, 300, 4), param("a")], {"n": count}) + def test_every_face_names_its_shape(self): + """What set_params carries per-face materials by: a repeat's copies share their shape's index.""" + b = built([{"shape": "box", "size": [1, 1, 1]}, + {"shape": "repeat", "count": 3, "step": [2, 0, 0], "of": {"shape": "box", "size": [1, 1, 1]}}, + {"shape": "tube", "r0": 1, "r1": 1, "length": 1, "segments": 8}]) + self.assertEqual(b.shape.tolist(), [0] * 6 + [1] * 18 + [2] * 10) + self.assertEqual((b.shape.dtype, b.shell_count), (np.int32, 5)) + def test_sockets_are_right_handed_frames(self): socket = {"name": "s", "type": "mount", "size": "2*a", "at": ["a", 2, 3], "z": "+x", "y": "+z"} kit = core.check_kit(document(params=[param("a")], sockets=[socket])) From ee2f6af9e4b8b6dc602ed92017ffa0a8aa6f160c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 15:21:36 +0100 Subject: [PATCH 070/223] mechanical kit: an eight-frustum bell and four-frustum elliptical tank domes Softens the cone banding on the nozzle and the two-cone tank ends. Params and sockets are unchanged. Co-Authored-By: Claude Fable 5.2 --- .../brokkr_kitbash/kits/mechanical.v0.json | 48 +++++++++++-------- 1 file changed, 29 insertions(+), 19 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json index 41d2da7..a47db06 100644 --- a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json @@ -28,21 +28,27 @@ {"shape": "tube", "r0": "1.6*throat_r", "r1": "1.6*throat_r", "length": "1.75*throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "0.15*throat_r"]}, {"shape": "tube", "r0": "1.6*throat_r", "r1": "throat_r+wall", "length": "throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.9*throat_r"]}, {"shape": "tube", "r0": "1.78*throat_r", "r1": "1.78*throat_r", "length": "0.5*throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.6*throat_r"]}, - {"shape": "tube", "r0": "throat_r+wall", "r1": "throat_r+wall+0.226*(exit_r-throat_r-wall)", "inner0": "throat_r", "inner1": "throat_r+0.226*(exit_r-throat_r-wall)", - "length": "0.12*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r"]}, - {"shape": "tube", "r0": "throat_r+wall+0.226*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.482*(exit_r-throat_r-wall)", "inner0": "throat_r+0.226*(exit_r-throat_r-wall)", "inner1": "throat_r+0.482*(exit_r-throat_r-wall)", - "length": "0.16*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.12*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.482*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "inner0": "throat_r+0.482*(exit_r-throat_r-wall)", "inner1": "throat_r+0.75*(exit_r-throat_r-wall)", - "length": "0.22*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.28*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.9375*(exit_r-throat_r-wall)", "inner0": "throat_r+0.75*(exit_r-throat_r-wall)", "inner1": "throat_r+0.9375*(exit_r-throat_r-wall)", - "length": "0.25*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.5*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.9375*(exit_r-throat_r-wall)", "r1": "exit_r", "inner0": "throat_r+0.9375*(exit_r-throat_r-wall)", "inner1": "exit_r-wall", - "length": "0.25*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.75*length"]}, - {"shape": "tube", "r0": "throat_r+2.4*wall+0.5795*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.616*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.5795*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.616*(exit_r-throat_r-wall)", - "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.36*length"]}, - {"shape": "tube", "r0": "throat_r+2.4*wall+0.825*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.8475*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.825*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.8475*(exit_r-throat_r-wall)", + {"shape": "tube", "r0": "throat_r+wall", "r1": "throat_r+wall+0.1164*(exit_r-throat_r-wall)", "inner0": "throat_r", "inner1": "throat_r+0.1164*(exit_r-throat_r-wall)", + "length": "0.06*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r"]}, + {"shape": "tube", "r0": "throat_r+wall+0.1164*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.2604*(exit_r-throat_r-wall)", "inner0": "throat_r+0.1164*(exit_r-throat_r-wall)", "inner1": "throat_r+0.2604*(exit_r-throat_r-wall)", + "length": "0.08*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.06*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.2604*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.4224*(exit_r-throat_r-wall)", "inner0": "throat_r+0.2604*(exit_r-throat_r-wall)", "inner1": "throat_r+0.4224*(exit_r-throat_r-wall)", + "length": "0.1*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.14*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.4224*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.5904*(exit_r-throat_r-wall)", "inner0": "throat_r+0.4224*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5904*(exit_r-throat_r-wall)", + "length": "0.12*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.24*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.5904*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5904*(exit_r-throat_r-wall)", "inner1": "throat_r+0.75*(exit_r-throat_r-wall)", + "length": "0.14*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.36*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.8844*(exit_r-throat_r-wall)", "inner0": "throat_r+0.75*(exit_r-throat_r-wall)", "inner1": "throat_r+0.8844*(exit_r-throat_r-wall)", + "length": "0.16*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.5*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.8844*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.9676*(exit_r-throat_r-wall)", "inner0": "throat_r+0.8844*(exit_r-throat_r-wall)", "inner1": "throat_r+0.9676*(exit_r-throat_r-wall)", + "length": "0.16*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.66*length"]}, + {"shape": "tube", "r0": "throat_r+wall+0.9676*(exit_r-throat_r-wall)", "r1": "exit_r", "inner0": "throat_r+0.9676*(exit_r-throat_r-wall)", "inner1": "exit_r-wall", + "length": "0.18*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.82*length"]}, + {"shape": "tube", "r0": "throat_r+2.4*wall+0.6132*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.6474*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.6132*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.6474*(exit_r-throat_r-wall)", + "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.38*length"]}, + {"shape": "tube", "r0": "throat_r+2.4*wall+0.834*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.8592*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.834*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.8592*(exit_r-throat_r-wall)", "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.6*length"]}, - {"shape": "tube", "r0": "throat_r+2.4*wall+0.965*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.9725*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.965*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.9725*(exit_r-throat_r-wall)", + {"shape": "tube", "r0": "throat_r+2.4*wall+0.9748*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.9802*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.9748*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.9802*(exit_r-throat_r-wall)", "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.86*length"]}, {"shape": "repeat", "count": 2, "step": ["3.4*throat_r", 0, 0], "of": {"shape": "box", "size": ["0.5*throat_r", "0.35*throat_r", "0.6*throat_r"], "at": ["-1.7*throat_r", 0, "throat_r"]}}, @@ -57,7 +63,7 @@ }, { "name": "tank", - "doc": "Pressure tank: domed ends with flanged ports, weld bands, two straps on saddle cradles and a mounting pad.", + "doc": "Pressure tank: elliptical domed ends with flanged ports, weld bands, two straps on saddle cradles and a mounting pad.", "params": [ {"name": "radius", "type": "number", "min": 0.12, "max": 0.35, "default": 0.22, "doc": "shell radius"}, {"name": "length", "type": "number", "min": 0.6, "max": 2.0, "default": 0.9, "doc": "port face to port face"}, @@ -67,11 +73,15 @@ "shapes": [ {"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.05*radius", "segments": "segments", "smooth": true}, {"shape": "tube", "r0": "0.2*radius", "r1": "0.2*radius", "length": "0.18*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.02*radius"]}, - {"shape": "tube", "r0": "0.47*radius", "r1": "0.85*radius", "length": "0.15*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.12*radius"]}, - {"shape": "tube", "r0": "0.85*radius", "r1": "radius", "length": "0.22*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.27*radius"]}, + {"shape": "tube", "r0": "0.47*radius", "r1": "0.6984*radius", "length": "0.07*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.12*radius"]}, + {"shape": "tube", "r0": "0.6984*radius", "r1": "0.8512*radius", "length": "0.08*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.19*radius"]}, + {"shape": "tube", "r0": "0.8512*radius", "r1": "0.9581*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.27*radius"]}, + {"shape": "tube", "r0": "0.9581*radius", "r1": "radius", "length": "0.12*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.37*radius"]}, {"shape": "tube", "r0": "radius", "r1": "radius", "length": "length-0.98*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.49*radius"]}, - {"shape": "tube", "r0": "radius", "r1": "0.85*radius", "length": "0.22*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.49*radius"]}, - {"shape": "tube", "r0": "0.85*radius", "r1": "0.47*radius", "length": "0.15*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.27*radius"]}, + {"shape": "tube", "r0": "radius", "r1": "0.9581*radius", "length": "0.12*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.49*radius"]}, + {"shape": "tube", "r0": "0.9581*radius", "r1": "0.8512*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.37*radius"]}, + {"shape": "tube", "r0": "0.8512*radius", "r1": "0.6984*radius", "length": "0.08*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.27*radius"]}, + {"shape": "tube", "r0": "0.6984*radius", "r1": "0.47*radius", "length": "0.07*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.19*radius"]}, {"shape": "tube", "r0": "0.2*radius", "r1": "0.2*radius", "length": "0.18*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.2*radius"]}, {"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.05*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.05*radius"]}, {"shape": "repeat", "count": 2, "step": [0, 0, "length-0.98*radius"], "of": From bd61f1cf1efb5fcf310bcc588821b59cfdea28b3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 16:18:38 +0100 Subject: [PATCH 071/223] brokkr_kitbash: attach, detach, boolean and apply; set_params keeps an assembly seated A connection belongs to the child: its parent pointer under an identity parent inverse and kit_socket, kit_parent_socket and kit_roll. core.mate derives its matrix_basis, core.mate_refusal says what may mate, and reports give the residual and whether it holds. set_params checks every connection the part is an end of before it writes, then seats the part and the parts attached to it. boolean adds an Exact, self-intersecting Boolean above the Bevel; apply bakes the evaluated mesh and marks the part baked. Cut aetheria-release:cut_spec:cut-chassis-kit-assembly.r1. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 279 ++++++++++- .../brokkr_kitbash/brokkr_actions.json | 122 ++++- surfaces/blender/brokkr_kitbash/core.py | 61 +++ surfaces/blender/tests/live/kitbash.py | 6 +- .../blender/tests/live/kitbash.result.json | 8 +- .../blender/tests/live/kitbash_assembly.py | 446 ++++++++++++++++++ .../tests/live/kitbash_assembly.result.json | 372 +++++++++++++++ surfaces/blender/tests/test_kitbash.py | 150 +++++- 8 files changed, 1414 insertions(+), 30 deletions(-) create mode 100644 surfaces/blender/tests/live/kitbash_assembly.py create mode 100644 surfaces/blender/tests/live/kitbash_assembly.result.json diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index eb004e0..5d8da04 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1,4 +1,4 @@ -"""Kitbash parts: place a parametric machine part from a kit, re-parameterise it, and report where its sockets are. +"""Kitbash parts: place parametric machine parts from a kit, mate them socket to socket, cut them, 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 @@ -9,9 +9,16 @@ WindowManager.brokkr_mesh_polish_result, as the polish operators do. What a placed part is lives on its object as three ID properties: kit_kit, kit_part and kit_params. The mesh is derived from them (set_params rebuilds it), and socket frames are derived again at every report: nothing else in the scene stores them. Two things would give a part a second owner and are refused: a mesh datablock shared with -another object (set_params), and a world transform that scales, mirrors or shears (set_params and report: a -part's size is its params). Placement, materials and export are Brokkr's own rows (setObjectTransform, assignMaterial, -exportGltf). +another object (set_params, apply), and a world transform that scales, mirrors or shears (a part's size is its +params). + +A connection belongs to the child: its parent pointer (under an identity parent inverse) and three more ID +properties, kit_socket, kit_parent_socket and kit_roll. Its matrix_basis is derived from them and both parts' +params by core.mate; attach and set_params write it, and a report says how far the child stands from it. A boolean +belongs to its Boolean modifier on the target (the modifier's object is the cutter; its name is a label). kit_baked +says apply replaced the mesh with the evaluated one: the params then only place the part's sockets. Placing a +loose part, hiding a cutter, materials and export are Brokkr's own rows (setObjectTransform, setObjectVisibility, +assignMaterial, exportGltf). """ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), "category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."} @@ -19,8 +26,10 @@ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), import json import math +import bmesh import bpy import numpy as np +from mathutils import Matrix try: from brokkr_mesh_polish import RESULT, PolishOperator, Refused, mesh_object @@ -31,7 +40,10 @@ except ImportError as error: # register() says so; the classes below only need from . import core KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" +SOCKET, PARENT_SOCKET, ROLL, BAKED = "kit_socket", "kit_parent_socket", "kit_roll", "kit_baked" +HELD = 1e-5 # a connection holds when its residual is at most this (as RIGID) BEVEL = "Kit Bevel" +BOOLEAN = "Kit Boolean " # a Boolean modifier's name is this and its cutter's name: a label, the cutter is modifier.object BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0) REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates @@ -90,10 +102,98 @@ def kit_part_of(obj): return core.part(core.load_kit(str(obj.get(KIT, ""))), str(obj[PART])), stored +def built_part(obj): + """(part, the part built at the object's stored params): where its sockets are, baked or not.""" + part, stored = kit_part_of(obj) + return part, core.build(part, stored) + + +def link(obj): + """The connection a child states, (its socket, the parent's socket, roll in degrees), or None. The parent is + obj.parent and is stored nowhere else. attach, set_params, detach and every report read it here.""" + if SOCKET not in obj: + return None + roll = obj.get(ROLL, 0.0) + return str(obj[SOCKET]), str(obj.get(PARENT_SOCKET, "")), float(roll) if core.finite(roll) else 0.0 + + +def attached(obj) -> list: + """The children that state a connection to obj.""" + return [child for child in obj.children if SOCKET in child] + + +def mated(parent, parent_part, parent_built, child, child_part, child_built, stated): + """(parent socket, child socket) of the connection `stated` between two built parts, or a refusal that names + it: parts of two kits, a socket name a part does not have, or sockets core.mate_refusal will not mate.""" + try: + sockets = core.joint(parent_part, parent_built, stated[1], child_part, child_built, stated[0]) + refusal = core.mate_refusal(core.load_kit(parent_part["kit"])["socketTypes"], *sockets) + except core.KitError as error: + refusal = str(error) + if refusal: + raise Refused(f"{child.name!r} on {parent.name!r}: {refusal}; nothing changed.") + return sockets + + +def seat(child, basis) -> None: + """Write an attached child's derived matrix_basis, under an identity parent inverse.""" + child.matrix_parent_inverse = Matrix.Identity(4) + child.matrix_basis = Matrix(np.asarray(basis).tolist()) + + +def connection_report(obj, part, built): + """None for a part that states no connection, else what it states and whether it holds: the parent is a part + of the same kit, both sockets exist, the parent inverse is the identity and the child stands within HELD of + core.mate. A child moved or re-parented by another action reads holds false until set_params seats it again.""" + stated = link(obj) + if stated is None: + return None + row = {"parent": obj.parent.name if obj.parent else None, "socket": stated[0], "parentSocket": stated[1], + "roll": round(stated[2], 6), "residual": None, "holds": False} + try: + if obj.parent is None: + return row + parent_part, parent_built = built_part(obj.parent) + parent_socket, socket = core.joint(parent_part, parent_built, stated[1], part, built, stated[0]) + except (Refused, core.KitError): + return row + row["residual"] = round(core.residual(obj.parent.matrix_world, parent_socket, obj.matrix_world, socket, stated[2]), 9) + row["holds"] = bool(np.abs(np.array(obj.matrix_parent_inverse) - np.eye(4)).max() <= HELD and row["residual"] <= HELD) + return row + + def part_report(obj, part, built) -> dict: + """A part as the scene has it. Reads stored properties and matrices only: no modifier is evaluated.""" return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, "faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), - "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world))} + "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world)), + "connection": connection_report(obj, part, built), "baked": bool(obj.get(BAKED, False))} + + +def own_mesh(obj, doing: str) -> None: + if obj.data.users > 1: + raise Refused(f"{obj.name!r} shares its mesh {obj.data.name!r} with {obj.data.users - 1} other user(s): {doing} it would change " + "them while their params stay. Give it its own mesh (place_part a new part) and set that; nothing changed.") + + +def booleans(obj) -> list: + return [{"cutter": m.object.name if m.object else None, "operation": m.operation} for m in obj.modifiers if m.type == "BOOLEAN"] + + +def evaluated_of(context, obj): + """(depsgraph, obj with its modifier stack evaluated). An Exact Boolean costs about a second a part, so only + boolean and apply call this; no report does.""" + depsgraph = context.evaluated_depsgraph_get() + return depsgraph, obj.evaluated_get(depsgraph) + + +def measured(mesh) -> dict: + """Faces, signed volume (overlapping shells count twice) and edges that do not join exactly two faces.""" + 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 carried_materials(mesh, old, new): @@ -145,8 +245,9 @@ class BROKKR_KITBASH_OT_place_part(PolishOperator): class BROKKR_KITBASH_OT_set_params(PolishOperator): - """Change params of a placed kit part and rebuild its mesh in place: its transform, parent, modifiers and - material slots stay, each shape keeps its faces' material, and the Bevel width follows""" + """Change params of a placed kit part and rebuild its mesh in place: its modifiers and material slots stay, + each shape keeps its faces' material, the Bevel width follows, and its connection and those of the parts + attached to it are seated again on the moved sockets""" bl_idname = "brokkr_kitbash.set_params" bl_label = "Set Kit Part Params" object_name: bpy.props.StringProperty(name="Object") @@ -156,10 +257,20 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): def work(self, context): obj = mesh_object(self.object_name) part, stored = kit_part_of(obj) - if obj.data.users > 1: - raise Refused(f"{obj.name!r} shares its mesh {obj.data.name!r} with {obj.data.users - 1} other user(s): rebuilding it would change " - "them while their params stay. Give it its own mesh (place_part a new part) and set that; nothing changed.") + if obj.get(BAKED): + raise Refused(f"{obj.name!r} is baked: apply replaced its mesh, and its params now only place its sockets. " + "place_part a new part to change them; nothing changed.") + own_mesh(obj, "rebuilding") built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored)) + seats, stated = [], link(obj) # every connection this part is an end of, checked against its new sockets before anything is written + if stated is not None: + if obj.parent is None: + raise Refused(f"{obj.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.") + parent_part, parent_built = built_part(obj.parent) + seats.append((obj, core.mate(*mated(obj.parent, parent_part, parent_built, obj, part, built, stated), stated[2]))) + for child in attached(obj): + child_part, child_built = built_part(child) + seats.append((child, core.mate(*mated(obj, part, built, child, child_part, child_built, link(child)), link(child)[2]))) try: old = core.build(part, stored) except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by @@ -172,9 +283,145 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): obj.data.update() sync_bevel(obj, built.bevel) obj[PARAMS] = json.dumps(built.params) + for seated, basis in seats: # deeper descendants follow through parenting: their sockets did not move + seat(seated, basis) + if seats: + context.view_layer.update() return part_report(obj, part, built) +class BROKKR_KITBASH_OT_attach(PolishOperator): + """Seat a socket of a kit part on a socket of another part of its kit and parent it there: origins together, + normals opposed, turned by roll about the parent socket's normal""" + bl_idname = "brokkr_kitbash.attach" + bl_label = "Attach Kit Part" + object_name: bpy.props.StringProperty(name="Object", description="The child: the part that moves") + socket: bpy.props.StringProperty(name="Socket", description="The child's socket") + parent_name: bpy.props.StringProperty(name="Parent") + parent_socket: bpy.props.StringProperty(name="Parent Socket") + roll: bpy.props.FloatProperty(name="Roll", default=0.0, min=-360.0, max=360.0, + description="Degrees about the parent socket's normal, right-handed; at 0 the two sockets' ys line up") + + @kit_work + def work(self, context): + child, parent = mesh_object(self.object_name), mesh_object(self.parent_name) + part, built = built_part(child) + parent_part, parent_built = built_part(parent) + if child == parent: + raise Refused(f"{child.name!r} cannot be attached to itself; nothing changed.") + if child.parent is not None: + raise Refused(f"{child.name!r} has a parent, {child.parent.name!r}: detach it first (setObjectParent with an empty parent " + "for a parent it was not attached to); nothing changed.") + ancestor = parent.parent + while ancestor is not None: + if ancestor == child: + raise Refused(f"{parent.name!r} is below {child.name!r}: attaching {child.name!r} to it would close a loop; nothing changed.") + ancestor = ancestor.parent + stated = (self.socket, self.parent_socket, float(self.roll)) + sockets = mated(parent, parent_part, parent_built, child, part, built, stated) + users = [c.name for c in attached(parent) if c.get(PARENT_SOCKET) == self.parent_socket] + if parent.get(SOCKET) == self.parent_socket: + users.append(parent.parent.name if parent.parent else parent.name) + if users: + raise Refused(f"Socket {self.parent_socket!r} of {parent.name!r} is occupied (by {users[0]!r}); nothing changed.") + users = [c.name for c in attached(child) if c.get(PARENT_SOCKET) == self.socket] + if users: + raise Refused(f"Socket {self.socket!r} of {child.name!r} is occupied (by {users[0]!r}); nothing changed.") + child.parent = parent + seat(child, core.mate(*sockets, stated[2])) + child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated + context.view_layer.update() + return part_report(child, part, built) + + +class BROKKR_KITBASH_OT_detach(PolishOperator): + """Clear a kit part's connection: it stays where it stands in the world, loses its parent, and the parts + attached to it stay attached to it""" + bl_idname = "brokkr_kitbash.detach" + bl_label = "Detach Kit Part" + object_name: bpy.props.StringProperty(name="Object") + + @kit_work + def work(self, context): + obj = mesh_object(self.object_name) + if SOCKET not in obj: + raise Refused(f"{obj.name!r} is not attached (it has no {SOCKET} property); nothing changed.") + part, built = built_part(obj) + world = obj.matrix_world.copy() + obj.parent = None + obj.matrix_world = world + for key in (SOCKET, PARENT_SOCKET, ROLL): + if key in obj: + del obj[key] + return part_report(obj, part, built) + + +class BROKKR_KITBASH_OT_boolean(PolishOperator): + """Cut a kit part with another mesh object through a live Boolean modifier (Exact, with self-intersection: kit + parts are overlapping shells) placed above the Bevel; evaluates the part once and reports the result""" + bl_idname = "brokkr_kitbash.boolean" + bl_label = "Boolean Kit Part" + object_name: bpy.props.StringProperty(name="Object", description="The kit part that is cut") + cutter: bpy.props.StringProperty(name="Cutter", description="Any other mesh object; it is not changed") + operation: bpy.props.EnumProperty(name="Operation", default="DIFFERENCE", items=[ + ("DIFFERENCE", "Difference", ""), ("UNION", "Union", ""), ("INTERSECT", "Intersect", "")]) + + @kit_work + def work(self, context): + obj = mesh_object(self.object_name) + part, built = built_part(obj) + cutter = bpy.data.objects.get(self.cutter) + if cutter is None or cutter.type != "MESH": + raise Refused(f"No mesh object named {self.cutter!r} to cut with; nothing changed.") + if cutter == obj: + raise Refused(f"{obj.name!r} cannot cut itself; nothing changed.") + if any(m.type == "BOOLEAN" and m.object == cutter for m in obj.modifiers): + raise Refused(f"{cutter.name!r} is already the object of a Boolean on {obj.name!r}; nothing changed.") + modifier = obj.modifiers.new(BOOLEAN + cutter.name, "BOOLEAN") + modifier.operation, modifier.object = self.operation, cutter + # TRANSFER: with the default (INDEX) the result gains an empty material slot for a cutter that has no materials + modifier.solver = "EXACT" + modifier.use_self = True + modifier.material_mode = "TRANSFER" + names = [m.name for m in obj.modifiers] + if BEVEL in names: # cut first, then bevel the cut's edges with the rest + obj.modifiers.move(len(names) - 1, names.index(BEVEL)) + report = part_report(obj, part, built) + _, evaluated = evaluated_of(context, obj) + report["booleans"], report["evaluated"] = booleans(obj), measured(evaluated.to_mesh()) + evaluated.to_mesh_clear() + return report + + +class BROKKR_KITBASH_OT_apply(PolishOperator): + """Bake a kit part: its mesh becomes its evaluated mesh (Booleans and Bevel applied), every modifier goes, its + material slots stay, and it is marked baked; its sockets and connections stay as they are""" + bl_idname = "brokkr_kitbash.apply" + bl_label = "Apply Kit Part" + object_name: bpy.props.StringProperty(name="Object") + + @kit_work + def work(self, context): + obj = mesh_object(self.object_name) + part, built = built_part(obj) + own_mesh(obj, "baking") + if not obj.modifiers: + raise Refused(f"{obj.name!r} has no modifiers to apply; nothing changed.") + cutters, slots = [row["cutter"] for row in booleans(obj)], len(obj.data.materials) + depsgraph, evaluated = evaluated_of(context, obj) + baked = bpy.data.meshes.new_from_object(evaluated, preserve_all_data_layers=True, depsgraph=depsgraph) + while len(baked.materials) > slots and baked.materials[len(baked.materials) - 1] is None: + baked.materials.pop() # a Boolean gives a part that had no material slot one empty slot + old, name = obj.data, obj.data.name + obj.data = baked + obj.modifiers.clear() + if old.users == 0: + bpy.data.meshes.remove(old) + baked.name = name + obj[BAKED] = True + return {**part_report(obj, part, built), **measured(baked), "cutters": cutters} + + class BROKKR_KITBASH_OT_describe(PolishOperator): """List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame at default params""" @@ -190,7 +437,8 @@ class BROKKR_KITBASH_OT_describe(PolishOperator): class BROKKR_KITBASH_OT_report(PolishOperator): - """Report placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world frame""" + """Report placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world frame, + the connection and whether it holds, and whether the part is baked""" bl_idname = "brokkr_kitbash.report" bl_label = "Report Kit Parts" bl_options = {"REGISTER"} @@ -200,14 +448,11 @@ class BROKKR_KITBASH_OT_report(PolishOperator): def work(self, context): chosen = [mesh_object(self.object_name)] if self.object_name else sorted( (o for o in context.scene.objects if o.type == "MESH" and PART in o), key=lambda o: o.name) - parts = [] - for obj in chosen: - part, stored = kit_part_of(obj) - parts.append(part_report(obj, part, core.build(part, stored))) - return bounded({"parts": parts}, "name an object to report it alone") + return bounded({"parts": [part_report(obj, *built_part(obj)) for obj in chosen]}, "name an object to report it alone") -classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report) +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_boolean, 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 b570c13..e75ec1b 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -45,7 +45,7 @@ }, { "name": "brokkr_kitbash.set_params", - "doc": "Change params of a placed kit part and rebuild its mesh in place; transform, parent, modifiers and materials stay. Refuses a mesh another object shares and a scaled part. Reports as place_part.", + "doc": "Change params of a placed kit part and rebuild its mesh in place; modifiers and materials stay, and its connection and the parts attached to it are seated again. Refuses a change that breaks a connection, a baked part, a mesh another object shares and a scaled part. Reports as place_part.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -93,7 +93,7 @@ }, { "name": "brokkr_kitbash.report", - "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world 4x4. Refuses a part scaled in the world: resize with set_params.", + "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds) and baked. Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", @@ -106,6 +106,124 @@ "doc": "empty: every object that is a kit part" } ] + }, + { + "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.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the child: the part that moves" + }, + { + "name": "socket", + "type": "string", + "required": true, + "chars": "id", + "minLength": 1, + "maxLength": 32, + "doc": "the child's socket; brokkr_kitbash.report lists a part's sockets" + }, + { + "name": "parent_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the part it is attached to" + }, + { + "name": "parent_socket", + "type": "string", + "required": true, + "chars": "id", + "minLength": 1, + "maxLength": 32, + "doc": "the parent's socket" + }, + { + "name": "roll", + "type": "number", + "minimum": -360, + "maximum": 360, + "default": 0, + "doc": "degrees about the parent socket's normal, right-handed; at 0 the two sockets' up axes line up" + } + ] + }, + { + "name": "brokkr_kitbash.detach", + "doc": "Clear a kit part's connection: it keeps its place in the world and loses its parent; parts attached to it stay attached to it.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + } + ] + }, + { + "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.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the kit part that is cut" + }, + { + "name": "cutter", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "any other mesh object" + }, + { + "name": "operation", + "type": "string", + "enum": [ + "DIFFERENCE", + "UNION", + "INTERSECT" + ], + "default": "DIFFERENCE" + } + ] + }, + { + "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.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + } + ] } ] } diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index a9b0c6b..49b3c36 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -8,6 +8,9 @@ expression is parsed with ast.parse and walked against a whitelist; nothing in a kit = load_kit("mechanical") built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, shell_count, sockets +Two sockets mate through mate (the child's matrix under its parent), mate_refusal (what may mate) and residual +(how far a placed child stands from its mate). + Every refusal is a KitError whose message names the kit, part and field. """ from __future__ import annotations @@ -493,6 +496,64 @@ def socket_rows(sockets: list, frame=None) -> list[dict]: return [{"name": s["name"], "type": s["type"], "size": round(s["size"], 6), "matrix": rows(frame @ s["matrix"])} for s in sockets] +# --- mating -------------------------------------------------------------------------------------------------- + +FLIP = np.diag([-1.0, 1.0, -1.0, 1.0]) # half a turn about y: a mating socket's z faces the other's, y stays up + + +def _roll(degrees: float) -> np.ndarray: + turn = np.eye(4) + turn[:3, :3] = _rotation((0.0, 0.0, degrees)) + return turn + + +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).""" + return parent_socket["matrix"] @ _roll(roll_degrees) @ FLIP @ np.linalg.inv(child_socket["matrix"]) + + +def residual(parent_world, parent_socket: dict, child_world, child_socket: dict, roll_degrees: float) -> float: + """How far a child stands from where mate puts it: the largest absolute entry of the difference between the + frame its socket should have in the world and the frame it has.""" + wanted = np.asarray(parent_world, dtype=np.float64) @ parent_socket["matrix"] @ _roll(roll_degrees) @ FLIP + return float(np.abs(wanted - np.asarray(child_world, dtype=np.float64) @ child_socket["matrix"]).max()) + + +EQUAL, SLACK = 0.01, 1e-9 # 'equal' sizes may differ by 1 percent of the larger; SLACK keeps a size at the limit inside it + + +def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict) -> str | None: + """None when the two sockets may mate, else a sentence naming both: they are of one type, and their sizes + agree as that type's match says ('equal': within 1 percent of the larger; 'fits': the child at most the parent).""" + p, c = parent_socket, child_socket + both = f"socket {c['name']!r} ({c['type']}, size {c['size']:.6g}) and parent socket {p['name']!r} ({p['type']}, size {p['size']:.6g})" + if p["type"] != c["type"]: + return f"{both} are of different types" + if kit_types[p["type"]]["match"] == "equal": + if abs(p["size"] - c["size"]) > EQUAL * max(p["size"], c["size"]) * (1 + SLACK): + return f"{both} are {p['type']} sockets, which mate at equal sizes (within 1 percent)" + elif c["size"] > p["size"] * (1 + SLACK): + return f"{both} are {p['type']} sockets, where the child fits the parent: it is larger" + return None + + +def joint(parent_part: dict, parent_built: Built, parent_socket: str, child_part: dict, child_built: Built, child_socket: str): + """(parent socket, child socket) of a connection between two built parts, by socket name. Refuses parts of + different kits (socket types belong to a kit) and a name the part has no socket for.""" + if parent_part["kit"] != child_part["kit"]: + raise KitError(f"part {child_part['name']!r} is of kit {child_part['kit']!r} and part {parent_part['name']!r} of kit " + f"{parent_part['kit']!r}: socket types belong to a kit, so parts of different kits do not mate") + found = [] + for part, built, name in ((parent_part, parent_built, parent_socket), (child_part, child_built, child_socket)): + match = [s for s in built.sockets if s["name"] == name] + if not match: + raise KitError(f"kit {part['kit']!r} part {part['name']!r} has no socket {name!r}; its sockets: " + f"{', '.join(s['name'] for s in built.sockets) or 'none'}") + found.append(match[0]) + return found[0], found[1] + + def describe(kit: dict, name: str = "") -> dict: """The kit's parts (or the one named): params with their bounds, and sockets in the part frame at default params.""" chosen = [part(kit, name)] if name else list(kit["parts"].values()) diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 410cab3..a05ee4e 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 four kitbash rows load as host actions with no errors", not R["hostErrors"] - and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", - "brokkr_kitbash.describe", "brokkr_kitbash.report"], [R["hostErrors"], R["hostRows"]]) +check("the eight 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", "boolean", "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 ab893bc..14da142 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 four kitbash rows load as host actions with no errors", + "name": "the eight kitbash rows load as host actions with no errors", "ok": true, "detail": null }, @@ -319,7 +319,11 @@ "brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", - "brokkr_kitbash.report" + "brokkr_kitbash.report", + "brokkr_kitbash.attach", + "brokkr_kitbash.detach", + "brokkr_kitbash.boolean", + "brokkr_kitbash.apply" ], "placed": { "nozzle": { diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py new file mode 100644 index 0000000..2bb8481 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -0,0 +1,446 @@ +"""Live proof, in a background Blender, of brokkr_kitbash assembly through run_intent: attach and its refusals, +set_params seating a part and the parts attached to it again, drift and how it is cleared, detach, boolean (Exact, +self-intersection on, above the Bevel) on two targets, and apply. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_assembly.py -- + +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. + +An Exact Boolean costs about a second a part and evaluation, so only two parts are ever cut here (the tank and +one plate). 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 + +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-assembly-")) +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] +kit = core.load_kit("mechanical") +# Metres (or a difference of unit vectors) between where a seated socket is and where its mate puts it, read from +# the two world matrices. Shipped worst 1.5e-07 (float32 matrices, parts a few metres from the origin); least +# claimed mutant 0.22 (A8, a part not seated again after its own extension changed); separation 1.5e6. +SEATED = 1.8e-4 +# Metres between how far a part moved and how far the socket that carries it moved. Shipped worst 2.7e-07; least +# claimed mutant 0.84 (A7, attached children not seated again); separation 3.1e6. +CARRIED = 4.8e-4 +# Degrees between the roll read from the two world frames and the roll asked for. Shipped worst 6.3e-06; least +# claimed mutant 74 (A2, roll sign reversed, at roll 37); separation 1.2e7. +ROLL = 2.2e-2 +# Largest entry of matrix_world after detach minus before. Shipped worst 1.5e-08; least claimed mutant 2.9 +# (A10, detach drops the world matrix); separation 1.9e8. +KEPT = 2.1e-4 +# Cubic metres left of the 1.8 m tank (its 20 shells as one solid) with a 0.3 m box cut from its wall. Shipped +# 0.2539; least claimed mutant 0.0079 (A11, self-intersection off: overlapping shells cancel); separation 32. +CUT = 0.045 + + +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 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(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 seated(child, socket, parent, parent_socket, roll=None): + """How far a child's socket is from seated on its parent's: origins apart, or normals not opposed. With a roll, + also records the degrees between it and the roll read from the two frames.""" + a, b = frame(parent, parent_socket), frame(child, socket) + if roll is not None: + read = math.degrees(math.atan2(np.cross(a[:3, 1], b[:3, 1]) @ a[:3, 2], a[:3, 1] @ b[:3, 1])) + reading("roll", abs((read - roll + 180.0) % 360.0 - 180.0)) + return max(float(np.abs(a[:3, 3] - b[:3, 3]).max()), float(np.abs(a[:3, 2] + b[:3, 2]).max())) + + +def connection(name): + receipt, report = send("brokkr_kitbash.report", object_name=name) + return report["parts"][0]["connection"] if report else {"error": receipt["message"]} + + +def holds(name, parent, socket, parent_socket, roll=0.0): + found = connection(name) or {} + return found == {**found, "parent": parent, "socket": socket, "parentSocket": parent_socket, "roll": roll, "holds": True} \ + and found.get("residual", 1.0) <= 1e-5, found + + +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: 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] + + +rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] +check("the eight 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", "boolean", "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 +tee = place("Tee", "pipe_fitting", "pipe_r=0.044", location=[-2.0, 0.5, 1.0], rotation=[1.1, 0.4, -0.7]) +nozzle = place("Nozzle", "nozzle", "throat_r=0.044", location=[0.0, 4.0, 0.0]) +spare = place("Spare", "nozzle", "throat_r=0.044", location=[0.0, 6.0, 0.0]) +wide = place("Wide", "nozzle", location=[0.0, 8.0, 0.0]) # throat 0.07: flange size 0.14 +radiator = place("Radiator", "radiator_stack", location=[0.0, 10.0, 0.0]) +send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3) +receipt, report = send("brokkr_kitbash.report", object_name="Tank") +check("a part nobody attached reports connection null and baked false", report and report["parts"][0]["connection"] is None + and report["parts"][0]["baked"] is False, report) + +receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0) +check("attach parents the nozzle to the tee under an identity parent inverse and stores the three properties", receipt["status"] == "accepted" + and nozzle.parent == tee and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)) + and (nozzle["kit_socket"], nozzle["kit_parent_socket"], nozzle["kit_roll"]) == ("mount", "c", 37.0) + and sorted(k for k in nozzle.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_parent_socket", "kit_part", "kit_roll", "kit_socket"], + [receipt["message"], dict(nozzle.items())]) +gap = reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) +check("attach seats the nozzle's mount on the tee's c: origins together, normals opposed, rolled 37 degrees", gap < SEATED and R["readings"]["roll"] < ROLL, dict(R["readings"])) +check("attach reports the child: its connection holds, and its sockets are the seated world frames", report + and report["connection"] == {**report["connection"], "parent": "Tee", "socket": "mount", "parentSocket": "c", "roll": 37.0, "holds": True} + and report["connection"]["residual"] <= 1e-5 and report["object"] == "Nozzle" + and np.abs(np.array(report["sockets"][0]["matrix"]) - frame(nozzle, "mount")).max() < 2e-6, report) +check("report shows the same connection", holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) +receipt, report = send("brokkr_kitbash.attach", object_name="Tee", socket="a", parent_name="Tank", parent_socket="port_b") +check("attach of the tee to the tank's port carries the nozzle with it", receipt["status"] == "accepted" and held(report) and report["connection"]["roll"] == 0.0 and reading("seated", seated(tee, "a", tank, "port_b", 0.0)) < SEATED + and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED and R["readings"]["roll"] < ROLL + and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], [receipt["message"], R["readings"]]) + +refused("sockets of different types", "brokkr_kitbash.attach", {"object_name": "Radiator", "socket": "base", "parent_name": "Tee", "parent_socket": "b"}, + "'Radiator' on 'Tee': socket 'base' (mount, size 0.15) and parent socket 'b' (flange, size 0.088) are of different types") +refused("flanges of different sizes", "brokkr_kitbash.attach", {"object_name": "Wide", "socket": "mount", "parent_name": "Tee", "parent_socket": "b"}, + "mate at equal sizes") +refused("a parent socket a child is on", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"}, + "Socket 'c' of 'Tee' is occupied (by 'Nozzle')") +refused("a parent socket the parent is attached by", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "a"}, + "Socket 'a' of 'Tee' is occupied (by 'Tank')") +refused("a loop through a grandchild", "brokkr_kitbash.attach", {"object_name": "Tank", "socket": "port_a", "parent_name": "Nozzle", "parent_socket": "mount"}, + "'Nozzle' is below 'Tank'") +refused("a child that has a parent", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "b"}, + "'Nozzle' has a parent, 'Tee'") +refused("a part to itself", "brokkr_kitbash.attach", {"object_name": "Tank", "socket": "port_a", "parent_name": "Tank", "parent_socket": "port_b"}, + "cannot be attached to itself") +refused("a socket the parent does not have", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "d"}, + "'Spare' on 'Tee': kit 'mechanical' part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c") +refused("a socket the child does not have", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "throat", "parent_name": "Tee", "parent_socket": "b"}, + "part 'nozzle' has no socket 'throat'") +refused("a child that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Plain", "socket": "a", "parent_name": "Tee", "parent_socket": "b"}, + "'Plain' is not a kit part") +refused("a parent that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Plain", "parent_socket": "b"}, + "'Plain' is not a kit part") +refused("detach of a part that is not attached", "brokkr_kitbash.detach", {"object_name": "Spare"}, "'Spare' is not attached") +send("brokkr_kitbash.detach", object_name="Tee") +send("setObjectTransform", targetObjectName="Tee", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) +refused("a child socket one of its own children is on", "brokkr_kitbash.attach", {"object_name": "Tee", "socket": "c", "parent_name": "Tank", "parent_socket": "port_b"}, + "Socket 'c' of 'Tee' is occupied (by 'Nozzle')") +send("brokkr_kitbash.attach", object_name="Tee", socket="a", parent_name="Tank", parent_socket="port_b") +receipt, report = send("brokkr_kitbash.attach", object_name="Spare", socket="mount", parent_name="Tee", parent_socket="b", roll=-90.0) +check("a second nozzle attaches to the tee's free socket, rolled -90", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(spare, "mount", tee, "b", -90.0)) < SEATED and R["readings"]["roll"] < ROLL, [receipt["message"], R["readings"]]) + +# --- set_params seats what is attached again ---------------------------------------------------------------------------------- +was = {name: np.array(bpy.data.objects[name].matrix_world) for name in ("Tank", "Tee", "Nozzle", "Spare")} +receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="length=1.8") +moved = {name: np.array(bpy.data.objects[name].matrix_world) - was[name] for name in was} +port = np.array(tank.matrix_world)[:3, :3] @ [0.0, 0.0, 0.9] # where port_b went: 0.9 along the tank's own z +check("set_params doubling the tank's length moves the tee and both nozzles by the port's displacement, and nothing turns", + receipt["status"] == "accepted" and np.abs(moved["Tank"]).max() == 0.0 + and all(reading("carried", np.abs(moved[n][:3, 3] - port).max()) < CARRIED and np.abs(moved[n][:3, :3]).max() < 1e-6 for n in ("Tee", "Nozzle", "Spare")), + [receipt["message"], {n: m[:3, 3].tolist() for n, m in moved.items()}, port.tolist()]) +check("after it every connection holds", holds("Tee", "Tank", "a", "port_b")[0] and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and holds("Spare", "Tee", "mount", "b", -90.0)[0] and reading("seated", seated(tee, "a", tank, "port_b")) < SEATED + and reading("seated", seated(nozzle, "mount", tee, "c")) < SEATED, [connection("Tee"), connection("Nozzle"), connection("Spare")]) +refused("set_params that breaks the part's own connection", "brokkr_kitbash.set_params", {"object_name": "Tee", "params": "pipe_r=0.06"}, + "'Tee' on 'Tank': socket 'a' (flange, size 0.12) and parent socket 'port_b' (flange, size 0.088)") +refused("set_params that breaks a child's connection", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "radius=0.3"}, + "'Tee' on 'Tank': socket 'a' (flange, size 0.088) and parent socket 'port_b' (flange, size 0.12)") +receipt, report = send("brokkr_kitbash.set_params", object_name="Tee", params="branch=0.4; run=0.6") +check("set_params on the tee keeps its own seat and moves each nozzle with its socket", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(tee, "a", tank, "port_b")) < SEATED and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED + and reading("seated", seated(spare, "mount", tee, "b", -90.0)) < SEATED and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and holds("Spare", "Tee", "mount", "b", -90.0)[0] and R["readings"]["roll"] < ROLL, [receipt["message"], R["readings"]]) + +# a strut hangs from one actuator's rod, and a second actuator hangs from the strut by its own rod +lift = place("Lift", "actuator", location=[4.0, 0.0, 0.0], rotation=[0.2, 0.9, -0.4]) # pivot size 0.054 +strut = place("Strut", "strut", "width=0.09") +ram = place("Ram", "actuator") +send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Lift", parent_socket="rod_end", roll=90.0) +send("brokkr_kitbash.attach", object_name="Ram", socket="rod_end", parent_name="Strut", parent_socket="end_b") +base = frame(ram, "base") +receipt, report = send("brokkr_kitbash.set_params", object_name="Ram", params="extension=0.5") +back = frame(ram, "base")[:3, 3] - base[:3, 3] +check("extending an actuator that hangs by its rod seats it again: the rod end stays, the body backs off by the travel", + reading("seated", seated(ram, "rod_end", strut, "end_b", 0.0)) < SEATED and receipt["status"] == "accepted" and held(report) + and reading("carried", np.abs(back - base[:3, 2] * 0.35).max()) < CARRIED, [receipt["message"], connection("Ram"), back.tolist()]) +tip = frame(strut, "end_b") +receipt, report = send("brokkr_kitbash.set_params", object_name="Lift", params="extension=0.6") +check("extending the actuator above moves the strut on its rod and the ram below with it", receipt["status"] == "accepted" + and holds("Strut", "Lift", "end_a", "rod_end", 90.0)[0] and holds("Ram", "Strut", "rod_end", "end_b")[0] + and reading("seated", seated(strut, "end_a", lift, "rod_end", 90.0)) < SEATED + and reading("carried", np.abs(frame(strut, "end_b")[:3, 3] - tip[:3, 3] - np.array(lift.matrix_world)[:3, 2] * 0.45).max()) < CARRIED, + [receipt["message"], connection("Strut"), connection("Ram")]) + +# --- drift and detach --------------------------------------------------------------------------------------------------------- +send("setObjectTransform", targetObjectName="Nozzle", location=[0.25, 0.0, 0.0]) +found = connection("Nozzle") or {} +check("setObjectTransform on an attached child shows in its report: holds false, with the residual", found.get("holds") is False and found["parent"] == "Tee" + and found["residual"] > 0.1, found) +refused("attach of a drifted child, which still has its parent", "brokkr_kitbash.attach", + {"object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"}, "'Nozzle' has a parent, 'Tee'") +send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") +check("set_params on its parent seats it again", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED, + connection("Nozzle")) +send("setObjectTransform", targetObjectName="Nozzle", rotationEuler=[0.0, 0.5, 0.0]) +drifted = connection("Nozzle") or {} +send("brokkr_kitbash.set_params", object_name="Nozzle", params="exit_r=0.3") +check("set_params on the drifted child itself seats it again", drifted.get("holds") is False and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED, [drifted, connection("Nozzle")]) +nozzle.matrix_parent_inverse = nozzle.matrix_basis.inverted() # as parenting by hand in the viewport leaves it; the basis below keeps the nozzle where it is +nozzle.matrix_basis = nozzle.matrix_basis @ nozzle.matrix_basis +bpy.context.view_layer.update() +found = connection("Nozzle") or {} +check("a parent inverse that is not the identity does not hold, wherever the child stands", found.get("holds") is False and found["residual"] <= 1e-5 + and seated(nozzle, "mount", tee, "c") < SEATED, found) +send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") +check("and set_params on the parent writes the identity back", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)), connection("Nozzle")) +send("setObjectParent", targetObjectName="Spare", parentObjectName="") +found = connection("Spare") +check("setObjectParent clearing an attached child's parent shows as a connection with no parent", found and found == {**found, "parent": None, "holds": False, "residual": None}, found) +refused("set_params on a part whose connection has no parent", "brokkr_kitbash.set_params", {"object_name": "Spare", "params": "exit_r=0.3"}, + "'Spare' states a connection and has no parent") +send("setObjectParent", targetObjectName="Spare", parentObjectName="Plain") +found = connection("Spare") or {} +refused("set_params on a part parented to something that is not a kit part", "brokkr_kitbash.set_params", {"object_name": "Spare", "params": "exit_r=0.3"}, + "'Plain' is not a kit part") +receipt, report = send("brokkr_kitbash.detach", object_name="Spare") +check("detach clears what is left of it", found.get("holds") is False and found.get("parent") == "Plain" and receipt["status"] == "accepted" and spare.parent is None + and report and report["connection"] is None and not [k for k in spare.keys() if k in ("kit_socket", "kit_parent_socket", "kit_roll")], [found, report]) + +before = {name: np.array(bpy.data.objects[name].matrix_world) for name in ("Tee", "Nozzle")} +receipt, report = send("brokkr_kitbash.detach", object_name="Tee") +check("detach leaves the tee where it stood, with no parent and no connection", receipt["status"] == "accepted" and tee.parent is None + and report and report["connection"] is None and sorted(k for k in tee.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_part"] + and reading("kept", max(np.abs(np.array(bpy.data.objects[n].matrix_world) - before[n]).max() for n in before)) < KEPT, [receipt["message"], R["readings"]]) +check("and the nozzle stays attached to the tee", nozzle.parent == tee and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) +send("brokkr_kitbash.attach", object_name="Tee", socket="b", parent_name="Tank", parent_socket="port_a", roll=180.0) +check("the freed tee attaches by another socket to the tank's other port", holds("Tee", "Tank", "b", "port_a", 180.0)[0] + and reading("seated", seated(tee, "b", tank, "port_a", 180.0)) < SEATED and R["readings"]["roll"] < ROLL, connection("Tee")) + +# --- boolean: the tank, with two material slots ----------------------------------------------------------------------------------- +send("assignMaterial", targetObjectName="Tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) +send("assignMaterial", targetObjectName="Tank", materialName="Strap Steel", color=[0.2, 0.2, 0.2]) +tank_built = core.build(kit["parts"]["tank"], json.loads(tank["kit_params"])) +STRAPS = sorted(set(tank_built.shape.tolist()))[-1] +tank.data.polygons.foreach_set("material_index", np.where(tank_built.shape == STRAPS, 1, 0).astype(np.int32)) +side = np.array(tank.matrix_world) @ [0.24, 0.0, 0.9, 1.0] # on the barrel's wall, halfway along +send("createObject", objectType="MESH", name="Box", location=side[:3].tolist(), size=0.3) +box = bpy.data.objects["Box"] +box_was = (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) +raw = measure(tank.data) +receipt, cut = send("brokkr_kitbash.boolean", object_name="Tank", cutter="Box") +modifier = tank.modifiers.get("Kit Boolean Box") +check("boolean adds a Boolean modifier above the Bevel: Exact, self-intersection on, difference, the cutter its object", + receipt["status"] == "accepted" and [m.name for m in tank.modifiers] == ["Kit Boolean Box", "Kit Bevel"] and modifier is not None and modifier.type == "BOOLEAN" + and (modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.object) == ("EXACT", True, "DIFFERENCE", "OBJECT", box), + [receipt["message"], [m.name for m in tank.modifiers]]) +shown, shown_slots = evaluated(tank) +check("boolean reports the evaluated mesh, with less volume than the uncut tank and no non-manifold edge", cut and cut["evaluated"] == shown + and CUT < cut["evaluated"]["volume"] < raw["volume"] - 0.005 and cut["evaluated"]["nonManifoldEdges"] == 0 + and cut["booleans"] == [{"cutter": "Box", "operation": "DIFFERENCE"}] and cut["faces"] == len(tank.data.polygons) == raw["faces"], + [cut and cut["evaluated"], shown, raw]) +R["tank"] = {"raw": raw, "cut": cut and cut["evaluated"]} +check("the cut tank shows the tank's two material slots and no other", shown_slots == ["Tank Paint", "Strap Steel"] and modifier is not None and modifier.material_mode == "TRANSFER", shown_slots) +check("boolean leaves the cutter as it was", (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) == box_was + and "kit_part" not in box, box_was) +refused("a cutter that already cuts the part", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Box", "operation": "UNION"}, + "'Box' is already the object of a Boolean on 'Tank'") +refused("the part as its own cutter", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Tank"}, "cannot cut itself") +refused("a cutter that does not exist", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Nothing"}, "No mesh object named 'Nothing'") +send("createObject", objectType="EMPTY", name="Marker") +refused("a cutter that is not a mesh", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Marker"}, "No mesh object named 'Marker'") +refused("boolean on a mesh that is not a kit part", "brokkr_kitbash.boolean", {"object_name": "Plain", "cutter": "Box"}, "'Plain' is not a kit part") +receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="segments=16") +resized, _ = evaluated(tank) +check("set_params on the cut tank rebuilds it under the live Boolean, and the tee stays on its port", receipt["status"] == "accepted" + and [m.name for m in tank.modifiers] == ["Kit Boolean Box", "Kit Bevel"] and tank.modifiers["Kit Boolean Box"].object == box + and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], report["params"]).counts) != raw["faces"] + and CUT < resized["volume"] < measure(tank.data)["volume"] - 0.005 and holds("Tee", "Tank", "b", "port_a", 180.0)[0], [receipt["message"], resized]) + +# --- apply ------------------------------------------------------------------------------------------------------------------------ +refused("apply on a mesh that is not a kit part", "brokkr_kitbash.apply", {"object_name": "Plain"}, "'Plain' is not a kit part") +slots = [s.material and s.material.name for s in tank.material_slots] +shown, shown_slots = evaluated(tank) +index = np.zeros(len(tank.data.polygons), dtype=np.int32) +tank.data.polygons.foreach_get("material_index", index) +mesh_name, meshes = tank.data.name, len(bpy.data.meshes) +sockets_before = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["sockets"] +receipt, baked = send("brokkr_kitbash.apply", object_name="Tank") +after = np.zeros(len(tank.data.polygons), dtype=np.int32) +tank.data.polygons.foreach_get("material_index", after) +check("apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name", + receipt["status"] == "accepted" and baked and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown == measure(tank.data) + and len(tank.modifiers) == 0 and tank.data.name == mesh_name and len(bpy.data.meshes) == meshes and baked["cutters"] == ["Box"], [receipt["message"], baked, shown]) +check("apply keeps the material slots exactly, and faces of both materials", slots == shown_slots == ["Tank Paint", "Strap Steel"] + and [s.material and s.material.name for s in tank.material_slots] == slots and [m and m.name for m in tank.data.materials] == slots + and index.max() == 1 and sorted(set(after.tolist())) == [0, 1], [slots, [m and m.name for m in tank.data.materials], sorted(set(after.tolist()))]) +check("apply marks the part baked and keeps what it is", tank.get("kit_baked") is True and baked and baked["baked"] is True and tank["kit_part"] == "tank" + and json.loads(tank["kit_params"])["segments"] == 16, dict(tank.items())) +refused("set_params on a baked part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, "'Tank' is baked") +refused("apply on a baked part with no modifiers left", "brokkr_kitbash.apply", {"object_name": "Tank"}, "'Tank' has no modifiers to apply") +receipt, report = send("brokkr_kitbash.report", object_name="Tank") +check("a baked part still reports its sockets where its params put them, and what is attached to it still holds", report and report["parts"][0]["baked"] is True + and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == baked["faces"] and holds("Tee", "Tank", "b", "port_a", 180.0)[0] + and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], report) +receipt, report = send("brokkr_kitbash.attach", object_name="Radiator", socket="base", parent_name="Tank", parent_socket="saddle") +check("a new part attaches to a baked one", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(radiator, "base", tank, "saddle", 0.0)) < SEATED, receipt["message"]) + +# --- the second target: a plate with no material slot, cut twice ---------------------------------------------------------------------- +plate = place("Plate", "plate", location=[0.0, -3.0, 0.0]) +send("createObject", objectType="MESH", name="Slot", location=[0.1, -3.0, 0.0], size=0.1) +send("createObject", objectType="MESH", name="Hole", location=[-0.1, -3.0, 0.0], size=0.05) +receipt, first = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Slot") +receipt, second = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Hole") +check("two cutters stack in the order they came, both above the Bevel", receipt["status"] == "accepted" + and [m.name for m in plate.modifiers] == ["Kit Boolean Slot", "Kit Boolean Hole", "Kit Bevel"] + and second["booleans"] == [{"cutter": "Slot", "operation": "DIFFERENCE"}, {"cutter": "Hole", "operation": "DIFFERENCE"}] + and second["evaluated"]["volume"] < first["evaluated"]["volume"] and first["evaluated"]["nonManifoldEdges"] == second["evaluated"]["nonManifoldEdges"] == 0 + and all(m.use_self and m.solver == "EXACT" for m in plate.modifiers if m.type == "BOOLEAN"), + [[m.name for m in plate.modifiers], first and first["evaluated"], second and second["evaluated"]]) +R["plate"] = {"raw": measure(plate.data), "slot": first and first["evaluated"], "slotAndHole": second and second["evaluated"]} +twin = plate.copy() +twin.name = "Plate_twin" +bpy.context.scene.collection.objects.link(twin) +refused("apply on a mesh a linked duplicate shares", "brokkr_kitbash.apply", {"object_name": "Plate"}, "shares its mesh 'Plate' with 1 other user(s): baking it") +bpy.data.objects.remove(twin) +shown, shown_slots = evaluated(plate) +receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") +check("apply on a part with no material slot leaves it with none (Blender's Boolean shows it with one empty slot)", receipt["status"] == "accepted" + and shown_slots == [None] and len(plate.data.materials) == 0 and len(plate.material_slots) == 0 and baked["cutters"] == ["Slot", "Hole"] + and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown, [shown_slots, len(plate.data.materials), len(plate.material_slots), baked]) +send("assignMaterial", targetObjectName="Plate", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) +send("createObject", objectType="MESH", name="Boss", location=[0.0, -3.0, 0.1], size=0.06) +send("assignMaterial", targetObjectName="Boss", materialName="Boss Brass", color=[0.6, 0.5, 0.2]) +send("setObjectTransform", targetObjectName="Boss", location=[0.0, -3.0, 0.02]) +receipt, third = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Boss", operation="UNION") +shown, shown_slots = evaluated(plate) +receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") +used = np.zeros(len(plate.data.polygons), dtype=np.int32) +plate.data.polygons.foreach_get("material_index", used) +check("a baked part is cut and baked again; a cutter that has a material brings it after the part's own slots, on the faces it made", + receipt["status"] == "accepted" and third["booleans"] == [{"cutter": "Boss", "operation": "UNION"}] and third["baked"] is True + and third["evaluated"]["volume"] > R["plate"]["slotAndHole"]["volume"] and shown_slots == ["Plate Paint", "Boss Brass"] + and [m and m.name for m in plate.data.materials] == ["Plate Paint", "Boss Brass"] and sorted(set(used.tolist())) == [0, 1] + and len(plate.modifiers) == 0, [third and third["evaluated"], shown_slots, [m and m.name for m in plate.data.materials], sorted(set(used.tolist()))]) +vent = place("Vent", "vent", "width=0.2; height=0.15") +receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Plate", parent_socket="front") +check("a vent that fits attaches to the baked plate's front", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(vent, "back", plate, "front", 0.0)) < SEATED, receipt["message"]) +refused("a loop of two", "brokkr_kitbash.attach", {"object_name": "Plate", "socket": "back", "parent_name": "Vent", "parent_socket": "back"}, + "'Vent' is below 'Plate'") +big = place("Big", "vent", "width=0.8; height=0.6") +refused("a part larger than the seat", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Plate", "parent_socket": "back"}, + "are mount sockets, where the child fits the parent: it is larger") + +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_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json new file mode 100644 index 0000000..3be8cda --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -0,0 +1,372 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "the eight kitbash rows load as host actions with no errors", + "ok": true, + "detail": null + }, + { + "name": "a part nobody attached reports connection null and baked false", + "ok": true, + "detail": null + }, + { + "name": "attach parents the nozzle to the tee under an identity parent inverse and stores the three properties", + "ok": true, + "detail": null + }, + { + "name": "attach seats the nozzle's mount on the tee's c: origins together, normals opposed, rolled 37 degrees", + "ok": true, + "detail": null + }, + { + "name": "attach reports the child: its connection holds, and its sockets are the seated world frames", + "ok": true, + "detail": null + }, + { + "name": "report shows the same connection", + "ok": true, + "detail": null + }, + { + "name": "attach of the tee to the tank's port carries the nozzle with it", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: sockets of different types", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: flanges of different sizes", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a parent socket a child is on", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a parent socket the parent is attached by", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a loop through a grandchild", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a child that has a parent", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a part to itself", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a socket the parent does not have", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a socket the child does not have", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a child that is not a kit part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a parent that is not a kit part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: detach of a part that is not attached", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a child socket one of its own children is on", + "ok": true, + "detail": null + }, + { + "name": "a second nozzle attaches to the tee's free socket, rolled -90", + "ok": true, + "detail": null + }, + { + "name": "set_params doubling the tank's length moves the tee and both nozzles by the port's displacement, and nothing turns", + "ok": true, + "detail": null + }, + { + "name": "after it every connection holds", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params that breaks the part's own connection", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params that breaks a child's connection", + "ok": true, + "detail": null + }, + { + "name": "set_params on the tee keeps its own seat and moves each nozzle with its socket", + "ok": true, + "detail": null + }, + { + "name": "extending an actuator that hangs by its rod seats it again: the rod end stays, the body backs off by the travel", + "ok": true, + "detail": null + }, + { + "name": "extending the actuator above moves the strut on its rod and the ram below with it", + "ok": true, + "detail": null + }, + { + "name": "setObjectTransform on an attached child shows in its report: holds false, with the residual", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: attach of a drifted child, which still has its parent", + "ok": true, + "detail": null + }, + { + "name": "set_params on its parent seats it again", + "ok": true, + "detail": null + }, + { + "name": "set_params on the drifted child itself seats it again", + "ok": true, + "detail": null + }, + { + "name": "a parent inverse that is not the identity does not hold, wherever the child stands", + "ok": true, + "detail": null + }, + { + "name": "and set_params on the parent writes the identity back", + "ok": true, + "detail": null + }, + { + "name": "setObjectParent clearing an attached child's parent shows as a connection with no parent", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a part whose connection has no parent", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a part parented to something that is not a kit part", + "ok": true, + "detail": null + }, + { + "name": "detach clears what is left of it", + "ok": true, + "detail": null + }, + { + "name": "detach leaves the tee where it stood, with no parent and no connection", + "ok": true, + "detail": null + }, + { + "name": "and the nozzle stays attached to the tee", + "ok": true, + "detail": null + }, + { + "name": "the freed tee attaches by another socket to the tank's other port", + "ok": true, + "detail": null + }, + { + "name": "boolean adds a Boolean modifier above the Bevel: Exact, self-intersection on, difference, the cutter its object", + "ok": true, + "detail": null + }, + { + "name": "boolean reports the evaluated mesh, with less volume than the uncut tank and no non-manifold edge", + "ok": true, + "detail": null + }, + { + "name": "the cut tank shows the tank's two material slots and no other", + "ok": true, + "detail": null + }, + { + "name": "boolean leaves the cutter as it was", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a cutter that already cuts the part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: the part as its own cutter", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a cutter that does not exist", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a cutter that is not a mesh", + "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, + "detail": null + }, + { + "name": "refused, scene unchanged: apply on a mesh that is not a kit part", + "ok": true, + "detail": null + }, + { + "name": "apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name", + "ok": true, + "detail": null + }, + { + "name": "apply keeps the material slots exactly, and faces of both materials", + "ok": true, + "detail": null + }, + { + "name": "apply marks the part baked and keeps what it is", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a baked part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: apply on a baked part with no modifiers left", + "ok": true, + "detail": null + }, + { + "name": "a baked part still reports its sockets where its params put them, and what is attached to it still holds", + "ok": true, + "detail": null + }, + { + "name": "a new part attaches to a baked one", + "ok": true, + "detail": null + }, + { + "name": "two cutters stack in the order they came, both above the Bevel", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: apply on a mesh a linked duplicate shares", + "ok": true, + "detail": null + }, + { + "name": "apply on a part with no material slot leaves it with none (Blender's Boolean shows it with one empty slot)", + "ok": true, + "detail": null + }, + { + "name": "a baked part is cut and baked again; a cutter that has a material brings it after the part's own slots, on the faces it made", + "ok": true, + "detail": null + }, + { + "name": "a vent that fits attaches to the baked plate's front", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a loop of two", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a part larger than the seat", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "readings": { + "carried": 2.7e-07, + "kept": 1.5e-08, + "roll": 6.3e-06, + "seated": 1.5e-07 + }, + "tank": { + "raw": { + "faces": 740, + "volume": 0.264901065, + "nonManifoldEdges": 0 + }, + "cut": { + "faces": 2337, + "volume": 0.25387923, + "nonManifoldEdges": 0 + } + }, + "plate": { + "raw": { + "faces": 44, + "volume": 0.002056141, + "nonManifoldEdges": 0 + }, + "slot": { + "faces": 504, + "volume": 0.001448832, + "nonManifoldEdges": 0 + }, + "slotAndHole": { + "faces": 558, + "volume": 0.001411154, + "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 5481efd..fe6aa5f 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -2,7 +2,7 @@ corner of its params, and the host action file against Brokkr's own checker. Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) -The operators are exercised in a real Blender by tests/live/kitbash.py. +The operators are exercised in a real Blender by tests/live/kitbash.py and tests/live/kitbash_assembly.py. Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is the built value, and each names the mutant it kills. @@ -389,6 +389,111 @@ 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 MateTests(unittest.TestCase): + """core.mate, residual, mate_refusal and joint. The four bounds sit at the geometric mean of the shipped worst + reading and the least claimed mutant's (lodur:ruling:deterministic-bound-margin); a shipped reading of exactly + 0 is taken as one float step (2.2e-16; 2.8e-14 degrees for the roll, which is read through a sum with 180).""" + PAIRS = [("pipe_fitting", {}, "c", "nozzle", {"throat_r": 0.05}, "mount"), ("pipe_fitting", {}, "b", "tank", {"radius": 0.25}, "port_b"), + ("strut", {"width": 0.09}, "end_b", "actuator", {"body_r": 0.06}, "rod_end"), ("tank", {}, "saddle", "radiator_stack", {}, "base"), + ("plate", {}, "front", "vent", {"width": 0.2, "height": 0.15}, "back")] + ORIGIN = 6.2e-8 # shipped 8.9e-16; least mutant 4.36 (the child socket's inverse replaced by its transpose); separation 4.9e15 + NORMAL = 2.1e-8 # shipped 0; least mutant 1.974 (A1, FLIP dropped); separation above 8e15 + ROLL = 2.2e-6 # degrees. shipped 0; least mutant 180 (A2, roll sign reversed, at roll -90); separation above 6e15 + RESIDUAL = 4.2e-8 # shipped 8.9e-16; least mutant 1.999 (A1 and A2 both); separation 2.2e15 + + @classmethod + def setUpClass(cls): + cls.kit = core.load_kit("mechanical") + + def sockets(self, parent, parent_params, parent_socket, child, child_params, child_socket): + parts = self.kit["parts"] + return core.joint(parts[parent], core.build(parts[parent], parent_params), parent_socket, + parts[child], core.build(parts[child], child_params), child_socket) + + def test_a_mated_child_sits_on_the_parent_socket_at_its_roll(self): + """mate-math, read from the two world frames and not through core.residual. Mutants A1 (FLIP dropped: the + normals agree instead of opposing) and A2 (roll sign reversed).""" + rng = random.Random("mate") + worst = {"origin": 0.0, "normal": 0.0, "roll": 0.0, "residual": 0.0} + for pair in self.PAIRS: + sp, sc = self.sockets(*pair) + self.assertIsNone(core.mate_refusal(self.kit["socketTypes"], sp, sc), pair) + for _ in range(4): + world = np.eye(4) + world[:3, :3] = core._rotation([rng.uniform(-180, 180) for _ in range(3)]) + world[:3, 3] = [rng.uniform(-5, 5) for _ in range(3)] + for roll in (0.0, 37.0, -90.0, 180.0): + child = world @ core.mate(sp, sc, roll) + a, b = world @ sp["matrix"], child @ sc["matrix"] + read = math.degrees(math.atan2(np.cross(a[:3, 1], b[:3, 1]) @ a[:3, 2], a[:3, 1] @ b[:3, 1])) # the child's y from the parent's, about the parent's z + worst["origin"] = max(worst["origin"], float(np.abs(a[:3, 3] - b[:3, 3]).max())) + worst["normal"] = max(worst["normal"], float(np.abs(a[:3, 2] + b[:3, 2]).max())) + worst["roll"] = max(worst["roll"], abs((read - roll + 180.0) % 360.0 - 180.0)) + worst["residual"] = max(worst["residual"], core.residual(world, sp, child, sc, roll)) + self.assertLess(np.abs(child[:3, :3].T @ child[:3, :3] - np.eye(3)).max(), 1e-12) + if roll == 0.0: + self.assertLess(np.abs(a[:3, 1] - b[:3, 1]).max(), self.NORMAL, "roll 0 lines the two ys up") + self.assertLess(worst["origin"], self.ORIGIN) + self.assertLess(worst["normal"], self.NORMAL) + self.assertLess(worst["roll"], self.ROLL) + self.assertLess(worst["residual"], self.RESIDUAL) + + def test_residual_is_how_far_the_child_stands_from_its_mate(self): + sp, sc = self.sockets(*self.PAIRS[0]) + world = np.eye(4) + world[:3, 3] = [1.0, 2.0, 3.0] + child = world @ core.mate(sp, sc, 37.0) + moved = child.copy() + moved[0, 3] += 0.25 + self.assertAlmostEqual(core.residual(world, sp, moved, sc, 37.0), 0.25, places=12) + self.assertGreater(core.residual(world, sp, child, sc, 38.0), 0.01) # the stated roll is part of the mate + self.assertEqual(core.FLIP.tolist(), [[-1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]) + + def test_what_may_mate(self): + """mate-refusal. Mutants A3 (fits reversed) and A4 (equal at 10 percent).""" + types = self.kit["socketTypes"] + socket = lambda name, kind, size: {"name": name, "type": kind, "size": size, "matrix": np.eye(4)} # noqa: E731 + self.assertRegex(core.mate_refusal(types, socket("p", "flange", 0.1), socket("c", "mount", 0.1)), + r"socket 'c' \(mount, size 0\.1\) and parent socket 'p' \(flange, size 0\.1\) are of different types") + for kind in ("flange", "pivot"): # equal: within 1 percent of the larger, the limit included + self.assertIsNone(core.mate_refusal(types, socket("p", kind, 100.0), socket("c", kind, 99.0))) + self.assertIsNone(core.mate_refusal(types, socket("p", kind, 99.0), socket("c", kind, 100.0))) + self.assertIsNone(core.mate_refusal(types, socket("p", kind, 0.2), socket("c", kind, 0.198))) + self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", kind, 100.0), socket("c", kind, 98.99))) + self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", kind, 98.99), socket("c", kind, 100.0))) + self.assertIsNone(core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3))) # fits: the child at most the parent + self.assertIsNone(core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.1))) + self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3 + 1e-6))) + self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.1), socket("c", "mount", 0.3))) + + def test_the_kit_s_own_flanges_do_not_meet_everywhere(self): + """A chamber flange (ribbed_cylinder, 0.16 and up) and the plumbing (pipe_fitting, 0.14 and down) never mate.""" + parts = self.kit["parts"] + drum = core.build(parts["ribbed_cylinder"], {"radius": 0.08}).sockets[1] + pipe = core.build(parts["pipe_fitting"], {"pipe_r": 0.07}).sockets[0] + self.assertEqual((drum["size"], pipe["size"]), (0.16, 0.14)) + self.assertIn("mate at equal sizes", core.mate_refusal(self.kit["socketTypes"], drum, pipe)) + + def test_a_joint_is_two_named_sockets_of_one_kit(self): + """The cross-kit refusal (one kit ships, so no scene can show it) and the unknown-socket refusals.""" + parts = self.kit["parts"] + tank, fitting = core.build(parts["tank"]), core.build(parts["pipe_fitting"]) + sp, sc = core.joint(parts["tank"], tank, "port_b", parts["pipe_fitting"], fitting, "a") + self.assertEqual((sp["name"], sc["name"]), ("port_b", "a")) + other = {**parts["pipe_fitting"], "kit": "hydraulic"} + with self.assertRaisesRegex(core.KitError, "part 'pipe_fitting' is of kit 'hydraulic' and part 'tank' of kit 'mechanical'.*do not mate"): + core.joint(parts["tank"], tank, "port_b", other, fitting, "a") + with self.assertRaisesRegex(core.KitError, "part 'tank' has no socket 'port_c'; its sockets: port_a, port_b, saddle"): + core.joint(parts["tank"], tank, "port_c", parts["pipe_fitting"], fitting, "a") + with self.assertRaisesRegex(core.KitError, "part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c"): + core.joint(parts["tank"], tank, "port_b", parts["pipe_fitting"], fitting, "d") + + +ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", + "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.boolean", "brokkr_kitbash.apply"] + + class HostFileTests(unittest.TestCase): def setUp(self): self.document = json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8")) @@ -396,8 +501,7 @@ class HostFileTests(unittest.TestCase): def test_brokkr_admits_the_file(self): """rows-check: Brokkr's own host-file checker.""" at.check_host(self.document, at.table()["charsets"]) - self.assertEqual([row["name"] for row in self.document["actions"]], - ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report"]) + self.assertEqual([row["name"] for row in self.document["actions"]], ROWS) def test_every_row_names_an_operator_and_property_the_add_on_defines(self): source = (SURFACE / "brokkr_kitbash" / "__init__.py").read_text(encoding="utf-8") @@ -421,11 +525,30 @@ class HostFileTests(unittest.TestCase): with self.assertRaises(at.IntentInvalid): at.validate({**envelope, "action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank", "location": "0,0,0"}, host) + def test_the_assembly_rows_take_scalars_inside_their_bounds(self): + host = [{**row, "host": "brokkr_kitbash"} for row in self.document["actions"]] + envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver"} + attach = {**envelope, "action": "brokkr_kitbash.attach", "object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"} + self.assertEqual(at.validate(attach, host)["roll"], 0) + self.assertEqual(at.validate({**attach, "roll": -360}, host)["roll"], -360) + boolean = {**envelope, "action": "brokkr_kitbash.boolean", "object_name": "Tank", "cutter": "Box"} + self.assertEqual(at.validate(boolean, host)["operation"], "DIFFERENCE") + for bad in ({**attach, "roll": 360.5}, {**attach, "socket": "a b"}, {**attach, "parent_socket": ""}, {**attach, "matrix": [1, 0, 0]}, + {**boolean, "operation": "SLICE"}, {**boolean, "solver": "EXACT"}, {**boolean, "cutter": ""}, + {**envelope, "action": "brokkr_kitbash.apply"}, {**envelope, "action": "brokkr_kitbash.detach", "object_name": "x" * 64}): + 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"]) + class OwnershipTests(unittest.TestCase): """The negative patterns of the cut: expressions are walked and never run, the bridge stays out, core needs no Blender, and schemas/ holds no second statement of the kit format.""" - PACKAGE = (r"\beval\(|\bexec\(|\bcompile\(", r"brokkr_bridge") + PACKAGE = (r"\beval\(|\bexec\(|\bcompile\(", r"brokkr_bridge", + r"\bsolver\s*=\s*[\"']MANIFOLD|\buse_self\s*=\s*False", # a boolean is Exact with self-intersection, nothing else + r"hide_render|hide_viewport|display_type", # a cutter's visibility is setObjectVisibility's + r"kit_parent_name|kit_parent\b|matrix_world_stored") # obj.parent has no second owner CORE = r"^import bpy|^from bpy|^import bmesh" SCHEMAS = r"brokkr\.kit\.v0" @@ -443,9 +566,24 @@ 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.""" + 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(source.count("to_mesh("), 1) + def test_the_patterns_bite(self): - for pattern, planted in zip(self.PACKAGE, ("value = eval(text)", "from brokkr_bridge import x")): - self.assertIsNotNone(re.search(pattern, planted)) + planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name') + self.assertEqual(len(planted), len(self.PACKAGE)) + for pattern, text in zip(self.PACKAGE, planted): + self.assertIsNotNone(re.search(pattern, text)) + for text in ("modifier.use_self = False", "cutter.display_type = 'WIRE'", "obj.hide_viewport = True", 'KEY = "kit_parent_name"'): + self.assertTrue(any(re.search(pattern, text) for pattern in self.PACKAGE[2:]), text) + self.assertIsNone(re.search(self.PACKAGE[4], 'PARENT_SOCKET = "kit_parent_socket"')) for planted in ("exec(text)", "code = compile(text, 'kit', 'eval')", "KIT = re.compile('x')"): self.assertIsNotNone(re.search(self.PACKAGE[0], planted)) for planted in ("import bpy", "x = 1\nfrom bpy import props", "import bmesh"): From 03f182fa06932216289612f296ae787ed4ae40f5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 16:18:39 +0100 Subject: [PATCH 072/223] docs: kitbash.md, assembling parts: connections, drift, boolean and apply Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 125 +++++++++++++++++++++++++++---- 1 file changed, 109 insertions(+), 16 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 8ce9c2c..d5c5d00 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1,12 +1,12 @@ # Kitbash parts: machinery from kits -`surfaces/blender/brokkr_kitbash` is a Blender add-on that places parametric machine parts from a **kit** and -reports where their **sockets** are. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks, +`surfaces/blender/brokkr_kitbash` is a Blender add-on that places parametric machine parts from a **kit**, mates +them **socket** to socket, cuts them with booleans and bakes them. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks, actuators, housings and plumbing an agent assembles offline under a hand-fit armor cage, baked once. It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish` and `brokkr_rig`: it imports the polish package's operator base, `Refused` and `mesh_object`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish` first; `brokkr_kitbash` refuses to register without it. `brokkr_actions.json` beside -its `__init__.py` lists the four operators agents may run. Every action writes a JSON report to +its `__init__.py` lists the eight operators agents may run. Every action writes a JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. Who owns what: @@ -24,8 +24,11 @@ Who owns what: `set_params` and `report` refuse a part whose world transform scales, mirrors or shears, its parents' included: a part's size is its params, and a socket's frame is a rotation and an origin. Set scale to 1 and resize with `set_params`. - -This add-on places and re-parameterises parts. Mating sockets, booleans and baking are not here. +- A connection between two parts belongs to the child: its parent pointer and its `kit_socket`, + `kit_parent_socket` and `kit_roll` properties. Where the child stands is derived from them + ("Assembling parts"). +- A boolean belongs to its Boolean modifier on the part that is cut. `kit_baked` says `apply` replaced the part's + mesh with the evaluated one. ## A part, end to end @@ -83,6 +86,73 @@ be compared when sockets are mated: `equal` (within 1 percent) or `fits` (the ch sits on a flat face of the part whose normal is its `z`; `test_kitbash` checks this for every part of a shipped kit at its default, smallest and largest params and at seeded draws between. +## Assembling parts + +**A connection** seats one socket of a child part on one socket of a parent part: the two origins together, the +two normals opposed, and the child turned `roll` degrees about the parent socket's normal (right-handed; at 0 the +two sockets' up axes line up). The child owns it. It is the child's parent pointer, under an identity parent +inverse, and three ID properties on the child: `kit_socket` (its own socket), `kit_parent_socket` and `kit_roll`. +Nothing else stores it: no parent name, no world matrix, no empties. The child's `matrix_basis` is derived, + +```text +matrix_basis = S_parent @ Rz(roll) @ FLIP @ inverse(S_child) FLIP = half a turn about y +``` + +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 +refuses, changing nothing: + +- a child that has a parent (`detach` it; `setObjectParent` with an empty parent clears a parent it was not + attached to); +- a parent that is the child, or is below it (a loop); +- an occupied socket: one a child is already attached to, or the one the part itself is attached by; +- a part that is not a kit part, or is scaled in the world. + +A part may carry a child on every socket but the one it hangs by, so assemblies are trees: tank, then a tee on +its port, then a nozzle on each free flange of the tee. + +**`set_params` keeps an assembly together.** Sockets move with params (an actuator's `rod_end` with `extension`, a +tank's `port_b` with `length`). After the rebuild `set_params` writes the derived `matrix_basis` of the part +itself, if it is attached, and of each part attached to it; what hangs further down follows through parenting. +Before it writes anything it checks every one of those connections against the part's new sockets, and a change +that breaks one (a `pipe_r` that no longer matches the flange it is bolted to) is refused, naming the +connection. + +**Drift.** `setObjectTransform` and `setObjectParent` are Brokkr's own rows and can move or re-parent an attached +child. Reports show it: a part's `connection` is `null`, or + +```json +{"parent": "Tee", "socket": "mount", "parentSocket": "c", "roll": 37.0, "residual": 2.1e-07, "holds": true} +``` + +`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 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` refuses it: `detach` clears what is left. +`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 many overlapping closed shells, and the faster solvers +give wrong solids for those (the 1.8 m tank minus a box keeps 0.254 m3 with self-intersection and 0.008 m3 +without). That costs about a second per part each time the part is evaluated (0.3 s for a pipe fitting, 1.5 s +for a tank, on Blender 5.3), so 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. + +**`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, followed by any a cutter brought. 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`. + ## Expressions Every numeric field of a shape or socket, and `bevel`, is a number or a string over the part's params: @@ -103,19 +173,24 @@ vertices overflow. | --- | --- | --- | | `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | | `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: transform, parent, 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. | -| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, and each socket's world frame. Changes nothing. | +| `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, and a baked part. | +| `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` 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.detach` | `object_name` | Clears the part's connection; it stays where it stands. Refuses a part that is not attached. | +| `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. | `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. A socket in a report is `{name, type, size, matrix}`: `matrix` is the 4x4 as four rows of 6 decimals, in world -space for `place_part`, `set_params` and `report`. Column 2 is the outward normal, column 1 up, column 3 the +space for every action that reports a placed part. Column 2 is the outward normal, column 1 up, column 3 the origin. A report over 16000 characters (what a receipt carries) is refused with advice to name one part or object. -Placement, look and export are Brokkr's own rows: `setObjectTransform`, `assignMaterial`, `exportGltf`. -`place_part` has no location or colour fields. +Placing a loose part, look, hiding a cutter and export are Brokkr's own rows: `setObjectTransform`, +`assignMaterial`, `setObjectVisibility`, `exportGltf`. `place_part` has no location or colour fields. Move an +assembly by its root: an attached part is placed by its connection. ## A recipe @@ -129,14 +204,23 @@ Placement, look and export are Brokkr's own rows: `setObjectTransform`, `assignM {"action": "brokkr_kitbash.place_part", "part": "tank", "object_name": "Tank", "params": "radius=0.3; length=1.4"}, {"action": "setObjectTransform", "targetObjectName": "Tank", "location": [0, 0.6, 0], "rotationEuler": [1.5708, 0, 0]}, {"action": "assignMaterial", "targetObjectName": "Tank", "materialName": "Machinery", "color": [0.35, 0.35, 0.35]}, - {"action": "brokkr_kitbash.place_part", "part": "nozzle", "object_name": "Nozzle"}, - {"action": "brokkr_kitbash.set_params", "object_name": "Nozzle", "params": "exit_r=0.32"}, - {"action": "brokkr_kitbash.report"}, - {"action": "exportGltf", "filepath": "engine.glb", "selection": ["Tank", "Nozzle"]} + {"action": "brokkr_kitbash.place_part", "part": "pipe_fitting", "object_name": "Tee", "params": "pipe_r=0.06"}, + {"action": "brokkr_kitbash.attach", "object_name": "Tee", "socket": "a", "parent_name": "Tank", "parent_socket": "port_b"}, + {"action": "brokkr_kitbash.place_part", "part": "nozzle", "object_name": "Nozzle", "params": "throat_r=0.06"}, + {"action": "brokkr_kitbash.attach", "object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "c", "roll": 90}, + {"action": "brokkr_kitbash.set_params", "object_name": "Tank", "params": "length=1.8"}, + {"action": "createObject", "objectType": "MESH", "name": "Cutter", "location": [0.3, 0.6, 0], "size": 0.2}, + {"action": "brokkr_kitbash.boolean", "object_name": "Tank", "cutter": "Cutter"}, + {"action": "setObjectVisibility", "targetObjectName": "Cutter", "visible": false}, + {"action": "brokkr_kitbash.apply", "object_name": "Tank"}, + {"action": "brokkr_kitbash.report", "object_name": "Nozzle"}, + {"action": "exportGltf", "filepath": "engine.glb", "selection": ["Tank", "Tee", "Nozzle"]} ]} ``` -The receipts file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the saved `.blend`. +The tank's port is 0.4 of its radius across (0.12 m here), so the tee and the nozzle are given the matching +`pipe_r` and `throat_r`. `set_params` on the tank carries the tee and the nozzle out with its port. The receipts +file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the saved `.blend`. ## The mechanical kit @@ -157,6 +241,13 @@ The receipts file holds each report in `hostResult`. `tools/turntable_recipe.py` `describe` gives the bounds and docs. +Which flanges can meet follows from the sizes: a tank port is `0.4*radius` (0.048 to 0.14), a pipe fitting's +three faces `2*pipe_r` (0.06 to 0.14), a nozzle's mount `2*throat_r` (0.08 to 0.24), and a ribbed cylinder's ends +`2*radius` (0.16 to 0.6). So tanks, fittings and nozzles plumb together, and a ribbed cylinder takes only a +nozzle (throat 0.08 and up) or another ribbed cylinder: its smallest flange is larger than the largest pipe. +Struts and actuators pin together when `0.6*width` equals `0.9*body_r`. Mounts (`fits`) take any part whose +seat is no larger than theirs. + ## Adding a part or a kit Edit the kit's JSON (or add `kits/.v0.json`, whose `kit` field is ``), then run the tests: @@ -170,4 +261,6 @@ 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_nine_parts_and_three_socket_types`. -The operators are exercised in a real Blender by `tests/live/kitbash.py`. +`MateTests` covers the mate arithmetic and what may mate. 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, boolean and apply). From 00521a8bd83c6c909df429f032f1a8da03ecf0eb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 17:39:17 +0100 Subject: [PATCH 073/223] brokkr_kitbash: lathe and repeat-about-an-axis shapes; nozzle, tank and tee rebuilt on them; a reducer core.py gains two shapes of brokkr.kit.v0. A lathe revolves a profile of [r, z] points about +z into one closed shell (poles on the axis, n-gon caps off it, or a loop); a repeat takes `around` (with `center`) in place of `step` and turns its copies about an axis. The mechanical kit drops the 15 tube shells of the nozzle body and bell, the tank's 13 dome and barrel tubes and its weld-band repeat, and the tee's 7 tubes and six bolt pairs; one lathe each replaces them (two for the tee), with bolts and lugs as repeats about an axis. The tee's branch hub is 1.2*pipe_r against the run hub's 1.3: two equal hubs crossing left non-manifold edges under an Exact Boolean. A tenth part, reducer, joins a ribbed cylinder's flange to the plumbing's. Sockets of the rebuilt parts are unchanged; the six other parts build byte-identical arrays. Tests: lathe and repeat-around shapes and refusals, the reducer, the equal rule's slack pinned at 2.2e-6 past the 1 percent. Cut aetheria-release:cut_spec:cut-kit-shape-vocabulary.r1. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/core.py | 108 ++++++++++++-- .../brokkr_kitbash/kits/mechanical.v0.json | 138 +++++++++-------- surfaces/blender/tests/live/kitbash.py | 10 +- .../blender/tests/live/kitbash.result.json | 42 ++++-- surfaces/blender/tests/test_kitbash.py | 139 +++++++++++++++++- 5 files changed, 331 insertions(+), 106 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 49b3c36..0df5aef 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1,9 +1,10 @@ """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, repeat) 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. An -expression is parsed with ast.parse and walked against a whitelist; nothing in a kit is ever run as Python. +(kits/.v0.json beside this file). 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. An expression is parsed with ast.parse and walked against a +whitelist; nothing in a kit is ever run as Python. kit = load_kit("mechanical") built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, shell_count, sockets @@ -34,7 +35,8 @@ AXES = {"+x": (1.0, 0.0, 0.0), "-x": (-1.0, 0.0, 0.0), "+y": (0.0, 1.0, 0.0), "- PLACED = ("at", "rot") SHAPES = {"tube": (("r0", "r1", "length", "segments"), ("inner0", "inner1", "smooth") + PLACED), "box": (("size",), PLACED), - "repeat": (("count", "step", "of"), ())} + "lathe": (("profile", "segments"), ("loop", "smooth") + PLACED), + "repeat": (("count", "of"), ("step", "around", "center"))} SEGMENTS = (3, 128) COPIES = (1, 256) @@ -190,22 +192,47 @@ def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict: if kind == "repeat": if inside_repeat: raise KitError(f"{where}: a repeat cannot hold a repeat") - return {"shape": kind, "count": parse(shape["count"], names, f"{where} count"), - "step": _vector(shape["step"], names, f"{where} step"), + if ("step" in shape) == ("around" in shape): + raise KitError(f"{where} takes exactly one of step (copies a step apart) and around (copies turned about an axis)") + made = {"shape": kind, "count": parse(shape["count"], names, f"{where} count"), "of": _shape(shape["of"], names, f"{where} of", inside_repeat=True)} + if "step" in shape: + if "center" in shape: + raise KitError(f"{where}: center goes with around, not with step") + made["step"] = _vector(shape["step"], names, f"{where} step") + else: + if not isinstance(shape["around"], str) or shape["around"] not in AXES: + raise KitError(f"{where}: around must be one of {', '.join(AXES)}") + made["around"] = shape["around"] + made["center"] = _vector(shape["center"], names, f"{where} center") if "center" in shape else ZERO + return made made = {"shape": kind, "where": where, "at": _vector(shape["at"], names, f"{where} at") if "at" in shape else ZERO, "rot": _vector(shape["rot"], names, f"{where} rot") if "rot" in shape else ZERO} if kind == "box": made["size"] = _vector(shape["size"], names, f"{where} size") return made - for key in ("r0", "r1", "length", "segments"): + for key in ("loop", "smooth"): + if not isinstance(shape.get(key, False), bool): + raise KitError(f"{where} {key} must be true or false") + made["smooth"] = shape.get("smooth", False) + made["segments"] = parse(shape["segments"], names, f"{where} segments") + if kind == "lathe": + made["loop"] = shape.get("loop", False) + least = 3 if made["loop"] else 2 + profile = shape["profile"] + if not isinstance(profile, list) or len(profile) < least: + raise KitError(f"{where} profile must be an array of at least {least} [r, z] points{' (it is a loop)' if made['loop'] else ''}") + made["profile"] = [] + for i, point in enumerate(profile): + if not isinstance(point, list) or len(point) != 2: + raise KitError(f"{where} profile[{i}] must be [r, z]: two numbers or expressions") + made["profile"].append([parse(value, names, f"{where} profile[{i}][{c}]") for c, value in enumerate(point)]) + return made + for key in ("r0", "r1", "length"): made[key] = parse(shape[key], names, f"{where} {key}") for key in ("inner0", "inner1"): made[key] = parse(shape.get(key, 0), names, f"{where} {key}") - if not isinstance(shape.get("smooth", False), bool): - raise KitError(f"{where} smooth must be true or false") - made["smooth"] = shape.get("smooth", False) return made @@ -360,7 +387,7 @@ def resolve_params(part: dict, given: dict, base: dict | None = None) -> dict: class Built(NamedTuple): """A part at given params, in the part's frame, metres. Face i has counts[i] corners, listed in order in - faces (quads and n-gon caps, wound outward); smooth[i] marks tube sides to shade smooth; shape[i] is the index, + faces (quads, a lathe's triangles at a pole, and n-gon caps, wound outward); smooth[i] marks the walls to shade smooth; shape[i] is the index, in the part's shapes list, of the shape the face belongs to (every copy of a repeat shares one). Each socket is {'name', 'type', 'size', 'matrix'} with matrix the 4x4 frame: column 2 the outward normal, column 1 up, column 0 = y cross z, column 3 the origin.""" @@ -424,6 +451,55 @@ def _tube(shape: dict, env): return V, faces, counts, smooth +def _lathe(shape: dict, env): + """A profile of [r, z] points revolved about +z, one ring per point. Open: an end on the axis (r exactly 0) is a + pole and the band to it triangles; an end off the axis gets a flat n-gon cap. Loop: the last point joins the + first. The profile is listed out along the bottom and up the outside (its closing polygon, down the axis for an + open one, has positive area in (r, z)), which makes every band and cap wind as a tube's.""" + where = shape["where"] + P = np.array([[r.value(env), z.value(env)] for r, z in shape["profile"]]) + n = _whole(shape["segments"], env, SEGMENTS) + loop, last = shape["loop"], len(P) - 1 + for i, (r, z) in enumerate(P): + if r < 0: + raise KitError(f"{where} profile[{i}]: r is {r}, below 0") + if r == 0 and (loop or 0 < i < last): + raise KitError(f"{where} profile[{i}]: r is 0; only the first and last point of an open profile may lie on the axis") + if (i > 0 or loop) and (P[i] == P[i - 1]).all(): + raise KitError(f"{where} profile[{i}]: [{r}, {z}] repeats the point before it{' (a loop closes itself)' if i == 0 else ''}") + ring = P if loop else np.vstack([P, [[0.0, P[last, 1]], [0.0, P[0, 1]]]]) + after = np.roll(ring, -1, axis=0) + area = 0.5 * float((ring[:, 0] * after[:, 1] - after[:, 0] * ring[:, 1]).sum()) + if not area > 0: + raise KitError(f"{where} profile: list it out along the bottom and up the outside; these points run the other way or enclose nothing " + f"(signed area {area:.6g} in r, z)") + angle = 2.0 * math.pi * np.arange(n) / n + cos, sin = np.cos(angle), np.sin(angle) + pole = P[:, 0] == 0 + start = np.concatenate([[0], np.cumsum(np.where(pole, 1, n))[:-1]]) + V = np.vstack([[[0.0, 0.0, z]] if on_axis else np.column_stack([r * cos, r * sin, np.full(n, z)]) for (r, z), on_axis in zip(P, pole)]) + k = np.arange(n) + j = (k + 1) % n + faces, counts, smooth = [], [], [] + for a, b in [(i, i + 1) for i in range(last)] + ([(last, 0)] if loop else []): + if pole[a]: + band = np.column_stack([np.full(n, start[a]), start[b] + j, start[b] + k]) + elif pole[b]: + band = np.column_stack([start[a] + k, start[a] + j, np.full(n, start[b])]) + else: + band = np.column_stack([start[a] + k, start[a] + j, start[b] + j, start[b] + k]) + faces.append(band.ravel()) + counts.append(np.full(n, band.shape[1])) + smooth.append(np.full(n, shape["smooth"] and P[a, 1] != P[b, 1])) # an annulus is flat + if not loop: + for end, corners in ((0, k[::-1]), (last, k)): + if not pole[end]: + faces.append(start[end] + corners) + counts.append([n]) + smooth.append([False]) + return V, np.concatenate(faces), np.concatenate(counts), np.concatenate(smooth).astype(bool) + + BOX_FACES = np.array([[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]) BOX_SIGNS = np.array([[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]]) * 0.5 @@ -436,7 +512,7 @@ def _box(shape: dict, env): def _placed(shape: dict, env): - V, faces, counts, smooth = (_tube if shape["shape"] == "tube" else _box)(shape, env) + V, faces, counts, smooth = {"tube": _tube, "box": _box, "lathe": _lathe}[shape["shape"]](shape, env) rotation = _rotation([e.value(env) for e in shape["rot"]]) return V @ rotation.T + np.array([e.value(env) for e in shape["at"]]), faces, counts, smooth @@ -451,9 +527,13 @@ def build(part: dict, params: dict | None = None) -> Built: for index, shape in enumerate(part["shapes"]): if shape["shape"] == "repeat": count = _whole(shape["count"], env, COPIES) - step = np.array([e.value(env) for e in shape["step"]]) V, faces, counts, smooth = _placed(shape["of"], env) - made = [(V + k * step, faces, counts, smooth) for k in range(count)] + if "step" in shape: + step = np.array([e.value(env) for e in shape["step"]]) + made = [(V + k * step, faces, counts, smooth) for k in range(count)] + else: # copy k turned k/count of a turn, right-handed, about the axis through center + axis, center = np.array(AXES[shape["around"]]), np.array([e.value(env) for e in shape["center"]]) + made = [((V - center) @ _rotation(axis * (360.0 * k / count)).T + center, faces, counts, smooth) for k in range(count)] else: made = [_placed(shape, env)] for shell in made: diff --git a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json index a47db06..a09c1a1 100644 --- a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json @@ -20,42 +20,26 @@ ], "bevel": "0.3*wall", "shapes": [ - {"shape": "tube", "r0": "2.1*throat_r", "r1": "2.1*throat_r", "length": "0.3*throat_r", "segments": "segments", "smooth": true}, - {"shape": "repeat", "count": 2, "step": ["2.62*throat_r", 0, 0], "of": - {"shape": "tube", "r0": "0.14*throat_r", "r1": "0.14*throat_r", "length": "0.35*throat_r", "segments": 6, "at": ["-1.31*throat_r", "-1.31*throat_r", "0.1*throat_r"]}}, - {"shape": "repeat", "count": 2, "step": ["2.62*throat_r", 0, 0], "of": - {"shape": "tube", "r0": "0.14*throat_r", "r1": "0.14*throat_r", "length": "0.35*throat_r", "segments": 6, "at": ["-1.31*throat_r", "1.31*throat_r", "0.1*throat_r"]}}, - {"shape": "tube", "r0": "1.6*throat_r", "r1": "1.6*throat_r", "length": "1.75*throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "0.15*throat_r"]}, - {"shape": "tube", "r0": "1.6*throat_r", "r1": "throat_r+wall", "length": "throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.9*throat_r"]}, - {"shape": "tube", "r0": "1.78*throat_r", "r1": "1.78*throat_r", "length": "0.5*throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.6*throat_r"]}, - {"shape": "tube", "r0": "throat_r+wall", "r1": "throat_r+wall+0.1164*(exit_r-throat_r-wall)", "inner0": "throat_r", "inner1": "throat_r+0.1164*(exit_r-throat_r-wall)", - "length": "0.06*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r"]}, - {"shape": "tube", "r0": "throat_r+wall+0.1164*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.2604*(exit_r-throat_r-wall)", "inner0": "throat_r+0.1164*(exit_r-throat_r-wall)", "inner1": "throat_r+0.2604*(exit_r-throat_r-wall)", - "length": "0.08*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.06*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.2604*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.4224*(exit_r-throat_r-wall)", "inner0": "throat_r+0.2604*(exit_r-throat_r-wall)", "inner1": "throat_r+0.4224*(exit_r-throat_r-wall)", - "length": "0.1*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.14*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.4224*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.5904*(exit_r-throat_r-wall)", "inner0": "throat_r+0.4224*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5904*(exit_r-throat_r-wall)", - "length": "0.12*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.24*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.5904*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5904*(exit_r-throat_r-wall)", "inner1": "throat_r+0.75*(exit_r-throat_r-wall)", - "length": "0.14*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.36*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.8844*(exit_r-throat_r-wall)", "inner0": "throat_r+0.75*(exit_r-throat_r-wall)", "inner1": "throat_r+0.8844*(exit_r-throat_r-wall)", - "length": "0.16*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.5*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.8844*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.9676*(exit_r-throat_r-wall)", "inner0": "throat_r+0.8844*(exit_r-throat_r-wall)", "inner1": "throat_r+0.9676*(exit_r-throat_r-wall)", - "length": "0.16*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.66*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.9676*(exit_r-throat_r-wall)", "r1": "exit_r", "inner0": "throat_r+0.9676*(exit_r-throat_r-wall)", "inner1": "exit_r-wall", - "length": "0.18*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.82*length"]}, - {"shape": "tube", "r0": "throat_r+2.4*wall+0.6132*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.6474*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.6132*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.6474*(exit_r-throat_r-wall)", - "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.38*length"]}, - {"shape": "tube", "r0": "throat_r+2.4*wall+0.834*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.8592*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.834*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.8592*(exit_r-throat_r-wall)", - "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.6*length"]}, - {"shape": "tube", "r0": "throat_r+2.4*wall+0.9748*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.9802*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.9748*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.9802*(exit_r-throat_r-wall)", - "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.86*length"]}, - {"shape": "repeat", "count": 2, "step": ["3.4*throat_r", 0, 0], "of": - {"shape": "box", "size": ["0.5*throat_r", "0.35*throat_r", "0.6*throat_r"], "at": ["-1.7*throat_r", 0, "throat_r"]}}, - {"shape": "repeat", "count": 2, "step": [0, "3.4*throat_r", 0], "of": - {"shape": "box", "size": ["0.35*throat_r", "0.5*throat_r", "0.6*throat_r"], "at": [0, "-1.7*throat_r", "throat_r"]}}, - {"shape": "tube", "r0": "exit_r+1.6*wall", "r1": "exit_r+1.6*wall", "inner0": "exit_r-0.5*wall", "inner1": "exit_r-0.5*wall", - "length": "3*wall", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+length-2.5*wall"]} + {"shape": "lathe", "segments": "segments", "smooth": true, "profile": [ + ["2.1*throat_r", 0], ["2.1*throat_r", "0.3*throat_r"], ["1.6*throat_r", "0.3*throat_r"], ["1.6*throat_r", "1.6*throat_r"], ["1.78*throat_r", "1.6*throat_r"], ["1.78*throat_r", "2.1*throat_r"], ["1.48*throat_r+0.2*wall", "2.1*throat_r"], ["throat_r+wall", "2.9*throat_r"], + ["throat_r+wall+0.1164*(exit_r-throat_r-wall)", "2.9*throat_r+0.06*length"], + ["throat_r+wall+0.2604*(exit_r-throat_r-wall)", "2.9*throat_r+0.14*length"], + ["throat_r+wall+0.4224*(exit_r-throat_r-wall)", "2.9*throat_r+0.24*length"], + ["throat_r+wall+0.5904*(exit_r-throat_r-wall)", "2.9*throat_r+0.36*length"], + ["throat_r+wall+0.6132*(exit_r-throat_r-wall)", "2.9*throat_r+0.38*length"], ["throat_r+2.4*wall+0.6132*(exit_r-throat_r-wall)", "2.9*throat_r+0.38*length"], ["throat_r+2.4*wall+0.6474*(exit_r-throat_r-wall)", "2.9*throat_r+0.41*length"], ["throat_r+wall+0.6474*(exit_r-throat_r-wall)", "2.9*throat_r+0.41*length"], + ["throat_r+wall+0.75*(exit_r-throat_r-wall)", "2.9*throat_r+0.5*length"], + ["throat_r+wall+0.834*(exit_r-throat_r-wall)", "2.9*throat_r+0.6*length"], ["throat_r+2.4*wall+0.834*(exit_r-throat_r-wall)", "2.9*throat_r+0.6*length"], ["throat_r+2.4*wall+0.8592*(exit_r-throat_r-wall)", "2.9*throat_r+0.63*length"], ["throat_r+wall+0.8592*(exit_r-throat_r-wall)", "2.9*throat_r+0.63*length"], + ["throat_r+wall+0.8844*(exit_r-throat_r-wall)", "2.9*throat_r+0.66*length"], + ["throat_r+wall+0.9676*(exit_r-throat_r-wall)", "2.9*throat_r+0.82*length"], + ["throat_r+wall+0.9748*(exit_r-throat_r-wall)", "2.9*throat_r+0.86*length"], ["throat_r+2.4*wall+0.9748*(exit_r-throat_r-wall)", "2.9*throat_r+0.86*length"], ["throat_r+2.4*wall+0.9802*(exit_r-throat_r-wall)", "2.9*throat_r+0.89*length"], ["throat_r+wall+0.9802*(exit_r-throat_r-wall)", "2.9*throat_r+0.89*length"], + ["throat_r+wall+(1-0.18*min(2.5*wall,0.08*length)/length)*(exit_r-throat_r-wall)", "2.9*throat_r+length-min(2.5*wall,0.08*length)"], ["exit_r+1.6*wall", "2.9*throat_r+length-min(2.5*wall,0.08*length)"], ["exit_r+1.6*wall", "2.9*throat_r+length+0.5*wall"], ["exit_r-0.5*wall", "2.9*throat_r+length+0.5*wall"], ["exit_r-wall", "2.9*throat_r+length"], + ["throat_r+0.9676*(exit_r-throat_r-wall)", "2.9*throat_r+0.82*length"], ["throat_r+0.8844*(exit_r-throat_r-wall)", "2.9*throat_r+0.66*length"], ["throat_r+0.75*(exit_r-throat_r-wall)", "2.9*throat_r+0.5*length"], ["throat_r+0.5904*(exit_r-throat_r-wall)", "2.9*throat_r+0.36*length"], + ["throat_r+0.4224*(exit_r-throat_r-wall)", "2.9*throat_r+0.24*length"], ["throat_r+0.2604*(exit_r-throat_r-wall)", "2.9*throat_r+0.14*length"], ["throat_r+0.1164*(exit_r-throat_r-wall)", "2.9*throat_r+0.06*length"], + ["throat_r", "2.9*throat_r"]]}, + {"shape": "repeat", "count": 4, "around": "+z", "of": + {"shape": "tube", "r0": "0.14*throat_r", "r1": "0.14*throat_r", "length": "0.35*throat_r", "segments": 6, "at": ["1.31*throat_r", "1.31*throat_r", "0.1*throat_r"]}}, + {"shape": "repeat", "count": 4, "around": "+z", "of": + {"shape": "box", "size": ["0.5*throat_r", "0.35*throat_r", "0.6*throat_r"], "at": ["1.7*throat_r", 0, "throat_r"]}} ], "sockets": [ {"name": "mount", "type": "flange", "size": "2*throat_r", "at": [0, 0, 0], "z": "-z", "y": "+y"} @@ -71,23 +55,16 @@ ], "bevel": "0.008*radius", "shapes": [ - {"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.05*radius", "segments": "segments", "smooth": true}, - {"shape": "tube", "r0": "0.2*radius", "r1": "0.2*radius", "length": "0.18*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.02*radius"]}, - {"shape": "tube", "r0": "0.47*radius", "r1": "0.6984*radius", "length": "0.07*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.12*radius"]}, - {"shape": "tube", "r0": "0.6984*radius", "r1": "0.8512*radius", "length": "0.08*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.19*radius"]}, - {"shape": "tube", "r0": "0.8512*radius", "r1": "0.9581*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.27*radius"]}, - {"shape": "tube", "r0": "0.9581*radius", "r1": "radius", "length": "0.12*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.37*radius"]}, - {"shape": "tube", "r0": "radius", "r1": "radius", "length": "length-0.98*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.49*radius"]}, - {"shape": "tube", "r0": "radius", "r1": "0.9581*radius", "length": "0.12*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.49*radius"]}, - {"shape": "tube", "r0": "0.9581*radius", "r1": "0.8512*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.37*radius"]}, - {"shape": "tube", "r0": "0.8512*radius", "r1": "0.6984*radius", "length": "0.08*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.27*radius"]}, - {"shape": "tube", "r0": "0.6984*radius", "r1": "0.47*radius", "length": "0.07*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.19*radius"]}, - {"shape": "tube", "r0": "0.2*radius", "r1": "0.2*radius", "length": "0.18*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.2*radius"]}, - {"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.05*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.05*radius"]}, - {"shape": "repeat", "count": 2, "step": [0, 0, "length-0.98*radius"], "of": - {"shape": "tube", "r0": "1.012*radius", "r1": "1.012*radius", "inner0": "0.97*radius", "inner1": "0.97*radius", "length": "0.04*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.47*radius"]}}, + {"shape": "lathe", "segments": "segments", "smooth": true, "profile": [ + ["0.3*radius", 0], ["0.3*radius", "0.05*radius"], ["0.2*radius", "0.05*radius"], ["0.2*radius", "0.12*radius"], + ["0.47*radius", "0.12*radius"], ["0.6984*radius", "0.19*radius"], ["0.8512*radius", "0.27*radius"], ["0.9581*radius", "0.37*radius"], + ["0.9965*radius", "0.47*radius"], ["1.012*radius", "0.47*radius"], ["1.012*radius", "0.51*radius"], ["radius", "0.51*radius"], + ["radius", "length-0.51*radius"], ["1.012*radius", "length-0.51*radius"], ["1.012*radius", "length-0.47*radius"], ["0.9965*radius", "length-0.47*radius"], + ["0.9581*radius", "length-0.37*radius"], ["0.8512*radius", "length-0.27*radius"], ["0.6984*radius", "length-0.19*radius"], ["0.47*radius", "length-0.12*radius"], + ["0.2*radius", "length-0.12*radius"], ["0.2*radius", "length-0.05*radius"], ["0.3*radius", "length-0.05*radius"], ["0.3*radius", "length"]]}, {"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of": - {"shape": "tube", "r0": "1.035*radius", "r1": "1.035*radius", "inner0": "0.97*radius", "inner1": "0.97*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.44*radius+0.22*(length-0.98*radius)"]}}, + {"shape": "lathe", "loop": true, "segments": "segments", "smooth": true, "at": [0, 0, "0.44*radius+0.22*(length-0.98*radius)"], + "profile": [["0.97*radius", 0], ["1.035*radius", 0], ["1.035*radius", "0.1*radius"], ["0.97*radius", "0.1*radius"]]}}, {"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of": {"shape": "box", "size": ["1.3*radius", "0.55*radius", "0.1*radius"], "at": [0, "-0.85*radius", "0.49*radius+0.22*(length-0.98*radius)"]}}, {"shape": "box", "size": ["1.5*radius", "0.08*radius", "0.56*(length-0.98*radius)+0.3*radius"], "at": [0, "-1.14*radius", "length/2"]} @@ -200,25 +177,19 @@ ], "bevel": "min(0.15*flange_t,0.06*(flange_r-pipe_r))", "shapes": [ - {"shape": "tube", "r0": "pipe_r", "r1": "pipe_r", "length": "run-flange_t", "segments": "segments", "smooth": true, "at": [0, 0, "0.5*flange_t"]}, - {"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true}, - {"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true, "at": [0, 0, "run-flange_t"]}, - {"shape": "tube", "r0": "1.3*pipe_r", "r1": "1.3*pipe_r", "length": "min(3*pipe_r,run-4*flange_t)", "segments": "segments", "smooth": true, "at": [0, 0, "run/2-min(3*pipe_r,run-4*flange_t)/2"]}, - {"shape": "tube", "r0": "pipe_r", "r1": "pipe_r", "length": "branch-0.5*flange_t", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": [0, 0, "run/2"]}, - {"shape": "tube", "r0": "1.3*pipe_r", "r1": "1.3*pipe_r", "length": "min(2.2*pipe_r,branch-2*flange_t)", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": [0, 0, "run/2"]}, - {"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": ["branch-flange_t", 0, "run/2"]}, - {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": - {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "-0.3536*(flange_r+pipe_r)", "0.15*flange_t"]}}, - {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": - {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "0.3536*(flange_r+pipe_r)", "0.15*flange_t"]}}, - {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": - {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "-0.3536*(flange_r+pipe_r)", "run-1.5*flange_t"]}}, - {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": - {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "0.3536*(flange_r+pipe_r)", "run-1.5*flange_t"]}}, - {"shape": "repeat", "count": 2, "step": [0, 0, "0.7072*(flange_r+pipe_r)"], "of": - {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "rot": [0, 90, 0], "at": ["branch-1.5*flange_t", "-0.3536*(flange_r+pipe_r)", "run/2-0.3536*(flange_r+pipe_r)"]}}, - {"shape": "repeat", "count": 2, "step": [0, 0, "0.7072*(flange_r+pipe_r)"], "of": - {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "rot": [0, 90, 0], "at": ["branch-1.5*flange_t", "0.3536*(flange_r+pipe_r)", "run/2-0.3536*(flange_r+pipe_r)"]}} + {"shape": "lathe", "segments": "segments", "smooth": true, "profile": [ + ["flange_r", 0], ["flange_r", "flange_t"], ["pipe_r", "flange_t"], + ["pipe_r", "run/2-min(3*pipe_r,run-4*flange_t)/2"], ["1.3*pipe_r", "run/2-min(3*pipe_r,run-4*flange_t)/2"], ["1.3*pipe_r", "run/2+min(3*pipe_r,run-4*flange_t)/2"], ["pipe_r", "run/2+min(3*pipe_r,run-4*flange_t)/2"], + ["pipe_r", "run-flange_t"], ["flange_r", "run-flange_t"], ["flange_r", "run"]]}, + {"shape": "lathe", "segments": "segments", "smooth": true, "profile": [ + ["1.2*pipe_r", 0], ["1.2*pipe_r", "min(2.2*pipe_r,branch-2*flange_t)"], ["pipe_r", "min(2.2*pipe_r,branch-2*flange_t)"], + ["pipe_r", "branch-flange_t"], ["flange_r", "branch-flange_t"], ["flange_r", "branch"]], "rot": [0, 90, 0], "at": [0, 0, "run/2"]}, + {"shape": "repeat", "count": 4, "around": "+z", "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["0.3536*(flange_r+pipe_r)", "0.3536*(flange_r+pipe_r)", "0.15*flange_t"]}}, + {"shape": "repeat", "count": 4, "around": "+z", "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["0.3536*(flange_r+pipe_r)", "0.3536*(flange_r+pipe_r)", "run-1.5*flange_t"]}}, + {"shape": "repeat", "count": 4, "around": "+x", "center": [0, 0, "run/2"], "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "rot": [0, 90, 0], "at": ["branch-1.5*flange_t", "0.3536*(flange_r+pipe_r)", "run/2+0.3536*(flange_r+pipe_r)"]}} ], "sockets": [ {"name": "a", "type": "flange", "size": "2*pipe_r", "at": [0, 0, 0], "z": "-z", "y": "+y"}, @@ -300,6 +271,31 @@ {"name": "back", "type": "mount", "size": "min(width,height)", "at": [0, 0, 0], "z": "-z", "y": "+y"}, {"name": "front", "type": "mount", "size": "0.76*min(width,height)", "at": [0, 0, "thickness"], "z": "+z", "y": "+y"} ] + }, + { + "name": "reducer", + "doc": "Concentric reducer: a cone between a large and a small bolted flange, joining a chamber or housing to the plumbing.", + "params": [ + {"name": "big_r", "type": "number", "min": 0.08, "max": 0.3, "default": 0.12, "doc": "large bore radius"}, + {"name": "small_r", "type": "number", "min": 0.024, "max": 0.07, "default": 0.05, "doc": "small bore radius"}, + {"name": "length", "type": "number", "min": 0.12, "max": 0.6, "default": 0.25, "doc": "big face to small face"}, + {"name": "flange_t", "type": "number", "min": 0.01, "max": 0.04, "default": 0.02, "doc": "flange thickness"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"} + ], + "bevel": "0.15*flange_t", + "shapes": [ + {"shape": "lathe", "segments": "segments", "smooth": true, "profile": [ + ["1.35*big_r", 0], ["1.35*big_r", "flange_t"], ["big_r", "flange_t"], ["big_r", "flange_t+0.15*(length-2*flange_t)"], + ["small_r", "length-flange_t-0.15*(length-2*flange_t)"], ["small_r", "length-flange_t"], ["1.9*small_r", "length-flange_t"], ["1.9*small_r", "length"]]}, + {"shape": "repeat", "count": 8, "around": "+z", "of": + {"shape": "tube", "r0": "0.077*big_r", "r1": "0.077*big_r", "length": "1.35*flange_t", "segments": 6, "at": ["1.175*big_r", 0, "0.15*flange_t"]}}, + {"shape": "repeat", "count": 4, "around": "+z", "of": + {"shape": "tube", "r0": "0.198*small_r", "r1": "0.198*small_r", "length": "1.35*flange_t", "segments": 6, "at": ["1.45*small_r", 0, "length-1.5*flange_t"]}} + ], + "sockets": [ + {"name": "big", "type": "flange", "size": "2*big_r", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "small", "type": "flange", "size": "2*small_r", "at": [0, 0, "length"], "z": "+z", "y": "+y"} + ] } ] } diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index a05ee4e..19d7920 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -1,5 +1,5 @@ """Live proof, in a background Blender, that the brokkr_kitbash rows are admitted by Brokkr as host actions and that -the mechanical kit goes through run_intent: describe, place_part for all nine parts, setObjectTransform, +the mechanical kit goes through run_intent: describe, place_part for all ten parts, setObjectTransform, assignMaterial, set_params, report, the refusals, and exportGltf. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash.py -- @@ -81,7 +81,7 @@ check("the eight kitbash rows load as host actions with no errors", not R["hostE kit = core.load_kit("mechanical") receipt, described = send("brokkr_kitbash.describe") names = [p["name"] for p in described["parts"]] if described else [] -check("describe lists nine parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 9 +check("describe lists ten parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 10 and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")]) receipt, one = send("brokkr_kitbash.describe", part="actuator") check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"] @@ -114,7 +114,7 @@ for index, name in enumerate(names): check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"] and report["sockets"] == core.socket_rows(reference.sockets), report) -check("nine parts are nine mesh objects", len(bpy.data.objects) == 9 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) +check("ten parts are ten mesh objects", len(bpy.data.objects) == 10 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) # --- set_params keeps what is not derived -------------------------------------------------------------------------------- tank = bpy.data.objects["P_tank"] @@ -225,7 +225,7 @@ receipt, alone = send("brokkr_kitbash.set_params", object_name="P_vent", params= check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"]) receipt, whole = send("brokkr_kitbash.report") -check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 9, receipt["message"]) +check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 10, receipt["message"]) # --- export --------------------------------------------------------------------------------------------------------------- receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names]) @@ -234,7 +234,7 @@ meshes = -1 if glb.is_file(): blob = glb.read_bytes() meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", [])) -check("exportGltf of all nine parts succeeds", receipt["status"] == "accepted" and meshes == 9, [receipt["message"], meshes]) +check("exportGltf of all ten parts succeeds", receipt["status"] == "accepted" and meshes == 10, [receipt["message"], meshes]) R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]} for name, report in placed.items() if report} diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 14da142..d935e1d 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -7,7 +7,7 @@ "detail": null }, { - "name": "describe lists nine parts, whole, inside a receipt", + "name": "describe lists ten parts, whole, inside a receipt", "ok": true, "detail": null }, @@ -157,7 +157,22 @@ "detail": null }, { - "name": "nine parts are nine mesh objects", + "name": "place_part reducer: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part reducer: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part reducer: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "ten parts are ten mesh objects", "ok": true, "detail": null }, @@ -302,7 +317,7 @@ "detail": null }, { - "name": "exportGltf of all nine parts succeeds", + "name": "exportGltf of all ten parts succeeds", "ok": true, "detail": null } @@ -327,16 +342,16 @@ ], "placed": { "nozzle": { - "faces": 1312, - "shells": 24, + "faces": 994, + "shells": 9, "bevel": 0.0024, "sockets": [ "mount" ] }, "tank": { - "faces": 740, - "shells": 20, + "faces": 764, + "shells": 6, "bevel": 0.00176, "sockets": [ "port_a", @@ -372,8 +387,8 @@ ] }, "pipe_fitting": { - "faces": 278, - "shells": 19, + "faces": 436, + "shells": 14, "bevel": 0.0027, "sockets": [ "a", @@ -405,6 +420,15 @@ "back", "front" ] + }, + "reducer": { + "faces": 266, + "shells": 13, + "bevel": 0.003, + "sockets": [ + "big", + "small" + ] } }, "ok": true diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index fe6aa5f..a84645c 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -282,6 +282,91 @@ class ShapeTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, "count is .*whole number from 1 to 256"): built([shape], [param("n", 0, 300, 4), param("a")], {"n": count}) + def test_lathes_are_closed_oriented_and_hold_their_volume(self): + """lathe-shape. Mutants K1 (first cap not reversed), K2 (pole triangles reversed) and K7 (a loop's closing + band dropped) break the edge census; K3 (horizontal bands smooth) the smooth flags.""" + capped = [[0.5, 0], [0.5, 0.4], [0.3, 0.4], [0.3, 1.0], [0.6, 1.0], [0.6, 1.2]] # a cap at each end, two annuli + spindle = [[0, 0], [0.5, 0.3], [0.5, 1.0], [0, 1.4]] # a pole at each end + cup = [[0, 0], [0.5, 0], [0.7, 1.0], [0.6, 1.0], [0.4, 0.1]] # a pole, then back down inside to a cap + ring = [[0.4, 0], [0.6, 0], [0.6, 0.2], [0.4, 0.2]] + for n in (3, 32): + for profile, loop, faces, flat in ((capped, False, 5 * n + 2, [1, 3]), (spindle, False, 3 * n, []), (cup, False, 4 * n + 1, [0, 2]), + (ring, True, 4 * n, [0, 2])): + b = built([{"shape": "lathe", "profile": profile, "segments": n, "smooth": True, "loop": loop}]) + joined = profile + profile[:1] if loop else profile + expected = sum(frustum(r0, r1, z1 - z0, n) for (r0, z0), (r1, z1) in zip(joined, joined[1:])) + self.assertTrue(closed_and_oriented(b), (profile, n)) + self.assertGreater(expected, 0.01) + self.assertLess(abs(signed_volume(b) - expected), 1e-9 * expected) + self.assertEqual((len(b.counts), b.shell_count), (faces, 1)) + bands = len(joined) - 1 + self.assertEqual(b.smooth.tolist(), [i not in flat for i in range(bands) for _ in range(n)] + [False] * (faces - bands * n)) + self.assertFalse(built([{"shape": "lathe", "profile": profile, "segments": n, "loop": loop}]).smooth.any()) + b = built([{"shape": "lathe", "profile": spindle, "segments": 8}]) + self.assertEqual(b.counts.tolist(), [3] * 8 + [4] * 8 + [3] * 8) + self.assertEqual((len(b.V), b.V[0].tolist(), b.V[-1].tolist()), (18, [0.0, 0.0, 0.0], [0.0, 0.0, 1.4])) + b = built([{"shape": "lathe", "profile": capped, "segments": 8, "rot": [0, 90, 0], "at": [1, 0, 0]}]) # placed as a tube is: +z turns to +x + self.assertTrue(np.allclose([b.V[:, 0].min(), b.V[:, 0].max()], [1.0, 2.2], atol=1e-12)) + self.assertEqual(b.counts.tolist(), [4] * 40 + [8, 8]) + grown = built([{"shape": "lathe", "profile": [["a", 0], ["a", "2*a"]], "segments": 8}], [param("a")], {"a": 0.5}) # expressions, and the least profile + self.assertLess(abs(signed_volume(grown) - frustum(0.5, 0.5, 1.0, 8)), 1e-12) + + def test_what_a_lathe_refuses_names_the_point(self): + """Mutants K4 (the orientation refusal dropped) and K8 (r = 0 allowed inside a profile).""" + ring = [[0.4, 0], [0.6, 0], [0.6, 0.2], [0.4, 0.2]] + lathe = lambda profile, **more: [{"shape": "lathe", "profile": profile, "segments": 8, **more}] # noqa: E731 + for shapes, message in ( + (lathe([[1, 0]]), r"shape 0 \(lathe\) profile must be an array of at least 2 \[r, z\] points"), + (lathe([[1, 0], [1, 1]], loop=True), r"profile must be an array of at least 3 \[r, z\] points \(it is a loop\)"), + (lathe("round"), r"profile must be an array of at least 2"), + (lathe([[1, 0], [1, 1, 0]]), r"profile\[1\] must be \[r, z\]"), + (lathe([[1, 0], 1]), r"profile\[1\] must be \[r, z\]"), + (lathe([[1, 0], [1, "q"]]), r"profile\[1\]\[1\]: 'q' names 'q'"), + (lathe([[1, 0], [1, 1]], loop=1), r"loop must be true or false"), + (lathe([[1, 0], [1, 1]], smooth="yes"), r"smooth must be true or false"), + (lathe([[1, 0], [1, 1]], inner0=0.5), r"shape 0 \(lathe\) has no key 'inner0'"), + (lathe([[1, 0], [-0.1, 0.5], [1, 1]]), r"profile\[1\]: r is -0\.1, below 0"), + (lathe([[1, 0], [0, 0.5], [1, 1]]), r"profile\[1\]: r is 0; only the first and last point of an open profile"), + (lathe([[0, 0], [0.6, 0], [0.6, 0.2]], loop=True), r"profile\[0\]: r is 0; only the first and last"), + (lathe([[1, 0], [1, 1], [1, 1], [0.5, 1]]), r"profile\[2\]: \[1\.0, 1\.0\] repeats the point before it"), + (lathe(ring + ring[:1], loop=True), r"profile\[0\]: \[0\.4, 0\.0\] repeats the point before it \(a loop closes itself\)"), + (lathe([[1, 1], [1, 0]]), r"shape 0 \(lathe\) profile: list it out along the bottom and up the outside"), + (lathe(ring[::-1], loop=True), r"profile: list it out along the bottom and up the outside"), + (lathe([[0, 0], [0, 1]]), r"enclose nothing \(signed area 0 in r, z\)"), + (lathe([[1, 0], [1, 1]], segments=2), r"segments is 2\.0: it must be a whole number from 3 to 128")): + with self.assertRaisesRegex(core.KitError, message): + built(shapes) + + def test_repeat_around_turns_copies_about_the_axis(self): + """repeat-around. Mutants K5 (copy k turned k*360/(count+1)) and K6 (center ignored).""" + box = {"shape": "box", "size": [0.2, 0.2, 0.2]} + for shape, expected in ( + ({"count": 4, "around": "+z", "of": {**box, "at": [1, 0, 0.5]}}, [[1, 0, 0.5], [0, 1, 0.5], [-1, 0, 0.5], [0, -1, 0.5]]), + ({"count": 4, "around": "-z", "of": {**box, "at": [1, 0, 0.5]}}, [[1, 0, 0.5], [0, -1, 0.5], [-1, 0, 0.5], [0, 1, 0.5]]), + ({"count": 4, "around": "+x", "center": [0, 1, "2*a"], "of": {**box, "at": [3, 1, 3]}}, [[3, 1, 3], [3, 0, 2], [3, 1, 1], [3, 2, 2]]), + ({"count": "n", "around": "+y", "center": [1, 0, 0], "of": {**box, "at": [1, 5, 1]}}, [[1, 5, 1], [1 + 0.75 ** 0.5, 5, -0.5], [1 - 0.75 ** 0.5, 5, -0.5]])): + b = built([{"shape": "box", "size": [1, 1, 1]}, {"shape": "repeat", **shape}], [param("a"), param("n", 1, 300, 3)]) + copies = len(expected) + self.assertEqual((b.shell_count, b.shape.tolist()), (1 + copies, [0] * 6 + [1] * 6 * copies)) + self.assertTrue(np.allclose(b.V[8:].reshape(copies, 8, 3).mean(axis=1), expected, atol=1e-12), shape) + self.assertTrue(closed_and_oriented(b)) + self.assertLess(abs(signed_volume(b) - 1.0 - 0.008 * copies), 1e-12) + turned = built([{"shape": "repeat", "count": 3, "around": "+z", "of": {"shape": "lathe", "profile": [[0.1, 0], [0.1, 1]], "segments": 8, "at": [1, 0, 0]}}]) + self.assertTrue(closed_and_oriented(turned)) + self.assertEqual((turned.shell_count, len(turned.counts)), (3, 30)) + of = {"shape": "repeat", "count": 2, "of": box} + for change, message in (({"step": [1, 0, 0], "around": "+z"}, r"shape 0 \(repeat\) takes exactly one of step .* and around"), + ({}, r"takes exactly one of step .* and around"), + ({"center": [0, 0, 0]}, r"takes exactly one of step"), + ({"step": [1, 0, 0], "center": [0, 0, 0]}, r"shape 0 \(repeat\): center goes with around, not with step"), + ({"around": "up"}, r"around must be one of \+x, -x, \+y, -y, \+z, -z"), + ({"around": ["+z"]}, r"around must be one of"), + ({"around": "+z", "center": [0, 0]}, r"center must be an array of three"), + ({"around": "+z", "of": {"shape": "repeat", "count": 2, "around": "+x", "of": box}}, r"a repeat cannot hold a repeat"), + ({"around": "+z", "count": 257}, r"count is .*whole number from 1 to 256")): + with self.assertRaisesRegex(core.KitError, message): + built([{**of, **change}]) + def test_every_face_names_its_shape(self): """What set_params carries per-face materials by: a repeat's copies share their shape's index.""" b = built([{"shape": "box", "size": [1, 1, 1]}, @@ -330,20 +415,21 @@ class ParamTests(unittest.TestCase): @unittest.skipIf(np is None, "numpy is not installed") class MechanicalKitTests(unittest.TestCase): - PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "pipe_fitting", "radiator_stack", "vent", "plate"] + PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "pipe_fitting", "radiator_stack", "vent", "plate", "reducer"] @classmethod def setUpClass(cls): cls.kit = core.load_kit("mechanical") - def test_the_kit_is_the_nine_parts_and_three_socket_types(self): + def test_the_kit_is_the_ten_parts_and_three_socket_types(self): self.assertEqual(list(self.kit["parts"]), self.PARTS) self.assertEqual({k: v["match"] for k, v in self.kit["socketTypes"].items()}, {"flange": "equal", "mount": "fits", "pivot": "equal"}) self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, { "nozzle": [("mount", "flange")], "tank": [("port_a", "flange"), ("port_b", "flange"), ("saddle", "mount")], "ribbed_cylinder": [("end_a", "flange"), ("end_b", "flange")], "strut": [("end_a", "pivot"), ("end_b", "pivot")], "actuator": [("base", "pivot"), ("rod_end", "pivot")], "pipe_fitting": [("a", "flange"), ("b", "flange"), ("c", "flange")], - "radiator_stack": [("base", "mount")], "vent": [("back", "mount")], "plate": [("back", "mount"), ("front", "mount")]}) + "radiator_stack": [("base", "mount")], "vent": [("back", "mount")], "plate": [("back", "mount"), ("front", "mount")], + "reducer": [("big", "flange"), ("small", "flange")]}) def test_every_part_holds_everywhere(self): """kit-parts-hold-everywhere. Mutant M8 (flip one socket's z in the kit): no face at that origin faces it.""" @@ -451,7 +537,7 @@ class MateTests(unittest.TestCase): self.assertEqual(core.FLIP.tolist(), [[-1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]) def test_what_may_mate(self): - """mate-refusal. Mutants A3 (fits reversed) and A4 (equal at 10 percent).""" + """mate-refusal. Mutants A3 (fits reversed), A4 (equal at 10 percent) and K10 (the equal rule's slack 5e-3).""" types = self.kit["socketTypes"] socket = lambda name, kind, size: {"name": name, "type": kind, "size": size, "matrix": np.eye(4)} # noqa: E731 self.assertRegex(core.mate_refusal(types, socket("p", "flange", 0.1), socket("c", "mount", 0.1)), @@ -462,19 +548,47 @@ class MateTests(unittest.TestCase): self.assertIsNone(core.mate_refusal(types, socket("p", kind, 0.2), socket("c", kind, 0.198))) self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", kind, 100.0), socket("c", kind, 98.99))) self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", kind, 98.99), socket("c", kind, 100.0))) + # equal-slack: past the 1 percent by 2.2e-6 of it. Shipped slack 1e-9; least mutant 5e-3 (K10); separation 2200 each side + self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", kind, 100.0), socket("c", kind, 100.0 - 1.0000022))) + self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", kind, 100.0 - 1.0000022), socket("c", kind, 100.0))) self.assertIsNone(core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3))) # fits: the child at most the parent self.assertIsNone(core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.1))) self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3 + 1e-6))) self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.1), socket("c", "mount", 0.3))) + self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3 * (1 + 2.2e-6)))) def test_the_kit_s_own_flanges_do_not_meet_everywhere(self): - """A chamber flange (ribbed_cylinder, 0.16 and up) and the plumbing (pipe_fitting, 0.14 and down) never mate.""" + """A chamber flange (ribbed_cylinder, 0.16 and up) and the plumbing (pipe_fitting, 0.14 and down) never mate + face to face.""" parts = self.kit["parts"] drum = core.build(parts["ribbed_cylinder"], {"radius": 0.08}).sockets[1] pipe = core.build(parts["pipe_fitting"], {"pipe_r": 0.07}).sockets[0] self.assertEqual((drum["size"], pipe["size"]), (0.16, 0.14)) self.assertIn("mate at equal sizes", core.mate_refusal(self.kit["socketTypes"], drum, pipe)) + def test_a_reducer_bridges_chamber_and_plumbing(self): + """reducer-bridges, at the ends of each range. Mutant K16 (the reducer's sockets swapped end for end): each + socket then lies on the other flange's face.""" + parts, types = self.kit["parts"], self.kit["socketTypes"] + for big_r, small_r in ((0.08, 0.024), (0.3, 0.07), (0.08, 0.07), (0.3, 0.024)): + reducer = core.build(parts["reducer"], {"big_r": big_r, "small_r": small_r}) + big, small = reducer.sockets + self.assertEqual((big["name"], small["name"], big["size"], small["size"]), ("big", "small", 2 * big_r, 2 * small_r)) + drum = core.build(parts["ribbed_cylinder"], {"radius": big_r}).sockets[1] + tee = core.build(parts["pipe_fitting"], {"pipe_r": max(small_r, 0.03)}).sockets[0] + port = core.build(parts["tank"], {"radius": {0.024: 0.12, 0.07: 0.35}[small_r]}).sockets[1] + self.assertIsNone(core.mate_refusal(types, drum, big)) + self.assertIsNone(core.mate_refusal(types, big, drum)) + self.assertIsNone(core.mate_refusal(types, port, small)) + if small_r >= 0.03: + self.assertIsNone(core.mate_refusal(types, small, tee)) + for a, b in ((big, small), (small, big), (drum, small), (tee, big), (port, big)): + self.assertIn("mate at equal sizes", core.mate_refusal(types, a, b)) + for socket, flange in ((big, 1.35 * big_r), (small, 1.9 * small_r)): # the face a socket lies on is its own flange's + face = reducer.V[np.abs(reducer.V[:, 2] - socket["matrix"][2, 3]) < 1e-12] + self.assertAlmostEqual(float(np.linalg.norm(face[:, :2], axis=1).max()), flange, places=12) + self.assertEqual([s["matrix"][:3, 2].tolist() for s in reducer.sockets], [[0.0, 0.0, -1.0], [0.0, 0.0, 1.0]]) + def test_a_joint_is_two_named_sockets_of_one_kit(self): """The cross-kit refusal (one kit ships, so no scene can show it) and the unknown-socket refusals.""" parts = self.kit["parts"] @@ -548,7 +662,8 @@ class OwnershipTests(unittest.TestCase): PACKAGE = (r"\beval\(|\bexec\(|\bcompile\(", r"brokkr_bridge", r"\bsolver\s*=\s*[\"']MANIFOLD|\buse_self\s*=\s*False", # a boolean is Exact with self-intersection, nothing else r"hide_render|hide_viewport|display_type", # a cutter's visibility is setObjectVisibility's - r"kit_parent_name|kit_parent\b|matrix_world_stored") # obj.parent has no second owner + r"kit_parent_name|kit_parent\b|matrix_world_stored", # obj.parent has no second owner + r"SCREW|\"ARRAY\"|spin\(") # core makes every vertex: no modifier or bmesh op makes kit geometry CORE = r"^import bpy|^from bpy|^import bmesh" SCHEMAS = r"brokkr\.kit\.v0" @@ -576,8 +691,18 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(source.count("evaluated_of("), 3) self.assertEqual(source.count("to_mesh("), 1) + def test_only_attach_writes_the_roll(self): + """kit_roll is the one statement of a connection's roll: set_params and the reports read it and never write it back.""" + source = self.sources()["__init__.py"] + writes = re.findall(r'[^\n]*(?:\[ROLL\]|\["kit_roll"\])\s*=(?!=)[^\n]*', source) + self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated"]) + self.assertIn(writes[0], source.split("class BROKKR_KITBASH_OT_attach")[1].split("class BROKKR_KITBASH_OT_")[0]) + def test_the_patterns_bite(self): - planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name') + planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name', + 'obj.modifiers.new("Turn", "SCREW")') + for text in ('obj.modifiers.new("Bolts", "ARRAY")', "bmesh.ops.spin(bm, geom=geom)"): + self.assertIsNotNone(re.search(self.PACKAGE[5], text)) self.assertEqual(len(planted), len(self.PACKAGE)) for pattern, text in zip(self.PACKAGE, planted): self.assertIsNotNone(re.search(pattern, text)) From ea426d58a6923b1a6809a5e7e762a8b222d0610e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 17:39:17 +0100 Subject: [PATCH 074/223] brokkr_kitbash: a roll that is not a number does not hold; apply leaves no face outside the slots link() reads a hand-written kit_roll that is not a finite number as roll None: the report says roll null and holds false, and set_params on the child or its parent refuses it and leaves the property as written. apply gives faces a cutter made from an empty slot of its own the part's first slot. kitbash_assembly.py: the tank is cut where four shells overlap (the barrel is one shell now, so a box through it alone no longer tells self-intersection from none), a tee is cut with no non-manifold edge, a child moved 3.2e-4 m reads holds false, and apply keeps a part's own empty last slot. Closes the three Low findings of verdict cut-chassis-kit-assembly.s1. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 23 +++-- .../blender/tests/live/kitbash_assembly.py | 86 ++++++++++++++++--- .../tests/live/kitbash_assembly.result.json | 80 ++++++++++++++++- 3 files changed, 166 insertions(+), 23 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 5d8da04..4b1ada6 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -110,11 +110,12 @@ def built_part(obj): def link(obj): """The connection a child states, (its socket, the parent's socket, roll in degrees), or None. The parent is - obj.parent and is stored nowhere else. attach, set_params, detach and every report read it here.""" + obj.parent and is stored nowhere else. attach, set_params, detach and every report read it here. A kit_roll + that is not a finite number (written by hand) is roll None: the connection is stated and cannot hold.""" if SOCKET not in obj: return None roll = obj.get(ROLL, 0.0) - return str(obj[SOCKET]), str(obj.get(PARENT_SOCKET, "")), float(roll) if core.finite(roll) else 0.0 + return str(obj[SOCKET]), str(obj.get(PARENT_SOCKET, "")), float(roll) if core.finite(roll) else None def attached(obj) -> list: @@ -124,7 +125,10 @@ def attached(obj) -> list: def mated(parent, parent_part, parent_built, child, child_part, child_built, stated): """(parent socket, child socket) of the connection `stated` between two built parts, or a refusal that names - it: parts of two kits, a socket name a part does not have, or sockets core.mate_refusal will not mate.""" + it: a roll that is not a number, parts of two kits, a socket name a part does not have, or sockets + core.mate_refusal will not mate.""" + if stated[2] is None: + raise Refused(f"{child.name!r} on {parent.name!r}: its {ROLL} is not a number: detach it and attach it again; nothing changed.") try: sockets = core.joint(parent_part, parent_built, stated[1], child_part, child_built, stated[0]) refusal = core.mate_refusal(core.load_kit(parent_part["kit"])["socketTypes"], *sockets) @@ -143,15 +147,16 @@ def seat(child, basis) -> None: def connection_report(obj, part, built): """None for a part that states no connection, else what it states and whether it holds: the parent is a part - of the same kit, both sockets exist, the parent inverse is the identity and the child stands within HELD of - core.mate. A child moved or re-parented by another action reads holds false until set_params seats it again.""" + of the same kit, both sockets exist, the roll is a number, the parent inverse is the identity and the child + stands within HELD of core.mate. A child moved or re-parented by another action reads holds false until + set_params seats it again.""" stated = link(obj) if stated is None: return None row = {"parent": obj.parent.name if obj.parent else None, "socket": stated[0], "parentSocket": stated[1], - "roll": round(stated[2], 6), "residual": None, "holds": False} + "roll": None if stated[2] is None else round(stated[2], 6), "residual": None, "holds": False} try: - if obj.parent is None: + if obj.parent is None or stated[2] is None: return row parent_part, parent_built = built_part(obj.parent) parent_socket, socket = core.joint(parent_part, parent_built, stated[1], part, built, stated[0]) @@ -412,6 +417,10 @@ class BROKKR_KITBASH_OT_apply(PolishOperator): baked = bpy.data.meshes.new_from_object(evaluated, preserve_all_data_layers=True, depsgraph=depsgraph) while len(baked.materials) > slots and baked.materials[len(baked.materials) - 1] is None: baked.materials.pop() # a Boolean gives a part that had no material slot one empty slot + index = np.zeros(len(baked.polygons), dtype=np.int32) + baked.polygons.foreach_get("material_index", index) + if (index < 0).any(): # faces from a cutter's empty slot: slot 0, as faces from a cutter with no material + baked.polygons.foreach_set("material_index", np.maximum(index, 0)) old, name = obj.data, obj.data.name obj.data = baked obj.modifiers.clear() diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 2bb8481..a9f342e 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -1,15 +1,17 @@ """Live proof, in a background Blender, of brokkr_kitbash assembly through run_intent: attach and its refusals, -set_params seating a part and the parts attached to it again, drift and how it is cleared, detach, boolean (Exact, -self-intersection on, above the Bevel) on two targets, and apply. Not part of the unittest run: it needs Blender. +set_params seating a part and the parts attached to it again, drift and how it is cleared, a roll that is not a +number, detach, boolean (Exact, self-intersection on, above the Bevel), and apply with its material slots. Not part +of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_assembly.py -- Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses without them). is an absolute path; writes .result.json and exits 1 when a check failed. -An Exact Boolean costs about a second a part and evaluation, so only two parts are ever cut here (the tank and -one plate). 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. +An Exact Boolean costs a few tenths of a second a part and evaluation (docs/kitbash.md), so few parts are cut +here: the tank, a tee and three plates. Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the +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 @@ -69,9 +71,14 @@ ROLL = 2.2e-2 # Largest entry of matrix_world after detach minus before. Shipped worst 1.5e-08; least claimed mutant 2.9 # (A10, detach drops the world matrix); separation 1.9e8. KEPT = 2.1e-4 -# Cubic metres left of the 1.8 m tank (its 20 shells as one solid) with a 0.3 m box cut from its wall. Shipped -# 0.2539; least claimed mutant 0.0079 (A11, self-intersection off: overlapping shells cancel); separation 32. -CUT = 0.045 +# Cubic metres left of the 1.8 m tank (its 6 shells as one solid) with a 0.3 m box cut through its lower cradle, the +# pad, a strap and the barrel's wall, where four shells overlap. Shipped 0.2508; least claimed mutant 0.0060 (K15, self- +# intersection off: overlapping shells cancel); separation 6.5 each side. A box through the barrel alone no longer +# tells the two apart: the barrel is one shell. +CUT = 0.039 +# Metres an attached child is moved to read holds false. HELD is a rule, 1e-5; least claimed mutant 1e-2 (K12); +# the geometric mean of the two, separation 32 each side. +NUDGE = 3.2e-4 def check(name, ok, detail=None): @@ -137,7 +144,7 @@ def held(report): 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: o[k] for k in sorted(o.keys()) if k.startswith("kit_")}, [(m.name, m.type) for m in o.modifiers], + {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) @@ -298,6 +305,27 @@ check("a parent inverse that is not the identity does not hold, wherever the chi send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") check("and set_params on the parent writes the identity back", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)), connection("Nozzle")) +push = np.array(tee.matrix_world)[:3, :3].T @ [NUDGE, 0.0, 0.0] # NUDGE along the world's x, in the tee's frame +send("setObjectTransform", targetObjectName="Nozzle", location=(np.array(nozzle.matrix_basis)[:3, 3] + push).tolist()) +found = connection("Nozzle") or {} +check("a child moved by NUDGE does not hold, and its residual is the move", found.get("holds") is False + and abs(reading("nudged", found.get("residual") or 0.0) - NUDGE) < 0.1 * NUDGE, found) +send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") +check("and set_params on its parent seats it again", holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) +for written in (float("nan"), "x"): # a kit_roll nobody's attach wrote + nozzle["kit_roll"] = written + found = connection("Nozzle") or {} + check(f"a kit_roll of {written!r} reports roll null and does not hold", found.get("roll", 0.0) is None and found.get("holds") is False + and found.get("residual", 0.0) is None and found.get("parent") == "Tee", found) + refused(f"set_params on a child whose kit_roll is {written!r}", "brokkr_kitbash.set_params", {"object_name": "Nozzle", "params": "exit_r=0.3"}, + "'Nozzle' on 'Tee': its kit_roll is not a number: detach it and attach it again") + refused(f"set_params on the parent of a child whose kit_roll is {written!r}", "brokkr_kitbash.set_params", {"object_name": "Tee", "params": "run=0.6"}, + "'Nozzle' on 'Tee': its kit_roll is not a number") +receipt, report = send("brokkr_kitbash.detach", object_name="Nozzle") +check("detach clears a roll that is not a number", receipt["status"] == "accepted" and nozzle.parent is None and report and report["connection"] is None + and "kit_roll" not in nozzle, [receipt["message"], dict(nozzle.items())]) +receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0) +check("and the nozzle attaches again", receipt["status"] == "accepted" and held(report) and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) send("setObjectParent", targetObjectName="Spare", parentObjectName="") found = connection("Spare") check("setObjectParent clearing an attached child's parent shows as a connection with no parent", found and found == {**found, "parent": None, "holds": False, "residual": None}, found) @@ -325,9 +353,9 @@ check("the freed tee attaches by another socket to the tank's other port", holds send("assignMaterial", targetObjectName="Tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) send("assignMaterial", targetObjectName="Tank", materialName="Strap Steel", color=[0.2, 0.2, 0.2]) tank_built = core.build(kit["parts"]["tank"], json.loads(tank["kit_params"])) -STRAPS = sorted(set(tank_built.shape.tolist()))[-1] +STRAPS = 1 # the tank's second shape: the repeat of two straps tank.data.polygons.foreach_set("material_index", np.where(tank_built.shape == STRAPS, 1, 0).astype(np.int32)) -side = np.array(tank.matrix_world) @ [0.24, 0.0, 0.9, 1.0] # on the barrel's wall, halfway along +side = np.array(tank.matrix_world) @ [0.0, -0.22, 0.4564, 1.0] # under the barrel at the lower cradle: cradle, pad, strap and wall send("createObject", objectType="MESH", name="Box", location=side[:3].tolist(), size=0.3) box = bpy.data.objects["Box"] box_was = (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) @@ -340,7 +368,8 @@ check("boolean adds a Boolean modifier above the Bevel: Exact, self-intersection [receipt["message"], [m.name for m in tank.modifiers]]) shown, shown_slots = evaluated(tank) check("boolean reports the evaluated mesh, with less volume than the uncut tank and no non-manifold edge", cut and cut["evaluated"] == shown - and CUT < cut["evaluated"]["volume"] < raw["volume"] - 0.005 and cut["evaluated"]["nonManifoldEdges"] == 0 + and CUT < reading("cut", cut["evaluated"]["volume"]) < raw["volume"] - 0.005 and cut["evaluated"]["nonManifoldEdges"] == 0 + and int(np.count_nonzero(tank_built.shape == STRAPS)) == 2 * 4 * 24 and cut["booleans"] == [{"cutter": "Box", "operation": "DIFFERENCE"}] and cut["faces"] == len(tank.data.polygons) == raw["faces"], [cut and cut["evaluated"], shown, raw]) R["tank"] = {"raw": raw, "cut": cut and cut["evaluated"]} @@ -437,6 +466,39 @@ big = place("Big", "vent", "width=0.8; height=0.6") refused("a part larger than the seat", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Plate", "parent_socket": "back"}, "are mount sockets, where the child fits the parent: it is larger") +# --- a tee is one solid under the Boolean ----------------------------------------------------------------------------------------- +place("Cross", "pipe_fitting", location=[0.0, -6.0, 0.0]) # pipe_r 0.05, the default +send("createObject", objectType="MESH", name="Bar", location=[0.0, -6.0, 0.0], size=1.0) +send("setObjectTransform", targetObjectName="Bar", scale=[0.3, 3.0, 0.3]) +receipt, cut = send("brokkr_kitbash.boolean", object_name="Cross", cutter="Bar") +R["tee"] = cut and cut["evaluated"] +check("a tee with a box cut from it has no non-manifold edge: its branch hub is narrower than its run hub", receipt["status"] == "accepted" and cut + and cut["evaluated"]["nonManifoldEdges"] == 0 and 0.004 < cut["evaluated"]["volume"] < 0.008, [receipt["message"], cut and cut["evaluated"]]) + +# --- apply and empty material slots ----------------------------------------------------------------------------------------------- +keeper = place("Keeper", "plate", location=[0.0, -9.0, 0.0]) +send("assignMaterial", targetObjectName="Keeper", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) +keeper.data.materials.append(None) # an empty last slot the part was given +send("createObject", objectType="MESH", name="Bare", location=[0.1, -9.0, 0.0], size=0.1) +send("brokkr_kitbash.boolean", object_name="Keeper", cutter="Bare") +receipt, baked = send("brokkr_kitbash.apply", object_name="Keeper") +check("apply keeps a part's own empty last slot when the cutter has no material", receipt["status"] == "accepted" + and [m and m.name for m in keeper.data.materials] == ["Plate Paint", None] and len(keeper.material_slots) == 2, + [receipt["message"], [m and m.name for m in keeper.data.materials]]) +gapped = place("Gapped", "plate", location=[0.0, -12.0, 0.0]) +send("assignMaterial", targetObjectName="Gapped", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) +send("createObject", objectType="MESH", name="Gap", location=[0.1, -12.0, 0.0], size=0.1) +gap = bpy.data.objects["Gap"] +gap.data.materials.append(None) # the cutter's faces are in an empty first slot +gap.data.materials.append(bpy.data.materials["Boss Brass"]) +send("brokkr_kitbash.boolean", object_name="Gapped", cutter="Gap") +receipt, baked = send("brokkr_kitbash.apply", object_name="Gapped") +used = np.zeros(len(gapped.data.polygons), dtype=np.int32) +gapped.data.polygons.foreach_get("material_index", used) +check("apply leaves no face outside the material slots when a cutter's first slot is empty", receipt["status"] == "accepted" and len(used) > 44 + and used.min() >= 0 and used.max() < len(gapped.data.materials) and not gapped.data.validate_material_indices() and not gapped.data.validate(verbose=False), + [receipt["message"], int(used.min()), int(used.max()), [m and m.name for m in gapped.data.materials]]) + 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") diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index 3be8cda..e51d21b 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -171,6 +171,56 @@ "ok": true, "detail": null }, + { + "name": "a child moved by NUDGE does not hold, and its residual is the move", + "ok": true, + "detail": null + }, + { + "name": "and set_params on its parent seats it again", + "ok": true, + "detail": null + }, + { + "name": "a kit_roll of nan reports roll null and does not hold", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a child whose kit_roll is nan", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on the parent of a child whose kit_roll is nan", + "ok": true, + "detail": null + }, + { + "name": "a kit_roll of 'x' reports roll null and does not hold", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a child whose kit_roll is 'x'", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on the parent of a child whose kit_roll is 'x'", + "ok": true, + "detail": null + }, + { + "name": "detach clears a roll that is not a number", + "ok": true, + "detail": null + }, + { + "name": "and the nozzle attaches again", + "ok": true, + "detail": null + }, { "name": "setObjectParent clearing an attached child's parent shows as a connection with no parent", "ok": true, @@ -330,24 +380,41 @@ "name": "refused, scene unchanged: a part larger than the seat", "ok": true, "detail": null + }, + { + "name": "a tee with a box cut from it has no non-manifold edge: its branch hub is narrower than its run hub", + "ok": true, + "detail": null + }, + { + "name": "apply keeps a part's own empty last slot when the cutter has no material", + "ok": true, + "detail": null + }, + { + "name": "apply leaves no face outside the material slots when a cutter's first slot is empty", + "ok": true, + "detail": null } ], "hostErrors": [], "readings": { "carried": 2.7e-07, + "cut": 0.25, "kept": 1.5e-08, + "nudged": 0.00032, "roll": 6.3e-06, "seated": 1.5e-07 }, "tank": { "raw": { - "faces": 740, - "volume": 0.264901065, + "faces": 764, + "volume": 0.264485537, "nonManifoldEdges": 0 }, "cut": { - "faces": 2337, - "volume": 0.25387923, + "faces": 2250, + "volume": 0.250847643, "nonManifoldEdges": 0 } }, @@ -368,5 +435,10 @@ "nonManifoldEdges": 0 } }, + "tee": { + "faces": 1661, + "volume": 0.006031088, + "nonManifoldEdges": 0 + }, "ok": true } \ No newline at end of file From c7d2a2ba22538e1e621f21246310917645a881c6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 17:39:17 +0100 Subject: [PATCH 075/223] docs: kitbash.md: lathe and repeat about an axis, the reducer, Boolean cost as measured Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 61 +++++++++++++++++++++++--------- 1 file changed, 44 insertions(+), 17 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index d5c5d00..814e7da 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -72,7 +72,23 @@ then y, then z, about the shape's own origin) place it, rotation first; both def | --- | --- | --- | | `tube` | `r0`, `r1`, `length`, `segments`, `inner0`?, `inner1`?, `smooth`? | A frustum on +z from radius `r0` at z=0 to `r1` at z=`length`, with n-gon caps. Inner radii above 0 make it hollow (an inner wall and two flat end rings); they are both above 0 or both 0, and below the outer radius. `segments` is 3 to 128. `smooth` shades the walls smooth; caps stay flat. | | `box` | `size` | A box centred on its origin; every size above 0. | -| `repeat` | `count`, `step`, `of` | `count` copies (1 to 256) of one tube or box at `k * step`, k from 0. A repeat cannot hold a repeat. | +| `lathe` | `profile`, `segments`, `loop`?, `smooth`? | A profile of `[r, z]` points revolved about +z into one shell, a ring of `segments` (3 to 128) vertices per point. An open profile's end on the axis (`r` exactly 0) is a pole; an end off the axis gets a flat n-gon cap. With `loop` true the last point joins the first and there are no caps (a ring: 3 points or more). `smooth` shades the walls smooth; a band between two points of one `z` (an annulus) and the caps stay flat. | +| `repeat` | `count`, `of`, and `step` or `around` with `center`? | `count` copies (1 to 256) of one tube, box or lathe: at `k * step`, k from 0, or turned `k * 360 / count` degrees, right-handed, about the axis `around` (one of `+x -x +y -y +z -z`) through `center` (default the origin). Exactly one of `step` and `around`. A repeat cannot hold a repeat. | + +A lathe's profile is listed out along the bottom and up the outside, as this flanged stub is: a cap of radius 0.1 +at z=0, the flange's rim, its top face, the pipe, and a cap of radius 0.05 at z=0.3. + +```json +{"shape": "lathe", "segments": 24, "smooth": true, + "profile": [[0.1, 0], [0.1, 0.02], [0.05, 0.02], [0.05, 0.3]]} +``` + +The rule behind "up the outside": the profile, closed down the axis from its last `z` to its first (a loop closes +itself), has positive area in (r, z). A profile listed the other way is refused, and so are a negative `r`, an +`r` of 0 anywhere but an open profile's two ends, and a point that repeats the one before it. A profile may turn +back down inside itself (a bell's inner wall); one that crosses itself is not caught, and builds a shell that is +not a solid. A turned part with many steps is one lathe, and so one shell, where a stack of tubes is one shell +each: a Boolean on it costs less ("Assembling parts"). Shells may overlap (a pad that runs into a tank), and a part is then not one solid: reports give the shell count. @@ -129,25 +145,32 @@ 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 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` refuses it: `detach` clears what is left. -`detach` keeps the part where it stands in the world and leaves the parts attached to it attached. +for; `holds` is true when the parent is a kit part of the same kit, 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` +refuses it: `detach` clears what is left. +A `kit_roll` that is not a finite number (only a hand can write one) reads `roll` `null` and `holds` false, and +`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 many overlapping closed shells, and the faster solvers -give wrong solids for those (the 1.8 m tank minus a box keeps 0.254 m3 with self-intersection and 0.008 m3 -without). That costs about a second per part each time the part is evaluated (0.3 s for a pipe fitting, 1.5 s -for a tank, on Blender 5.3), so keep live booleans few and `apply` them when the shape is settled. `boolean` +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: on Blender 5.3 a box cut from a part at its defaults takes +0.51 s for the tank (6 shells; 1.53 s when it was 20), 0.40 s for the nozzle (9 shells; 1.25 s at 24) and 0.24 s +for a pipe fitting (14 shells; 0.31 s at 19), each time the part 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. **`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, followed by any a cutter brought. A baked part +and `kit_baked` is set. 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 @@ -224,7 +247,7 @@ file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the ## The mechanical kit -`kits/mechanical.v0.json`: nine parts, each along +z, with socket types `flange` (equal), `mount` (fits) and +`kits/mechanical.v0.json`: ten parts, each along +z, with socket types `flange` (equal), `mount` (fits) and `pivot` (equal). | part | params | sockets | @@ -238,15 +261,19 @@ file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the | `radiator_stack` | `fins`, `fin_w`, `fin_h`, `fin_t`, `pitch`, `segments` | `base` (mount) | | `vent` | `width`, `height`, `depth`, `slats`, `slat_t`, `tilt` | `back` (mount) | | `plate` | `width`, `height`, `thickness` | `back`, `front` (mount) | +| `reducer` | `big_r`, `small_r`, `length`, `flange_t`, `segments` | `big`, `small` (flange) | `describe` gives the bounds and docs. Which flanges can meet follows from the sizes: a tank port is `0.4*radius` (0.048 to 0.14), a pipe fitting's three faces `2*pipe_r` (0.06 to 0.14), a nozzle's mount `2*throat_r` (0.08 to 0.24), and a ribbed cylinder's ends -`2*radius` (0.16 to 0.6). So tanks, fittings and nozzles plumb together, and a ribbed cylinder takes only a -nozzle (throat 0.08 and up) or another ribbed cylinder: its smallest flange is larger than the largest pipe. -Struts and actuators pin together when `0.6*width` equals `0.9*body_r`. Mounts (`fits`) take any part whose -seat is no larger than theirs. +`2*radius` (0.16 to 0.6). So tanks, fittings and nozzles plumb together, and a ribbed cylinder takes a nozzle +(throat 0.08 and up) or another ribbed cylinder face to face: its smallest flange is larger than the largest +pipe. A reducer joins the two: its `big` face is `2*big_r` (0.16 to 0.6, a ribbed cylinder's whole range) and +its `small` face `2*small_r` (0.048 to 0.14, the tank ports' and the fittings'), so a chamber hangs in a tank's +tree as tank, tee, reducer, ribbed cylinder, nozzle. Struts and actuators pin together when `0.6*width` equals +`0.9*body_r`; both ends of each lie on its own axis, so pinned parts chain in a line. Mounts (`fits`) take any +part whose seat is no larger than theirs. ## Adding a part or a kit @@ -260,7 +287,7 @@ python -m unittest discover -s surfaces/blender/tests -p "test_kitbash.py" -v 16 seeded draws, and checks that every shell is closed and wound outward, every socket frame is right-handed and 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_nine_parts_and_three_socket_types`. +part of `mechanical` also joins the part and socket list in `test_the_kit_is_the_ten_parts_and_three_socket_types`. `MateTests` covers the mate arithmetic and what may mate. 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, boolean and apply). From d1d0dc7605fcb10ba5eed34644a11519ee134c30 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 18:56:56 +0100 Subject: [PATCH 076/223] brokkr_kitbash: sharp lathe points; a flat profile is refused to a tolerance; pins for the lip and the apply clamp A lathe profile point may be [r, z, "sharp"]: Built.sharp lists the ring edges of the marked points in every copy, and write_mesh sets sharp_edge on exactly those edges. check_kit refuses any other third item, a fourth, and a mark at an open profile's end. The reducer's two cone rings are sharp. _lathe refuses a closing area at or below FLAT (5.1e-10) of the square of the profile's largest coordinate, so a constant-z profile is refused whatever its digits (shipped least 6.1e-3, float noise 4.3e-17). test_no_lathe_profile_crosses_itself walks every lathe of the kit at every corner of its params: the nozzle lip fix is pinned. kitbash_assembly.py gives the Gap cutter two brass faces and asks that each face keeps its own slot. kitbash.md: the reducer mates a fitting only from small_r 0.03, and Boolean cost as ratios plus the times read through the add-on. Takes the five Low findings of verdict cut-kit-shape-vocabulary.s1 (cut kit-joints). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 8 ++- surfaces/blender/brokkr_kitbash/core.py | 57 +++++++++++----- .../brokkr_kitbash/kits/mechanical.v0.json | 4 +- surfaces/blender/docs/kitbash.md | 36 +++++++--- surfaces/blender/tests/live/kitbash.py | 15 ++++ .../blender/tests/live/kitbash.result.json | 55 +++++++++++++++ .../blender/tests/live/kitbash_assembly.py | 7 ++ .../tests/live/kitbash_assembly.result.json | 5 ++ surfaces/blender/tests/test_kitbash.py | 68 ++++++++++++++++++- 9 files changed, 224 insertions(+), 31 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 4b1ada6..5f77073 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -59,7 +59,8 @@ def kit_work(work): def write_mesh(mesh, built) -> None: - """The built part into an empty mesh datablock: vertices, n-gon faces, and flat shading on every face not marked smooth.""" + """The built part into an empty mesh datablock: vertices, n-gon faces, flat shading on every face not marked + smooth, and sharp_edge on exactly the edges built.sharp lists.""" mesh.vertices.add(len(built.V)) mesh.vertices.foreach_set("co", built.V.astype(np.float32).ravel()) mesh.loops.add(len(built.faces)) @@ -69,6 +70,11 @@ def write_mesh(mesh, built) -> None: sharp = mesh.attributes.get("sharp_face") or mesh.attributes.new("sharp_face", "BOOLEAN", "FACE") sharp.data.foreach_set("value", ~built.smooth) mesh.update(calc_edges=True) + ends = np.zeros(2 * len(mesh.edges), dtype=np.int32) + mesh.edges.foreach_get("vertices", ends) + key = lambda pairs: pairs.min(axis=1).astype(np.int64) * len(built.V) + pairs.max(axis=1) # noqa: E731 + crease = mesh.attributes.get("sharp_edge") or mesh.attributes.new("sharp_edge", "BOOLEAN", "EDGE") + crease.data.foreach_set("value", np.isin(key(ends.reshape(-1, 2)), key(built.sharp))) def sync_bevel(obj, width: float) -> None: diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 0df5aef..489bac0 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -3,14 +3,16 @@ 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 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. An expression is parsed with ast.parse and walked against a +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 whitelist; nothing in a kit is ever run as Python. kit = load_kit("mechanical") - built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, shell_count, sockets + built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, sharp, shell_count, sockets Two sockets mate through mate (the child's matrix under its parent), mate_refusal (what may mate) and residual -(how far a placed child stands from its mate). +(how far a placed child stands from its mate). 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. """ @@ -223,11 +225,15 @@ def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict: profile = shape["profile"] if not isinstance(profile, list) or len(profile) < least: raise KitError(f"{where} profile must be an array of at least {least} [r, z] points{' (it is a loop)' if made['loop'] else ''}") - made["profile"] = [] + made["profile"], made["sharp"] = [], [] for i, point in enumerate(profile): - if not isinstance(point, list) or len(point) != 2: - raise KitError(f"{where} profile[{i}] must be [r, z]: two numbers or expressions") - made["profile"].append([parse(value, names, f"{where} profile[{i}][{c}]") for c, value in enumerate(point)]) + if not isinstance(point, list) or len(point) not in (2, 3) or (len(point) == 3 and point[2] != "sharp"): + raise KitError(f"{where} profile[{i}] must be [r, z] or [r, z, \"sharp\"]: two numbers or expressions, and the mark") + if len(point) == 3 and not made["loop"] and i in (0, len(profile) - 1): + raise KitError(f"{where} profile[{i}] is marked sharp at an end of an open profile: an end is a flat cap or a pole, " + "and has no ring to crease") + made["profile"].append([parse(value, names, f"{where} profile[{i}][{c}]") for c, value in enumerate(point[:2])]) + made["sharp"].append(len(point) == 3) return made for key in ("r0", "r1", "length"): made[key] = parse(shape[key], names, f"{where} {key}") @@ -388,7 +394,9 @@ def resolve_params(part: dict, given: dict, base: dict | None = None) -> dict: class Built(NamedTuple): """A part at given params, in the part's frame, metres. Face i has counts[i] corners, listed in order in faces (quads, a lathe's triangles at a pole, and n-gon caps, wound outward); smooth[i] marks the walls to shade smooth; shape[i] is the index, - in the part's shapes list, of the shape the face belongs to (every copy of a repeat shares one). Each socket is + in the part's shapes list, of the shape the face belongs to (every copy of a repeat shares one). sharp is an + (E, 2) array of vertex index pairs: the edges shaded as a crease, which are the rings of the lathe profile points + marked "sharp", in every copy. Each socket is {'name', 'type', 'size', 'matrix'} with matrix the 4x4 frame: column 2 the outward normal, column 1 up, column 0 = y cross z, column 3 the origin.""" V: np.ndarray @@ -396,6 +404,7 @@ class Built(NamedTuple): counts: np.ndarray smooth: np.ndarray shape: np.ndarray + sharp: np.ndarray shell_count: int sockets: list bevel: float @@ -448,14 +457,24 @@ def _tube(shape: dict, env): faces = np.concatenate([side.ravel(), k[::-1], n + k]) counts = np.concatenate([np.full(n, 4), [n, n]]) smooth = np.concatenate([np.full(n, shape["smooth"]), [False, False]]) - return V, faces, counts, smooth + return V, faces, counts, smooth, NO_SHARP + + +NO_SHARP = np.zeros((0, 2), dtype=np.int64) +# A lathe profile encloses nothing when its closing polygon's area is at most FLAT times the square of its largest +# coordinate. Shipped least 6.1e-3 (the tank's strap, over every lathe of the kit at each corner of its part's params +# and 16 draws); the largest a flat profile reads through float rounding 4.3e-17 (the 266 constant-z profiles among +# 3000 random ones of three decimals); FLAT is their geometric mean, separation 1.2e7 each side +# (lodur:ruling:deterministic-bound-margin). +FLAT = 5.1e-10 def _lathe(shape: dict, env): """A profile of [r, z] points revolved about +z, one ring per point. Open: an end on the axis (r exactly 0) is a pole and the band to it triangles; an end off the axis gets a flat n-gon cap. Loop: the last point joins the first. The profile is listed out along the bottom and up the outside (its closing polygon, down the axis for an - open one, has positive area in (r, z)), which makes every band and cap wind as a tube's.""" + open one, has positive area in (r, z)), which makes every band and cap wind as a tube's. The fifth array returned + is the ring edges of the points marked sharp.""" where = shape["where"] P = np.array([[r.value(env), z.value(env)] for r, z in shape["profile"]]) n = _whole(shape["segments"], env, SEGMENTS) @@ -470,7 +489,7 @@ def _lathe(shape: dict, env): ring = P if loop else np.vstack([P, [[0.0, P[last, 1]], [0.0, P[0, 1]]]]) after = np.roll(ring, -1, axis=0) area = 0.5 * float((ring[:, 0] * after[:, 1] - after[:, 0] * ring[:, 1]).sum()) - if not area > 0: + if not area > FLAT * float(np.abs(P).max()) ** 2: raise KitError(f"{where} profile: list it out along the bottom and up the outside; these points run the other way or enclose nothing " f"(signed area {area:.6g} in r, z)") angle = 2.0 * math.pi * np.arange(n) / n @@ -497,7 +516,8 @@ def _lathe(shape: dict, env): faces.append(start[end] + corners) counts.append([n]) smooth.append([False]) - return V, np.concatenate(faces), np.concatenate(counts), np.concatenate(smooth).astype(bool) + sharp = [np.column_stack([start[i] + k, start[i] + j]) for i in range(len(P)) if shape["sharp"][i]] # never an end (check_kit), so never a pole + return V, np.concatenate(faces), np.concatenate(counts), np.concatenate(smooth).astype(bool), np.concatenate(sharp) if sharp else NO_SHARP BOX_FACES = np.array([[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]) @@ -508,13 +528,13 @@ def _box(shape: dict, env): size = np.array([e.value(env) for e in shape["size"]]) if not (size > 0).all(): raise KitError(f"{shape['where']}: every size must be above 0, got {size.tolist()}") - return BOX_SIGNS * size, BOX_FACES.ravel(), np.full(6, 4), np.zeros(6, dtype=bool) + return BOX_SIGNS * size, BOX_FACES.ravel(), np.full(6, 4), np.zeros(6, dtype=bool), NO_SHARP def _placed(shape: dict, env): - V, faces, counts, smooth = {"tube": _tube, "box": _box, "lathe": _lathe}[shape["shape"]](shape, env) + V, faces, counts, smooth, sharp = {"tube": _tube, "box": _box, "lathe": _lathe}[shape["shape"]](shape, env) rotation = _rotation([e.value(env) for e in shape["rot"]]) - return V @ rotation.T + np.array([e.value(env) for e in shape["at"]]), faces, counts, smooth + return V @ rotation.T + np.array([e.value(env) for e in shape["at"]]), faces, counts, smooth, sharp def build(part: dict, params: dict | None = None) -> Built: @@ -527,13 +547,13 @@ def build(part: dict, params: dict | None = None) -> Built: for index, shape in enumerate(part["shapes"]): if shape["shape"] == "repeat": count = _whole(shape["count"], env, COPIES) - V, faces, counts, smooth = _placed(shape["of"], env) + V, faces, counts, smooth, sharp = _placed(shape["of"], env) if "step" in shape: step = np.array([e.value(env) for e in shape["step"]]) - made = [(V + k * step, faces, counts, smooth) for k in range(count)] + made = [(V + k * step, faces, counts, smooth, sharp) for k in range(count)] else: # copy k turned k/count of a turn, right-handed, about the axis through center axis, center = np.array(AXES[shape["around"]]), np.array([e.value(env) for e in shape["center"]]) - made = [((V - center) @ _rotation(axis * (360.0 * k / count)).T + center, faces, counts, smooth) for k in range(count)] + made = [((V - center) @ _rotation(axis * (360.0 * k / count)).T + center, faces, counts, smooth, sharp) for k in range(count)] else: made = [_placed(shape, env)] for shell in made: @@ -560,6 +580,7 @@ def build(part: dict, params: dict | None = None) -> Built: counts=np.concatenate([s[2] for s in shells]).astype(np.int32), smooth=np.concatenate([s[3] for s in shells]).astype(bool), shape=np.concatenate([np.full(len(s[2]), o) for s, o in zip(shells, owner)]).astype(np.int32), + sharp=np.concatenate([s[4] + o for s, o in zip(shells, offsets)]).astype(np.int32), shell_count=len(shells), sockets=sockets, bevel=bevel, params=env) diff --git a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json index a09c1a1..2d170a9 100644 --- a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json @@ -285,8 +285,8 @@ "bevel": "0.15*flange_t", "shapes": [ {"shape": "lathe", "segments": "segments", "smooth": true, "profile": [ - ["1.35*big_r", 0], ["1.35*big_r", "flange_t"], ["big_r", "flange_t"], ["big_r", "flange_t+0.15*(length-2*flange_t)"], - ["small_r", "length-flange_t-0.15*(length-2*flange_t)"], ["small_r", "length-flange_t"], ["1.9*small_r", "length-flange_t"], ["1.9*small_r", "length"]]}, + ["1.35*big_r", 0], ["1.35*big_r", "flange_t"], ["big_r", "flange_t"], ["big_r", "flange_t+0.15*(length-2*flange_t)", "sharp"], + ["small_r", "length-flange_t-0.15*(length-2*flange_t)", "sharp"], ["small_r", "length-flange_t"], ["1.9*small_r", "length-flange_t"], ["1.9*small_r", "length"]]}, {"shape": "repeat", "count": 8, "around": "+z", "of": {"shape": "tube", "r0": "0.077*big_r", "r1": "0.077*big_r", "length": "1.35*flange_t", "segments": 6, "at": ["1.175*big_r", 0, "0.15*flange_t"]}}, {"shape": "repeat", "count": 4, "around": "+z", "of": diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 814e7da..8fc9341 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -72,7 +72,7 @@ then y, then z, about the shape's own origin) place it, rotation first; both def | --- | --- | --- | | `tube` | `r0`, `r1`, `length`, `segments`, `inner0`?, `inner1`?, `smooth`? | A frustum on +z from radius `r0` at z=0 to `r1` at z=`length`, with n-gon caps. Inner radii above 0 make it hollow (an inner wall and two flat end rings); they are both above 0 or both 0, and below the outer radius. `segments` is 3 to 128. `smooth` shades the walls smooth; caps stay flat. | | `box` | `size` | A box centred on its origin; every size above 0. | -| `lathe` | `profile`, `segments`, `loop`?, `smooth`? | A profile of `[r, z]` points revolved about +z into one shell, a ring of `segments` (3 to 128) vertices per point. An open profile's end on the axis (`r` exactly 0) is a pole; an end off the axis gets a flat n-gon cap. With `loop` true the last point joins the first and there are no caps (a ring: 3 points or more). `smooth` shades the walls smooth; a band between two points of one `z` (an annulus) and the caps stay flat. | +| `lathe` | `profile`, `segments`, `loop`?, `smooth`? | A profile of `[r, z]` points revolved about +z into one shell, a ring of `segments` (3 to 128) vertices per point. An open profile's end on the axis (`r` exactly 0) is a pole; an end off the axis gets a flat n-gon cap. With `loop` true the last point joins the first and there are no caps (a ring: 3 points or more). `smooth` shades the walls smooth; a band between two points of one `z` (an annulus) and the caps stay flat. A point written `[r, z, "sharp"]` is a crease. | | `repeat` | `count`, `of`, and `step` or `around` with `center`? | `count` copies (1 to 256) of one tube, box or lathe: at `k * step`, k from 0, or turned `k * 360 / count` degrees, right-handed, about the axis `around` (one of `+x -x +y -y +z -z`) through `center` (default the origin). Exactly one of `step` and `around`. A repeat cannot hold a repeat. | A lathe's profile is listed out along the bottom and up the outside, as this flanged stub is: a cap of radius 0.1 @@ -85,10 +85,24 @@ at z=0, the flange's rim, its top face, the pipe, and a cap of radius 0.05 at z= The rule behind "up the outside": the profile, closed down the axis from its last `z` to its first (a loop closes itself), has positive area in (r, z). A profile listed the other way is refused, and so are a negative `r`, an -`r` of 0 anywhere but an open profile's two ends, and a point that repeats the one before it. A profile may turn -back down inside itself (a bell's inner wall); one that crosses itself is not caught, and builds a shell that is -not a solid. A turned part with many steps is one lathe, and so one shell, where a stack of tubes is one shell -each: a Boolean on it costs less ("Assembling parts"). +`r` of 0 anywhere but an open profile's two ends, and a point that repeats the one before it. A flat profile +(every point at one `z`) encloses nothing and is refused whatever its digits: the area must be above 5.1e-10 of +the square of the profile's largest coordinate, which float rounding does not reach and no real profile comes +near. A profile may turn back down inside itself (a bell's inner wall); one that crosses itself is not caught by +`core`, and builds a shell that is not a solid. For a shipped kit `test_no_lathe_profile_crosses_itself` catches +it, at every corner of the part's params. A turned part with many steps is one lathe, and so one shell, where a +stack of tubes is one shell each: a Boolean on it costs less ("Assembling parts"). + +Smooth shading rounds every bend of a smooth lathe, and the Bevel only cuts edges sharper than 30 degrees. Where +a turned part should show a hard line at a shallower bend (a cone leaving a neck), mark the point: + +```json +["big_r", "flange_t+0.15*(length-2*flange_t)", "sharp"] +``` + +The ring of edges at that point is then shaded as a crease (`Built.sharp`, written to the mesh's `sharp_edge` +attribute by `place_part` and `set_params`). The mark is per point and authored: no angle decides it. It is +refused at an open profile's two ends, which are a cap or a pole. No modifier or auto-smooth setting takes part. Shells may overlap (a pad that runs into a tank), and a part is then not one solid: reports give the shell count. @@ -159,9 +173,12 @@ cut's edges are bevelled with the rest. The modifier's object is the cutter; the 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: on Blender 5.3 a box cut from a part at its defaults takes -0.51 s for the tank (6 shells; 1.53 s when it was 20), 0.40 s for the nozzle (9 shells; 1.25 s at 24) and 0.24 s -for a pipe fitting (14 shells; 0.31 s at 19), each time the part is evaluated. Keep live booleans few and +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 (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.55 s for the tank, 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 part pays it 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 @@ -270,7 +287,8 @@ three faces `2*pipe_r` (0.06 to 0.14), a nozzle's mount `2*throat_r` (0.08 to 0. `2*radius` (0.16 to 0.6). So tanks, fittings and nozzles plumb together, and a ribbed cylinder takes a nozzle (throat 0.08 and up) or another ribbed cylinder face to face: its smallest flange is larger than the largest pipe. A reducer joins the two: its `big` face is `2*big_r` (0.16 to 0.6, a ribbed cylinder's whole range) and -its `small` face `2*small_r` (0.048 to 0.14, the tank ports' and the fittings'), so a chamber hangs in a tank's +its `small` face `2*small_r` (0.048 to 0.14): a tank port over that whole range, and a fitting's face only from +`small_r` 0.03, the smallest pipe. So a chamber hangs in a tank's tree as tank, tee, reducer, ribbed cylinder, nozzle. Struts and actuators pin together when `0.6*width` equals `0.9*body_r`; both ends of each lie on its own axis, so pinned parts chain in a line. Mounts (`fits`) take any part whose seat is no larger than theirs. diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 19d7920..22ec15c 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -100,6 +100,13 @@ for index, name in enumerate(names): flat = np.zeros(max(faces, 0), dtype=bool) if obj: obj.data.attributes["sharp_face"].data.foreach_get("value", flat) + crease = obj.data.attributes.get("sharp_edge") if obj else None + creased = np.zeros(len(obj.data.edges) if crease else 0, dtype=bool) + if crease: + crease.data.foreach_get("value", creased) + marked = sorted(tuple(sorted(edge.vertices)) for edge, on in zip(obj.data.edges, creased) if on) if crease else None + check(f"place_part {name}: sharp_edge is true on exactly core's sharp edges ({len(reference.sharp)})", + marked == sorted(tuple(sorted(pair)) for pair in reference.sharp.tolist()), [marked and len(marked), len(reference.sharp)]) bevel = obj.modifiers.get("Kit Bevel") if obj else None evaluated = len(obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) if obj else -1 placed[name] = report @@ -117,6 +124,14 @@ for index, name in enumerate(names): check("ten parts are ten mesh objects", len(bpy.data.objects) == 10 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) # --- set_params keeps what is not derived -------------------------------------------------------------------------------- +reducer = bpy.data.objects["P_reducer"] +send("brokkr_kitbash.set_params", object_name="P_reducer", params="segments=12") +creased = np.zeros(len(reducer.data.edges), dtype=bool) +reducer.data.attributes["sharp_edge"].data.foreach_get("value", creased) +rings = [np.array([reducer.data.vertices[v].co[:] for edge, on in zip(reducer.data.edges, creased) if on for v in edge.vertices])] +check("the reducer's creases are its two cone rings, 24 edges each at 24 segments, and set_params writes them again: 12 each at 12", + len(core.build(kit["parts"]["reducer"]).sharp) == 48 and int(creased.sum()) == 24 + and sorted(set(np.round(np.linalg.norm(rings[0][:, :2], axis=1), 5).tolist())) == [0.05, 0.12], int(creased.sum())) tank = bpy.data.objects["P_tank"] send("setObjectTransform", targetObjectName="P_tank", location=[1.0, 2.0, 3.0], rotationEuler=[0.3, -0.2, 0.5], scale=[1.0, 1.0, 1.0]) send("assignMaterial", targetObjectName="P_tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index d935e1d..9deceab 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -21,6 +21,11 @@ "ok": true, "detail": null }, + { + "name": "place_part nozzle: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part nozzle: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -36,6 +41,11 @@ "ok": true, "detail": null }, + { + "name": "place_part tank: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part tank: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -51,6 +61,11 @@ "ok": true, "detail": null }, + { + "name": "place_part ribbed_cylinder: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part ribbed_cylinder: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -66,6 +81,11 @@ "ok": true, "detail": null }, + { + "name": "place_part strut: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part strut: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -81,6 +101,11 @@ "ok": true, "detail": null }, + { + "name": "place_part actuator: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part actuator: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -96,6 +121,11 @@ "ok": true, "detail": null }, + { + "name": "place_part pipe_fitting: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part pipe_fitting: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -111,6 +141,11 @@ "ok": true, "detail": null }, + { + "name": "place_part radiator_stack: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part radiator_stack: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -126,6 +161,11 @@ "ok": true, "detail": null }, + { + "name": "place_part vent: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part vent: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -141,6 +181,11 @@ "ok": true, "detail": null }, + { + "name": "place_part plate: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part plate: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -156,6 +201,11 @@ "ok": true, "detail": null }, + { + "name": "place_part reducer: sharp_edge is true on exactly core's sharp edges (48)", + "ok": true, + "detail": null + }, { "name": "place_part reducer: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -176,6 +226,11 @@ "ok": true, "detail": null }, + { + "name": "the reducer's creases are its two cone rings, 24 edges each at 24 segments, and set_params writes them again: 12 each at 12", + "ok": true, + "detail": null + }, { "name": "set_params doubling the tank's length doubles its z extent", "ok": true, diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index a9f342e..8b5b3f7 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -491,6 +491,7 @@ send("createObject", objectType="MESH", name="Gap", location=[0.1, -12.0, 0.0], gap = bpy.data.objects["Gap"] gap.data.materials.append(None) # the cutter's faces are in an empty first slot gap.data.materials.append(bpy.data.materials["Boss Brass"]) +gap.data.polygons[0].material_index = gap.data.polygons[1].material_index = 1 # two of its faces are brass; the rest stay in the empty slot send("brokkr_kitbash.boolean", object_name="Gapped", cutter="Gap") receipt, baked = send("brokkr_kitbash.apply", object_name="Gapped") used = np.zeros(len(gapped.data.polygons), dtype=np.int32) @@ -498,6 +499,12 @@ gapped.data.polygons.foreach_get("material_index", used) check("apply leaves no face outside the material slots when a cutter's first slot is empty", receipt["status"] == "accepted" and len(used) > 44 and used.min() >= 0 and used.max() < len(gapped.data.materials) and not gapped.data.validate_material_indices() and not gapped.data.validate(verbose=False), [receipt["message"], int(used.min()), int(used.max()), [m and m.name for m in gapped.data.materials]]) +names = [m and m.name for m in gapped.data.materials] +brass = [p.index for p in gapped.data.polygons if "Boss Brass" in names and p.material_index == names.index("Boss Brass")] +far = [p.index for p in gapped.data.polygons if (gapped.matrix_world @ p.center).x < -0.05] # the plate's half the cutter does not reach +check("and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", + names[0] == "Plate Paint" and 0 < len(brass) < len(used) and far and all(used[i] == 0 for i in far) + and all(abs((gapped.matrix_world @ gapped.data.polygons[i].center).x - 0.1) < 0.051 for i in brass), [names, len(brass), len(far), sorted(set(used.tolist()))]) R["ok"] = all(c["ok"] for c in R["checks"]) R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index e51d21b..6957612 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -395,6 +395,11 @@ "name": "apply leaves no face outside the material slots when a cutter's first slot is empty", "ok": true, "detail": null + }, + { + "name": "and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", + "ok": true, + "detail": null } ], "hostErrors": [], diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index a84645c..980679d 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -11,6 +11,7 @@ from __future__ import annotations import copy import importlib.util +import itertools import json import math import random @@ -319,7 +320,12 @@ class ShapeTests(unittest.TestCase): (lathe([[1, 0]]), r"shape 0 \(lathe\) profile must be an array of at least 2 \[r, z\] points"), (lathe([[1, 0], [1, 1]], loop=True), r"profile must be an array of at least 3 \[r, z\] points \(it is a loop\)"), (lathe("round"), r"profile must be an array of at least 2"), - (lathe([[1, 0], [1, 1, 0]]), r"profile\[1\] must be \[r, z\]"), + (lathe([[1, 0], [1, 1, 0]]), r"profile\[1\] must be \[r, z\] or \[r, z, \"sharp\"\]"), + (lathe([[1, 0], [1, 1, "soft"], [0.5, 1]]), r"profile\[1\] must be \[r, z\] or \[r, z, \"sharp\"\]"), + (lathe([[1, 0], [1, 1, "sharp", 0], [0.5, 1]]), r"profile\[1\] must be \[r, z\] or"), + (lathe([[1, 0, "sharp"], [1, 1], [0.5, 1]]), r"profile\[0\] is marked sharp at an end of an open profile"), + (lathe([[1, 0], [1, 1], [0.5, 1, "sharp"]]), r"profile\[2\] is marked sharp at an end of an open profile"), + (lathe([[1, 0], [1, 1], [0, 1.5, "sharp"]]), r"profile\[2\] is marked sharp at an end"), # a pole is an end (lathe([[1, 0], 1]), r"profile\[1\] must be \[r, z\]"), (lathe([[1, 0], [1, "q"]]), r"profile\[1\]\[1\]: 'q' names 'q'"), (lathe([[1, 0], [1, 1]], loop=1), r"loop must be true or false"), @@ -333,10 +339,34 @@ class ShapeTests(unittest.TestCase): (lathe([[1, 1], [1, 0]]), r"shape 0 \(lathe\) profile: list it out along the bottom and up the outside"), (lathe(ring[::-1], loop=True), r"profile: list it out along the bottom and up the outside"), (lathe([[0, 0], [0, 1]]), r"enclose nothing \(signed area 0 in r, z\)"), + # flat-profile. Mutant J10 (the tolerance back to 0): the first builds, on an area of 1.6e-17 that is float rounding + (lathe([[0.129, 0.686], [1.592, 0.686]]), r"enclose nothing \(signed area \S+e-17 in r, z\)"), + (lathe([[1.592, 0.686], [0.129, 0.686]]), r"enclose nothing \(signed area 0 in r, z\)"), + (lathe([[0.1, 0.3], [0.7, 0.3]]), r"enclose nothing \(signed area 0 in r, z\)"), (lathe([[1, 0], [1, 1]], segments=2), r"segments is 2\.0: it must be a whole number from 3 to 128")): with self.assertRaisesRegex(core.KitError, message): built(shapes) + def test_a_sharp_point_marks_its_ring_in_every_copy(self): + """sharp-points. Mutant J9 (a copy's pairs not offset by the vertices before it): every copy names the first's ring.""" + n = 8 + profile = [[0, 0], [0.5, 0.2, "sharp"], [0.5, 0.6], [0.3, 0.8, "sharp"], [0.3, 1.0]] # a pole first: its ring is one vertex + b = built([{"shape": "box", "size": [1, 1, 1]}, + {"shape": "repeat", "count": 3, "step": [2, 0, 0], "of": {"shape": "lathe", "profile": profile, "segments": n, "smooth": True}}]) + each = 1 + 4 * n + expected = [[8 + c * each + 1 + i * n + k, 8 + c * each + 1 + i * n + (k + 1) % n] for c in range(3) for i in (0, 2) for k in range(n)] + self.assertEqual(b.sharp.tolist(), expected) + self.assertEqual((b.sharp.dtype, b.sharp.shape, len(b.V)), (np.int32, (48, 2), 8 + 3 * each)) + radius = np.linalg.norm(b.V[b.sharp[:, 0]][:, :2] - np.repeat([[0, 0], [2, 0], [4, 0]], 2 * n, axis=0), axis=1) + self.assertTrue(np.allclose(radius, np.tile(np.repeat([0.5, 0.3], n), 3), atol=1e-12)) # each pair lies on its own copy's marked ring + plain = built([{"shape": "lathe", "profile": [point[:2] for point in profile], "segments": n}, {"shape": "tube", "r0": 1, "r1": 1, "length": 1, "segments": n}]) + self.assertEqual((plain.sharp.shape, plain.sharp.dtype), ((0, 2), np.int32)) + self.assertEqual(plain.V.tobytes(), built([{"shape": "lathe", "profile": profile, "segments": n}, {"shape": "tube", "r0": 1, "r1": 1, "length": 1, "segments": n}]).V.tobytes()) + ring = built([{"shape": "lathe", "loop": True, "segments": n, "profile": [[0.4, 0, "sharp"], [0.6, 0], [0.6, 0.2], [0.4, 0.2, "sharp"]]}]) # a loop has no end + self.assertEqual(ring.sharp.tolist(), [[i * n + k, i * n + (k + 1) % n] for i in (0, 3) for k in range(n)]) + thin = built([{"shape": "lathe", "profile": [[0.5, 0], [0.5, 1e-6]], "segments": n}]) # thin is not flat: 2e-6 of its extent squared + self.assertGreater(signed_volume(thin), 0.0) + def test_repeat_around_turns_copies_about_the_axis(self): """repeat-around. Mutants K5 (copy k turned k*360/(count+1)) and K6 (center ignored).""" box = {"shape": "box", "size": [0.2, 0.2, 0.2]} @@ -452,6 +482,42 @@ class MechanicalKitTests(unittest.TestCase): self.assertLess(socket_seat(b, socket), 1e-6, f"{name}.{socket['name']} {given}") self.assertGreater(socket["size"], 0.0) + def test_no_lathe_profile_crosses_itself(self): + """profile-simple: closed, outward and positive volume do not see a profile that crosses itself, and core does not + check it. Mutant J11 (the nozzle's lip min(2.5*wall, 0.08*length) to 0.2*length): crosses at length 0.25, wall 0.015.""" + def side(a, b, c): + return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + + def cross(a, b, c, d): # the two segments share a point (touching counts): their boxes overlap and each straddles the other's line + if any(max(min(a[x], b[x]), min(c[x], d[x])) > min(max(a[x], b[x]), max(c[x], d[x])) for x in (0, 1)): + return False # also what tells two stretches of one straight line apart (the bell between its hoops) + return side(a, b, c) * side(a, b, d) <= 0 and side(c, d, a) * side(c, d, b) <= 0 + + self.assertTrue(cross((0, 0), (2, 2), (0, 2), (2, 0)) and cross((0, 0), (2, 0), (1, 0), (1, 1)) and cross((0, 0), (2, 0), (1, 0), (3, 0))) + self.assertFalse(cross((0, 0), (2, 0), (0, 1), (2, 1)) or cross((0, 0), (1, 1), (2, 2), (3, 3)) or cross((0, 0), (2, 0), (3, -1), (3, 1))) + lathes = 0 + for name, part in self.kit["parts"].items(): + found = [s if s["shape"] == "lathe" else s["of"] for s in part["shapes"] if "lathe" in (s["shape"], s.get("of", {}).get("shape"))] + rng = random.Random(f"mechanical.{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"]}) + draws += [dict(zip([p["name"] for p in part["params"]], corner)) for corner in itertools.product(*[(p["min"], p["max"]) for p in part["params"]])] + for lathe in found: + lathes += 1 + for given in draws: + env = core.resolve_params(part, given) + points = [(r.value(env), z.value(env)) for r, z in lathe["profile"]] + segments = list(zip(points, points[1:] + points[:1] if lathe["loop"] else points[1:])) + count = len(segments) + for i in range(count): + for j in range(i + 2, count): + if lathe["loop"] and i == 0 and j == count - 1: + continue # neighbours round the loop + self.assertFalse(cross(*segments[i], *segments[j]), f"{name} profile segments {i} and {j} at {given}") + self.assertEqual(lathes, 6) + def test_extension_moves_the_rod_end_and_nothing_else(self): part = self.kit["parts"]["actuator"] short, long = core.build(part, {"extension": 0.0}), core.build(part, {"extension": 0.5}) From 8224125d1f34a8f0a0637cca1548b31bbe244174 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 19:02:38 +0100 Subject: [PATCH 077/223] brokkr_kitbash: pivot sockets on the pin axis, tank mount lugs, a bracket The strut's and actuator's end-face pivot sockets (z along the part) are gone. Each pin now carries a socket on each of its end faces, z along the pin and y along the part: end_a, end_a_back, end_b, end_b_back; base, base_back, rod_end, rod_end_back. Two pinned parts share the pin's axis and the connection's roll is the hinge angle. Scripts that attach by the old names still attach; where the part lands changes. The tank gains a mount lug on each side of each strap (shapes 4 and 5, sockets lug_a, lug_b, lug_a_back, lug_b_back); its other shapes and sockets build the same bytes. A bracket (part 11) seats a pin on a flat mount: its pivot face lies on its plate's centre plane, so a bracket turned half about its mount pins on the same plane facing the first. Every other part builds byte-identical V, faces, counts, smooth and shape against f329f56 (21 draws each). A box cut from the tank reads 502 ms at 6 shells and 507 ms at 10 (4 alternating processes of 5). Cut kit-joints. Co-Authored-By: Claude Fable 5.2 --- .../brokkr_kitbash/kits/mechanical.v0.json | 53 ++++++++++--- surfaces/blender/docs/kitbash.md | 41 ++++++---- surfaces/blender/tests/live/kitbash.py | 10 +-- .../blender/tests/live/kitbash.result.json | 54 +++++++++++-- .../blender/tests/live/kitbash_assembly.py | 2 +- .../tests/live/kitbash_assembly.result.json | 14 ++-- surfaces/blender/tests/test_kitbash.py | 75 ++++++++++++++++--- 7 files changed, 196 insertions(+), 53 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json index 2d170a9..1da5a7b 100644 --- a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json @@ -47,7 +47,7 @@ }, { "name": "tank", - "doc": "Pressure tank: elliptical domed ends with flanged ports, weld bands, two straps on saddle cradles and a mounting pad.", + "doc": "Pressure tank: elliptical domed ends with flanged ports, weld bands, two straps on saddle cradles, a mounting pad, and a mount lug on each side of each strap.", "params": [ {"name": "radius", "type": "number", "min": 0.12, "max": 0.35, "default": 0.22, "doc": "shell radius"}, {"name": "length", "type": "number", "min": 0.6, "max": 2.0, "default": 0.9, "doc": "port face to port face"}, @@ -67,12 +67,20 @@ "profile": [["0.97*radius", 0], ["1.035*radius", 0], ["1.035*radius", "0.1*radius"], ["0.97*radius", "0.1*radius"]]}}, {"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of": {"shape": "box", "size": ["1.3*radius", "0.55*radius", "0.1*radius"], "at": [0, "-0.85*radius", "0.49*radius+0.22*(length-0.98*radius)"]}}, - {"shape": "box", "size": ["1.5*radius", "0.08*radius", "0.56*(length-0.98*radius)+0.3*radius"], "at": [0, "-1.14*radius", "length/2"]} + {"shape": "box", "size": ["1.5*radius", "0.08*radius", "0.56*(length-0.98*radius)+0.3*radius"], "at": [0, "-1.14*radius", "length/2"]}, + {"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of": + {"shape": "box", "size": ["0.1*radius", "0.35*radius", "0.3*radius"], "at": ["1.07*radius", 0, "0.49*radius+0.22*(length-0.98*radius)"]}}, + {"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of": + {"shape": "box", "size": ["0.1*radius", "0.35*radius", "0.3*radius"], "at": ["-1.07*radius", 0, "0.49*radius+0.22*(length-0.98*radius)"]}} ], "sockets": [ {"name": "port_a", "type": "flange", "size": "0.4*radius", "at": [0, 0, 0], "z": "-z", "y": "+y"}, {"name": "port_b", "type": "flange", "size": "0.4*radius", "at": [0, 0, "length"], "z": "+z", "y": "+y"}, - {"name": "saddle", "type": "mount", "size": "1.5*radius", "at": [0, "-1.18*radius", "length/2"], "z": "-y", "y": "+z"} + {"name": "saddle", "type": "mount", "size": "1.5*radius", "at": [0, "-1.18*radius", "length/2"], "z": "-y", "y": "+z"}, + {"name": "lug_a", "type": "mount", "size": "0.3*radius", "at": ["1.12*radius", 0, "0.49*radius+0.22*(length-0.98*radius)"], "z": "+x", "y": "+z"}, + {"name": "lug_b", "type": "mount", "size": "0.3*radius", "at": ["1.12*radius", 0, "0.49*radius+0.78*(length-0.98*radius)"], "z": "+x", "y": "+z"}, + {"name": "lug_a_back", "type": "mount", "size": "0.3*radius", "at": ["-1.12*radius", 0, "0.49*radius+0.22*(length-0.98*radius)"], "z": "-x", "y": "+z"}, + {"name": "lug_b_back", "type": "mount", "size": "0.3*radius", "at": ["-1.12*radius", 0, "0.49*radius+0.78*(length-0.98*radius)"], "z": "-x", "y": "+z"} ] }, { @@ -107,7 +115,7 @@ }, { "name": "strut", - "doc": "Structural strut: an I-beam with web stiffeners between two pinned end blocks.", + "doc": "Structural strut: an I-beam with web stiffeners between two end blocks, each on a cross pin; a socket on each end face of each pin.", "params": [ {"name": "length", "type": "number", "min": 0.3, "max": 2.0, "default": 0.8, "doc": "end face to end face"}, {"name": "width", "type": "number", "min": 0.04, "max": 0.12, "default": 0.08, "doc": "flange width (x)"}, @@ -127,13 +135,15 @@ {"shape": "box", "size": ["0.9*width", "0.7*thickness", "0.08*width"], "at": [0, 0, "0.9*width+(length-1.8*width)/4"]}} ], "sockets": [ - {"name": "end_a", "type": "pivot", "size": "0.6*width", "at": [0, 0, 0], "z": "-z", "y": "+y"}, - {"name": "end_b", "type": "pivot", "size": "0.6*width", "at": [0, 0, "length"], "z": "+z", "y": "+y"} + {"name": "end_a", "type": "pivot", "size": "0.6*width", "at": [0, "0.85*thickness", "0.45*width"], "z": "+y", "y": "+z"}, + {"name": "end_a_back", "type": "pivot", "size": "0.6*width", "at": [0, "-0.85*thickness", "0.45*width"], "z": "-y", "y": "+z"}, + {"name": "end_b", "type": "pivot", "size": "0.6*width", "at": [0, "0.85*thickness", "length-0.45*width"], "z": "+y", "y": "+z"}, + {"name": "end_b_back", "type": "pivot", "size": "0.6*width", "at": [0, "-0.85*thickness", "length-0.45*width"], "z": "-y", "y": "+z"} ] }, { "name": "actuator", - "doc": "Tie-rod hydraulic cylinder: pinned base eye, square caps, barrel, ports, and a rod with its eye; extension moves rod_end.", + "doc": "Tie-rod hydraulic cylinder: base eye and rod eye each on a cross pin with a socket on each end face, square caps, barrel, ports; extension moves the rod eye.", "params": [ {"name": "body_r", "type": "number", "min": 0.05, "max": 0.12, "default": 0.06, "doc": "barrel radius"}, {"name": "body_len", "type": "number", "min": 0.2, "max": 1.0, "default": 0.4, "doc": "barrel length between caps"}, @@ -160,8 +170,10 @@ {"shape": "tube", "r0": "0.45*body_r", "r1": "0.45*body_r", "length": "1.3*body_r", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.65*body_r", "3.8*body_r+body_len+extension"]} ], "sockets": [ - {"name": "base", "type": "pivot", "size": "0.9*body_r", "at": [0, 0, 0], "z": "-z", "y": "+y"}, - {"name": "rod_end", "type": "pivot", "size": "0.9*body_r", "at": [0, 0, "4.5*body_r+body_len+extension"], "z": "+z", "y": "+y"} + {"name": "base", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "0.8*body_r"], "z": "+y", "y": "+z"}, + {"name": "base_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "0.8*body_r"], "z": "-y", "y": "+z"}, + {"name": "rod_end", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "3.8*body_r+body_len+extension"], "z": "+y", "y": "+z"}, + {"name": "rod_end_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "3.8*body_r+body_len+extension"], "z": "-y", "y": "+z"} ] }, { @@ -296,6 +308,29 @@ {"name": "big", "type": "flange", "size": "2*big_r", "at": [0, 0, 0], "z": "-z", "y": "+y"}, {"name": "small", "type": "flange", "size": "2*small_r", "at": [0, 0, "length"], "z": "+z", "y": "+y"} ] + }, + { + "name": "bracket", + "doc": "Lug bracket: a square foot plate and one ear carrying a pin. The ear's pin face lies on the plate's centre plane, so a second bracket turned half about its mount pins on the same plane, facing the first.", + "params": [ + {"name": "pin_r", "type": "number", "min": 0.012, "max": 0.054, "default": 0.027, "doc": "pin radius"}, + {"name": "height", "type": "number", "min": 0.08, "max": 0.3, "default": 0.1, "doc": "mount face to pin axis"}, + {"name": "width", "type": "number", "min": 0.03, "max": 0.3, "default": 0.09, "doc": "foot plate side"}, + {"name": "ear_t", "type": "number", "min": 0.006, "max": 0.04, "default": 0.014, "doc": "ear thickness (x)"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of the rounds"} + ], + "bevel": "0.12*min(ear_t,0.25*width)", + "shapes": [ + {"shape": "box", "size": ["width", "width", "0.2*min(width,height)"], "at": [0, 0, "0.1*min(width,height)"]}, + {"shape": "box", "size": ["ear_t", "2.6*pin_r", "height-0.2*min(width,height)"], "at": ["-0.5*ear_t", 0, "0.5*height+0.1*min(width,height)"]}, + {"shape": "tube", "r0": "1.3*pin_r", "r1": "1.3*pin_r", "length": "ear_t", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": ["-ear_t", 0, "height"]}, + {"shape": "tube", "r0": "pin_r", "r1": "pin_r", "length": "0.6*pin_r", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": ["-ear_t-0.6*pin_r", 0, "height"]} + ], + "sockets": [ + {"name": "mount", "type": "mount", "size": "width", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "pivot", "type": "pivot", "size": "2*pin_r", "at": [0, 0, "height"], "z": "+x", "y": "+z"}, + {"name": "pivot_back", "type": "pivot", "size": "2*pin_r", "at": ["-ear_t-0.6*pin_r", 0, "height"], "z": "-x", "y": "+z"} + ] } ] } diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 8fc9341..1ba8a66 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -116,6 +116,11 @@ be compared when sockets are mated: `equal` (within 1 percent) or `fits` (the ch sits on a flat face of the part whose normal is its `z`; `test_kitbash` checks this for every part of a shipped kit at its default, smallest and largest params and at seeded draws between. +A pin joint is a socket whose `z` runs along the pin, with its origin on the pin's end face and its `y` along the +part. Two such sockets mate face to face on one pin axis, and the roll of the connection is then the hinge +angle: at 0 the two parts line up, side by side. A pin carries a socket on each of its end faces (`end_a` and +`end_a_back`), so a part can be pinned from either side, and by both at once. + ## Assembling parts **A connection** seats one socket of a child part on one socket of a parent part: the two origins together, the @@ -174,11 +179,12 @@ always Exact with self-intersection on: a kit part is several overlapping closed 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 (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.55 s for the tank, 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 part pays it each time it is evaluated. Keep live booleans few and +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 @@ -264,21 +270,22 @@ file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the ## The mechanical kit -`kits/mechanical.v0.json`: ten parts, each along +z, with socket types `flange` (equal), `mount` (fits) and +`kits/mechanical.v0.json`: eleven parts, each along +z, with socket types `flange` (equal), `mount` (fits) and `pivot` (equal). | part | params | sockets | | --- | --- | --- | | `nozzle` | `throat_r`, `exit_r`, `length`, `wall`, `segments` | `mount` (flange) | -| `tank` | `radius`, `length`, `segments` | `port_a`, `port_b` (flange), `saddle` (mount) | +| `tank` | `radius`, `length`, `segments` | `port_a`, `port_b` (flange), `saddle` (mount), `lug_a`, `lug_b`, `lug_a_back`, `lug_b_back` (mount): a lug on each side (+x, and -x for `_back`) of each strap | | `ribbed_cylinder` | `radius`, `length`, `ribs`, `rib_depth`, `rib_width`, `segments` | `end_a`, `end_b` (flange) | -| `strut` | `length`, `width`, `thickness`, `segments` | `end_a`, `end_b` (pivot) | -| `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `rod_end` (pivot); `rod_end` moves with `extension` | +| `strut` | `length`, `width`, `thickness`, `segments` | `end_a`, `end_a_back`, `end_b`, `end_b_back` (pivot): the two end faces of the pin at each end | +| `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `base_back`, `rod_end`, `rod_end_back` (pivot); the rod end's two move with `extension` | | `pipe_fitting` | `pipe_r`, `run`, `branch`, `flange_r`, `flange_t`, `segments` | `a`, `b`, `c` (flange) | | `radiator_stack` | `fins`, `fin_w`, `fin_h`, `fin_t`, `pitch`, `segments` | `base` (mount) | | `vent` | `width`, `height`, `depth`, `slats`, `slat_t`, `tilt` | `back` (mount) | | `plate` | `width`, `height`, `thickness` | `back`, `front` (mount) | | `reducer` | `big_r`, `small_r`, `length`, `flange_t`, `segments` | `big`, `small` (flange) | +| `bracket` | `pin_r`, `height`, `width`, `ear_t`, `segments` | `mount` (mount), `pivot`, `pivot_back` (pivot) | `describe` gives the bounds and docs. @@ -289,9 +296,17 @@ three faces `2*pipe_r` (0.06 to 0.14), a nozzle's mount `2*throat_r` (0.08 to 0. pipe. A reducer joins the two: its `big` face is `2*big_r` (0.16 to 0.6, a ribbed cylinder's whole range) and its `small` face `2*small_r` (0.048 to 0.14): a tank port over that whole range, and a fitting's face only from `small_r` 0.03, the smallest pipe. So a chamber hangs in a tank's -tree as tank, tee, reducer, ribbed cylinder, nozzle. Struts and actuators pin together when `0.6*width` equals -`0.9*body_r`; both ends of each lie on its own axis, so pinned parts chain in a line. Mounts (`fits`) take any -part whose seat is no larger than theirs. +tree as tank, tee, reducer, ribbed cylinder, nozzle. Mounts (`fits`) take any part whose seat is no larger than +theirs. + +Pins: a strut's are `0.6*width` across (0.024 to 0.072), an actuator's `0.9*body_r` (0.045 to 0.108) and a +bracket's `2*pin_r` (0.024 to 0.108), so a bracket can be sized to either, and a strut pins to an actuator when +`0.6*width` equals `0.9*body_r`. Pinned parts hinge: the roll is the angle between them. A bracket is how a pin +meets a flat seat: its `mount` sits on a plate, a saddle or a tank lug (a lug seats a plate up to `0.3*radius` +wide), and its pin runs across the seat's up axis, so on a tank lug at roll 0 a leg swings in a plane through +the tank's axis. The bracket's `pivot` face lies on its plate's centre plane, so a bracket on a second lug of +the same side, turned half (roll 180), pins on the same plane facing the first. An actuator on one and a strut +on the other then lie in one plane and can meet at a pin: a braced leg. ## Adding a part or a kit @@ -305,7 +320,7 @@ python -m unittest discover -s surfaces/blender/tests -p "test_kitbash.py" -v 16 seeded draws, and checks that every shell is closed and wound outward, every socket frame is right-handed and 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_ten_parts_and_three_socket_types`. +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 `tests/live/kitbash.py` (placing and re-parameterising) and `tests/live/kitbash_assembly.py` (attach, detach, `set_params` on assemblies, boolean and apply). diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 22ec15c..94b812c 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -1,5 +1,5 @@ """Live proof, in a background Blender, that the brokkr_kitbash rows are admitted by Brokkr as host actions and that -the mechanical kit goes through run_intent: describe, place_part for all ten parts, setObjectTransform, +the mechanical kit goes through run_intent: describe, place_part for all eleven parts, setObjectTransform, assignMaterial, set_params, report, the refusals, and exportGltf. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash.py -- @@ -81,7 +81,7 @@ check("the eight kitbash rows load as host actions with no errors", not R["hostE kit = core.load_kit("mechanical") receipt, described = send("brokkr_kitbash.describe") names = [p["name"] for p in described["parts"]] if described else [] -check("describe lists ten parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 10 +check("describe lists eleven parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 11 and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")]) receipt, one = send("brokkr_kitbash.describe", part="actuator") check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"] @@ -121,7 +121,7 @@ for index, name in enumerate(names): check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"] and report["sockets"] == core.socket_rows(reference.sockets), report) -check("ten parts are ten mesh objects", len(bpy.data.objects) == 10 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) +check("eleven parts are eleven mesh objects", len(bpy.data.objects) == 11 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) # --- set_params keeps what is not derived -------------------------------------------------------------------------------- reducer = bpy.data.objects["P_reducer"] @@ -240,7 +240,7 @@ receipt, alone = send("brokkr_kitbash.set_params", object_name="P_vent", params= check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"]) receipt, whole = send("brokkr_kitbash.report") -check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 10, receipt["message"]) +check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 11, receipt["message"]) # --- export --------------------------------------------------------------------------------------------------------------- receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names]) @@ -249,7 +249,7 @@ meshes = -1 if glb.is_file(): blob = glb.read_bytes() meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", [])) -check("exportGltf of all ten parts succeeds", receipt["status"] == "accepted" and meshes == 10, [receipt["message"], meshes]) +check("exportGltf of all eleven parts succeeds", receipt["status"] == "accepted" and meshes == 11, [receipt["message"], meshes]) R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]} for name, report in placed.items() if report} diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 9deceab..7b0de47 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -7,7 +7,7 @@ "detail": null }, { - "name": "describe lists ten parts, whole, inside a receipt", + "name": "describe lists eleven parts, whole, inside a receipt", "ok": true, "detail": null }, @@ -222,7 +222,27 @@ "detail": null }, { - "name": "ten parts are ten mesh objects", + "name": "place_part bracket: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, + { + "name": "place_part bracket: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part bracket: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part bracket: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "eleven parts are eleven mesh objects", "ok": true, "detail": null }, @@ -372,7 +392,7 @@ "detail": null }, { - "name": "exportGltf of all ten parts succeeds", + "name": "exportGltf of all eleven parts succeeds", "ok": true, "detail": null } @@ -405,13 +425,17 @@ ] }, "tank": { - "faces": 764, - "shells": 6, + "faces": 788, + "shells": 10, "bevel": 0.00176, "sockets": [ "port_a", "port_b", - "saddle" + "saddle", + "lug_a", + "lug_b", + "lug_a_back", + "lug_b_back" ] }, "ribbed_cylinder": { @@ -429,7 +453,9 @@ "bevel": 0.0015, "sockets": [ "end_a", - "end_b" + "end_a_back", + "end_b", + "end_b_back" ] }, "actuator": { @@ -438,7 +464,9 @@ "bevel": 0.0024, "sockets": [ "base", - "rod_end" + "base_back", + "rod_end", + "rod_end_back" ] }, "pipe_fitting": { @@ -484,6 +512,16 @@ "big", "small" ] + }, + "bracket": { + "faces": 64, + "shells": 4, + "bevel": 0.00168, + "sockets": [ + "mount", + "pivot", + "pivot_back" + ] } }, "ok": true diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 8b5b3f7..184a4d2 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -272,7 +272,7 @@ receipt, report = send("brokkr_kitbash.set_params", object_name="Ram", params="e back = frame(ram, "base")[:3, 3] - base[:3, 3] check("extending an actuator that hangs by its rod seats it again: the rod end stays, the body backs off by the travel", reading("seated", seated(ram, "rod_end", strut, "end_b", 0.0)) < SEATED and receipt["status"] == "accepted" and held(report) - and reading("carried", np.abs(back - base[:3, 2] * 0.35).max()) < CARRIED, [receipt["message"], connection("Ram"), back.tolist()]) + and reading("carried", np.abs(back + base[:3, 1] * 0.35).max()) < CARRIED, [receipt["message"], connection("Ram"), back.tolist()]) # a pivot's y is the part's axis tip = frame(strut, "end_b") receipt, report = send("brokkr_kitbash.set_params", object_name="Lift", params="extension=0.6") check("extending the actuator above moves the strut on its rod and the ram below with it", receipt["status"] == "accepted" diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index 6957612..df36b95 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -404,22 +404,22 @@ ], "hostErrors": [], "readings": { - "carried": 2.7e-07, + "carried": 2.6e-07, "cut": 0.25, "kept": 1.5e-08, "nudged": 0.00032, - "roll": 6.3e-06, - "seated": 1.5e-07 + "roll": 6.6e-06, + "seated": 2.1e-07 }, "tank": { "raw": { - "faces": 764, - "volume": 0.264485537, + "faces": 788, + "volume": 0.264932753, "nonManifoldEdges": 0 }, "cut": { - "faces": 2250, - "volume": 0.250847643, + "faces": 2566, + "volume": 0.251287573, "nonManifoldEdges": 0 } }, diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 980679d..05da9e8 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -445,21 +445,27 @@ class ParamTests(unittest.TestCase): @unittest.skipIf(np is None, "numpy is not installed") class MechanicalKitTests(unittest.TestCase): - PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "pipe_fitting", "radiator_stack", "vent", "plate", "reducer"] + PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "pipe_fitting", "radiator_stack", "vent", "plate", "reducer", "bracket"] @classmethod def setUpClass(cls): cls.kit = core.load_kit("mechanical") - def test_the_kit_is_the_ten_parts_and_three_socket_types(self): + def test_the_kit_is_the_eleven_parts_and_three_socket_types(self): self.assertEqual(list(self.kit["parts"]), self.PARTS) self.assertEqual({k: v["match"] for k, v in self.kit["socketTypes"].items()}, {"flange": "equal", "mount": "fits", "pivot": "equal"}) self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, { - "nozzle": [("mount", "flange")], "tank": [("port_a", "flange"), ("port_b", "flange"), ("saddle", "mount")], - "ribbed_cylinder": [("end_a", "flange"), ("end_b", "flange")], "strut": [("end_a", "pivot"), ("end_b", "pivot")], - "actuator": [("base", "pivot"), ("rod_end", "pivot")], "pipe_fitting": [("a", "flange"), ("b", "flange"), ("c", "flange")], + "nozzle": [("mount", "flange")], + "tank": [("port_a", "flange"), ("port_b", "flange"), ("saddle", "mount"), ("lug_a", "mount"), ("lug_b", "mount"), ("lug_a_back", "mount"), ("lug_b_back", "mount")], + "ribbed_cylinder": [("end_a", "flange"), ("end_b", "flange")], + "strut": [("end_a", "pivot"), ("end_a_back", "pivot"), ("end_b", "pivot"), ("end_b_back", "pivot")], + "actuator": [("base", "pivot"), ("base_back", "pivot"), ("rod_end", "pivot"), ("rod_end_back", "pivot")], + "pipe_fitting": [("a", "flange"), ("b", "flange"), ("c", "flange")], "radiator_stack": [("base", "mount")], "vent": [("back", "mount")], "plate": [("back", "mount"), ("front", "mount")], - "reducer": [("big", "flange"), ("small", "flange")]}) + "reducer": [("big", "flange"), ("small", "flange")], "bracket": [("mount", "mount"), ("pivot", "pivot"), ("pivot_back", "pivot")]}) + tank = core.build(self.kit["parts"]["tank"]) + self.assertEqual(sorted(set(tank.shape.tolist())), [0, 1, 2, 3, 4, 5]) # the straps stay shape 1; the lugs are appended as 4 and 5 + self.assertEqual((int((tank.shape == 1).sum()), int((tank.shape >= 4).sum())), (2 * 4 * 24, 4 * 6)) def test_every_part_holds_everywhere(self): """kit-parts-hold-everywhere. Mutant M8 (flip one socket's z in the kit): no face at that origin faces it.""" @@ -520,9 +526,14 @@ class MechanicalKitTests(unittest.TestCase): def test_extension_moves_the_rod_end_and_nothing_else(self): part = self.kit["parts"]["actuator"] - short, long = core.build(part, {"extension": 0.0}), core.build(part, {"extension": 0.5}) - self.assertEqual(short.sockets[0]["matrix"].tolist(), long.sockets[0]["matrix"].tolist()) - self.assertAlmostEqual(long.sockets[1]["matrix"][2, 3] - short.sockets[1]["matrix"][2, 3], 0.5, places=12) + short, long = ({s["name"]: s["matrix"] for s in core.build(part, {"extension": e}).sockets} for e in (0.0, 0.5)) + for name in ("base", "base_back"): + self.assertEqual(short[name].tolist(), long[name].tolist()) + for name in ("rod_end", "rod_end_back"): + moved = long[name] - short[name] + self.assertAlmostEqual(moved[2, 3], 0.5, places=12) # along the part's z + moved[2, 3] = 0.0 + self.assertEqual(float(np.abs(moved).max()), 0.0) def test_builds_are_deterministic(self): """build-deterministic.""" @@ -591,6 +602,50 @@ class MateTests(unittest.TestCase): self.assertLess(worst["roll"], self.ROLL) self.assertLess(worst["residual"], self.RESIDUAL) + def test_a_pin_hinges_at_its_roll(self): + """pin-hinge. A pivot's z runs along its pin and its y along the part, so two pinned members share the pin's axis + and stand the roll apart about it; at roll 0 they line up. Mutant J2 (the strut's end_b with y -z): half a turn off. + Bounds are MateTests' own: the readings are the same arithmetic.""" + parts = self.kit["parts"] + strut, ram = core.build(parts["strut"], {"width": 0.09}), core.build(parts["actuator"], {"body_r": 0.06}) + worst = {"origin": 0.0, "normal": 0.0, "angle": 0.0} + for parent_name in ("end_a", "end_a_back", "end_b", "end_b_back"): + for child_name in ("base", "base_back", "rod_end", "rod_end_back"): + sp, sc = core.joint(parts["strut"], strut, parent_name, parts["actuator"], ram, child_name) + self.assertIsNone(core.mate_refusal(self.kit["socketTypes"], sp, sc)) + self.assertEqual((abs(sp["matrix"][1, 2]), sp["matrix"][2, 1], abs(sc["matrix"][1, 2]), sc["matrix"][2, 1]), (1.0, 1.0, 1.0, 1.0)) # z the pin (the part's y), y the part's z + for roll in (0.0, 37.0, -90.0, 150.0): + child = core.mate(sp, sc, roll) # the strut stands at the identity + pin, there = sp["matrix"][:3, 2], child @ sc["matrix"] + read = math.degrees(math.atan2(np.cross([0.0, 0.0, 1.0], child[:3, 2]) @ pin, child[2, 2])) # the ram's +z from the strut's, about the pin + worst["origin"] = max(worst["origin"], float(np.abs(sp["matrix"][:3, 3] - there[:3, 3]).max())) + worst["normal"] = max(worst["normal"], float(np.abs(pin + there[:3, 2]).max())) + worst["angle"] = max(worst["angle"], abs((read - roll + 180.0) % 360.0 - 180.0)) + self.assertLess(worst["origin"], self.ORIGIN) + self.assertLess(worst["normal"], self.NORMAL) + self.assertLess(worst["angle"], self.ROLL) + + def test_a_bracket_turned_half_pins_on_its_own_plane(self): + """bracket-half-turn. A bracket seated on a lug at roll 0 and one seated there at roll 180 put their pivots at one + point with normals opposed, because the pivot face lies on the mount's centre plane; so brackets on two lugs, one + turned half, face each other across one plane and a brace between them closes. Mutant J1 (the pivot face at + x = -ear_t): the two origins stand 2*ear_t apart. Mutant J13 (a lug socket's z flipped) dies in kit-holds.""" + parts = self.kit["parts"] + tank = core.build(parts["tank"], {"radius": 0.3}) + for given in ({}, {"width": 0.03, "height": 0.3, "ear_t": 0.04, "pin_r": 0.054}): + bracket = core.build(parts["bracket"], given) + for lug in ("lug_a", "lug_b", "lug_a_back", "lug_b_back"): + sp, sc = core.joint(parts["tank"], tank, lug, parts["bracket"], bracket, "mount") + self.assertIsNone(core.mate_refusal(self.kit["socketTypes"], sp, sc)) + pivot = next(s["matrix"] for s in bracket.sockets if s["name"] == "pivot") + straight, turned = core.mate(sp, sc, 0.0) @ pivot, core.mate(sp, sc, 180.0) @ pivot + self.assertLess(float(np.abs(straight[:3, 3] - turned[:3, 3]).max()), self.ORIGIN) + self.assertLess(float(np.abs(straight[:3, 2] + turned[:3, 2]).max()), self.NORMAL) + self.assertLess(max(abs(float(straight[:3, 2] @ sp["matrix"][:3, k])) for k in (1, 2)), self.NORMAL) # the pin runs across the tank: a leg swings in a plane through its axis + self.assertAlmostEqual(float((straight[:3, 3] - sp["matrix"][:3, 3]) @ sp["matrix"][:3, 2]), bracket.params["height"], places=12) + with_default_tank = core.joint(parts["tank"], core.build(parts["tank"]), "lug_a", parts["bracket"], core.build(parts["bracket"]), "mount") + self.assertIn("it is larger", core.mate_refusal(self.kit["socketTypes"], *with_default_tank)) # a lug seats a plate up to 0.3 of the tank's radius + def test_residual_is_how_far_the_child_stands_from_its_mate(self): sp, sc = self.sockets(*self.PAIRS[0]) world = np.eye(4) @@ -664,7 +719,7 @@ class MateTests(unittest.TestCase): other = {**parts["pipe_fitting"], "kit": "hydraulic"} with self.assertRaisesRegex(core.KitError, "part 'pipe_fitting' is of kit 'hydraulic' and part 'tank' of kit 'mechanical'.*do not mate"): core.joint(parts["tank"], tank, "port_b", other, fitting, "a") - with self.assertRaisesRegex(core.KitError, "part 'tank' has no socket 'port_c'; its sockets: port_a, port_b, saddle"): + with self.assertRaisesRegex(core.KitError, "part 'tank' has no socket 'port_c'; its sockets: port_a, port_b, saddle, lug_a, lug_b, lug_a_back, lug_b_back"): core.joint(parts["tank"], tank, "port_c", parts["pipe_fitting"], fitting, "a") with self.assertRaisesRegex(core.KitError, "part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c"): core.joint(parts["tank"], tank, "port_b", parts["pipe_fitting"], fitting, "d") From 3ae142555cd74b9626be7545619e2756372f1117 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 19:10:08 +0100 Subject: [PATCH 078/223] brokkr_kitbash: close states a loop's closing joint and never moves anything Connections stay a tree owned by the child. A loop is closed by a closure: the closing part's kit_close_socket, kit_close_to (an object pointer) and kit_close_to_socket. brokkr_kitbash.close writes them only when the two sockets already meet (core.closure_residual within HELD, any roll) and writes nothing else; detach clears them, and now also accepts a part that states only a closure. Reports derive a closure's residual and holds each time. attach's inline occupancy scan is gone: occupant() is the one rule for attach and close, and counts closures at both ends. set_params refuses a change after which a closure's two sockets may no longer mate, checking closures before connections so the refusal names the closure, and otherwise only reports: its report lists every closure in the scene as closures [{part, to, holds}]. kitbash_assembly.py builds a braced leg on a tank's two lugs with rolls from the law of cosines and closes it; test_a_brace_closes_on_a_leg does the same in numpy (2.2e-16). Cut kit-joints. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 171 +++++++++++++++--- .../brokkr_kitbash/brokkr_actions.json | 45 ++++- surfaces/blender/brokkr_kitbash/core.py | 9 + surfaces/blender/docs/kitbash.md | 63 ++++++- surfaces/blender/tests/live/kitbash.py | 4 +- .../blender/tests/live/kitbash.result.json | 3 +- .../blender/tests/live/kitbash_assembly.py | 130 ++++++++++++- .../tests/live/kitbash_assembly.result.json | 142 ++++++++++++++- surfaces/blender/tests/test_kitbash.py | 72 +++++++- 9 files changed, 592 insertions(+), 47 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 5f77073..4e9c72b 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -19,6 +19,11 @@ belongs to its Boolean modifier on the target (the modifier's object is the cutt says apply replaced the mesh with the evaluated one: the params then only place the part's sockets. Placing a loose part, hiding a cutter, materials and export are Brokkr's own rows (setObjectTransform, setObjectVisibility, assignMaterial, exportGltf). + +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 +solves a loop: a closure never places a part, and a report says how far its two sockets stand apart. """ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), "category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."} @@ -41,7 +46,8 @@ from . import core KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" SOCKET, PARENT_SOCKET, ROLL, BAKED = "kit_socket", "kit_parent_socket", "kit_roll", "kit_baked" -HELD = 1e-5 # a connection holds when its residual is at most this (as RIGID) +CLOSE, CLOSE_TO, CLOSE_TO_SOCKET = "kit_close_socket", "kit_close_to", "kit_close_to_socket" +HELD = 1e-5 # a connection or a closure holds when its residual is at most this (as RIGID) BEVEL = "Kit Bevel" BOOLEAN = "Kit Boolean " # a Boolean modifier's name is this and its cutter's name: a label, the cutter is modifier.object BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0) @@ -129,10 +135,49 @@ def attached(obj) -> list: return [child for child in obj.children if SOCKET in child] -def mated(parent, parent_part, parent_built, child, child_part, child_built, stated): +def closure(obj): + """The closure a part states, (its socket, the other part or None, the other part's socket), or None. The + other part is a pointer: it follows a rename and reads None once the part is deleted. close, set_params, + detach and every report read it here.""" + if CLOSE not in obj: + return None + other = obj.get(CLOSE_TO) + return str(obj[CLOSE]), other if isinstance(other, bpy.types.Object) else None, str(obj.get(CLOSE_TO_SOCKET, "")) + + +def closing_on(part) -> list: + """The parts whose closure names this one.""" + return [obj for obj in bpy.data.objects if CLOSE in obj and obj.get(CLOSE_TO) == part] + + +def occupant(part, socket: str): + """The name of what holds a socket of a part, or None: a child attached there, the parent the part itself is + attached by, the part its own closure closes on, or a part whose closure names it there. The one occupancy + rule, for attach and close.""" + for child in attached(part): + if child.get(PARENT_SOCKET) == socket: + return child.name + if part.get(SOCKET) == socket: + return part.parent.name if part.parent else part.name + if part.get(CLOSE) == socket: + return closure(part)[1].name if closure(part)[1] else part.name + for other in closing_on(part): + if other.get(CLOSE_TO_SOCKET) == socket: + return other.name + return None + + +def free(part, socket: str) -> None: + holder = occupant(part, socket) + if holder is not None: + raise Refused(f"Socket {socket!r} of {part.name!r} is occupied (by {holder!r}); nothing changed.") + + +def mated(parent, parent_part, parent_built, child, child_part, child_built, stated, how="on"): """(parent socket, child socket) of the connection `stated` between two built parts, or a refusal that names it: a roll that is not a number, parts of two kits, a socket name a part does not have, or sockets - core.mate_refusal will not mate.""" + core.mate_refusal will not mate. A closure is checked here too (how "closing on"), the part it names as the + parent.""" if stated[2] is None: raise Refused(f"{child.name!r} on {parent.name!r}: its {ROLL} is not a number: detach it and attach it again; nothing changed.") try: @@ -141,7 +186,7 @@ def mated(parent, parent_part, parent_built, child, child_part, child_built, sta except core.KitError as error: refusal = str(error) if refusal: - raise Refused(f"{child.name!r} on {parent.name!r}: {refusal}; nothing changed.") + raise Refused(f"{child.name!r} {how} {parent.name!r}: {refusal}; nothing changed.") return sockets @@ -173,12 +218,55 @@ def connection_report(obj, part, built): return row +def closure_report(obj, part, built): + """None for a part that states no closure, else what it states and whether it holds: the other part is a kit + part of the same kit, both sockets exist, and the two stand within HELD of meeting (core.closure_residual). + `to` is null when the other part is gone or is not a part of this kit. Derived at each report; stored nowhere.""" + stated = closure(obj) + if stated is None: + return None + row = {"to": None, "socket": stated[0], "toSocket": stated[2], "residual": None, "holds": False} + try: + if stated[1] is None: + return row + other_part, other_built = built_part(stated[1]) + if other_part["kit"] != part["kit"]: + return row + row["to"] = stated[1].name + there, here = core.joint(other_part, other_built, stated[2], part, built, stated[0]) + except (Refused, core.KitError): + return row + row["residual"] = round(core.closure_residual(stated[1].matrix_world, there, obj.matrix_world, here), 9) + row["holds"] = bool(row["residual"] <= HELD) + return row + + +def scene_closures(context, report: dict) -> list: + """Every closure stated in the scene as {part, to, holds}, by part name, for a set_params report: a change of + params can open a closure anywhere below the part. Rows are left out, and counted in closuresOmitted, once + the report would pass what a receipt carries.""" + rows, size = [], len(json.dumps(report, separators=(",", ":"))) + 40 + for obj in sorted((o for o in context.scene.objects if o.type == "MESH" and CLOSE in o), key=lambda o: o.name): + try: + found = closure_report(obj, *built_part(obj)) + except (Refused, core.KitError): + found = {"to": None, "holds": False} + row = {"part": obj.name, "to": found["to"], "holds": found["holds"]} + size += len(json.dumps(row, separators=(",", ":"))) + 1 + if size > REPORT_LIMIT: + report["closuresOmitted"] = report.get("closuresOmitted", 0) + 1 + else: + rows.append(row) + return rows + + def part_report(obj, part, built) -> dict: """A part as the scene has it. Reads stored properties and matrices only: no modifier is evaluated.""" return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, "faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world)), - "connection": connection_report(obj, part, built), "baked": bool(obj.get(BAKED, False))} + "connection": connection_report(obj, part, built), "closure": closure_report(obj, part, built), + "baked": bool(obj.get(BAKED, False))} def own_mesh(obj, doing: str) -> None: @@ -258,7 +346,7 @@ class BROKKR_KITBASH_OT_place_part(PolishOperator): class BROKKR_KITBASH_OT_set_params(PolishOperator): """Change params of a placed kit part and rebuild its mesh in place: its modifiers and material slots stay, each shape keeps its faces' material, the Bevel width follows, and its connection and those of the parts - attached to it are seated again on the moved sockets""" + attached to it are seated again on the moved sockets; a closure is never seated, only reported""" bl_idname = "brokkr_kitbash.set_params" bl_label = "Set Kit Part Params" object_name: bpy.props.StringProperty(name="Object") @@ -273,6 +361,11 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): "place_part a new part to change them; nothing changed.") own_mesh(obj, "rebuilding") built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored)) + closing = closure(obj) # a closure this part is an end of must still be one its new sockets may make; where they stand is only reported + if closing is not None and closing[1] is not None: + mated(closing[1], *built_part(closing[1]), obj, part, built, (closing[0], closing[2], 0.0), "closing on") + for other in closing_on(obj): + mated(obj, part, built, other, *built_part(other), (closure(other)[0], closure(other)[2], 0.0), "closing on") seats, stated = [], link(obj) # every connection this part is an end of, checked against its new sockets before anything is written if stated is not None: if obj.parent is None: @@ -298,7 +391,9 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): seat(seated, basis) if seats: context.view_layer.update() - return part_report(obj, part, built) + report = part_report(obj, part, built) + report["closures"] = scene_closures(context, report) + return report class BROKKR_KITBASH_OT_attach(PolishOperator): @@ -330,14 +425,8 @@ class BROKKR_KITBASH_OT_attach(PolishOperator): ancestor = ancestor.parent stated = (self.socket, self.parent_socket, float(self.roll)) sockets = mated(parent, parent_part, parent_built, child, part, built, stated) - users = [c.name for c in attached(parent) if c.get(PARENT_SOCKET) == self.parent_socket] - if parent.get(SOCKET) == self.parent_socket: - users.append(parent.parent.name if parent.parent else parent.name) - if users: - raise Refused(f"Socket {self.parent_socket!r} of {parent.name!r} is occupied (by {users[0]!r}); nothing changed.") - users = [c.name for c in attached(child) if c.get(PARENT_SOCKET) == self.socket] - if users: - raise Refused(f"Socket {self.socket!r} of {child.name!r} is occupied (by {users[0]!r}); nothing changed.") + free(parent, self.parent_socket) + free(child, self.socket) child.parent = parent seat(child, core.mate(*sockets, stated[2])) child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated @@ -346,8 +435,8 @@ class BROKKR_KITBASH_OT_attach(PolishOperator): class BROKKR_KITBASH_OT_detach(PolishOperator): - """Clear a kit part's connection: it stays where it stands in the world, loses its parent, and the parts - attached to it stay attached to it""" + """Clear a kit part's connection and the closure it states: it stays where it stands in the world, loses its + parent, and the parts attached to it stay attached to it""" bl_idname = "brokkr_kitbash.detach" bl_label = "Detach Kit Part" object_name: bpy.props.StringProperty(name="Object") @@ -355,18 +444,50 @@ class BROKKR_KITBASH_OT_detach(PolishOperator): @kit_work def work(self, context): obj = mesh_object(self.object_name) - if SOCKET not in obj: - raise Refused(f"{obj.name!r} is not attached (it has no {SOCKET} property); nothing changed.") + if SOCKET not in obj and CLOSE not in obj: + raise Refused(f"{obj.name!r} is not attached (it has no {SOCKET} property) and states no closure; nothing changed.") part, built = built_part(obj) - world = obj.matrix_world.copy() - obj.parent = None - obj.matrix_world = world - for key in (SOCKET, PARENT_SOCKET, ROLL): + if SOCKET in obj: + world = obj.matrix_world.copy() + obj.parent = None + obj.matrix_world = world + for key in (SOCKET, PARENT_SOCKET, ROLL, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET): if key in obj: del obj[key] return part_report(obj, part, built) +class BROKKR_KITBASH_OT_close(PolishOperator): + """State that a socket of a kit part meets a socket of another part of its kit, closing a loop the tree of + connections cannot: accepted only when the two already meet, origins together and normals opposed, and it + moves nothing""" + bl_idname = "brokkr_kitbash.close" + bl_label = "Close Kit Loop" + object_name: bpy.props.StringProperty(name="Object", description="The closing part: it states the closure") + socket: bpy.props.StringProperty(name="Socket", description="The closing part's socket") + other_name: bpy.props.StringProperty(name="Other", description="The part it closes on") + other_socket: bpy.props.StringProperty(name="Other Socket") + + @kit_work + def work(self, context): + obj, other = mesh_object(self.object_name), mesh_object(self.other_name) + part, built = built_part(obj) + other_part, other_built = built_part(other) + if obj == other: + raise Refused(f"{obj.name!r} cannot close on itself; nothing changed.") + if closure(obj) is not None: + raise Refused(f"{obj.name!r} already states a closure (its socket {closure(obj)[0]!r}): a part states one, and detach clears it; nothing changed.") + there, here = mated(other, other_part, other_built, obj, part, built, (self.socket, self.other_socket, 0.0), "closing on") + free(other, self.other_socket) + free(obj, self.socket) + apart = core.closure_residual(other.matrix_world, there, obj.matrix_world, here) + if apart > HELD: + raise Refused(f"Socket {self.socket!r} of {obj.name!r} and socket {self.other_socket!r} of {other.name!r} stand {apart:.6g} m apart: " + "place them so they meet (attach with the roll that closes the loop); nothing changed.") + obj[CLOSE], obj[CLOSE_TO], obj[CLOSE_TO_SOCKET] = self.socket, other, self.other_socket + return part_report(obj, part, built) + + class BROKKR_KITBASH_OT_boolean(PolishOperator): """Cut a kit part with another mesh object through a live Boolean modifier (Exact, with self-intersection: kit parts are overlapping shells) placed above the Bevel; evaluates the part once and reports the result""" @@ -453,7 +574,7 @@ class BROKKR_KITBASH_OT_describe(PolishOperator): class BROKKR_KITBASH_OT_report(PolishOperator): """Report placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world frame, - the connection and whether it holds, and whether the part is baked""" + the connection and the closure and whether each holds, and whether the part is baked""" bl_idname = "brokkr_kitbash.report" bl_label = "Report Kit Parts" bl_options = {"REGISTER"} @@ -467,7 +588,7 @@ class BROKKR_KITBASH_OT_report(PolishOperator): classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report, - BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_apply) + BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, 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 e75ec1b..6bd1ba7 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -160,7 +160,7 @@ }, { "name": "brokkr_kitbash.detach", - "doc": "Clear a kit part's connection: it keeps its place in the world and loses its parent; parts attached to it stay attached to it.", + "doc": "Clear a kit part's connection and the closure it states: it keeps its place in the world and loses its parent; parts attached to it stay attached to it.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -174,6 +174,49 @@ } ] }, + { + "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.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the closing part: it states the closure, one at most" + }, + { + "name": "socket", + "type": "string", + "required": true, + "chars": "id", + "minLength": 1, + "maxLength": 32, + "doc": "the closing part's socket" + }, + { + "name": "other_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the part it closes on" + }, + { + "name": "other_socket", + "type": "string", + "required": true, + "chars": "id", + "minLength": 1, + "maxLength": 32, + "doc": "that part's socket" + } + ] + }, { "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.", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 489bac0..3f7c3cf 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -621,6 +621,15 @@ def residual(parent_world, parent_socket: dict, child_world, child_socket: dict, return float(np.abs(wanted - np.asarray(child_world, dtype=np.float64) @ child_socket["matrix"]).max()) +def closure_residual(world_a, socket_a: dict, world_b, socket_b: dict) -> float: + """How far two sockets of two placed parts stand from meeting as a pin: the larger of the largest difference + between their origins (metres) and the largest entry of the sum of their normals (0 when opposed). Roll is not + read: a closure is a pin, free about its axis.""" + a = np.asarray(world_a, dtype=np.float64) @ socket_a["matrix"] + b = np.asarray(world_b, dtype=np.float64) @ socket_b["matrix"] + return float(max(np.abs(a[:3, 3] - b[:3, 3]).max(), np.abs(a[:3, 2] + b[:3, 2]).max())) + + EQUAL, SLACK = 0.01, 1e-9 # 'equal' sizes may differ by 1 percent of the larger; SLACK keeps a size at the limit inside it diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 1ba8a66..bee7098 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -6,7 +6,7 @@ actuators, housings and plumbing an agent assembles offline under a hand-fit arm add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish` and `brokkr_rig`: it imports the polish package's operator base, `Refused` and `mesh_object`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish` first; `brokkr_kitbash` refuses to register without it. `brokkr_actions.json` beside -its `__init__.py` lists the eight operators agents may run. Every action writes a JSON report to +its `__init__.py` lists the nine operators agents may run. Every action writes a JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. Who owns what: @@ -27,6 +27,9 @@ Who owns what: - A connection between two parts belongs to the child: its parent pointer and its `kit_socket`, `kit_parent_socket` and `kit_roll` properties. Where the child stands is derived from them ("Assembling parts"). +- A closure, the joint that closes a loop, belongs to the closing part: its `kit_close_socket`, `kit_close_to` + and `kit_close_to_socket` properties. Only `close` writes them and only `detach` clears them. A closure places + nothing: whether it holds is derived at each report. - A boolean belongs to its Boolean modifier on the part that is cut. `kit_baked` says `apply` replaced the part's mesh with the evaluated one. @@ -143,11 +146,54 @@ refuses, changing nothing: - a child that has a parent (`detach` it; `setObjectParent` with an empty parent clears a parent it was not attached to); - a parent that is the child, or is below it (a loop); -- an occupied socket: one a child is already attached to, or the one the part itself is attached by; +- an occupied socket: one a child is already attached to, the one the part itself is attached by, or one a + closure holds, at either end; - a part that is not a kit part, or is scaled in the world. -A part may carry a child on every socket but the one it hangs by, so assemblies are trees: tank, then a tee on -its port, then a nozzle on each free flange of the tee. +A part may carry a child on every socket but the one it hangs by. Connections are a tree: tank, then a tee on +its port, then a nozzle on each free flange of the tee. Nothing moves a part but `attach` and `set_params`, +through that tree. + +**A closure** states the one thing a tree cannot: that a part's second socket also meets something. A brace +hangs from its own bracket by one pin (a connection); its other pin meets the leg's rod (a closure), and the +hull, leg and brace are then a loop. The closing part owns it, one at most, as three ID properties: +`kit_close_socket` (its own socket), `kit_close_to` (the other part, held as a pointer, so it follows a rename +and reads empty once that part is deleted) and `kit_close_to_socket`. A spanning tree plus loop-closing +constraints is how closed chains are usually stated (Featherstone, Rigid Body Dynamics Algorithms, ch. 8; +MuJoCo's `connect` equality on its kinematic tree). + +`close` writes those three properties and nothing else. It never moves a part: it is accepted only when the two +sockets already meet, origins together and normals opposed within 1e-5, at any roll (a closure is a pin). It +refuses, changing nothing: a part that is not a kit part or is scaled, a part closing on itself, two sockets +that may not mate (the part it names counts as the parent), an occupied socket at either end, a part that +already states a closure, and two sockets that do not meet, saying how far apart they stand. + +Making them meet is the caller's work, and nothing in the add-on solves a loop. For two members pinned in one +plane it is a triangle. With `a` and `b` the two members' pin-to-pin lengths and `d` the distance between the +two fixed pins, the angle at the first fixed pin between the line to the second and the first member is + +```text +acos((a*a + d*d - b*b) / (2*a*d)) +``` + +which gives the point where the free pins meet. Each member's roll is then the angle, about its fixed pin's +`z`, from that socket's `y` to the direction of the meeting point. `report` gives every socket's world frame to +read these from. + +A part's report carries `closure`: `null`, or + +```json +{"to": "Leg", "socket": "end_b", "toSocket": "rod_end", "residual": 3.9e-07, "holds": true} +``` + +`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. `to` is `null`, and `holds` false, when the other part +is gone or is not a part of this kit. 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 +moves a socket (an actuator's `extension` under a closed brace) is accepted and opens the closure: the report +of `set_params` lists every closure in the scene as `closures: [{part, to, holds}]`, so the caller sees which +ones it opened and can solve the rolls again, `detach` and `attach` the members, and find the closure holding. +`detach` clears the closing part's closure together with its connection. **`set_params` keeps an assembly together.** Sockets move with params (an actuator's `rod_end` with `extension`, a tank's `port_b` with `length`). After the rebuild `set_params` writes the derived `matrix_basis` of the part @@ -219,10 +265,11 @@ vertices overflow. | --- | --- | --- | | `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | | `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, and a baked part. | -| `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` and `baked`. Changes nothing and evaluates no modifier. | +| `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}` (with `closuresOmitted`, a count, if they would not fit a receipt). | +| `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.detach` | `object_name` | Clears the part's connection; it stays where it stands. Refuses a part that is not attached. | +| `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. | @@ -323,4 +370,4 @@ builds: a `min` or `max` in an expression keeps a derived length positive where 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 `tests/live/kitbash.py` (placing and re-parameterising) and `tests/live/kitbash_assembly.py` (attach, detach, -`set_params` on assemblies, boolean and apply). +`set_params` on assemblies, a braced leg closed by `close`, boolean and apply). diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 94b812c..b4be991 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 eight kitbash rows load as host actions with no errors", not R["hostErrors"] +check("the nine 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", "boolean", "apply")], [R["hostErrors"], R["hostRows"]]) + "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "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 7b0de47..765c5af 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 eight kitbash rows load as host actions with no errors", + "name": "the nine kitbash rows load as host actions with no errors", "ok": true, "detail": null }, @@ -412,6 +412,7 @@ "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", + "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.apply" ], diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 184a4d2..27341a9 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -1,6 +1,6 @@ """Live proof, in a background Blender, of brokkr_kitbash assembly through run_intent: attach and its refusals, -set_params seating a part and the parts attached to it again, drift and how it is cleared, a roll that is not a -number, detach, boolean (Exact, self-intersection on, above the Bevel), and apply with its material slots. Not part +set_params seating a part and the parts attached to it again, a braced leg closed by close and what set_params, +attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (Exact, self-intersection on, above the Bevel), and apply with its material slots. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_assembly.py -- @@ -17,6 +17,7 @@ import importlib.util import json import math import os +import re import sys import tempfile import types @@ -174,8 +175,8 @@ def evaluated(obj): rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] -check("the eight 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", "boolean", "apply")], [R["hostErrors"], rows]) +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]) # --- attach ------------------------------------------------------------------------------------------------------------- tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088 @@ -229,7 +230,7 @@ refused("a child that is not a kit part", "brokkr_kitbash.attach", {"object_name "'Plain' is not a kit part") refused("a parent that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Plain", "parent_socket": "b"}, "'Plain' is not a kit part") -refused("detach of a part that is not attached", "brokkr_kitbash.detach", {"object_name": "Spare"}, "'Spare' is not attached") +refused("detach of a part that is not attached", "brokkr_kitbash.detach", {"object_name": "Spare"}, "'Spare' is not attached (it has no kit_socket property) and states no closure") send("brokkr_kitbash.detach", object_name="Tee") send("setObjectTransform", targetObjectName="Tee", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) refused("a child socket one of its own children is on", "brokkr_kitbash.attach", {"object_name": "Tee", "socket": "c", "parent_name": "Tank", "parent_socket": "port_b"}, @@ -281,6 +282,125 @@ check("extending the actuator above moves the strut on its rod and the ram below and reading("carried", np.abs(frame(strut, "end_b")[:3, 3] - tip[:3, 3] - np.array(lift.matrix_world)[:3, 2] * 0.45).max()) < CARRIED, [receipt["message"], connection("Strut"), connection("Ram")]) +# --- a closure: a brace from a second bracket closes on the leg's rod pin ------------------------------------------------------------ +hull = place("Hull", "tank", "radius=0.3; length=1.2", location=[6.0, 0.0, 2.0], rotation=[0.0, math.pi, 0.4]) # lug size 0.09 +upper, lower = place("Upper", "bracket"), place("Lower", "bracket") # pin 0.054, plate 0.09 +send("brokkr_kitbash.attach", object_name="Upper", socket="mount", parent_name="Hull", parent_socket="lug_b") +send("brokkr_kitbash.attach", object_name="Lower", socket="mount", parent_name="Hull", parent_socket="lug_a", roll=180.0) # turned half: its pin face looks back at Upper's +leg, brace, tie = place("Leg", "actuator"), place("Brace", "strut", "width=0.09; length=1.1"), place("Tie", "strut", "width=0.09") +p1, p2 = frame(upper, "pivot"), frame(lower, "pivot") +check("a bracket turned half on the next lug pins on the first one's plane, facing it", abs((p2[:3, 3] - p1[:3, 3]) @ p1[:3, 2]) < SEATED + and np.abs(p1[:3, 2] + p2[:3, 2]).max() < SEATED, [p1.tolist(), p2.tolist()]) +span = {name: core.build(kit["parts"][part], given) for name, part, given in (("leg", "actuator", {}), ("brace", "strut", {"width": 0.09, "length": 1.1}))} +a = next(s for s in span["leg"].sockets if s["name"] == "rod_end")["matrix"][2, 3] - next(s for s in span["leg"].sockets if s["name"] == "base")["matrix"][2, 3] +b = next(s for s in span["brace"].sockets if s["name"] == "end_b")["matrix"][2, 3] - next(s for s in span["brace"].sockets if s["name"] == "end_a")["matrix"][2, 3] +d = float(np.linalg.norm(p2[:3, 3] - p1[:3, 3])) +corner = math.acos((a * a + d * d - b * b) / (2 * a * d)) # the law of cosines: the angle at the upper pin between the hull and the leg +knee = p1[:3, 3] + a * (math.cos(corner) * (p2[:3, 3] - p1[:3, 3]) / d + math.sin(corner) * frame(hull, "lug_b")[:3, 2]) + + +def roll_to(pin, toward): + """The roll that points a pinned member's axis (its socket's y) from this pin toward a point in the pin's plane.""" + toward = (toward - pin[:3, 3]) / np.linalg.norm(toward - pin[:3, 3]) + return math.degrees(math.atan2(np.cross(pin[:3, 1], toward) @ pin[:3, 2], pin[:3, 1] @ toward)) + + +def closure_of(name): + receipt, report = send("brokkr_kitbash.report", object_name=name) + return report["parts"][0]["closure"] if report else {"error": receipt["message"]} + + +def without_closures(state): + return {name: (*row[:3], {k: v for k, v in row[3].items() if not k.startswith("kit_close")}, *row[4:]) for name, row in state[0].items()}, state[1] + + +CLOSING = {"object_name": "Brace", "socket": "end_b", "other_name": "Leg", "other_socket": "rod_end"} +send("brokkr_kitbash.attach", object_name="Leg", socket="base", parent_name="Upper", parent_socket="pivot", roll=roll_to(p1, knee)) +send("brokkr_kitbash.attach", object_name="Brace", socket="end_a", parent_name="Lower", parent_socket="pivot", roll=roll_to(p2, knee) + 1.0) +apart = core.closure_residual(np.array(leg.matrix_world), next(s for s in span["leg"].sockets if s["name"] == "rod_end"), + np.array(brace.matrix_world), next(s for s in span["brace"].sockets if s["name"] == "end_b")) +state = scene_state() +receipt, _ = send("brokkr_kitbash.close", **CLOSING) +named = re.search(r"Socket 'end_b' of 'Brace' and socket 'rod_end' of 'Leg' stand (\S+) m apart: place them so they meet", str(receipt["message"])) +check("refused, scene unchanged: close of a brace that stands 1 degree off, naming how far apart the two sockets are", receipt["status"] != "accepted" + and named and abs(float(named.group(1)) - apart) < 1e-5 and 0.01 < apart < 0.02 and scene_state() == state, [receipt["message"], apart]) +send("brokkr_kitbash.detach", object_name="Brace") +send("brokkr_kitbash.attach", object_name="Brace", socket="end_a", parent_name="Lower", parent_socket="pivot", roll=roll_to(p2, knee)) +state = scene_state() +receipt, report = send("brokkr_kitbash.close", **CLOSING) +check("close states the closure on the brace when its end_b meets the leg's rod pin, and moves nothing", receipt["status"] == "accepted" + and reading("seated", seated(brace, "end_b", leg, "rod_end")) < SEATED and without_closures(scene_state()) == without_closures(state) + and (brace["kit_close_socket"], brace["kit_close_to"], brace["kit_close_to_socket"]) == ("end_b", leg, "rod_end") + and sorted(k for k in brace.keys() if k.startswith("kit_close")) == ["kit_close_socket", "kit_close_to", "kit_close_to_socket"] + and not [k for k in leg.keys() if k.startswith("kit_close")], [receipt["message"], dict(brace.items())]) +check("close reports the part: its closure holds, and its connection still does", report and report["object"] == "Brace" + and report["closure"] == {**report["closure"], "to": "Leg", "socket": "end_b", "toSocket": "rod_end", "holds": True} + and reading("closed", report["closure"]["residual"]) <= 1e-5 and held(report) and closure_of("Brace") == report["closure"] + and closure_of("Leg") is None, report) +refused("a second closure on a part that states one", "brokkr_kitbash.close", + {"object_name": "Brace", "socket": "end_b_back", "other_name": "Leg", "other_socket": "rod_end_back"}, "'Brace' already states a closure (its socket 'end_b')") +refused("close on a socket a closure holds", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end"}, + "Socket 'rod_end' of 'Leg' is occupied (by 'Brace')") +refused("close on the closing socket itself", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Brace", "other_socket": "end_b"}, + "Socket 'end_b' of 'Brace' is occupied (by 'Leg')") +refused("close on a socket a part is attached by", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "base"}, + "Socket 'base' of 'Leg' is occupied (by 'Upper')") +refused("close by a socket a part is attached by", "brokkr_kitbash.close", {"object_name": "Leg", "socket": "base", "other_name": "Tie", "other_socket": "end_a"}, + "Socket 'base' of 'Leg' is occupied (by 'Upper')") +refused("attach onto a socket a closure holds", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Leg", "parent_socket": "rod_end"}, + "Socket 'rod_end' of 'Leg' is occupied (by 'Brace')") +refused("attach onto the closing socket", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Brace", "parent_socket": "end_b"}, + "Socket 'end_b' of 'Brace' is occupied (by 'Leg')") +refused("close of a part on itself", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Tie", "other_socket": "end_b"}, "'Tie' cannot close on itself") +refused("close of sockets that may not mate", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Hull", "other_socket": "lug_a_back"}, + "'Tie' closing on 'Hull': socket 'end_a' (pivot, size 0.054) and parent socket 'lug_a_back' (mount, size 0.09) are of different types") +refused("close of two sockets that are apart", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end_back"}, "m apart: place them so they meet") +refused("close on a mesh that is not a kit part", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Plain", "other_socket": "a"}, "'Plain' is not a kit part") +refused("close of a socket the part does not have", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_c", "other_name": "Leg", "other_socket": "rod_end_back"}, + "part 'strut' has no socket 'end_c'") +was = np.array(brace.matrix_world) +receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") +found = closure_of("Brace") +check("set_params that moves the leg's rod pin is accepted and moves no brace: the closure reads holds false with the rod's travel, here and in the report's closures", + receipt["status"] == "accepted" and report and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": False}] and report["closure"] is None + and found["holds"] is False and 0.05 < found["residual"] <= 0.15 + 1e-5 and np.array_equal(np.array(brace.matrix_world), was) + and holds("Brace", "Lower", "end_a", "pivot", connection("Brace")["roll"])[0], [receipt["message"], report and report.get("closures"), found]) +receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") +check("and with the rod back the closure holds again: it is read from where the parts stand, not stored", receipt["status"] == "accepted" + and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": True}] and closure_of("Brace")["holds"] is True, [report and report.get("closures"), closure_of("Brace")]) +refused("set_params on the part a closure names, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Leg", "params": "body_r=0.07"}, + "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.054) and parent socket 'rod_end' (pivot, size 0.063)") +refused("set_params on the closing part, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Brace", "params": "width=0.1"}, + "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.06) and parent socket 'rod_end' (pivot, size 0.054)") +receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") +check("set_params on the closing part that keeps its pin size is accepted and lists its own closure: a brace 0.1 shorter stops 0.1 short of the rod pin", + receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": False}] and report["closure"]["holds"] is False + and held(report) and 0.1 / math.sqrt(3) - 1e-5 <= report["closure"]["residual"] <= 0.1 + 1e-5, [receipt["message"], report and report["closure"]]) +send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.1") +before = np.array(brace.matrix_world) +receipt, report = send("brokkr_kitbash.detach", object_name="Brace") +check("detach clears the brace's closure with its connection, and it stays where it stood", receipt["status"] == "accepted" and report and report["closure"] is None + and report["connection"] is None and not [k for k in brace.keys() if k.startswith(("kit_close", "kit_socket", "kit_parent", "kit_roll"))] and brace.parent is None + and reading("kept", np.abs(np.array(brace.matrix_world) - before).max()) < KEPT, [receipt["message"], dict(brace.items())]) +receipt, report = send("brokkr_kitbash.close", **CLOSING) +check("a loose part that meets a socket may state a closure too", receipt["status"] == "accepted" and report["closure"]["holds"] is True and report["connection"] is None, receipt["message"]) +leg.name = "Shin" +found = closure_of("Brace") +check("a closure follows its other part through a rename", found.get("to") == "Shin" and found.get("holds") is True, found) +leg.name = "Leg" +send("brokkr_kitbash.detach", object_name="Leg") +bpy.data.objects.remove(leg) +found = closure_of("Brace") +receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") +check("a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", found == {**found, "to": None, "residual": None, "holds": False} + and found.get("toSocket") == "rod_end" and receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": None, "holds": False}], [found, receipt["message"]]) +before = np.array(brace.matrix_world) +receipt, report = send("brokkr_kitbash.detach", object_name="Brace") +check("detach of a part that states only a closure clears it and leaves the part where it stood", receipt["status"] == "accepted" and report["closure"] is None + and not [k for k in brace.keys() if k.startswith("kit_close")] and np.array_equal(np.array(brace.matrix_world), before), [receipt["message"], dict(brace.items())]) +receipt, report = send("brokkr_kitbash.attach", object_name="Tie", socket="end_a", parent_name="Brace", parent_socket="end_b") +check("and the socket the closure held is free again", receipt["status"] == "accepted" and held(report), receipt["message"]) + # --- drift and detach --------------------------------------------------------------------------------------------------------- send("setObjectTransform", targetObjectName="Nozzle", location=[0.25, 0.0, 0.0]) found = connection("Nozzle") or {} diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index df36b95..ad7a3a7 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 eight kitbash rows load as host actions with no errors", + "name": "the nine kitbash rows load as host actions with no errors", "ok": true, "detail": null }, @@ -141,6 +141,141 @@ "ok": true, "detail": null }, + { + "name": "a bracket turned half on the next lug pins on the first one's plane, facing it", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close of a brace that stands 1 degree off, naming how far apart the two sockets are", + "ok": true, + "detail": null + }, + { + "name": "close states the closure on the brace when its end_b meets the leg's rod pin, and moves nothing", + "ok": true, + "detail": null + }, + { + "name": "close reports the part: its closure holds, and its connection still does", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a second closure on a part that states one", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close on a socket a closure holds", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close on the closing socket itself", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close on a socket a part is attached by", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close by a socket a part is attached by", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: attach onto a socket a closure holds", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: attach onto the closing socket", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close of a part on itself", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close of sockets that may not mate", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close of two sockets that are apart", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close on a mesh that is not a kit part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close of a socket the part does not have", + "ok": true, + "detail": null + }, + { + "name": "set_params that moves the leg's rod pin is accepted and moves no brace: the closure reads holds false with the rod's travel, here and in the report's closures", + "ok": true, + "detail": null + }, + { + "name": "and with the rod back the closure holds again: it is read from where the parts stand, not stored", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on the part a closure names, to a size its pin no longer mates", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on the closing part, to a size its pin no longer mates", + "ok": true, + "detail": null + }, + { + "name": "set_params on the closing part that keeps its pin size is accepted and lists its own closure: a brace 0.1 shorter stops 0.1 short of the rod pin", + "ok": true, + "detail": null + }, + { + "name": "detach clears the brace's closure with its connection, and it stays where it stood", + "ok": true, + "detail": null + }, + { + "name": "a loose part that meets a socket may state a closure too", + "ok": true, + "detail": null + }, + { + "name": "a closure follows its other part through a rename", + "ok": true, + "detail": null + }, + { + "name": "a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", + "ok": true, + "detail": null + }, + { + "name": "detach of a part that states only a closure clears it and leaves the part where it stood", + "ok": true, + "detail": null + }, + { + "name": "and the socket the closure held is free again", + "ok": true, + "detail": null + }, { "name": "setObjectTransform on an attached child shows in its report: holds false, with the residual", "ok": true, @@ -405,11 +540,12 @@ "hostErrors": [], "readings": { "carried": 2.6e-07, + "closed": 3.9e-07, "cut": 0.25, - "kept": 1.5e-08, + "kept": 6e-08, "nudged": 0.00032, "roll": 6.6e-06, - "seated": 2.1e-07 + "seated": 3.9e-07 }, "tank": { "raw": { diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 05da9e8..7300431 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -646,6 +646,52 @@ class MateTests(unittest.TestCase): with_default_tank = core.joint(parts["tank"], core.build(parts["tank"]), "lug_a", parts["bracket"], core.build(parts["bracket"]), "mount") self.assertIn("it is larger", core.mate_refusal(self.kit["socketTypes"], *with_default_tank)) # a lug seats a plate up to 0.3 of the tank's radius + CLOSED = 2.5e-9 # shipped 2.2e-16; least mutant 0.028 (J1, the bracket's pivot face 2*ear_t off its centre plane); separation 1.1e7 + + def brace(self, length, turned=180.0, off=0.0): + """(leg world, its rod_end, brace world, its end_b) of a braced leg on a tank's +x lugs: a bracket on lug_b + carries an actuator by its base, a bracket on lug_a at roll `turned` carries a strut of this length by end_a, + and the two rolls are solved by the law of cosines so the strut's end_b meets the rod's pin.""" + parts = self.kit["parts"] + built = {name: core.build(parts[part], given) for name, part, given in ( + ("tank", "tank", {"radius": 0.3, "length": 1.2}), ("bracket", "bracket", {}), ("leg", "actuator", {}), ("brace", "strut", {"width": 0.09, "length": length}))} + socket = lambda name, key: next(s for s in built[name].sockets if s["name"] == key) # noqa: E731 + upper = core.mate(socket("tank", "lug_b"), socket("bracket", "mount"), 0.0) + lower = core.mate(socket("tank", "lug_a"), socket("bracket", "mount"), turned) + p1, p2 = upper @ socket("bracket", "pivot")["matrix"], lower @ socket("bracket", "pivot")["matrix"] + a = socket("leg", "rod_end")["matrix"][2, 3] - socket("leg", "base")["matrix"][2, 3] # pin to pin along the leg + b = socket("brace", "end_b")["matrix"][2, 3] - socket("brace", "end_a")["matrix"][2, 3] + d = float(np.linalg.norm(p2[:3, 3] - p1[:3, 3])) + along, out = (p2[:3, 3] - p1[:3, 3]) / d, np.array([1.0, 0.0, 0.0]) # down the tank, and away from it + angle = math.acos((a * a + d * d - b * b) / (2 * a * d)) # at the upper pin, between the tank and the leg + knee = p1[:3, 3] + a * (math.cos(angle) * along + math.sin(angle) * out) + + def roll_to(pin, toward): # the roll that points a pinned member's axis (its socket's y) from this pin toward a point + toward = (toward - pin[:3, 3]) / np.linalg.norm(toward - pin[:3, 3]) + return math.degrees(math.atan2(np.cross(pin[:3, 1], toward) @ pin[:3, 2], pin[:3, 1] @ toward)) + + leg = upper @ core.mate(socket("bracket", "pivot"), socket("leg", "base"), roll_to(p1, knee)) + strut = lower @ core.mate(socket("bracket", "pivot"), socket("brace", "end_a"), roll_to(p2, knee) + off) + return leg, socket("leg", "rod_end"), strut, socket("brace", "end_b") + + def test_a_brace_closes_on_a_leg(self): + """closure. A tree states the leg and the brace; the brace's far pin meets the leg's only by the rolls. Mutants J1 + (the bracket's pivot face at x = -ear_t: the turned bracket pins 2*ear_t off the plane), J3 (closure_residual + drops the normal term: a bracket not turned reads 0) and J2.""" + worst = 0.0 + for length in (0.9, 1.1, 1.3): + worst = max(worst, core.closure_residual(*self.brace(length))) + self.assertAlmostEqual(core.closure_residual(*self.brace(length, turned=0.0)), 2.0, places=9) # not turned: the two pin faces look the same way + chord = 2 * (length - 0.081) * math.sin(math.radians(0.5)) # the brace swung 1 degree off: its far pin moves this far, and the residual is the move's largest entry + self.assertTrue(chord / math.sqrt(3) - 1e-12 <= core.closure_residual(*self.brace(length, off=1.0)) <= chord + 1e-12) + self.assertLess(worst, self.CLOSED) + leg, rod_end, strut, end_b = self.brace(1.1) + turned = strut @ core._roll(0.0) + turned[:3, :3] = strut[:3, :3] @ np.linalg.inv(end_b["matrix"][:3, :3]) @ core._rotation((0.0, 0.0, 77.0)) @ end_b["matrix"][:3, :3] + turned[:3, 3] += (strut @ end_b["matrix"])[:3, 3] - (turned @ end_b["matrix"])[:3, 3] + self.assertLess(core.closure_residual(leg, rod_end, turned, end_b), self.CLOSED) # a closure is a pin: any turn about it still meets + self.assertGreater(core.residual(leg, rod_end, turned, end_b, 0.0), 0.5) + def test_residual_is_how_far_the_child_stands_from_its_mate(self): sp, sc = self.sockets(*self.PAIRS[0]) world = np.eye(4) @@ -726,7 +772,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.boolean", "brokkr_kitbash.apply"] + "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.apply"] class HostFileTests(unittest.TestCase): @@ -767,10 +813,14 @@ class HostFileTests(unittest.TestCase): self.assertEqual(at.validate(attach, host)["roll"], 0) self.assertEqual(at.validate({**attach, "roll": -360}, host)["roll"], -360) boolean = {**envelope, "action": "brokkr_kitbash.boolean", "object_name": "Tank", "cutter": "Box"} + close = {**envelope, "action": "brokkr_kitbash.close", "object_name": "Brace", "socket": "end_b", "other_name": "Leg", "other_socket": "rod_end"} + self.assertEqual(at.validate(close, host)["other_socket"], "rod_end") self.assertEqual(at.validate(boolean, host)["operation"], "DIFFERENCE") for bad in ({**attach, "roll": 360.5}, {**attach, "socket": "a b"}, {**attach, "parent_socket": ""}, {**attach, "matrix": [1, 0, 0]}, {**boolean, "operation": "SLICE"}, {**boolean, "solver": "EXACT"}, {**boolean, "cutter": ""}, - {**envelope, "action": "brokkr_kitbash.apply"}, {**envelope, "action": "brokkr_kitbash.detach", "object_name": "x" * 64}): + {**envelope, "action": "brokkr_kitbash.apply"}, {**envelope, "action": "brokkr_kitbash.detach", "object_name": "x" * 64}, + {**close, "socket": "end b"}, {**close, "other_socket": "x" * 33}, {**close, "other_name": ""}, {**close, "roll": 10}, + {k: v for k, v in close.items() if k != "other_socket"}): with self.assertRaises(at.IntentInvalid, msg=str(bad)): at.validate(bad, host) for row in self.document["actions"][4:]: @@ -819,6 +869,24 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated"]) self.assertIn(writes[0], source.split("class BROKKR_KITBASH_OT_attach")[1].split("class BROKKR_KITBASH_OT_")[0]) + def test_only_close_writes_a_closure(self): + """A closure is the closing part's three properties: close assigns them, detach deletes them, nothing else does + either, and close assigns nothing that places a part (mutant J4: close seats the part).""" + source = self.sources()["__init__.py"] + bodies = {body.split("(")[0]: body for body in source.split("class BROKKR_KITBASH_OT_")[1:]} + keys = r"(?:CLOSE|CLOSE_TO|CLOSE_TO_SOCKET|\"kit_close_\w+\")" + assigned = re.findall(rf"[^\n]*\[{keys}\][^\n=]*=(?!=)[^\n]*", source) + self.assertEqual(assigned, [" obj[CLOSE], obj[CLOSE_TO], obj[CLOSE_TO_SOCKET] = self.socket, other, self.other_socket"]) + self.assertIn(assigned[0], bodies["close"]) + deleted = re.findall(r"[^\n]*\(SOCKET, PARENT_SOCKET, ROLL, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET\)[^\n]*\n[^\n]*\n\s*del obj\[key\]", source) + self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 1, True)) + self.assertEqual(source.count("CLOSE_TO]"), 1) # the one subscript write above; every read goes through .get + placing = r"matrix_basis|matrix_world\s*=(?!=)|matrix_parent_inverse|\.parent\s*=(?!=)|\bseat\(|\.location|\.rotation" + self.assertIsNone(re.search(placing, bodies["close"])) + for text in ("child.matrix_basis = basis", "obj.matrix_world = world", "obj.parent = other", "seat(obj, basis)"): + self.assertIsNotNone(re.search(placing, text)) + self.assertIsNotNone(re.search(placing, bodies["attach"])) + def test_the_patterns_bite(self): planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name', 'obj.modifiers.new("Turn", "SCREW")') From dc8dcdb0c3f1edee14aa33ec8a04fe7a1f992ffc Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 19:17:56 +0100 Subject: [PATCH 079/223] kitbash_assembly.py: a closure check that finds no closure fails by name instead of raising Mutant J5 (occupant ignores closures) ended the script on an AttributeError before any check printed; it now dies on the three occupancy refusals. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/kitbash_assembly.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 27341a9..bd1d656 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -310,6 +310,10 @@ def closure_of(name): return report["parts"][0]["closure"] if report else {"error": receipt["message"]} +def closure_row(name): + return closure_of(name) or {} + + def without_closures(state): return {name: (*row[:3], {k: v for k, v in row[3].items() if not k.startswith("kit_close")}, *row[4:]) for name, row in state[0].items()}, state[1] @@ -360,14 +364,14 @@ refused("close of a socket the part does not have", "brokkr_kitbash.close", {"ob "part 'strut' has no socket 'end_c'") was = np.array(brace.matrix_world) receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") -found = closure_of("Brace") +found = closure_row("Brace") check("set_params that moves the leg's rod pin is accepted and moves no brace: the closure reads holds false with the rod's travel, here and in the report's closures", receipt["status"] == "accepted" and report and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": False}] and report["closure"] is None and found["holds"] is False and 0.05 < found["residual"] <= 0.15 + 1e-5 and np.array_equal(np.array(brace.matrix_world), was) and holds("Brace", "Lower", "end_a", "pivot", connection("Brace")["roll"])[0], [receipt["message"], report and report.get("closures"), found]) receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") check("and with the rod back the closure holds again: it is read from where the parts stand, not stored", receipt["status"] == "accepted" - and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": True}] and closure_of("Brace")["holds"] is True, [report and report.get("closures"), closure_of("Brace")]) + and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": True}] and closure_row("Brace").get("holds") is True, [report and report.get("closures"), closure_of("Brace")]) refused("set_params on the part a closure names, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Leg", "params": "body_r=0.07"}, "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.054) and parent socket 'rod_end' (pivot, size 0.063)") refused("set_params on the closing part, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Brace", "params": "width=0.1"}, @@ -383,16 +387,16 @@ check("detach clears the brace's closure with its connection, and it stays where and report["connection"] is None and not [k for k in brace.keys() if k.startswith(("kit_close", "kit_socket", "kit_parent", "kit_roll"))] and brace.parent is None and reading("kept", np.abs(np.array(brace.matrix_world) - before).max()) < KEPT, [receipt["message"], dict(brace.items())]) receipt, report = send("brokkr_kitbash.close", **CLOSING) -check("a loose part that meets a socket may state a closure too", receipt["status"] == "accepted" and report["closure"]["holds"] is True and report["connection"] is None, receipt["message"]) +check("a loose part that meets a socket may state a closure too", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True and report["connection"] is None, receipt["message"]) leg.name = "Shin" -found = closure_of("Brace") +found = closure_row("Brace") check("a closure follows its other part through a rename", found.get("to") == "Shin" and found.get("holds") is True, found) leg.name = "Leg" send("brokkr_kitbash.detach", object_name="Leg") bpy.data.objects.remove(leg) -found = closure_of("Brace") +found = closure_row("Brace") receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") -check("a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", found == {**found, "to": None, "residual": None, "holds": False} +check("a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", found and found == {**found, "to": None, "residual": None, "holds": False} and found.get("toSocket") == "rod_end" and receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": None, "holds": False}], [found, receipt["message"]]) before = np.array(brace.matrix_world) receipt, report = send("brokkr_kitbash.detach", object_name="Brace") From 13ba0d05ac85655fe76ba15f14024710353ce5ea Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 20:15:01 +0100 Subject: [PATCH 080/223] brokkr_kitbash: a closure on a deleted, unlinked, scaled or doubly held part reads broken, with a reason Fixes the findings of verdict cut-kit-joints.s1. closure() reads the other part as gone when the pointer is empty or the object is in no collection: the pointer itself keeps a part deleted with the Delete operator in the file as an orphan, and the closure read it as holding. close refuses a part in no collection, and an orphaned closing part holds no socket. A closure's report gains reason, null when it holds: the other part is gone (to null); it cannot be read against (scaled by hand, not a kit part, of another kit; to names it); another part's closure names the same socket, as a duplicated closing part leaves, and then neither holds; or the sockets stand apart. set_params lists the closures its own part is an end of first, then the broken, then the rest, and leaves rows off the end when a receipt is full. It reads each kit file once per report: 3.9 s to 0.39 s at 150 closures, 12.8 s to 1.16 s at 450 (the cost was linear, two kit parses a closure). kitbash_assembly.py: close of a brace moved 3.2e-4 is refused, a receipt with room for one row keeps the opened closure and counts the other, and the unlink, Delete, scale and duplicate cases. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 106 +++++++++++------- surfaces/blender/docs/kitbash.md | 21 ++-- .../blender/tests/live/kitbash_assembly.py | 77 ++++++++++++- .../tests/live/kitbash_assembly.result.json | 61 ++++++++++ 4 files changed, 215 insertions(+), 50 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 4e9c72b..8edb244 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -95,9 +95,10 @@ def sync_bevel(obj, width: float) -> None: RIGID = 1e-5 # how far a world matrix's 3x3 may stand from a rotation -def kit_part_of(obj): +def kit_part_of(obj, kits=None): """(part, stored params) of a placed part, read from its ID properties. Refuses a part whose world transform is - not rigid: its socket frames would not be frames, and its size would have a second owner.""" + not rigid: its socket frames would not be frames, and its size would have a second owner. `kits` is a dict one + call may pass to read each kit file once while it reads many parts; nothing keeps it between calls.""" if PART not in obj: raise Refused(f"{obj.name!r} is not a kit part (it has no {PART} property); place_part makes one.") turn = np.array(obj.matrix_world)[:3, :3] @@ -111,12 +112,15 @@ def kit_part_of(obj): stored = None if not isinstance(stored, dict): raise Refused(f"{obj.name!r} has a {PARAMS} property that is not a JSON object.") - return core.part(core.load_kit(str(obj.get(KIT, ""))), str(obj[PART])), stored + name, kits = str(obj.get(KIT, "")), {} if kits is None else kits + if name not in kits: + kits[name] = core.load_kit(name) + return core.part(kits[name], str(obj[PART])), stored -def built_part(obj): +def built_part(obj, kits=None): """(part, the part built at the object's stored params): where its sockets are, baked or not.""" - part, stored = kit_part_of(obj) + part, stored = kit_part_of(obj, kits) return part, core.build(part, stored) @@ -137,17 +141,27 @@ def attached(obj) -> list: def closure(obj): """The closure a part states, (its socket, the other part or None, the other part's socket), or None. The - other part is a pointer: it follows a rename and reads None once the part is deleted. close, set_params, - detach and every report read it here.""" + other part is a pointer: it follows a rename. It reads None once the part is gone, which is when the pointer is + empty or the object is in no collection: the pointer itself keeps a deleted object in the file as an orphan. + close, set_params, detach and every report read it here.""" if CLOSE not in obj: return None other = obj.get(CLOSE_TO) - return str(obj[CLOSE]), other if isinstance(other, bpy.types.Object) else None, str(obj.get(CLOSE_TO_SOCKET, "")) + return str(obj[CLOSE]), other if isinstance(other, bpy.types.Object) and other.users_collection else None, str(obj.get(CLOSE_TO_SOCKET, "")) + + +def closers() -> dict: + """{(part, socket): [the parts in the scene whose closure names that socket]}, from one pass over the objects.""" + found = {} + for obj in bpy.data.objects: + if CLOSE in obj and obj.users_collection and closure(obj)[1] is not None: + found.setdefault((closure(obj)[1], closure(obj)[2]), []).append(obj) + return found def closing_on(part) -> list: """The parts whose closure names this one.""" - return [obj for obj in bpy.data.objects if CLOSE in obj and obj.get(CLOSE_TO) == part] + return [obj for (other, _), found in closers().items() if other == part for obj in found] def occupant(part, socket: str): @@ -161,9 +175,8 @@ def occupant(part, socket: str): return part.parent.name if part.parent else part.name if part.get(CLOSE) == socket: return closure(part)[1].name if closure(part)[1] else part.name - for other in closing_on(part): - if other.get(CLOSE_TO_SOCKET) == socket: - return other.name + for other in closers().get((part, socket), []): + return other.name return None @@ -218,46 +231,56 @@ def connection_report(obj, part, built): return row -def closure_report(obj, part, built): - """None for a part that states no closure, else what it states and whether it holds: the other part is a kit - part of the same kit, both sockets exist, and the two stand within HELD of meeting (core.closure_residual). - `to` is null when the other part is gone or is not a part of this kit. Derived at each report; stored nowhere.""" +def closure_report(obj, part, built, held=None, kits=None): + """None for a part that states no closure, else what it states, whether it holds and, when it does not, why + not: the other part is gone (`to` null); it is not a part this one can be read against (not a kit part, of + another kit, scaled, or without that socket); another part's closure names the same socket (a duplicated + closing part); or the two sockets stand more than HELD from meeting (core.closure_residual). Derived at each + report; stored nowhere. `held` is closers() and `kits` kit_part_of's, for a caller that reports many.""" stated = closure(obj) if stated is None: return None - row = {"to": None, "socket": stated[0], "toSocket": stated[2], "residual": None, "holds": False} + row = {"to": None, "socket": stated[0], "toSocket": stated[2], "residual": None, "holds": False, "reason": None} + if stated[1] is None: + row["reason"] = "the part it closed on is gone: deleted, or in no collection" + return row + row["to"] = stated[1].name try: - if stated[1] is None: - return row - other_part, other_built = built_part(stated[1]) - if other_part["kit"] != part["kit"]: - return row - row["to"] = stated[1].name + other_part, other_built = built_part(stated[1], kits) there, here = core.joint(other_part, other_built, stated[2], part, built, stated[0]) - except (Refused, core.KitError): + except (Refused, core.KitError) as error: + row["reason"] = str(error) return row row["residual"] = round(core.closure_residual(stated[1].matrix_world, there, obj.matrix_world, here), 9) - row["holds"] = bool(row["residual"] <= HELD) + rivals = [o.name for o in (closers() if held is None else held).get((stated[1], stated[2]), []) if o != obj] + if rivals: + row["reason"] = f"socket {stated[2]!r} of {stated[1].name!r} is also closed on by {rivals[0]!r}: one of them was copied; detach one" + elif row["residual"] > HELD: + row["reason"] = f"the two sockets stand {row['residual']:.6g} m apart" + row["holds"] = row["reason"] is None return row -def scene_closures(context, report: dict) -> list: - """Every closure stated in the scene as {part, to, holds}, by part name, for a set_params report: a change of - params can open a closure anywhere below the part. Rows are left out, and counted in closuresOmitted, once - the report would pass what a receipt carries.""" - rows, size = [], len(json.dumps(report, separators=(",", ":"))) + 40 - for obj in sorted((o for o in context.scene.objects if o.type == "MESH" and CLOSE in o), key=lambda o: o.name): +def scene_closures(context, report: dict, ends=()) -> list: + """Every closure stated in the scene as {part, to, holds}, for a set_params report: a change of params can open + a closure anywhere below the part. The closures `ends` are parts of come first, then those that do not hold, + then the rest, each by name; rows that would take the report past what a receipt carries are left off the end + and counted in closuresOmitted.""" + held, kits, rows = closers(), {}, [] + for obj in (o for o in context.scene.objects if o.type == "MESH" and CLOSE in o): try: - found = closure_report(obj, *built_part(obj)) - except (Refused, core.KitError): - found = {"to": None, "holds": False} - row = {"part": obj.name, "to": found["to"], "holds": found["holds"]} + found = closure_report(obj, *built_part(obj, kits), held, kits) + except (Refused, core.KitError): # the closing part itself cannot be read (scaled) + found = {"to": closure(obj)[1].name if closure(obj)[1] else None, "holds": False} + rows.append((obj not in ends and closure(obj)[1] not in ends, found["holds"], obj.name, {"part": obj.name, "to": found["to"], "holds": found["holds"]})) + kept, size = [], len(json.dumps(report, separators=(",", ":"))) + 40 + for *_, row in sorted(rows, key=lambda r: r[:3]): size += len(json.dumps(row, separators=(",", ":"))) + 1 if size > REPORT_LIMIT: - report["closuresOmitted"] = report.get("closuresOmitted", 0) + 1 - else: - rows.append(row) - return rows + report["closuresOmitted"] = len(rows) - len(kept) + break + kept.append(row) + return kept def part_report(obj, part, built) -> dict: @@ -392,7 +415,7 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): if seats: context.view_layer.update() report = part_report(obj, part, built) - report["closures"] = scene_closures(context, report) + report["closures"] = scene_closures(context, report, (obj,)) return report @@ -475,6 +498,9 @@ class BROKKR_KITBASH_OT_close(PolishOperator): other_part, other_built = built_part(other) if obj == other: raise Refused(f"{obj.name!r} cannot close on itself; nothing changed.") + for gone in (obj, other): + if not gone.users_collection: + raise Refused(f"{gone.name!r} is in no collection (a deleted object something still points to): a closure is between parts in the scene; nothing changed.") if closure(obj) is not None: raise Refused(f"{obj.name!r} already states a closure (its socket {closure(obj)[0]!r}): a part states one, and detach clears it; nothing changed.") there, here = mated(other, other_part, other_built, obj, part, built, (self.socket, self.other_socket, 0.0), "closing on") diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index bee7098..b46d57a 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -157,14 +157,15 @@ through that tree. **A closure** states the one thing a tree cannot: that a part's second socket also meets something. A brace hangs from its own bracket by one pin (a connection); its other pin meets the leg's rod (a closure), and the hull, leg and brace are then a loop. The closing part owns it, one at most, as three ID properties: -`kit_close_socket` (its own socket), `kit_close_to` (the other part, held as a pointer, so it follows a rename -and reads empty once that part is deleted) and `kit_close_to_socket`. A spanning tree plus loop-closing +`kit_close_socket` (its own socket), `kit_close_to` (the other part, held as a pointer, so it follows a rename) +and `kit_close_to_socket`. The pointer keeps a deleted part in the file as an orphan, so a part counts as gone +when the pointer is empty or the object is in no collection. A spanning tree plus loop-closing constraints is how closed chains are usually stated (Featherstone, Rigid Body Dynamics Algorithms, ch. 8; MuJoCo's `connect` equality on its kinematic tree). `close` writes those three properties and nothing else. It never moves a part: it is accepted only when the two sockets already meet, origins together and normals opposed within 1e-5, at any roll (a closure is a pin). It -refuses, changing nothing: a part that is not a kit part or is scaled, a part closing on itself, two sockets +refuses, changing nothing: a part that is not a kit part, is scaled or is in no collection, a part closing on itself, two sockets that may not mate (the part it names counts as the parent), an occupied socket at either end, a part that already states a closure, and two sockets that do not meet, saying how far apart they stand. @@ -183,15 +184,19 @@ read these from. A part's report carries `closure`: `null`, or ```json -{"to": "Leg", "socket": "end_b", "toSocket": "rod_end", "residual": 3.9e-07, "holds": true} +{"to": "Leg", "socket": "end_b", "toSocket": "rod_end", "residual": 3.9e-07, "holds": true, "reason": null} ``` `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. `to` is `null`, and `holds` false, when the other part -is gone or is not a part of this kit. A closure is never seated. `set_params` on either end refuses a change +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`); +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 moves a socket (an actuator's `extension` under a closed brace) is accepted and opens the closure: the report -of `set_params` lists every closure in the scene as `closures: [{part, to, holds}]`, so the caller sees which +of `set_params` lists every closure in the scene as `closures: [{part, to, holds}]`, those its own part is an +end of first, then those that do not hold, then the rest, so the caller sees which ones it opened and can solve the rolls again, `detach` and `attach` the members, and find the closure holding. `detach` clears the closing part's closure together with its connection. @@ -265,7 +270,7 @@ vertices overflow. | --- | --- | --- | | `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | | `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}` (with `closuresOmitted`, a count, if they would not fit a receipt). | +| `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.detach` | `object_name` | Clears the part's connection and the closure it states; it stays where it stands. Refuses a part that has neither. | diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index bd1d656..d5a4a00 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -26,6 +26,7 @@ from pathlib import Path import bmesh import bpy import numpy as np +from mathutils import Matrix SURFACE = Path(__file__).resolve().parents[2] sys.path.insert(0, str(SURFACE / "tools")) @@ -330,6 +331,16 @@ check("refused, scene unchanged: close of a brace that stands 1 degree off, nami and named and abs(float(named.group(1)) - apart) < 1e-5 and 0.01 < apart < 0.02 and scene_state() == state, [receipt["message"], apart]) send("brokkr_kitbash.detach", object_name="Brace") send("brokkr_kitbash.attach", object_name="Brace", socket="end_a", parent_name="Lower", parent_socket="pivot", roll=roll_to(p2, knee)) +# close-tolerance: the brace moved NUDGE (3.2e-4) off its seat. close accepts up to HELD, 1e-5; least claimed mutant 5e-4 (N2, 50 times +# HELD); NUDGE is 32 times the one and 0.64 of the other, as for the connection's own check below. +seat_was = np.array(brace.matrix_basis)[:3, 3] +send("setObjectTransform", targetObjectName="Brace", location=(seat_was + np.array(lower.matrix_world)[:3, :3].T @ [0.0, 0.0, NUDGE]).tolist()) +state = scene_state() +receipt, _ = send("brokkr_kitbash.close", **CLOSING) +named = re.search(r"stand (\S+) m apart", str(receipt["message"])) +check("refused, scene unchanged: close of a brace moved by NUDGE, which a report would read as not held", receipt["status"] != "accepted" and named + and abs(reading("close nudged", float(named.group(1))) - NUDGE) < 0.1 * NUDGE and scene_state() == state, receipt["message"]) +send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.1") # seats it again state = scene_state() receipt, report = send("brokkr_kitbash.close", **CLOSING) check("close states the closure on the brace when its end_b meets the leg's rod pin, and moves nothing", receipt["status"] == "accepted" @@ -339,7 +350,7 @@ check("close states the closure on the brace when its end_b meets the leg's rod and not [k for k in leg.keys() if k.startswith("kit_close")], [receipt["message"], dict(brace.items())]) check("close reports the part: its closure holds, and its connection still does", report and report["object"] == "Brace" and report["closure"] == {**report["closure"], "to": "Leg", "socket": "end_b", "toSocket": "rod_end", "holds": True} - and reading("closed", report["closure"]["residual"]) <= 1e-5 and held(report) and closure_of("Brace") == report["closure"] + and reading("closed", report["closure"]["residual"]) <= 1e-5 and report["closure"]["reason"] is None and held(report) and closure_of("Brace") == report["closure"] and closure_of("Leg") is None, report) refused("a second closure on a part that states one", "brokkr_kitbash.close", {"object_name": "Brace", "socket": "end_b_back", "other_name": "Leg", "other_socket": "rod_end_back"}, "'Brace' already states a closure (its socket 'end_b')") @@ -372,6 +383,51 @@ check("set_params that moves the leg's rod pin is accepted and moves no brace: t receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") check("and with the rod back the closure holds again: it is read from where the parts stand, not stored", receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": True}] and closure_row("Brace").get("holds") is True, [report and report.get("closures"), closure_of("Brace")]) +# closures-omitted: a second closure, named to sort first, far from the leg; then a receipt with room for one row. Mutant N5 (never +# omit) lists two rows; rows by name alone would keep Aa_Loose and drop the one this call opened. +anchor, loose = place("Aa_Anchor", "strut", "width=0.09", location=[0.0, -20.0, 0.0]), place("Aa_Loose", "strut", "width=0.09") +meet = Matrix((np.array(anchor.matrix_world) @ core.mate(next(s for s in core.build(kit["parts"]["strut"], {"width": 0.09}).sockets if s["name"] == "end_b"), + next(s for s in core.build(kit["parts"]["strut"], {"width": 0.09}).sockets if s["name"] == "end_a"), 40.0)).tolist()) +send("setObjectTransform", targetObjectName="Aa_Loose", location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) +receipt, report = send("brokkr_kitbash.close", object_name="Aa_Loose", socket="end_a", other_name="Aa_Anchor", other_socket="end_b") +check("a loose part placed to meet a socket closes on it", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) +receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") +ROWS = [{"part": "Brace", "to": "Leg", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] +check("set_params lists the closures its own part is an end of first, then the rest", receipt["status"] == "accepted" and report["closures"] == ROWS + and "closuresOmitted" not in report, report and report.get("closures")) +addon = sys.modules["brokkr_kitbash"] +limit = addon.REPORT_LIMIT +addon.REPORT_LIMIT = len(json.dumps({k: v for k, v in report.items() if k != "closures"}, separators=(",", ":"))) + 40 + len(json.dumps(ROWS[0], separators=(",", ":"))) + 1 +receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") +addon.REPORT_LIMIT = limit +check("with room for one row in the receipt, set_params keeps the closure it opened and counts the other in closuresOmitted", receipt["status"] == "accepted" + and report["closures"] == ROWS[:1] and report.get("closuresOmitted") == 1 and np.array_equal(np.array(brace.matrix_world), was), report and [report.get("closures"), report.get("closuresOmitted")]) +receipt, report = send("brokkr_kitbash.set_params", object_name="Aa_Anchor", params="length=0.9") +check("and a closure another part's set_params opened comes before one that holds", receipt["status"] == "accepted" + and report["closures"] == [{"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}, {"part": "Brace", "to": "Leg", "holds": False}], report and report.get("closures")) +send("brokkr_kitbash.detach", object_name="Aa_Loose") +send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") +leg.scale = (1.0001, 1.0, 1.0) +bpy.context.view_layer.update() +found = closure_row("Brace") +leg.scale = (1.0, 1.0, 1.0) +bpy.context.view_layer.update() +check("a closure on a part scaled by hand reads broken, naming the part and why, not gone", found.get("to") == "Leg" and found.get("holds") is False and found.get("residual") is None + and "'Leg' is scaled, mirrored or sheared" in str(found.get("reason")) and closure_row("Brace").get("holds") is True, found) +twin = brace.copy() # as Shift-D leaves it: a second part stating the same closure +twin.data = brace.data.copy() +twin.name = "Brace_twin" +bpy.context.scene.collection.objects.link(twin) +found, other = closure_row("Brace"), closure_row("Brace_twin") +check("two parts that state a closure on one socket both read not held, each naming the other", found.get("holds") is False and other.get("holds") is False + and "is also closed on by 'Brace_twin'" in str(found.get("reason")) and "is also closed on by 'Brace'" in str(other.get("reason")), [found, other]) +tie["keeper"] = twin # something still points at the copy, so Delete leaves it in the file with its closure properties +with bpy.context.temp_override(selected_objects=[twin], active_object=twin): + bpy.ops.object.delete() +check("and with the copy deleted the closure holds again, though the copy is still in the file stating its own", closure_row("Brace").get("holds") is True + and bpy.data.objects.get("Brace_twin") is not None and "kit_close_to" in bpy.data.objects["Brace_twin"], closure_of("Brace")) +del tie["keeper"] +bpy.data.objects.remove(bpy.data.objects["Brace_twin"]) refused("set_params on the part a closure names, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Leg", "params": "body_r=0.07"}, "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.054) and parent socket 'rod_end' (pivot, size 0.063)") refused("set_params on the closing part, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Brace", "params": "width=0.1"}, @@ -393,7 +449,24 @@ found = closure_row("Brace") check("a closure follows its other part through a rename", found.get("to") == "Shin" and found.get("holds") is True, found) leg.name = "Leg" send("brokkr_kitbash.detach", object_name="Leg") -bpy.data.objects.remove(leg) +homes = list(leg.users_collection) +for home in homes: + home.objects.unlink(leg) +found = closure_row("Brace") +check("a closure on a part unlinked from every collection reads to null, holds false, with the reason", found.get("to", 0) is None and found.get("holds") is False + and "gone" in str(found.get("reason")) and "Leg" in bpy.data.objects, found) +for home in homes: + home.objects.link(leg) +check("and holds again once the part is linked back", closure_row("Brace").get("holds") is True, closure_of("Brace")) +with bpy.context.temp_override(selected_objects=[leg], active_object=leg): + bpy.ops.object.delete() # the ordinary Delete: the closure's pointer keeps the object in the file as an orphan +found = closure_row("Brace") +check("a closure on a part deleted with the Delete operator reads to null, holds false, though the object is still in the file", found.get("to", 0) is None + and found.get("holds") is False and found.get("residual", 0) is None and bpy.data.objects.get("Leg") is not None and brace.get("kit_close_to") is not None, [found, list(bpy.data.objects.keys())]) +refused("close onto a deleted part that is still in the file", "brokkr_kitbash.close", + {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end_back"}, "'Leg' is in no collection") +if "Leg" in bpy.data.objects: + bpy.data.objects.remove(bpy.data.objects["Leg"]) found = closure_row("Brace") receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") check("a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", found and found == {**found, "to": None, "residual": None, "holds": False} diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index ad7a3a7..98697ee 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -151,6 +151,11 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: close of a brace moved by NUDGE, which a report would read as not held", + "ok": true, + "detail": null + }, { "name": "close states the closure on the brace when its end_b meets the leg's rod pin, and moves nothing", "ok": true, @@ -231,6 +236,41 @@ "ok": true, "detail": null }, + { + "name": "a loose part placed to meet a socket closes on it", + "ok": true, + "detail": null + }, + { + "name": "set_params lists the closures its own part is an end of first, then the rest", + "ok": true, + "detail": null + }, + { + "name": "with room for one row in the receipt, set_params keeps the closure it opened and counts the other in closuresOmitted", + "ok": true, + "detail": null + }, + { + "name": "and a closure another part's set_params opened comes before one that holds", + "ok": true, + "detail": null + }, + { + "name": "a closure on a part scaled by hand reads broken, naming the part and why, not gone", + "ok": true, + "detail": null + }, + { + "name": "two parts that state a closure on one socket both read not held, each naming the other", + "ok": true, + "detail": null + }, + { + "name": "and with the copy deleted the closure holds again, though the copy is still in the file stating its own", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: set_params on the part a closure names, to a size its pin no longer mates", "ok": true, @@ -261,6 +301,26 @@ "ok": true, "detail": null }, + { + "name": "a closure on a part unlinked from every collection reads to null, holds false, with the reason", + "ok": true, + "detail": null + }, + { + "name": "and holds again once the part is linked back", + "ok": true, + "detail": null + }, + { + "name": "a closure on a part deleted with the Delete operator reads to null, holds false, though the object is still in the file", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close onto a deleted part that is still in the file", + "ok": true, + "detail": null + }, { "name": "a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", "ok": true, @@ -540,6 +600,7 @@ "hostErrors": [], "readings": { "carried": 2.6e-07, + "close nudged": 0.00032, "closed": 3.9e-07, "cut": 0.25, "kept": 6e-08, From ae56f48d701ade3b7541f751cc21e4adaee7cca3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 02:00:19 +0100 Subject: [PATCH 081/223] mesh_object refuses an object in no collection A deleted object a closure still points to stays in the file; attach, set_params, report, boolean and every polish operator found it by name. The refusal moves from close into mesh_object, which they all share (finding cut-kit-joints.s2.attach-onto-orphan-and-ends-first-unpinned, part 1). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 3 --- surfaces/blender/brokkr_mesh_polish/__init__.py | 2 ++ 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 8edb244..3e19063 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -498,9 +498,6 @@ class BROKKR_KITBASH_OT_close(PolishOperator): other_part, other_built = built_part(other) if obj == other: raise Refused(f"{obj.name!r} cannot close on itself; nothing changed.") - for gone in (obj, other): - if not gone.users_collection: - raise Refused(f"{gone.name!r} is in no collection (a deleted object something still points to): a closure is between parts in the scene; nothing changed.") if closure(obj) is not None: raise Refused(f"{obj.name!r} already states a closure (its socket {closure(obj)[0]!r}): a part states one, and detach clears it; nothing changed.") there, here = mated(other, other_part, other_built, obj, part, built, (self.socket, self.other_socket, 0.0), "closing on") diff --git a/surfaces/blender/brokkr_mesh_polish/__init__.py b/surfaces/blender/brokkr_mesh_polish/__init__.py index 915ab5d..d1043c1 100644 --- a/surfaces/blender/brokkr_mesh_polish/__init__.py +++ b/surfaces/blender/brokkr_mesh_polish/__init__.py @@ -32,6 +32,8 @@ def mesh_object(name: str): obj = bpy.data.objects.get(name) if obj is None or obj.type != "MESH": raise Refused(f"No mesh object named {name!r}.") + if not obj.users_collection: + raise Refused(f"{name!r} is in no collection (a deleted object something still points to); nothing changed.") return obj From a3172c031b99673e64ac15980a3c3f60a5a8a591 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 02:02:34 +0100 Subject: [PATCH 082/223] brokkr_kitbash: one Boolean modifier per operation over a collection of cutters, on any mesh The per-cutter modifier (Kit Boolean , operand OBJECT) is gone. A target carries at most Kit Difference, Kit Union and Kit Intersect, each Exact with self-intersection, each over a collection in no scene; operation_collection is the one way a cutter comes to cut, and booleans() reads the three collections. boolean takes any rigid mesh target; apply removes the collections it emptied of users and leaves the cutter objects. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 106 ++++++++++++------ .../blender/tests/live/kitbash_assembly.py | 29 ++--- surfaces/blender/tests/test_kitbash.py | 6 +- 3 files changed, 92 insertions(+), 49 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 3e19063..cb5b956 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -14,12 +14,17 @@ params). A connection belongs to the child: its parent pointer (under an identity parent inverse) and three more ID properties, kit_socket, kit_parent_socket and kit_roll. Its matrix_basis is derived from them and both parts' -params by core.mate; attach and set_params write it, and a report says how far the child stands from it. A boolean -belongs to its Boolean modifier on the target (the modifier's object is the cutter; its name is a label). kit_baked +params by core.mate; attach and set_params write it, and a report says how far the child stands from it. kit_baked says apply replaced the mesh with the evaluated one: the params then only place the part's sockets. Placing a loose part, hiding a cutter, materials and export are Brokkr's own rows (setObjectTransform, setObjectVisibility, assignMaterial, exportGltf). +A Boolean belongs to the target: any mesh, kit part or not, carries at most one Exact Boolean modifier per +operation (Kit Difference, Kit Union, Kit Intersect, evaluated in that order above the Bevel), and that modifier's +collection holds the cutters. One Boolean over a collection of eight cutters costs what one cutter costs; eight +modifiers cost seven times that (docs/kitbash.md). Which cutters cut a target is stored nowhere else: the +collection's name is a label, and it is linked to no scene. + Connections are a tree. A loop (a brace from one branch to another) is closed by a closure: three ID properties on the closing part, kit_close_socket, kit_close_to (a pointer to the other part) and kit_close_to_socket. close writes them, only when the two sockets already meet, and writes nothing else; detach clears them. Nothing here @@ -49,7 +54,7 @@ SOCKET, PARENT_SOCKET, ROLL, BAKED = "kit_socket", "kit_parent_socket", "kit_rol CLOSE, CLOSE_TO, CLOSE_TO_SOCKET = "kit_close_socket", "kit_close_to", "kit_close_to_socket" HELD = 1e-5 # a connection or a closure holds when its residual is at most this (as RIGID) BEVEL = "Kit Bevel" -BOOLEAN = "Kit Boolean " # a Boolean modifier's name is this and its cutter's name: a label, the cutter is modifier.object +OPERATIONS = ("DIFFERENCE", "UNION", "INTERSECT") # a target's Boolean modifiers, "Kit " + operation.title(), in the order they are evaluated BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0) REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates @@ -95,17 +100,23 @@ def sync_bevel(obj, width: float) -> None: RIGID = 1e-5 # how far a world matrix's 3x3 may stand from a rotation -def kit_part_of(obj, kits=None): - """(part, stored params) of a placed part, read from its ID properties. Refuses a part whose world transform is - not rigid: its socket frames would not be frames, and its size would have a second owner. `kits` is a dict one - call may pass to read each kit file once while it reads many parts; nothing keeps it between calls.""" - if PART not in obj: - raise Refused(f"{obj.name!r} is not a kit part (it has no {PART} property); place_part makes one.") +def rigid(obj) -> None: + """Refuses an object whose world transform scales, mirrors or shears: a frame under it (a socket, a cutter) would + not be a frame, and a kit part's size would have a second owner.""" turn = np.array(obj.matrix_world)[:3, :3] if np.abs(turn.T @ turn - np.eye(3)).max() > RIGID or np.linalg.det(turn) < 0: scale = ", ".join(f"{s:.4g}" for s in obj.matrix_world.to_scale()) raise Refused(f"{obj.name!r} is scaled, mirrored or sheared in the world (scale {scale}): a kit part's size is its params. " "Set its scale, and its parents', to 1 (setObjectTransform) and resize it with set_params.") + + +def kit_part_of(obj, kits=None): + """(part, stored params) of a placed part, read from its ID properties. Refuses a part whose world transform is + not rigid (rigid). `kits` is a dict one call may pass to read each kit file once while it reads many parts; + nothing keeps it between calls.""" + if PART not in obj: + raise Refused(f"{obj.name!r} is not a kit part (it has no {PART} property); place_part makes one.") + rigid(obj) try: stored = json.loads(obj.get(PARAMS, "{}")) except ValueError: @@ -298,13 +309,46 @@ def own_mesh(obj, doing: str) -> None: "them while their params stay. Give it its own mesh (place_part a new part) and set that; nothing changed.") +def operation_collection(target, operation: str, make: bool = False): + """The collection whose mesh objects the target's Kit Boolean modifier cuts with, or None when the + target has no such modifier. With `make`, the modifier (Exact, self-intersection on, materials transferred) and + its collection are made: the modifier goes above the Kit Bevel and above the Kit modifier of any later + operation, so the stack reads difference, union, intersect, bevel. The one way a cutter comes to cut a target: + boolean and cut add to this collection, and booleans() reads it.""" + name = "Kit " + operation.title() + modifier = target.modifiers.get(name) + if modifier is None: + if not make: + return None + modifier = target.modifiers.new(name, "BOOLEAN") + modifier.operation, modifier.operand_type, modifier.solver, modifier.use_self = operation, "COLLECTION", "EXACT", True + modifier.material_mode = "TRANSFER" # with the default (INDEX) the result gains an empty material slot for a cutter that has no materials + names = [m.name for m in target.modifiers] + below = [names.index(n) for n in [BEVEL] + ["Kit " + o.title() for o in OPERATIONS[OPERATIONS.index(operation) + 1:]] if n in names] + if below: # cut first, then bevel the cut's edges with the rest + target.modifiers.move(len(names) - 1, min(below)) + if modifier.collection is None and make: + modifier.collection = bpy.data.collections.new(f"{target.name} {operation.lower()}") + return modifier.collection + + def booleans(obj) -> list: - return [{"cutter": m.object.name if m.object else None, "operation": m.operation} for m in obj.modifiers if m.type == "BOOLEAN"] + """What cuts a target, as {cutter, operation} rows: difference, then union, then intersect, each in the order + its cutters were added.""" + return [{"cutter": cutter.name, "operation": operation} for operation in OPERATIONS + for cutter in getattr(operation_collection(obj, operation), "objects", ())] + + +def uncut(target, cutter) -> None: + """Refuses a cutter that already cuts the target, under any operation.""" + for operation in OPERATIONS: + if cutter in getattr(operation_collection(target, operation), "objects", ())[:]: + raise Refused(f"{cutter.name!r} already cuts {target.name!r} (its Kit {operation.title()} modifier's collection); nothing changed.") def evaluated_of(context, obj): - """(depsgraph, obj with its modifier stack evaluated). An Exact Boolean costs about a second a part, so only - boolean and apply call this; no report does.""" + """(depsgraph, obj with its modifier stack evaluated). An Exact Boolean costs from a few tenths of a second (a + kit part) to a few seconds (a subdivided shell), so only cut, boolean and apply call this; no report does.""" depsgraph = context.evaluated_depsgraph_get() return depsgraph, obj.evaluated_get(depsgraph) @@ -512,36 +556,25 @@ class BROKKR_KITBASH_OT_close(PolishOperator): class BROKKR_KITBASH_OT_boolean(PolishOperator): - """Cut a kit part with another mesh object through a live Boolean modifier (Exact, with self-intersection: kit - parts are overlapping shells) placed above the Bevel; evaluates the part once and reports the result""" + """Cut a mesh object, a kit part or any other, with another mesh object: the cutter joins the collection of the + target's one live Boolean modifier for the operation (Exact, with self-intersection: kit parts are overlapping + shells), above the Bevel; evaluates the target once and reports the result""" bl_idname = "brokkr_kitbash.boolean" bl_label = "Boolean Kit Part" - object_name: bpy.props.StringProperty(name="Object", description="The kit part that is cut") + object_name: bpy.props.StringProperty(name="Object", description="The mesh that is cut: a kit part or any mesh") cutter: bpy.props.StringProperty(name="Cutter", description="Any other mesh object; it is not changed") operation: bpy.props.EnumProperty(name="Operation", default="DIFFERENCE", items=[ ("DIFFERENCE", "Difference", ""), ("UNION", "Union", ""), ("INTERSECT", "Intersect", "")]) @kit_work def work(self, context): - obj = mesh_object(self.object_name) - part, built = built_part(obj) - cutter = bpy.data.objects.get(self.cutter) - if cutter is None or cutter.type != "MESH": - raise Refused(f"No mesh object named {self.cutter!r} to cut with; nothing changed.") + obj, cutter = mesh_object(self.object_name), mesh_object(self.cutter) if cutter == obj: raise Refused(f"{obj.name!r} cannot cut itself; nothing changed.") - if any(m.type == "BOOLEAN" and m.object == cutter for m in obj.modifiers): - raise Refused(f"{cutter.name!r} is already the object of a Boolean on {obj.name!r}; nothing changed.") - modifier = obj.modifiers.new(BOOLEAN + cutter.name, "BOOLEAN") - modifier.operation, modifier.object = self.operation, cutter - # TRANSFER: with the default (INDEX) the result gains an empty material slot for a cutter that has no materials - modifier.solver = "EXACT" - modifier.use_self = True - modifier.material_mode = "TRANSFER" - names = [m.name for m in obj.modifiers] - if BEVEL in names: # cut first, then bevel the cut's edges with the rest - obj.modifiers.move(len(names) - 1, names.index(BEVEL)) - report = part_report(obj, part, built) + report = part_report(obj, *built_part(obj)) if PART in obj else {"object": obj.name} + rigid(obj) + uncut(obj, cutter) + operation_collection(obj, self.operation, True).objects.link(cutter) _, evaluated = evaluated_of(context, obj) report["booleans"], report["evaluated"] = booleans(obj), measured(evaluated.to_mesh()) evaluated.to_mesh_clear() @@ -549,8 +582,9 @@ class BROKKR_KITBASH_OT_boolean(PolishOperator): class BROKKR_KITBASH_OT_apply(PolishOperator): - """Bake a kit part: its mesh becomes its evaluated mesh (Booleans and Bevel applied), every modifier goes, its - material slots stay, and it is marked baked; its sockets and connections stay as they are""" + """Bake a kit part: its mesh becomes its evaluated mesh (Booleans and Bevel applied), every modifier goes with + the collections its Booleans held, its material slots stay, and it is marked baked; its sockets and connections + stay as they are, and so do the cutter objects""" bl_idname = "brokkr_kitbash.apply" bl_label = "Apply Kit Part" object_name: bpy.props.StringProperty(name="Object") @@ -572,8 +606,12 @@ class BROKKR_KITBASH_OT_apply(PolishOperator): if (index < 0).any(): # faces from a cutter's empty slot: slot 0, as faces from a cutter with no material baked.polygons.foreach_set("material_index", np.maximum(index, 0)) old, name = obj.data, obj.data.name + held = [found for found in (operation_collection(obj, operation) for operation in OPERATIONS) if found is not None] obj.data = baked obj.modifiers.clear() + for collection in held: # a collection another object's modifier still reads (a copied part) stays + if collection.users == 0: + bpy.data.collections.remove(collection) if old.users == 0: bpy.data.meshes.remove(old) baked.name = name diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index d5a4a00..1b2b5aa 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -1,6 +1,6 @@ """Live proof, in a background Blender, of brokkr_kitbash assembly through run_intent: attach and its refusals, set_params seating a part and the parts attached to it again, a braced leg closed by close and what set_params, -attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (Exact, self-intersection on, above the Bevel), and apply with its material slots. Not part +attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (one Exact Boolean modifier per operation over a collection of cutters, self-intersection on, above the Bevel), and apply with its material slots. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_assembly.py -- @@ -558,10 +558,12 @@ box = bpy.data.objects["Box"] box_was = (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) raw = measure(tank.data) receipt, cut = send("brokkr_kitbash.boolean", object_name="Tank", cutter="Box") -modifier = tank.modifiers.get("Kit Boolean Box") -check("boolean adds a Boolean modifier above the Bevel: Exact, self-intersection on, difference, the cutter its object", - receipt["status"] == "accepted" and [m.name for m in tank.modifiers] == ["Kit Boolean Box", "Kit Bevel"] and modifier is not None and modifier.type == "BOOLEAN" - and (modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.object) == ("EXACT", True, "DIFFERENCE", "OBJECT", box), +modifier = tank.modifiers.get("Kit Difference") +check("boolean adds one Boolean modifier above the Bevel: Exact, self-intersection on, difference, over a collection that holds the cutter and is in no scene", + receipt["status"] == "accepted" and [m.name for m in tank.modifiers] == ["Kit Difference", "Kit Bevel"] and modifier is not None and modifier.type == "BOOLEAN" + and (modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.object) == ("EXACT", True, "DIFFERENCE", "COLLECTION", None) + and modifier.collection.objects[:] == [box] and modifier.collection.name == "Tank difference" + and not any(modifier.collection in c.children_recursive for c in [s.collection for s in bpy.data.scenes]), [receipt["message"], [m.name for m in tank.modifiers]]) shown, shown_slots = evaluated(tank) check("boolean reports the evaluated mesh, with less volume than the uncut tank and no non-manifold edge", cut and cut["evaluated"] == shown @@ -572,18 +574,17 @@ check("boolean reports the evaluated mesh, with less volume than the uncut tank R["tank"] = {"raw": raw, "cut": cut and cut["evaluated"]} check("the cut tank shows the tank's two material slots and no other", shown_slots == ["Tank Paint", "Strap Steel"] and modifier is not None and modifier.material_mode == "TRANSFER", shown_slots) check("boolean leaves the cutter as it was", (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) == box_was - and "kit_part" not in box, box_was) + and "kit_part" not in box and bpy.context.scene.collection in box.users_collection, box_was) refused("a cutter that already cuts the part", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Box", "operation": "UNION"}, - "'Box' is already the object of a Boolean on 'Tank'") + "'Box' already cuts 'Tank' (its Kit Difference modifier's collection)") refused("the part as its own cutter", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Tank"}, "cannot cut itself") refused("a cutter that does not exist", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Nothing"}, "No mesh object named 'Nothing'") send("createObject", objectType="EMPTY", name="Marker") refused("a cutter that is not a mesh", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Marker"}, "No mesh object named 'Marker'") -refused("boolean on a mesh that is not a kit part", "brokkr_kitbash.boolean", {"object_name": "Plain", "cutter": "Box"}, "'Plain' is not a kit part") receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="segments=16") resized, _ = evaluated(tank) check("set_params on the cut tank rebuilds it under the live Boolean, and the tee stays on its port", receipt["status"] == "accepted" - and [m.name for m in tank.modifiers] == ["Kit Boolean Box", "Kit Bevel"] and tank.modifiers["Kit Boolean Box"].object == box + and [m.name for m in tank.modifiers] == ["Kit Difference", "Kit Bevel"] and tank.modifiers["Kit Difference"].collection.objects[:] == [box] and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], report["params"]).counts) != raw["faces"] and CUT < resized["volume"] < measure(tank.data)["volume"] - 0.005 and holds("Tee", "Tank", "b", "port_a", 180.0)[0], [receipt["message"], resized]) @@ -593,14 +594,15 @@ slots = [s.material and s.material.name for s in tank.material_slots] shown, shown_slots = evaluated(tank) index = np.zeros(len(tank.data.polygons), dtype=np.int32) tank.data.polygons.foreach_get("material_index", index) -mesh_name, meshes = tank.data.name, len(bpy.data.meshes) +mesh_name, meshes, collections = tank.data.name, len(bpy.data.meshes), len(bpy.data.collections) sockets_before = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["sockets"] receipt, baked = send("brokkr_kitbash.apply", object_name="Tank") after = np.zeros(len(tank.data.polygons), dtype=np.int32) tank.data.polygons.foreach_get("material_index", after) check("apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name", receipt["status"] == "accepted" and baked and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown == measure(tank.data) - and len(tank.modifiers) == 0 and tank.data.name == mesh_name and len(bpy.data.meshes) == meshes and baked["cutters"] == ["Box"], [receipt["message"], baked, shown]) + and len(tank.modifiers) == 0 and tank.data.name == mesh_name and len(bpy.data.meshes) == meshes and baked["cutters"] == ["Box"] + and len(bpy.data.collections) == collections - 1 and "Tank difference" not in bpy.data.collections and "Box" in bpy.context.scene.objects, [receipt["message"], baked, shown]) check("apply keeps the material slots exactly, and faces of both materials", slots == shown_slots == ["Tank Paint", "Strap Steel"] and [s.material and s.material.name for s in tank.material_slots] == slots and [m and m.name for m in tank.data.materials] == slots and index.max() == 1 and sorted(set(after.tolist())) == [0, 1], [slots, [m and m.name for m in tank.data.materials], sorted(set(after.tolist()))]) @@ -622,8 +624,9 @@ send("createObject", objectType="MESH", name="Slot", location=[0.1, -3.0, 0.0], send("createObject", objectType="MESH", name="Hole", location=[-0.1, -3.0, 0.0], size=0.05) receipt, first = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Slot") receipt, second = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Hole") -check("two cutters stack in the order they came, both above the Bevel", receipt["status"] == "accepted" - and [m.name for m in plate.modifiers] == ["Kit Boolean Slot", "Kit Boolean Hole", "Kit Bevel"] +check("two cutters share one Boolean modifier above the Bevel, in its collection in the order they came", receipt["status"] == "accepted" + and [m.name for m in plate.modifiers] == ["Kit Difference", "Kit Bevel"] + and [o.name for o in plate.modifiers["Kit Difference"].collection.objects] == ["Slot", "Hole"] and second["booleans"] == [{"cutter": "Slot", "operation": "DIFFERENCE"}, {"cutter": "Hole", "operation": "DIFFERENCE"}] and second["evaluated"]["volume"] < first["evaluated"]["volume"] and first["evaluated"]["nonManifoldEdges"] == second["evaluated"]["nonManifoldEdges"] == 0 and all(m.use_self and m.solver == "EXACT" for m in plate.modifiers if m.type == "BOOLEAN"), diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 7300431..44f97d0 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -834,7 +834,8 @@ class OwnershipTests(unittest.TestCase): r"\bsolver\s*=\s*[\"']MANIFOLD|\buse_self\s*=\s*False", # a boolean is Exact with self-intersection, nothing else r"hide_render|hide_viewport|display_type", # a cutter's visibility is setObjectVisibility's r"kit_parent_name|kit_parent\b|matrix_world_stored", # obj.parent has no second owner - r"SCREW|\"ARRAY\"|spin\(") # core makes every vertex: no modifier or bmesh op makes kit geometry + r"SCREW|\"ARRAY\"|spin\(", # core makes every vertex: no modifier or bmesh op makes kit geometry + r"Kit Boolean |operand_type\s*=\s*[\"']OBJECT") # cutters cut through one collection Boolean per operation, never a modifier each CORE = r"^import bpy|^from bpy|^import bmesh" SCHEMAS = r"brokkr\.kit\.v0" @@ -889,7 +890,8 @@ class OwnershipTests(unittest.TestCase): def test_the_patterns_bite(self): planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name', - 'obj.modifiers.new("Turn", "SCREW")') + 'obj.modifiers.new("Turn", "SCREW")', 'modifier.operand_type = "OBJECT"') + self.assertIsNotNone(re.search(self.PACKAGE[6], 'obj.modifiers.new("Kit Boolean " + cutter.name, "BOOLEAN")')) for text in ('obj.modifiers.new("Bolts", "ARRAY")', "bmesh.ops.spin(bm, geom=geom)"): self.assertIsNotNone(re.search(self.PACKAGE[5], text)) self.assertEqual(len(planted), len(self.PACKAGE)) From 972d51e1ee0e85d1abdaf9c2bd2c79d085d1c368 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 02:03:48 +0100 Subject: [PATCH 083/223] brokkr_kitbash: parts of two kits mate by the socket types both declare alike core.joint no longer refuses parts of different kits. mate_refusal takes the child kit's socketTypes and the two kit names: a type the child's kit does not declare with the parent kit's match is refused naming both kits; then the shared size rule. One kit reads as before. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 26 +++++++++++---------- surfaces/blender/brokkr_kitbash/core.py | 21 ++++++++++------- surfaces/blender/tests/test_kitbash.py | 26 ++++++++++++++++++--- 3 files changed, 50 insertions(+), 23 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index cb5b956..52a9ce0 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -199,14 +199,16 @@ def free(part, socket: str) -> None: def mated(parent, parent_part, parent_built, child, child_part, child_built, stated, how="on"): """(parent socket, child socket) of the connection `stated` between two built parts, or a refusal that names - it: a roll that is not a number, parts of two kits, a socket name a part does not have, or sockets - core.mate_refusal will not mate. A closure is checked here too (how "closing on"), the part it names as the - parent.""" + it: a roll that is not a number, a socket name a part does not have, or sockets core.mate_refusal will not + mate. The parts may be of two kits: they mate when both kits declare the socket's type alike. A closure is + checked here too (how "closing on"), the part it names as the parent.""" if stated[2] is None: raise Refused(f"{child.name!r} on {parent.name!r}: its {ROLL} is not a number: detach it and attach it again; nothing changed.") try: sockets = core.joint(parent_part, parent_built, stated[1], child_part, child_built, stated[0]) - refusal = core.mate_refusal(core.load_kit(parent_part["kit"])["socketTypes"], *sockets) + kits = (parent_part["kit"], child_part["kit"]) + refusal = core.mate_refusal(core.load_kit(kits[0])["socketTypes"], *sockets, + None if kits[0] == kits[1] else core.load_kit(kits[1])["socketTypes"], kits) except core.KitError as error: refusal = str(error) if refusal: @@ -221,8 +223,8 @@ def seat(child, basis) -> None: def connection_report(obj, part, built): - """None for a part that states no connection, else what it states and whether it holds: the parent is a part - of the same kit, both sockets exist, the roll is a number, the parent inverse is the identity and the child + """None for a part that states no connection, else what it states and whether it holds: the parent is a kit + part, both sockets exist, the roll is a number, the parent inverse is the identity and the child stands within HELD of core.mate. A child moved or re-parented by another action reads holds false until set_params seats it again.""" stated = link(obj) @@ -244,8 +246,8 @@ def connection_report(obj, part, built): def closure_report(obj, part, built, held=None, kits=None): """None for a part that states no closure, else what it states, whether it holds and, when it does not, why - not: the other part is gone (`to` null); it is not a part this one can be read against (not a kit part, of - another kit, scaled, or without that socket); another part's closure names the same socket (a duplicated + not: the other part is gone (`to` null); it is not a part this one can be read against (not a kit part, + scaled, or without that socket); another part's closure names the same socket (a duplicated closing part); or the two sockets stand more than HELD from meeting (core.closure_residual). Derived at each report; stored nowhere. `held` is closers() and `kits` kit_part_of's, for a caller that reports many.""" stated = closure(obj) @@ -464,8 +466,8 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): class BROKKR_KITBASH_OT_attach(PolishOperator): - """Seat a socket of a kit part on a socket of another part of its kit and parent it there: origins together, - normals opposed, turned by roll about the parent socket's normal""" + """Seat a socket of a kit part on a socket of another part, of its kit or of any kit whose socket types agree, + and parent it there: origins together, normals opposed, turned by roll about the parent socket's normal""" bl_idname = "brokkr_kitbash.attach" bl_label = "Attach Kit Part" object_name: bpy.props.StringProperty(name="Object", description="The child: the part that moves") @@ -525,8 +527,8 @@ class BROKKR_KITBASH_OT_detach(PolishOperator): class BROKKR_KITBASH_OT_close(PolishOperator): - """State that a socket of a kit part meets a socket of another part of its kit, closing a loop the tree of - connections cannot: accepted only when the two already meet, origins together and normals opposed, and it + """State that a socket of a kit part meets a socket of another part, of its kit or of any kit whose socket types + agree, closing a loop the tree of connections cannot: accepted only when the two already meet, origins together and normals opposed, and it moves nothing""" bl_idname = "brokkr_kitbash.close" bl_label = "Close Kit Loop" diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 3f7c3cf..5713ab6 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -11,7 +11,8 @@ whitelist; nothing in a kit is ever run as Python. built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, sharp, shell_count, sockets Two sockets mate through mate (the child's matrix under its parent), mate_refusal (what may mate) and residual -(how far a placed child stands from its mate). closure_residual is how far two sockets stand from meeting as a pin, +(how far a placed child stands from its mate). Socket types are a vocabulary kits share: parts of two kits mate when +both kits declare the socket's type with the same match rule. closure_residual is how far two sockets stand from meeting as a pin, whatever the roll: what closes a loop the tree of connections cannot state. Every refusal is a KitError whose message names the kit, part and field. @@ -633,13 +634,20 @@ def closure_residual(world_a, socket_a: dict, world_b, socket_b: dict) -> float: EQUAL, SLACK = 0.01, 1e-9 # 'equal' sizes may differ by 1 percent of the larger; SLACK keeps a size at the limit inside it -def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict) -> str | None: +def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict, child_types: dict | None = None, kits=("the parent's", "the child's")) -> str | None: """None when the two sockets may mate, else a sentence naming both: they are of one type, and their sizes - agree as that type's match says ('equal': within 1 percent of the larger; 'fits': the child at most the parent).""" + agree as that type's match says ('equal': within 1 percent of the larger; 'fits': the child at most the parent). + kit_types is the socketTypes of the parent's kit. For parts of two kits, child_types is the socketTypes of the + child's and `kits` the two kits' names: socket types are a vocabulary kits share, and the two sockets mate only + when the child's kit declares the type with the same match.""" p, c = parent_socket, child_socket both = f"socket {c['name']!r} ({c['type']}, size {c['size']:.6g}) and parent socket {p['name']!r} ({p['type']}, size {p['size']:.6g})" if p["type"] != c["type"]: return f"{both} are of different types" + if child_types is not None and child_types.get(c["type"], {}).get("match") != kit_types[p["type"]]["match"]: + theirs = child_types.get(c["type"], {}).get("match") + return (f"{both}: kit {kits[0]!r} declares socket type {p['type']!r} with match {kit_types[p['type']]['match']!r} and kit {kits[1]!r} " + f"{'with match ' + repr(theirs) if theirs else 'does not declare it'}; parts of two kits mate by socket types both declare alike") if kit_types[p["type"]]["match"] == "equal": if abs(p["size"] - c["size"]) > EQUAL * max(p["size"], c["size"]) * (1 + SLACK): return f"{both} are {p['type']} sockets, which mate at equal sizes (within 1 percent)" @@ -649,11 +657,8 @@ def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict) -> st def joint(parent_part: dict, parent_built: Built, parent_socket: str, child_part: dict, child_built: Built, child_socket: str): - """(parent socket, child socket) of a connection between two built parts, by socket name. Refuses parts of - different kits (socket types belong to a kit) and a name the part has no socket for.""" - if parent_part["kit"] != child_part["kit"]: - raise KitError(f"part {child_part['name']!r} is of kit {child_part['kit']!r} and part {parent_part['name']!r} of kit " - f"{parent_part['kit']!r}: socket types belong to a kit, so parts of different kits do not mate") + """(parent socket, child socket) of a connection between two built parts, of one kit or of two, by socket name. + Refuses a name the part has no socket for. Whether the two may mate is mate_refusal's: their socket types decide.""" found = [] for part, built, name in ((parent_part, parent_built, parent_socket), (child_part, child_built, child_socket)): match = [s for s in built.sockets if s["name"] == name] diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 44f97d0..fc9fd43 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -724,6 +724,24 @@ class MateTests(unittest.TestCase): self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.1), socket("c", "mount", 0.3))) self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3 * (1 + 2.2e-6)))) + def test_kits_mate_by_the_socket_types_they_share(self): + """cross-kit-types. Mutant S5 (mate_refusal ignores the child kit's match): a mount another kit declares 'equal' mates.""" + types = self.kit["socketTypes"] + socket = lambda name, kind, size: {"name": name, "type": kind, "size": size, "matrix": np.eye(4)} # noqa: E731 + hydraulic = copy.deepcopy(types) + for kind, big, small in (("flange", 100.0, 99.0), ("pivot", 0.2, 0.198), ("mount", 0.3, 0.1)): + self.assertIsNone(core.mate_refusal(types, socket("p", kind, big), socket("c", kind, small), hydraulic, ("mechanical", "hydraulic"))) + self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", "flange", 100.0), socket("c", "flange", 98.0), hydraulic, ("mechanical", "hydraulic"))) + odd = {**hydraulic, "mount": {"match": "equal", "doc": ""}} + self.assertRegex(core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3), odd, ("mechanical", "odd")), + r"kit 'mechanical' declares socket type 'mount' with match 'fits' and kit 'odd' with match 'equal'; parts of two kits mate by socket types both declare alike") + self.assertRegex(core.mate_refusal(odd, socket("p", "mount", 0.3), socket("c", "mount", 0.3), types, ("odd", "mechanical")), + r"kit 'odd' declares socket type 'mount' with match 'equal' and kit 'mechanical' with match 'fits'") + self.assertRegex(core.mate_refusal(types, socket("p", "pivot", 0.2), socket("c", "pivot", 0.2), {"mount": types["mount"]}, ("mechanical", "bare")), + r"kit 'mechanical' declares socket type 'pivot' with match 'equal' and kit 'bare' does not declare it") + self.assertIn("are of different types", core.mate_refusal(types, socket("p", "flange", 0.1), socket("c", "mount", 0.1), odd, ("mechanical", "odd"))) + self.assertIsNone(core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3), None)) # one kit: as before + def test_the_kit_s_own_flanges_do_not_meet_everywhere(self): """A chamber flange (ribbed_cylinder, 0.16 and up) and the plumbing (pipe_fitting, 0.14 and down) never mate face to face.""" @@ -757,14 +775,16 @@ class MateTests(unittest.TestCase): self.assertEqual([s["matrix"][:3, 2].tolist() for s in reducer.sockets], [[0.0, 0.0, -1.0], [0.0, 0.0, 1.0]]) def test_a_joint_is_two_named_sockets_of_one_kit(self): - """The cross-kit refusal (one kit ships, so no scene can show it) and the unknown-socket refusals.""" + """A joint of one kit or of two (what may mate is mate_refusal's), and the unknown-socket refusals.""" parts = self.kit["parts"] tank, fitting = core.build(parts["tank"]), core.build(parts["pipe_fitting"]) sp, sc = core.joint(parts["tank"], tank, "port_b", parts["pipe_fitting"], fitting, "a") self.assertEqual((sp["name"], sc["name"]), ("port_b", "a")) other = {**parts["pipe_fitting"], "kit": "hydraulic"} - with self.assertRaisesRegex(core.KitError, "part 'pipe_fitting' is of kit 'hydraulic' and part 'tank' of kit 'mechanical'.*do not mate"): - core.joint(parts["tank"], tank, "port_b", other, fitting, "a") + sp, sc = core.joint(parts["tank"], tank, "port_b", other, fitting, "a") + self.assertEqual((sp["name"], sp["size"], sc["name"], sc["size"]), ("port_b", tank.sockets[1]["size"], "a", fitting.sockets[0]["size"])) + with self.assertRaisesRegex(core.KitError, "kit 'hydraulic' part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c"): + core.joint(parts["tank"], tank, "port_b", other, fitting, "d") with self.assertRaisesRegex(core.KitError, "part 'tank' has no socket 'port_c'; its sockets: port_a, port_b, saddle, lug_a, lug_b, lug_a_back, lug_b_back"): core.joint(parts["tank"], tank, "port_c", parts["pipe_fitting"], fitting, "a") with self.assertRaisesRegex(core.KitError, "part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c"): From c6aeeff52ba67a8ce6d087dbc53b11de47f0d196 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 02:35:14 +0100 Subject: [PATCH 084/223] brokkr_kitbash.cut: cut any mesh at a ray with a part of the cutters kit whose floor is a socket kits/cutters.v0.json: box, cyl, slot and slab, spanning z from -depth to +lift; box, cyl and slot carry a floor socket (mount) on the bottom of the recess. core.surface_frame is the cutter's frame at the hit. cut casts at the target with its Kit Booleans off, places the cutter as a kit part parented to the target under an identity parent inverse and adds it to the difference collection: the cutter object owns the recess frame and size, and machinery attaches to its floor with the ordinary attach. tests/live/kitbash_shell.py: cut on a cage that is not a kit part, a vent on a floor, the three Boolean modifiers, the refusals, an object in no collection, and the ends-first order of a set_params report's closures (finding cut-kit-joints.s2.attach-onto-orphan-and-ends-first-unpinned, part 2). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 74 +++- .../brokkr_kitbash/brokkr_actions.json | 126 +++++- surfaces/blender/brokkr_kitbash/core.py | 22 +- .../brokkr_kitbash/kits/cutters.v0.json | 80 ++++ surfaces/blender/docs/kitbash.md | 108 +++-- surfaces/blender/tests/live/kitbash.py | 4 +- .../blender/tests/live/kitbash.result.json | 3 +- .../blender/tests/live/kitbash_assembly.py | 4 +- .../tests/live/kitbash_assembly.result.json | 15 +- surfaces/blender/tests/live/kitbash_shell.py | 371 ++++++++++++++++++ .../tests/live/kitbash_shell.result.json | 279 +++++++++++++ surfaces/blender/tests/test_kitbash.py | 171 +++++++- 12 files changed, 1204 insertions(+), 53 deletions(-) create mode 100644 surfaces/blender/brokkr_kitbash/kits/cutters.v0.json create mode 100644 surfaces/blender/tests/live/kitbash_shell.py create mode 100644 surfaces/blender/tests/live/kitbash_shell.result.json diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 52a9ce0..430fde2 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1,4 +1,5 @@ -"""Kitbash parts: place parametric machine parts from a kit, mate them socket to socket, cut them, and bake them. +"""Kitbash parts: place parametric machine parts from a kit, mate them socket to socket, cut them and any other +mesh, and bake them. A host add-on for Brokkr beside brokkr_mesh_polish and brokkr_rig (it imports the polish package's operator base, Refused and mesh_object, and nothing from Brokkr): brokkr_actions.json beside this file lists the operators agents @@ -25,6 +26,11 @@ collection holds the cutters. One Boolean over a collection of eight cutters cos modifiers cost seven times that (docs/kitbash.md). Which cutters cut a target is stored nowhere else: the collection's name is a label, and it is linked to no scene. +cut cuts a mesh where a ray meets it. The cut is a placed part of the cutters kit, parented to the target under an +identity parent inverse: its matrix_basis is the recess frame and its params the recess size, so moving or resizing +the cutter object moves the cut and its floor socket together, and nothing else stores either. Machinery attaches +to the floor socket with the ordinary attach. + Connections are a tree. A loop (a brace from one branch to another) is closed by a closure: three ID properties on the closing part, kit_close_socket, kit_close_to (a pointer to the other part) and kit_close_to_socket. close writes them, only when the two sockets already meet, and writes nothing else; detach clears them. Nothing here @@ -39,7 +45,8 @@ import math import bmesh import bpy import numpy as np -from mathutils import Matrix +from mathutils import Matrix, Vector +from mathutils.bvhtree import BVHTree try: from brokkr_mesh_polish import RESULT, PolishOperator, Refused, mesh_object @@ -54,6 +61,7 @@ SOCKET, PARENT_SOCKET, ROLL, BAKED = "kit_socket", "kit_parent_socket", "kit_rol CLOSE, CLOSE_TO, CLOSE_TO_SOCKET = "kit_close_socket", "kit_close_to", "kit_close_to_socket" HELD = 1e-5 # a connection or a closure holds when its residual is at most this (as RIGID) BEVEL = "Kit Bevel" +CUTTERS = "cutters" # the kit whose parts cut places OPERATIONS = ("DIFFERENCE", "UNION", "INTERSECT") # a target's Boolean modifiers, "Kit " + operation.title(), in the order they are evaluated BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0) REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates @@ -583,6 +591,65 @@ class BROKKR_KITBASH_OT_boolean(PolishOperator): return report +class BROKKR_KITBASH_OT_cut(PolishOperator): + """Cut a mesh object, a kit part or any other, where a ray meets it: places a part of the cutters kit on the + surface there (z the surface normal, y the projection of up, turned by roll), parented to the target, and adds it + to the target's difference Boolean; the cutter's floor socket is where machinery attaches""" + bl_idname = "brokkr_kitbash.cut" + bl_label = "Cut At Ray" + object_name: bpy.props.StringProperty(name="Object", description="The mesh that is cut: a kit part or any mesh") + cutter_name: bpy.props.StringProperty(name="Cutter", description="The new cutter object's name") + part: bpy.props.EnumProperty(name="Part", default="box", items=[("box", "Box", ""), ("cyl", "Cylinder", ""), ("slot", "Slot", ""), ("slab", "Slab", "")]) + params: bpy.props.StringProperty(name="Params", description="name=value; name=value ... the rest take the cutter part's defaults") + origin_x: bpy.props.FloatProperty(name="Origin X", description="The ray's origin, in the target's own frame") + origin_y: bpy.props.FloatProperty(name="Origin Y") + origin_z: bpy.props.FloatProperty(name="Origin Z") + direction_x: bpy.props.FloatProperty(name="Direction X", description="The ray's direction, in the target's own frame") + direction_y: bpy.props.FloatProperty(name="Direction Y") + direction_z: bpy.props.FloatProperty(name="Direction Z") + up_x: bpy.props.FloatProperty(name="Up X", default=0.0, description="Which way the cutter's y points, in the target's own frame") + up_y: bpy.props.FloatProperty(name="Up Y", default=0.0) + up_z: bpy.props.FloatProperty(name="Up Z", default=1.0) + roll: bpy.props.FloatProperty(name="Roll", default=0.0, min=-360.0, max=360.0, description="Degrees about the surface normal, right-handed") + + @kit_work + def work(self, context): + target = mesh_object(self.object_name) + rigid(target) + if self.cutter_name in bpy.data.objects: + raise Refused(f"An object named {self.cutter_name!r} exists; nothing changed.") + part = core.part(core.load_kit(CUTTERS), self.part) + built = core.build(part, core.parse_params(self.params)) + origin, direction = Vector((self.origin_x, self.origin_y, self.origin_z)), Vector((self.direction_x, self.direction_y, self.direction_z)) + if direction.length == 0.0: + raise Refused("The ray's direction is zero; nothing changed.") + cuts = [m for m in (target.modifiers.get("Kit " + operation.title()) for operation in OPERATIONS) if m is not None and m.show_viewport] + try: # the surface as designed, not as already cut: a second cut on the ray of a through bay lands where the first did + for modifier in cuts: + modifier.show_viewport = False + depsgraph, _ = evaluated_of(context, target) + hit, normal, _, _ = BVHTree.FromObject(target, depsgraph).ray_cast(origin, direction.normalized()) + finally: + for modifier in cuts: + modifier.show_viewport = True + if hit is None: + raise Refused(f"The ray from {tuple(round(v, 6) for v in origin)} along {tuple(round(v, 6) for v in direction)} misses {target.name!r}; nothing changed.") + if normal.dot(direction) > 0: + normal = -normal + frame = core.surface_frame(hit, normal, (self.up_x, self.up_y, self.up_z), self.roll) + mesh = bpy.data.meshes.new(self.cutter_name) + write_mesh(mesh, built) + cutter = bpy.data.objects.new(self.cutter_name, mesh) + context.scene.collection.objects.link(cutter) + sync_bevel(cutter, built.bevel) + cutter[KIT], cutter[PART], cutter[PARAMS] = part["kit"], part["name"], json.dumps(built.params) + cutter.parent = target + cutter.matrix_world = target.matrix_world @ Matrix(frame.tolist()) # read by the report below; no depsgraph update, which would evaluate the Boolean + seat(cutter, frame) + operation_collection(target, "DIFFERENCE", True).objects.link(cutter) + return {"object": target.name, "cutter": part_report(cutter, part, built), "booleans": booleans(target)} + + class BROKKR_KITBASH_OT_apply(PolishOperator): """Bake a kit part: its mesh becomes its evaluated mesh (Booleans and Bevel applied), every modifier goes with the collections its Booleans held, its material slots stay, and it is marked baked; its sockets and connections @@ -651,7 +718,8 @@ class BROKKR_KITBASH_OT_report(PolishOperator): classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report, - BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_apply) + BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, + BROKKR_KITBASH_OT_apply) def register(): diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 6bd1ba7..cf8de59 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -109,7 +109,7 @@ }, { "name": "brokkr_kitbash.attach", - "doc": "Seat a socket of a kit part on a socket of another part of its kit and parent it there: origins together, normals opposed. Refuses sockets of different types or sizes that do not match, an occupied socket, a child that has a parent, and a loop. Reports the child with its connection.", + "doc": "Seat a socket of a kit part on a socket of a part of any kit whose socket types agree and parent it there: origins together, normals opposed. Refuses sockets of different types or sizes that do not match, an occupied socket, a child that has a parent, and a loop. Reports the child with its connection.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -176,7 +176,7 @@ }, { "name": "brokkr_kitbash.close", - "doc": "Close a loop: state that a socket of a kit part meets a socket of another part of its kit, where attach cannot (the part already has its parent). Accepted only when the two sockets already meet, origins together and normals opposed, any roll; it moves nothing. Attach the parts with the rolls that make them meet first; brokkr_kitbash.report shows the closure and whether it holds.", + "doc": "Close a loop: state that a socket of a kit part meets a socket of a part of any kit whose socket types agree, where attach cannot (the part already has its parent). Accepted only when the two sockets already meet, origins together and normals opposed, any roll; it moves nothing. Attach the parts with the rolls that make them meet first; brokkr_kitbash.report shows the closure and whether it holds.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -219,7 +219,7 @@ }, { "name": "brokkr_kitbash.boolean", - "doc": "Cut a kit part with another mesh object through a live Boolean modifier (Exact, self-intersection on) above its Bevel. Evaluates the part once, about a second: reports the result's faces, volume and non-manifold edges. The cutter is not changed; hide it with setObjectVisibility.", + "doc": "Cut a mesh, a kit part or any other, with another mesh object: the cutter joins the collection of the target's one live Boolean modifier for the operation (Exact, self-intersection on; difference, then union, then intersect, above its Bevel). Evaluates the target once, from a few tenths of a second to a few seconds: reports the result's faces, volume and non-manifold edges. The cutter is not changed; hide it with setObjectVisibility.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -230,7 +230,7 @@ "required": true, "minLength": 1, "maxLength": 63, - "doc": "the kit part that is cut" + "doc": "the mesh that is cut: a kit part or any mesh" }, { "name": "cutter", @@ -252,6 +252,124 @@ } ] }, + { + "name": "brokkr_kitbash.cut", + "doc": "Cut a mesh, a kit part or any other, where a ray meets it: places a part of the cutters kit (box, cyl, slot or slab; brokkr_kitbash.describe with kit cutters) on the surface there, parented to the target, and adds it to the target's difference Boolean. The ray is cast at the target without its cuts. The cutter's floor socket (type mount, at the bottom of the recess, facing out) takes a part by brokkr_kitbash.attach; move the cut with setObjectTransform on the cutter, resize it with set_params, hide the cutter with setObjectVisibility. Does not evaluate the Boolean itself (boolean does, and reports it). Reports the cutter with its sockets, and booleans.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the mesh that is cut: a kit part or any mesh, not scaled" + }, + { + "name": "cutter_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the new cutter object's name; refused when an object has it" + }, + { + "name": "part", + "type": "string", + "required": true, + "enum": [ + "box", + "cyl", + "slot", + "slab" + ], + "doc": "a part of the cutters kit" + }, + { + "name": "params", + "type": "string", + "maxLength": 4000, + "default": "", + "doc": "name=value; name=value ... depth below the surface, lift above it, and the part's own; the rest take its defaults" + }, + { + "name": "origin_x", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true, + "doc": "the ray's origin, in the target's own frame" + }, + { + "name": "origin_y", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true + }, + { + "name": "origin_z", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true + }, + { + "name": "direction_x", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true, + "doc": "the ray's direction, in the target's own frame; any length but zero" + }, + { + "name": "direction_y", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true + }, + { + "name": "direction_z", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true + }, + { + "name": "up_x", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 0, + "doc": "which way the cutter's y points, in the target's own frame; refused along the surface normal" + }, + { + "name": "up_y", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 0 + }, + { + "name": "up_z", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 1 + }, + { + "name": "roll", + "type": "number", + "minimum": -360, + "maximum": 360, + "default": 0, + "doc": "degrees about the surface normal, right-handed" + } + ] + }, { "name": "brokkr_kitbash.apply", "doc": "Bake a kit part: its mesh becomes its evaluated mesh, every modifier goes, material slots stay, and it is marked baked (set_params then refuses it). Sockets and connections stay. Refuses a part with no modifiers and a mesh another object shares.", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 5713ab6..066f233 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1,7 +1,8 @@ """The kit format: what a kit document may say, and the geometry and socket frames a part and its params produce. numpy and the standard library only, no Blender: tests/test_kitbash.py runs this file as it is. A kit is data -(kits/.v0.json beside this file). A part is a list of shapes (tube, box, lathe, and a repeat of one of +(kits/.v0.json beside this file: mechanical, the machine parts, and cutters, the parts brokkr_kitbash.cut +places to cut a mesh, each with its recess floor as a socket). A part is a list of shapes (tube, box, lathe, and a repeat of one of them, a step apart or turned about an axis) whose numbers may be expressions over the part's params, and a list of sockets, each a frame on one of the part's flat faces. A lathe profile point may be marked sharp: its ring of edges is then a crease (Built.sharp). An expression is parsed with ast.parse and walked against a @@ -12,7 +13,8 @@ whitelist; nothing in a kit is ever run as Python. Two sockets mate through mate (the child's matrix under its parent), mate_refusal (what may mate) and residual (how far a placed child stands from its mate). Socket types are a vocabulary kits share: parts of two kits mate when -both kits declare the socket's type with the same match rule. closure_residual is how far two sockets stand from meeting as a pin, +both kits declare the socket's type with the same match rule. surface_frame is the frame a cutter takes where a ray +met a surface. closure_residual is how far two sockets stand from meeting as a pin, whatever the roll: what closes a loop the tree of connections cannot state. Every refusal is a KitError whose message names the kit, part and field. @@ -609,6 +611,22 @@ def _roll(degrees: float) -> np.ndarray: return turn +def surface_frame(point, normal, up, roll_degrees: float = 0.0) -> np.ndarray: + """The 4x4 frame at a point of a surface: z the unit normal, y the unit projection of `up` off z, x = y cross z, + then turned roll_degrees about z (right-handed, as mate's roll). Refuses a zero normal and an up along it.""" + point, z, up = (np.asarray(v, dtype=np.float64) for v in (point, normal, up)) + if not np.isfinite(z).all() or not np.linalg.norm(z) > 0: + raise KitError(f"normal {normal} has no direction") + z = z / np.linalg.norm(z) + y = up - z * (up @ z) + if not np.isfinite(y).all() or not np.linalg.norm(y) > 1e-6 * np.linalg.norm(up): + raise KitError(f"up {up.tolist()} runs along the surface normal {np.round(z, 6).tolist()} (or is zero): give an up that crosses it") + y = y / np.linalg.norm(y) + frame = np.eye(4) + frame[:3, 0], frame[:3, 1], frame[:3, 2], frame[:3, 3] = np.cross(y, z), y, z, point + return frame @ _roll(roll_degrees) + + def mate(parent_socket: dict, child_socket: dict, roll_degrees: float = 0.0) -> np.ndarray: """The child's 4x4 in its parent's frame that seats child_socket on parent_socket: origins together, normals opposed, the child turned roll_degrees about the parent socket's z (right-handed; at 0 the two ys line up).""" diff --git a/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json b/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json new file mode 100644 index 0000000..0677a9e --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json @@ -0,0 +1,80 @@ +{ + "schema": "brokkr.kit.v0", + "kit": "cutters", + "doc": "Cutters for brokkr_kitbash.cut: each part spans z from -depth to +lift in its frame, whose origin is where the ray met the surface and whose z is the surface normal; metres.", + "socketTypes": { + "mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"} + }, + "parts": [ + { + "name": "box", + "doc": "Rectangular recess or bay. Its floor socket faces out of the recess at the frame's centre (between the two middle copies when count is even).", + "params": [ + {"name": "width", "type": "number", "min": 0.005, "max": 8, "default": 0.2, "doc": "across (x)"}, + {"name": "height", "type": "number", "min": 0.005, "max": 8, "default": 0.2, "doc": "along up (y)"}, + {"name": "depth", "type": "number", "min": 0.001, "max": 2, "default": 0.02, "doc": "how far the cut goes below the surface; the floor is at z = -depth"}, + {"name": "lift", "type": "number", "min": 0, "max": 2, "default": 0.05, "doc": "how far the cutter stands above the hit point, so a curved surface is cut cleanly"}, + {"name": "count", "type": "integer", "min": 1, "max": 64, "default": 1, "doc": "copies in a row along y, centred on the frame (roll 90 turns the row along x)"}, + {"name": "pitch", "type": "number", "min": 0, "max": 4, "default": 0, "doc": "distance between copies"} + ], + "shapes": [ + {"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "box", "size": ["width", "height", "depth+lift"], "at": [0, "-(count-1)*pitch/2", "(lift-depth)/2"]}} + ], + "sockets": [ + {"name": "floor", "type": "mount", "size": "min(width,height)", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "cyl", + "doc": "Round recess or opening. Its floor socket faces out of the recess at the frame's centre (between the two middle copies when count is even).", + "params": [ + {"name": "r", "type": "number", "min": 0.0025, "max": 4, "default": 0.1, "doc": "radius"}, + {"name": "depth", "type": "number", "min": 0.001, "max": 2, "default": 0.02, "doc": "how far the cut goes below the surface; the floor is at z = -depth"}, + {"name": "lift", "type": "number", "min": 0, "max": 2, "default": 0.05, "doc": "how far the cutter stands above the hit point, so a curved surface is cut cleanly"}, + {"name": "count", "type": "integer", "min": 1, "max": 64, "default": 1, "doc": "copies in a row along y, centred on the frame (roll 90 turns the row along x)"}, + {"name": "pitch", "type": "number", "min": 0, "max": 4, "default": 0, "doc": "distance between copies"} + ], + "shapes": [ + {"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "tube", "r0": "r", "r1": "r", "length": "depth+lift", "segments": 32, "at": [0, "-(count-1)*pitch/2", "-depth"]}} + ], + "sockets": [ + {"name": "floor", "type": "mount", "size": "2*r", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "slot", + "doc": "Round-ended slot, long along x: a visor, a gill, a vent. width must exceed height. Its floor socket faces out of the recess at the frame's centre (between the two middle copies when count is even).", + "params": [ + {"name": "width", "type": "number", "min": 0.01, "max": 8, "default": 0.3, "doc": "end to end (x); more than height"}, + {"name": "height", "type": "number", "min": 0.005, "max": 4, "default": 0.05, "doc": "across the slot (y); the ends are half-rounds of this diameter"}, + {"name": "depth", "type": "number", "min": 0.001, "max": 2, "default": 0.02, "doc": "how far the cut goes below the surface; the floor is at z = -depth"}, + {"name": "lift", "type": "number", "min": 0, "max": 2, "default": 0.05, "doc": "how far the cutter stands above the hit point, so a curved surface is cut cleanly"}, + {"name": "count", "type": "integer", "min": 1, "max": 64, "default": 1, "doc": "copies in a row along y, centred on the frame (roll 90 turns the row along x)"}, + {"name": "pitch", "type": "number", "min": 0, "max": 4, "default": 0, "doc": "distance between copies"} + ], + "shapes": [ + {"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "box", "size": ["width-height", "height", "depth+lift"], "at": [0, "-(count-1)*pitch/2", "(lift-depth)/2"]}}, + {"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "tube", "r0": "height/2", "r1": "height/2", "length": "depth+lift", "segments": 32, "at": ["-(width-height)/2", "-(count-1)*pitch/2", "-depth"]}}, + {"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "tube", "r0": "height/2", "r1": "height/2", "length": "depth+lift", "segments": 32, "at": ["(width-height)/2", "-(count-1)*pitch/2", "-depth"]}} + ], + "sockets": [ + {"name": "floor", "type": "mount", "size": "height", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "slab", + "doc": "Panel break: a thin slab standing on the surface normal, long along y; roll turns it about the normal. No socket.", + "params": [ + {"name": "gap", "type": "number", "min": 0.002, "max": 0.2, "default": 0.02, "doc": "the break's width (x)"}, + {"name": "length", "type": "number", "min": 0.01, "max": 8, "default": 2, "doc": "along y"}, + {"name": "depth", "type": "number", "min": 0.001, "max": 2, "default": 0.02, "doc": "how far the cut goes below the surface; the floor is at z = -depth"}, + {"name": "lift", "type": "number", "min": 0, "max": 2, "default": 0.05, "doc": "how far the cutter stands above the hit point, so a curved surface is cut cleanly"} + ], + "shapes": [ + {"shape": "box", "size": ["gap", "length", "depth+lift"], "at": [0, 0, "(lift-depth)/2"]} + ], + "sockets": [ + ] + } + ] +} diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index b46d57a..26829ce 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -139,8 +139,12 @@ matrix_basis = S_parent @ Rz(roll) @ FLIP @ inverse(S_child) FLIP = half with `S` each socket's frame in its own part at that part's stored params (`core.mate`). `attach` and `set_params` write it; nothing else should. -**What may mate** (`core.mate_refusal`): two sockets of one kit and one type whose sizes agree as the type's -`match` says: `equal` within 1 percent of the larger, `fits` with the child at most the parent. `attach` also +**What may mate** (`core.mate_refusal`): two sockets of one type whose sizes agree as the type's +`match` says: `equal` within 1 percent of the larger, `fits` with the child at most the parent. Socket types are a +vocabulary kits share: parts of two kits mate when both kits declare the socket's type with the same `match` +(`cutters` declares `mount` as `mechanical` does, so a vent seats on a recess floor), and are refused, naming both +kits and the type, when one does not declare it or declares it otherwise. KSP's attach nodes and LDraw's snap +types are connector vocabularies of this kind: global, matched by type and size. `attach` also refuses, changing nothing: - a child that has a parent (`detach` it; `setObjectParent` with an empty parent clears a parent it was not @@ -190,7 +194,7 @@ A part's report carries `closure`: `null`, or `residual` is the larger of the largest difference between the two origins and the largest entry of the sum of the two normals; `holds` is true when it is at most 1e-5 and nothing below applies. When it does not hold, `reason` says why in a sentence: the other part is gone (`to` is then `null`); the other part cannot be read -against (not a kit part, of another kit, scaled by hand, or without that socket; `residual` is then `null`); +against (not a kit part, scaled by hand, or without that socket; `residual` is then `null`); another part's closure names the same socket, which a duplicated closing part leaves behind and which makes both read not held until one is detached; or the two sockets stand apart. A closure is never seated. `set_params` on either end refuses a change after which the two sockets may no longer mate (a pin of another size), naming the closure. A change that only @@ -215,7 +219,7 @@ child. Reports show it: a part's `connection` is `null`, or ``` `residual` is the largest entry of the difference between the socket's world frame and the frame its mate asks -for; `holds` is true when the parent is a kit part of the same kit, both sockets exist, the roll is a number, +for; `holds` is true when the parent is a kit part, both sockets exist, the roll is a number, the parent inverse is the identity and the residual is at most 1e-5. The next `set_params` on the child or on its parent (with any param, even at its current value) seats it again. A child whose parent was cleared or replaced by something that is not a kit part reads `holds` false with a `null` residual, and `set_params` @@ -224,32 +228,88 @@ A `kit_roll` that is not a finite number (only a hand can write one) reads `roll `set_params` on the child or its parent refuses it and leaves it as written: `detach` the child and `attach` it again. `detach` keeps the part where it stands in the world and leaves the parts attached to it attached. -**`boolean`** adds a Boolean modifier named `Kit Boolean ` to a kit part, above its `Kit Bevel`, so the -cut's edges are bevelled with the rest. The modifier's object is the cutter; the name is a label. The solver is -always Exact with self-intersection on: a kit part is several overlapping closed shells, and without it the -shells cancel where they overlap (the 1.8 m tank with a box cut through a cradle, the pad, a strap and the -barrel keeps 0.251 m3 with self-intersection and 0.006 m3 without). The cost grows with the shells that +**`boolean`** cuts a mesh, a kit part or any other, with another mesh object. A target carries at most one +Boolean modifier per operation, `Kit Difference`, `Kit Union` and `Kit Intersect`, evaluated in that order above +its `Kit Bevel` (so the cut's edges are bevelled with the rest), or at the end of the stack of a mesh that has no +Bevel. Each modifier cuts with a collection, and `boolean` adds the cutter to it: the modifier's collection is the +one statement of which cutters cut the target; its name (` difference`) is a label, and it is linked to no +scene, so it does not show in the outliner's scene tree. A cutter is listed once: `boolean` refuses one that +already cuts the target under any operation. The target must not be scaled. + +The solver is always Exact with self-intersection on: a kit part is several overlapping closed shells, and +without it the shells cancel where they overlap (the 1.8 m tank with a box cut through a cradle, the pad, a strap +and the barrel keeps 0.251 m3 with self-intersection and 0.006 m3 without). The cost grows with the shells that overlap, so each turned body of the kit is one lathe. What carries from machine to machine is the ratio to the same part built as a stack of tubes: 0.31 for the tank's turned body (6 shells against 20), 0.33 for the nozzle (9 against 24) and 0.81 for a pipe fitting (14 against 19). As absolute times, a box cut from a part at its defaults, placed through the add-on with its Bevel below the Boolean, evaluated in 0.50 to 0.55 s for the tank (two sessions), 0.49 s for the nozzle and 0.31 s for a pipe fitting on Blender 5.3 on the workstation Starfire (medians of four processes of five evaluations). The tank's four lugs, shells 7 to 10, add 1 percent to a cut -that misses them and 4 percent to one through them. The part pays this each time it is evaluated. Keep live booleans few and -`apply` them when the shape is settled. `boolean` -evaluates the part once and reports `evaluated: {faces, volume, nonManifoldEdges}`; `report` never evaluates a -modifier. The cutter is any other mesh object and is not changed: hide it with `setObjectVisibility`. A cutter -with no material leaves the part's material slots as they are; a cutter that has materials brings them, after -the part's own, on the faces it makes. +that misses them and 4 percent to one through them. -**`apply`** bakes a part: its mesh becomes the evaluated mesh (booleans and bevel applied), every modifier goes, -and `kit_baked` is set. The material slots are the part's own (an empty one it had included), followed by any +One Boolean over a collection is why cutters share a modifier. On a shell like a mech's pod (a loft of 6 rings of +8, Subsurf 3, Solidify 0.06: 5000 faces once cut) with 8 box and cylinder cutters placed by `cut`, one evaluation +took 1.89 s through the collection modifier, 12.6 s with a Boolean modifier for each cutter, and 1.81 s with the +eight cutters joined into one mesh (medians of five interleaved evaluations, Blender 5.3 on Starfire; an earlier +probe with raw cutters read 2.04, 14.7 and 1.94 s). All three give the same faces and volume. The cost is the +target's, hardly the cutters': one cutter on that shell already costs 1.4 s. The target pays it each time it is +evaluated, and Blender evaluates it after every action that changes it or a cutter. `apply` a kit part when its +shape is settled; a mesh that is not a kit part is baked by `exportGltf` with `applyModifiers`. `boolean` +evaluates the target once and reports `evaluated: {faces, volume, nonManifoldEdges}`; `report` never evaluates a +modifier. The cutter is any other mesh object and is not changed: hide it with `setObjectVisibility`. A cutter +with no material leaves the target's material slots as they are; a cutter that has materials brings them, after +the target's own, on the faces it makes. + +**`apply`** bakes a kit part: its mesh becomes the evaluated mesh (booleans and bevel applied), every modifier +goes with the collections its Booleans held, and `kit_baked` is set. The cutter objects stay: a cutter placed by +`cut` keeps its floor socket and what is attached to it. The material slots are the part's own (an empty one it had included), followed by any a cutter brought; faces a cutter made from an empty slot of its own take the part's first slot. A baked part keeps `kit_kit`, `kit_part`, `kit_params` and its connections: its sockets are still derived from the params, so what is attached to it stays attached and new parts can attach to it, and it can be cut and baked again. `set_params` refuses it, since the params no longer make the mesh. `exportGltf` with `applyModifiers` already exports the evaluated mesh; `apply` is for a baked `.blend`. +## Cutting a shell + +An armor plate is not a kit part: it is any mesh, usually a subdivided cage with a Solidify. `cut` cuts it, or a +kit part, where a ray meets it, and what it places is itself a kit part, of the kit `cutters`: + +| part | params (besides `depth`, `lift`) | socket | +| --- | --- | --- | +| `box` | `width` (x), `height` (y), `count`, `pitch` | `floor` (mount, size the smaller side) | +| `cyl` | `r`, `count`, `pitch` | `floor` (mount, size `2*r`) | +| `slot` | `width` (x, end to end), `height` (across; less than `width`), `count`, `pitch` | `floor` (mount, size `height`) | +| `slab` | `gap` (x), `length` (y) | none | + +A cutter's frame has its origin where the ray met the surface, `z` along the surface normal (turned to face +against the ray), `y` along the projection of `up` (default the target's +z; refused when it runs along the +normal) and is then turned `roll` degrees about the normal, right-handed (`core.surface_frame`). Its geometry +spans `z` from `-depth` to `+lift`: `depth` below the hit point and `lift` above it, so that a curved surface is +cut cleanly across the whole cutter (raise `lift` for a wide cutter on a tight curve). A `depth` beyond the wall's +thickness opens a hole. `count` copies stand `pitch` apart along `y`, centred on the frame: a row of gills (roll +90 turns the row along `x`). A `slab` is a panel break: a thin slab standing on the normal, long along `y`. + +The ray and `up` are given in the target's own frame, and the ray is cast at the target evaluated with its `Kit` +Booleans off: a second cut on the ray of a through bay lands on the surface as designed, not on the far wall +behind the bay. The target must not be scaled. + +The cutter object is parented to the target under an identity parent inverse and joins the collection of the +target's `Kit Difference` modifier. It owns the cut: its `matrix_basis` is the recess frame and its params the +recess size, and nothing else stores either. `setObjectTransform` on the cutter moves the cut, `set_params` +resizes it, and deleting the cutter removes the cut. `cut` does not hide the cutter: `setObjectVisibility` does, +and a hidden cutter still cuts. + +`box`, `cyl` and `slot` carry one socket, `floor`: on the bottom of the recess at `z = -depth`, at the frame's +centre, facing out of the recess. Machinery attaches there with the ordinary `attach` (a vent's `back`, a +sensor's `mount`), is a child of the cutter, and so follows the cut when the cutter moves and is seated again +when `set_params` changes its `depth`. With an even `count` and a `pitch` wider than the copies, the centre lies +between the two middle copies: use an odd count, or a cutter of its own, for a recess that carries a part. A +socket holds one part. + +`cut` reports `{object, cutter, booleans}`, the cutter as `report` would give it, with its `floor` in the world. +It does not evaluate the Boolean (its own work is a few milliseconds), but Blender evaluates the changed target +after the action as after any other: on the shell above each cut cost 1.4 to 1.9 s, one cutter to eight. + ## Expressions Every numeric field of a shape or socket, and `bevel`, is a number or a string over the part's params: @@ -272,11 +332,12 @@ vertices overflow. | `brokkr_kitbash.place_part` | `kit`, `part`, `object_name`, `params` | A new mesh object at the origin: the part's mesh, a `Kit Bevel` modifier when the part has a bevel, and the three ID properties. Refuses a name an object already has. | | `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. Seats the part and the parts attached to it again; refuses a change that breaks a connection or a closure's mate, and a baked part. Reports the part and `closures`, every closure in the scene as `{part, to, holds}`: its own first, then the broken, then the rest; rows that would not fit a receipt are left off the end and counted in `closuresOmitted`. Each closure in the scene adds a few milliseconds (both its parts are built again to find their sockets). | | `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, each socket's world frame, `connection`, `closure` and `baked`. Changes nothing and evaluates no modifier. | -| `brokkr_kitbash.attach` | `object_name` (the child), `socket`, `parent_name`, `parent_socket`, `roll` (degrees, -360 to 360, default 0) | Seats the child's socket on the parent's and parents it there. Reports the child. | +| `brokkr_kitbash.attach` | `object_name` (the child), `socket`, `parent_name`, `parent_socket`, `roll` (degrees, -360 to 360, default 0) | Seats the child's socket on the parent's and parents it there; the two parts are of one kit or of two whose socket types agree. Reports the child. | | `brokkr_kitbash.detach` | `object_name` | Clears the part's connection and the closure it states; it stays where it stands. Refuses a part that has neither. | | `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. | -| `brokkr_kitbash.boolean` | `object_name`, `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds a live Exact Boolean above the Bevel. Refuses a cutter that is the part, is not a mesh, or already cuts it. Reports the part, `booleans: [{cutter, operation}]` and `evaluated`. | -| `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the part and clears its modifiers. Refuses a part with no modifiers and a mesh another object shares. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | +| `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added) and `evaluated`. | +| `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the surface normal and a scaled target. Reports `object`, the `cutter` with its `floor` socket, and `booleans`. | +| `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers and a mesh another object shares. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored value (`set_params`). A value outside its bounds is refused with the bounds in the message. @@ -373,6 +434,9 @@ python -m unittest discover -s surfaces/blender/tests -p "test_kitbash.py" -v seated on a face that faces its `z`, and no build passes 20000 faces. Choose param ranges so every combination builds: a `min` or `max` in an expression keeps a derived length positive where two params could cross. A new part of `mechanical` also joins the part and socket list in `test_the_kit_is_the_eleven_parts_and_three_socket_types`. -`MateTests` covers the mate arithmetic and what may mate. The operators are exercised in a real Blender by +`CuttersKitTests` holds `cutters` to the same, with each floor on its cutter's bottom, and `SurfaceFrameTests` the +frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may mate, within a kit and across two. The operators are exercised in a real Blender by `tests/live/kitbash.py` (placing and re-parameterising) and `tests/live/kitbash_assembly.py` (attach, detach, -`set_params` on assemblies, a braced leg closed by `close`, boolean and apply). +`set_params` on assemblies, a braced leg closed by `close`, boolean and apply) and `tests/live/kitbash_shell.py` +(`cut` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no +collection). diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index b4be991..00e50c1 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -73,9 +73,9 @@ def extent(obj, axis=2): return float(co[:, axis].max() - co[:, axis].min()) -check("the nine kitbash rows load as host actions with no errors", not R["hostErrors"] +check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == [f"brokkr_kitbash.{name}" for name in ( - "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "apply")], [R["hostErrors"], R["hostRows"]]) + "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "cut", "apply")], [R["hostErrors"], R["hostRows"]]) # --- describe --------------------------------------------------------------------------------------------------------- kit = core.load_kit("mechanical") diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 765c5af..f5f3cb1 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -2,7 +2,7 @@ "blender": "5.3.0", "checks": [ { - "name": "the nine kitbash rows load as host actions with no errors", + "name": "the kitbash rows load as host actions with no errors", "ok": true, "detail": null }, @@ -414,6 +414,7 @@ "brokkr_kitbash.detach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", + "brokkr_kitbash.cut", "brokkr_kitbash.apply" ], "placed": { diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 1b2b5aa..188d821 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -176,8 +176,8 @@ def evaluated(obj): rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] -check("the nine kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == [f"brokkr_kitbash.{n}" for n in ( - "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "apply")], [R["hostErrors"], rows]) +check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == [f"brokkr_kitbash.{n}" for n in ( + "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "cut", "apply")], [R["hostErrors"], rows]) # --- attach ------------------------------------------------------------------------------------------------------------- tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088 diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index 98697ee..f7be6b4 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -2,7 +2,7 @@ "blender": "5.3.0", "checks": [ { - "name": "the nine kitbash rows load as host actions with no errors", + "name": "the kitbash rows load as host actions with no errors", "ok": true, "detail": null }, @@ -452,7 +452,7 @@ "detail": null }, { - "name": "boolean adds a Boolean modifier above the Bevel: Exact, self-intersection on, difference, the cutter its object", + "name": "boolean adds one Boolean modifier above the Bevel: Exact, self-intersection on, difference, over a collection that holds the cutter and is in no scene", "ok": true, "detail": null }, @@ -491,11 +491,6 @@ "ok": true, "detail": null }, - { - "name": "refused, scene unchanged: boolean on a mesh that is not a kit part", - "ok": true, - "detail": null - }, { "name": "set_params on the cut tank rebuilds it under the live Boolean, and the tee stays on its port", "ok": true, @@ -542,7 +537,7 @@ "detail": null }, { - "name": "two cutters stack in the order they came, both above the Bevel", + "name": "two cutters share one Boolean modifier above the Bevel, in its collection in the order they came", "ok": true, "detail": null }, @@ -632,8 +627,8 @@ "nonManifoldEdges": 0 }, "slotAndHole": { - "faces": 558, - "volume": 0.001411154, + "faces": 586, + "volume": 0.001411158, "nonManifoldEdges": 0 } }, diff --git a/surfaces/blender/tests/live/kitbash_shell.py b/surfaces/blender/tests/live/kitbash_shell.py new file mode 100644 index 0000000..6dc28f3 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_shell.py @@ -0,0 +1,371 @@ +"""Live proof, in a background Blender, of brokkr_kitbash shell cuts through run_intent: cut on a mesh that is not a kit +part (a subdivided, solidified cage), the one Boolean modifier per operation and its collection, a cast at the surface +without its cuts, machinery on a cutter's floor socket and what moves when the cutter moves or is resized, boolean on +any mesh, the refusals, an object in no collection, and the order of a set_params report's closures. Not part of the +unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_shell.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). is an absolute path; writes .result.json and exits 1 when a check failed. + +Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped worst reading +and the least claimed mutant's, both written beside it; the result file carries the readings. +""" +import importlib.util +import json +import math +import os +import sys +import tempfile +import types +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix, Vector +from mathutils.bvhtree import BVHTree + +SURFACE = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(SURFACE / "tools")) +import private_dirs # noqa: E402 + +_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) +if _refused: + raise SystemExit(_refused) +OUT = sys.argv[sys.argv.index("--") + 1] +if not Path(OUT).is_absolute(): + raise SystemExit(f"{OUT!r} is not an absolute path") +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules["brokkr_bridge"] = package +from brokkr_bridge import blender_target as bt # noqa: E402 + +import addon_utils # noqa: E402 + +spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_reference", SURFACE / "brokkr_kitbash" / "core.py") +core = importlib.util.module_from_spec(spec) # core as the unit tests load it: the frames every reading here is taken against +spec.loader.exec_module(core) + +sys.path.append(str(SURFACE)) +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_kitbash"): + addon_utils.enable(module, default_set=True) +target = bt.BrokkrBlenderTarget(bpy) +WORK = Path(tempfile.mkdtemp(prefix="brokkr-kitbash-shell-")) +target.configure_action_dirs("", str(WORK)) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}} +COUNT = [0] +kits = {name: core.load_kit(name) for name in ("mechanical", "cutters")} +# Largest entry of a cutter's matrix_basis minus core.surface_frame at the point where this script's own ray meets the +# cage evaluated before the cut. Shipped worst 5.1e-07 (float32 matrices); least claimed mutant 2.0 (X4, the roll's +# sign reversed, on the slab at roll 90); separation 2000 each side. +FRAMED = 1.0e-3 +# Metres between where a second cut on the through bay's ray lands and where the first did. Shipped 0 (the same +# evaluation twice), taken as one float32 step, 1.2e-07; least claimed mutant 1.4 (S2, cast with the cuts on: the ray +# goes through the bay to the far wall); separation 3400 each side. +RECAST = 4.1e-4 +# Metres, or a difference of unit vectors, between the back of a vent attached to a cutter's floor and the hit point +# taken depth along the normal, in the world. Shipped worst 1.8e-07; least claimed mutant 0.036 (S3, the floor socket +# at z=+depth, at depth 0.02); separation 450 each side. +FLOORED = 8.0e-5 + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised + + +def reading(name, value): + R["readings"][name] = max(R["readings"].get(name, 0.0), float(value)) + return float(value) + + +def send(action, **fields): + COUNT[0] += 1 + receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "test/driver", "action": action, **fields}) + result = None + if receipt.get("hostResult"): + try: + result = json.loads(receipt["hostResult"]) + except ValueError: + result = None + print("SEND", action, receipt["status"], str(receipt["message"])[:300], flush=True) + return receipt, result + + +def place(name, part, params="", location=None, rotation=None): + send("brokkr_kitbash.place_part", part=part, object_name=name, params=params) + if location is not None: + send("setObjectTransform", targetObjectName=name, location=location, rotationEuler=rotation or [0.0, 0.0, 0.0]) + return bpy.data.objects[name] + + +def held(report): + """An attach or set_params report whose connection holds.""" + return bool(report and report.get("connection") and report["connection"]["holds"] and report["connection"]["residual"] <= 1e-5) + + +def scene_state(): + return {o.name: (o.parent and o.parent.name, np.round(np.array(o.matrix_basis), 6).tolist(), np.round(np.array(o.matrix_parent_inverse), 6).tolist(), + {k: repr(o[k]) for k in sorted(o.keys()) if k.startswith("kit_")}, [(m.name, m.type) for m in o.modifiers], + o.data.name if o.type == "MESH" else None, len(o.data.polygons) if o.type == "MESH" else None, + [s.material and s.material.name for s in o.material_slots], o.hide_render) + for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes) + + +def refused(label, action, fields, expected): + state = scene_state() + receipt, _ = send(action, **fields) + check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state, + [receipt["status"], receipt["message"]]) + + +def measure(mesh): + bm = bmesh.new() + bm.from_mesh(mesh) + row = {"faces": len(bm.faces), "volume": round(bm.calc_volume(signed=True), 9), "nonManifoldEdges": sum(1 for e in bm.edges if not e.is_manifold)} + bm.free() + return row + + +def evaluated(obj): + """(faces, volume, non-manifold edges, material slot names) of the object with its modifiers, read here and not through the add-on.""" + shown = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()) + row = measure(shown.to_mesh()) + shown.to_mesh_clear() + return row, [m.name if m else None for m in shown.data.materials] + + +def frame(obj, socket): + """A socket's world frame, from the object's matrix_world and core's build of its stored params.""" + built = core.build(core.part(kits[obj["kit_kit"]], obj["kit_part"]), json.loads(obj["kit_params"])) + return np.array(obj.matrix_world, dtype=np.float64) @ next(s["matrix"] for s in built.sockets if s["name"] == socket) + + +def cast(obj, origin, direction): + """(hit, normal facing the ray) on the object as it is evaluated now, in its own frame: this script's own ray.""" + depsgraph = bpy.context.evaluated_depsgraph_get() + hit, normal, _, _ = BVHTree.FromObject(obj, depsgraph).ray_cast(Vector(origin), Vector(direction).normalized()) + return np.array(hit), np.array(-normal if normal.dot(Vector(direction)) > 0 else normal) + + +def cut(name, part, origin, direction, params="", **more): + return send("brokkr_kitbash.cut", object_name="Cage", cutter_name=name, part=part, params=params, + **{f"origin_{k}": v for k, v in zip("xyz", origin)}, **{f"direction_{k}": v for k, v in zip("xyz", direction)}, **more) + + +def stack(obj): + return [m.name for m in obj.modifiers] + + +# --- a cage: not a kit part. A closed loft of 6 rings of 8, subdivided and given a wall ---------------------------------- +bm = bmesh.new() +rings = [[bm.verts.new((r * math.cos(math.pi / 8 + k * math.pi / 4), r * math.sin(math.pi / 8 + k * math.pi / 4), z)) for k in range(8)] + for z, r in ((-1.0, 0.5), (-0.6, 0.7), (-0.2, 0.8), (0.2, 0.8), (0.6, 0.7), (1.0, 0.5))] +for low, high in zip(rings, rings[1:]): + for k in range(8): + bm.faces.new((low[k], low[(k + 1) % 8], high[(k + 1) % 8], high[k])) +bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) +mesh = bpy.data.meshes.new("Cage") +bm.to_mesh(mesh) +bm.free() +cage = bpy.data.objects.new("Cage", mesh) +bpy.context.scene.collection.objects.link(cage) +cage.modifiers.new("Subsurf", "SUBSURF").levels = 2 +wall = cage.modifiers.new("Solidify", "SOLIDIFY") +wall.thickness, wall.offset, wall.use_even_offset = 0.05, -1.0, True +cage.matrix_world = Matrix.Translation((4.0, -1.0, 2.0)) @ Matrix.Rotation(0.6, 4, "Z") @ Matrix.Rotation(-0.3, 4, "X") +bpy.context.view_layer.update() +world = np.array(cage.matrix_world, dtype=np.float64) +uncut, _ = evaluated(cage) +check("the cage is a closed wall before it is cut", uncut["nonManifoldEdges"] == 0 and 0.15 < uncut["volume"] < 0.4 and "kit_part" not in cage, uncut) +R["cage"] = {"uncut": uncut} + +# --- cut-at-ray: a through bay, a blind round recess, a row of gills and a panel break -------------------------------------- +CUTS = [("Bay", "box", (3.0, 0.0, 0.1), (-1.0, 0.0, 0.0), "width=0.3; height=0.3; depth=0.2", {}), + ("Recess", "cyl", (-3.0, 0.1, 0.2), (2.0, 0.0, 0.0), "r=0.1; depth=0.02", {}), + ("Gills", "slot", (0.1, 3.0, -0.2), (0.0, -1.0, 0.0), "width=0.3; height=0.04; count=4; pitch=0.08; depth=0.02", {}), + ("Break", "slab", (0.0, -3.0, 0.3), (0.0, 1.0, 0.0), "length=0.6; depth=0.1", {"roll": 90.0})] +frames, volume, falls, reports = {}, uncut["volume"], [], {} +for name, part, origin, direction, params, more in CUTS: + hit, normal = cast(cage, origin, direction) # before this cutter exists; the cuts made so far are far from this ray + frames[name] = core.surface_frame(hit, normal, (0.0, 0.0, 1.0), more.get("roll", 0.0)) + state = sorted(o.name for o in bpy.data.objects) + receipt, report = cut(name, part, origin, direction, params, **more) + reports[name] = report + cutter = bpy.data.objects.get(name) + ok = receipt["status"] == "accepted" and cutter is not None and sorted(o.name for o in bpy.data.objects) == sorted(state + [name]) + ok = ok and cutter.parent == cage and np.array_equal(np.array(cutter.matrix_parent_inverse), np.eye(4)) + ok = ok and reading("framed", np.abs(np.array(cutter.matrix_basis) - frames[name]).max()) < FRAMED + ok = ok and (cutter["kit_kit"], cutter["kit_part"]) == ("cutters", part) and bpy.context.scene.collection in cutter.users_collection + ok = ok and not cutter.hide_render and not cutter.hide_viewport and len(cutter.modifiers) == 0 + check(f"cut places the {part} cutter {name} on the cage where the ray meets it: parented under an identity inverse, its basis the surface frame", + ok, [receipt["message"], cutter and np.array(cutter.matrix_basis).tolist(), frames[name].tolist()]) + wanted = world @ frames[name] + check(f"cut reports {name} as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", report + and report["object"] == "Cage" and report["cutter"]["object"] == name and report["cutter"]["kit"] == "cutters" and "evaluated" not in report + and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in [c[0] for c in CUTS][:len(frames)]] + and [s["name"] for s in report["cutter"]["sockets"]] == ([] if part == "slab" else ["floor"]) + and (part == "slab" or np.abs(np.array(report["cutter"]["sockets"][0]["matrix"]) - wanted @ core.build(kits["cutters"]["parts"][part], report["cutter"]["params"]).sockets[0]["matrix"]).max() < 1e-4), + report) + shown, _ = evaluated(cage) + falls.append(shown["volume"] < volume - 1e-4 and shown["nonManifoldEdges"] == 0) + volume = shown["volume"] + R["cage"][name] = shown +modifier = cage.modifiers.get("Kit Difference") +check("four cuts give the cage one Boolean modifier after its own, over one collection of the four cutters in the order they came", + stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and modifier is not None + and (modifier.type, modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.material_mode) == ("BOOLEAN", "EXACT", True, "DIFFERENCE", "COLLECTION", "TRANSFER") + and [o.name for o in modifier.collection.objects] == [c[0] for c in CUTS] and modifier.collection.name == "Cage difference" + and not any(modifier.collection in s.collection.children_recursive for s in bpy.data.scenes), [stack(cage), modifier and modifier.operand_type]) +check("the evaluated cage stays a closed wall and loses volume with each cut", all(falls) and len(falls) == 4, R["cage"]) +receipt, report = send("brokkr_kitbash.report", object_name="") +check("report lists the cutters as kit parts and not the cage", report and [p["object"] for p in report["parts"]] == sorted(c[0] for c in CUTS) + and all(p["connection"] is None and p["baked"] is False for p in report["parts"]), report and [p["object"] for p in report["parts"]]) + +# --- cut-casts-the-uncut-surface -------------------------------------------------------------------------------------------- +through = cast(cage, CUTS[0][2], CUTS[0][3])[0] # as the cage is evaluated now, with its cuts: through the bay to the far wall +receipt, report = cut("Bay2", "cyl", CUTS[0][2], CUTS[0][3], "r=0.05; depth=0.2") +again = bpy.data.objects.get("Bay2") +check("a second cut on the through bay's ray lands where the first did, on the surface as it was before any cut, though the ray now passes through the bay", + receipt["status"] == "accepted" and again is not None and np.linalg.norm(through - frames["Bay"][:3, 3]) > 1.0 + and reading("recast", np.abs(np.array(again.matrix_basis)[:3, 3] - frames["Bay"][:3, 3]).max()) < RECAST + and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and all(m.show_viewport for m in cage.modifiers), + [receipt["message"], through.tolist(), frames["Bay"][:3, 3].tolist(), again and list(again.matrix_basis.translation)]) + +# --- floor-carries-machinery ------------------------------------------------------------------------------------------------ +recess = bpy.data.objects["Recess"] +vent = place("Vent", "vent", "width=0.2; height=0.15") # back size 0.135; the floor's is 0.2 +receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Recess", parent_socket="floor", roll=30.0) +floor = world @ frames["Recess"] @ np.array(Matrix.Translation((0.0, 0.0, -0.02))) # the hit point, depth along the normal +back = frame(vent, "back") +check("a mechanical vent attaches to the round recess's floor: its back on the hit point taken depth down the normal, facing in, and the connection holds", + receipt["status"] == "accepted" and held(report) and vent.parent == recess and report["connection"]["parent"] == "Recess" and report["kit"] == "mechanical" + and reading("floored", max(np.abs(back[:3, 3] - floor[:3, 3]).max(), np.abs(back[:3, 2] + floor[:3, 2]).max())) < FLOORED, + [receipt["message"], back.tolist(), floor.tolist()]) +big = place("Big", "vent", "width=0.8; height=0.6") +refused("a vent larger than the recess's floor", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Recess", "parent_socket": "floor"}, + "'Big' on 'Recess': socket 'back' (mount, size 0.54) and parent socket 'floor' (mount, size 0.2) are mount sockets, where the child fits the parent: it is larger") +nozzle = place("Nozzle", "nozzle") +refused("a flange on a floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Recess", "parent_socket": "floor"}, "are of different types") +refused("a second part on the floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Recess", "parent_socket": "floor"}, "'Nozzle' on 'Recess'") +refused("a part on a slab, which has no floor", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Break", "parent_socket": "floor"}, + "kit 'cutters' part 'slab' has no socket 'floor'; its sockets: none") +refused("detach of a cutter, which is placed and not attached", "brokkr_kitbash.detach", {"object_name": "Recess"}, "'Recess' is not attached") +before = evaluated(cage)[0] +moved_to = np.array(recess.matrix_basis)[:3, 3] + np.array(recess.matrix_basis)[:3, :3] @ [0.0, 0.25, 0.0] # along the cutter's own y: up the wall +was = frame(vent, "back") +send("setObjectTransform", targetObjectName="Recess", location=moved_to.tolist()) +shift = frame(vent, "back")[:3, 3] - was[:3, 3] +after = evaluated(cage)[0] +check("setObjectTransform on the cutter moves the cut and the vent on its floor together: the vent still holds, and the cage is cut elsewhere", + reading("floored", np.abs(shift - world[:3, :3] @ (moved_to - frames["Recess"][:3, 3])).max()) < FLOORED and abs(np.linalg.norm(shift) - 0.25) < 1e-4 + and (connection := send("brokkr_kitbash.report", object_name="Vent")[1]["parts"][0]["connection"])["holds"] is True + and after["nonManifoldEdges"] == 0 and after != before, [shift.tolist(), before, after]) +was = frame(vent, "back") +receipt, report = send("brokkr_kitbash.set_params", object_name="Recess", params="depth=0.04") +sunk = frame(vent, "back")[:3, 3] - was[:3, 3] +deeper = evaluated(cage)[0] +check("set_params depth=0.04 on the cutter deepens the cut and seats the vent on the new floor, 0.02 further down the normal", + receipt["status"] == "accepted" and report["params"]["depth"] == 0.04 and reading("floored", np.abs(sunk + was[:3, 2] * -0.02).max()) < FLOORED + and send("brokkr_kitbash.report", object_name="Vent")[1]["parts"][0]["connection"]["holds"] is True + and deeper["volume"] < after["volume"] - 1e-5 and deeper["nonManifoldEdges"] == 0 and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"], + [receipt["message"], sunk.tolist(), after, deeper]) +R["cage"]["deeper"] = deeper + +# --- boolean on any mesh, and the order of the three operations ----------------------------------------------------------------- +lump_at = world @ [0.0, 0.0, 1.0, 1.0] +send("createObject", objectType="MESH", name="Lump", location=lump_at[:3].tolist(), size=0.2) +receipt, report = send("brokkr_kitbash.boolean", object_name="Cage", cutter="Lump", operation="UNION") +check("boolean on the cage, which is not a kit part, adds a second modifier after the difference and reports the object, what cuts it and the evaluated mesh", + receipt["status"] == "accepted" and stack(cage) == ["Subsurf", "Solidify", "Kit Difference", "Kit Union"] + and sorted(report) == ["booleans", "evaluated", "object"] and report["object"] == "Cage" and report["evaluated"] == evaluated(cage)[0] + and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in ("Bay", "Recess", "Gills", "Break", "Bay2")] + [{"cutter": "Lump", "operation": "UNION"}] + and report["evaluated"]["volume"] > deeper["volume"], [receipt["message"], report]) +refused("cut-refusals: a cutter already in the target's union collection", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Lump"}, + "'Lump' already cuts 'Cage' (its Kit Union modifier's collection)") +refused("a cut's own cutter given to boolean again", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Bay", "operation": "INTERSECT"}, + "'Bay' already cuts 'Cage' (its Kit Difference modifier's collection)") +plate = place("Plate", "plate", location=[0.0, -6.0, 0.0]) +for name, size, operation in (("Boss", 0.06, "UNION"), ("Keep", 2.0, "INTERSECT"), ("Hole", 0.05, "DIFFERENCE")): + send("createObject", objectType="MESH", name=name, location=[0.0, -6.0, 0.0], size=size) + receipt, report = send("brokkr_kitbash.boolean", object_name="Plate", cutter=name, operation=operation) +check("a part cut by union, then intersect, then difference carries the three modifiers as difference, union, intersect, above its Bevel, and lists its cutters so", + receipt["status"] == "accepted" and stack(plate) == ["Kit Difference", "Kit Union", "Kit Intersect", "Kit Bevel"] + and report["booleans"] == [{"cutter": "Hole", "operation": "DIFFERENCE"}, {"cutter": "Boss", "operation": "UNION"}, {"cutter": "Keep", "operation": "INTERSECT"}] + and report["evaluated"]["nonManifoldEdges"] == 0 and report["kit"] == "mechanical", [stack(plate), report and report["booleans"]]) +collections = len(bpy.data.collections) +receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") +check("apply removes the three collections its modifiers held and leaves every cutter in the scene", receipt["status"] == "accepted" + and baked["cutters"] == ["Hole", "Boss", "Keep"] and len(bpy.data.collections) == collections - 3 and len(plate.modifiers) == 0 + and all(name in bpy.context.scene.objects for name in ("Hole", "Boss", "Keep")), [receipt["message"], [c.name for c in bpy.data.collections]]) +refused("apply on the cage, which is not a kit part", "brokkr_kitbash.apply", {"object_name": "Cage"}, "'Cage' is not a kit part") + +# --- cut-refusals ----------------------------------------------------------------------------------------------------------- +RAY = {"object_name": "Cage", "cutter_name": "New", "part": "box", "origin_x": 3.0, "origin_y": 0.0, "origin_z": 0.1, "direction_x": -1.0, "direction_y": 0.0, "direction_z": 0.0} +refused("a ray that misses", "brokkr_kitbash.cut", {**RAY, "origin_z": 5.0}, "The ray from (3.0, 0.0, 5.0) along (-1.0, 0.0, 0.0) misses 'Cage'") +refused("a ray of no direction", "brokkr_kitbash.cut", {**RAY, "direction_x": 0.0}, "The ray's direction is zero") +refused("a cutter name an object has", "brokkr_kitbash.cut", {**RAY, "cutter_name": "Bay"}, "An object named 'Bay' exists") +refused("a param the cutter part does not have", "brokkr_kitbash.cut", {**RAY, "params": "radius=0.1"}, "kit 'cutters' part 'box' has no param 'radius'") +refused("a slot wider across than along", "brokkr_kitbash.cut", {**RAY, "part": "slot", "params": "width=0.05; height=0.1"}, "every size must be above 0") +refused("a target that is not a mesh", "brokkr_kitbash.cut", {**RAY, "object_name": "Nothing"}, "No mesh object named 'Nothing'") +block = bpy.data.objects.new("Block", bpy.data.meshes.new("Block")) +bm = bmesh.new() +bmesh.ops.create_cube(bm, size=1.0) +bm.to_mesh(block.data) +bm.free() +bpy.context.scene.collection.objects.link(block) +block.location = (0.0, -9.0, 0.0) +bpy.context.view_layer.update() +DOWN = {**RAY, "object_name": "Block", "origin_x": 0.1, "origin_y": 0.1, "origin_z": 3.0, "direction_x": 0.0, "direction_z": -1.0} +refused("an up along the hit normal", "brokkr_kitbash.cut", DOWN, "up [0.0, 0.0, 1.0] runs along the surface normal [0.0, 0.0, 1.0]") +block.scale = (1.0, 1.0, 1.01) +bpy.context.view_layer.update() +refused("a scaled target", "brokkr_kitbash.cut", {**DOWN, "up_y": 1.0, "up_z": 0.0}, "'Block' is scaled, mirrored or sheared in the world (scale 1, 1, 1.01)") +refused("boolean on a scaled target", "brokkr_kitbash.boolean", {"object_name": "Block", "cutter": "Lump"}, "'Block' is scaled, mirrored or sheared") +block.scale = (1.0, 1.0, 1.0) +bpy.context.view_layer.update() +receipt, report = send("brokkr_kitbash.cut", **{**DOWN, "cutter_name": "Pocket", "up_y": 1.0, "up_z": 0.0, "roll": 90.0}) +pocket = bpy.data.objects.get("Pocket") +check("a cut on a plain cube with up +y and roll 90: the cutter's y points along -x, its floor 0.02 under the top face", receipt["status"] == "accepted" and pocket is not None + and np.abs(np.array(pocket.matrix_basis) - [[0, -1, 0, 0.1], [1, 0, 0, 0.1], [0, 0, 1, 0.5], [0, 0, 0, 1]]).max() < 1e-6 + and np.abs(np.array(report["cutter"]["sockets"][0]["matrix"])[:3, 3] - [0.1, -8.9, 0.48]).max() < 1e-6 and stack(block) == ["Kit Difference"], + [receipt["message"], pocket and np.array(pocket.matrix_basis).tolist()]) + +# --- cut-orphan and closures-ends-first ----------------------------------------------------------------------------------------- +strut = core.build(kits["mechanical"]["parts"]["strut"], {"width": 0.09}) +end = {name: next(s for s in strut.sockets if s["name"] == name) for name in ("end_a", "end_b")} +for pair, y in (("Zz", -20.0), ("Aa", -24.0)): # two closures that share no part; the open one is named to sort first + anchor, loose = place(f"{pair}_Anchor", "strut", "width=0.09", location=[0.0, y, 0.0]), place(f"{pair}_Loose", "strut", "width=0.09") + meet = Matrix((np.array(anchor.matrix_world) @ core.mate(end["end_b"], end["end_a"], 40.0)).tolist()) + send("setObjectTransform", targetObjectName=f"{pair}_Loose", location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) + send("brokkr_kitbash.close", object_name=f"{pair}_Loose", socket="end_a", other_name=f"{pair}_Anchor", other_socket="end_b") +send("brokkr_kitbash.set_params", object_name="Aa_Anchor", params="length=0.9") # opens Aa's closure +receipt, report = send("brokkr_kitbash.set_params", object_name="Zz_Anchor", params="width=0.09") +check("closures-ends-first: set_params on a part whose own closure holds lists it before another part's closure that is open, though that one sorts first by holds and by name", + receipt["status"] == "accepted" and report["closures"] == [{"part": "Zz_Loose", "to": "Zz_Anchor", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}], + report and report.get("closures")) +ghost = bpy.data.objects["Aa_Anchor"] +with bpy.context.temp_override(selected_objects=[ghost], active_object=ghost): + bpy.ops.object.delete() # the ordinary Delete: Aa_Loose's closure still points at it, so it stays in the file, in no collection +tie = place("Tie", "strut", "width=0.09") +check("a part deleted with the Delete operator that a closure points to is still in the file", bpy.data.objects.get("Aa_Anchor") is not None and not ghost.users_collection, list(bpy.data.objects.keys())) +GONE = "'Aa_Anchor' is in no collection (a deleted object something still points to)" +refused("cut-orphan: attach onto a deleted part's name", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Aa_Anchor", "parent_socket": "end_a"}, GONE) +refused("attach of a deleted part", "brokkr_kitbash.attach", {"object_name": "Aa_Anchor", "socket": "end_a", "parent_name": "Tie", "parent_socket": "end_a"}, GONE) +refused("set_params on a deleted part", "brokkr_kitbash.set_params", {"object_name": "Aa_Anchor", "params": "length=1.0"}, GONE) +refused("report of a deleted part", "brokkr_kitbash.report", {"object_name": "Aa_Anchor"}, GONE) +refused("cut on a deleted part", "brokkr_kitbash.cut", {**RAY, "object_name": "Aa_Anchor"}, GONE) +refused("boolean on a deleted part", "brokkr_kitbash.boolean", {"object_name": "Aa_Anchor", "cutter": "Lump"}, GONE) +refused("boolean with a deleted part as the cutter", "brokkr_kitbash.boolean", {"object_name": "Tie", "cutter": "Aa_Anchor"}, GONE) +refused("close onto a deleted part", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Aa_Anchor", "other_socket": "end_a"}, GONE) + +R["ok"] = all(c["ok"] for c in R["checks"]) +R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") +for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +print("READINGS", R["readings"], flush=True) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_shell.result.json b/surfaces/blender/tests/live/kitbash_shell.result.json new file mode 100644 index 0000000..90e7a0e --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_shell.result.json @@ -0,0 +1,279 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "the cage is a closed wall before it is cut", + "ok": true, + "detail": null + }, + { + "name": "cut places the box cutter Bay on the cage where the ray meets it: parented under an identity inverse, its basis the surface frame", + "ok": true, + "detail": null + }, + { + "name": "cut reports Bay as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", + "ok": true, + "detail": null + }, + { + "name": "cut places the cyl cutter Recess on the cage where the ray meets it: parented under an identity inverse, its basis the surface frame", + "ok": true, + "detail": null + }, + { + "name": "cut reports Recess as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", + "ok": true, + "detail": null + }, + { + "name": "cut places the slot cutter Gills on the cage where the ray meets it: parented under an identity inverse, its basis the surface frame", + "ok": true, + "detail": null + }, + { + "name": "cut reports Gills as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", + "ok": true, + "detail": null + }, + { + "name": "cut places the slab cutter Break on the cage where the ray meets it: parented under an identity inverse, its basis the surface frame", + "ok": true, + "detail": null + }, + { + "name": "cut reports Break as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", + "ok": true, + "detail": null + }, + { + "name": "four cuts give the cage one Boolean modifier after its own, over one collection of the four cutters in the order they came", + "ok": true, + "detail": null + }, + { + "name": "the evaluated cage stays a closed wall and loses volume with each cut", + "ok": true, + "detail": null + }, + { + "name": "report lists the cutters as kit parts and not the cage", + "ok": true, + "detail": null + }, + { + "name": "a second cut on the through bay's ray lands where the first did, on the surface as it was before any cut, though the ray now passes through the bay", + "ok": true, + "detail": null + }, + { + "name": "a mechanical vent attaches to the round recess's floor: its back on the hit point taken depth down the normal, facing in, and the connection holds", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a vent larger than the recess's floor", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a flange on a floor", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a second part on the floor", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a part on a slab, which has no floor", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: detach of a cutter, which is placed and not attached", + "ok": true, + "detail": null + }, + { + "name": "setObjectTransform on the cutter moves the cut and the vent on its floor together: the vent still holds, and the cage is cut elsewhere", + "ok": true, + "detail": null + }, + { + "name": "set_params depth=0.04 on the cutter deepens the cut and seats the vent on the new floor, 0.02 further down the normal", + "ok": true, + "detail": null + }, + { + "name": "boolean on the cage, which is not a kit part, adds a second modifier after the difference and reports the object, what cuts it and the evaluated mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut-refusals: a cutter already in the target's union collection", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a cut's own cutter given to boolean again", + "ok": true, + "detail": null + }, + { + "name": "a part cut by union, then intersect, then difference carries the three modifiers as difference, union, intersect, above its Bevel, and lists its cutters so", + "ok": true, + "detail": null + }, + { + "name": "apply removes the three collections its modifiers held and leaves every cutter in the scene", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: apply on the cage, which is not a kit part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a ray that misses", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a ray of no direction", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a cutter name an object has", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a param the cutter part does not have", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a slot wider across than along", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a target that is not a mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an up along the hit normal", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a scaled target", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean on a scaled target", + "ok": true, + "detail": null + }, + { + "name": "a cut on a plain cube with up +y and roll 90: the cutter's y points along -x, its floor 0.02 under the top face", + "ok": true, + "detail": null + }, + { + "name": "closures-ends-first: set_params on a part whose own closure holds lists it before another part's closure that is open, though that one sorts first by holds and by name", + "ok": true, + "detail": null + }, + { + "name": "a part deleted with the Delete operator that a closure points to is still in the file", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut-orphan: attach onto a deleted part's name", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: attach of a deleted part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a deleted part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: report of a deleted part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut on a deleted part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean on a deleted part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean with a deleted part as the cutter", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close onto a deleted part", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "readings": { + "floored": 1.8e-07, + "framed": 5.1e-07, + "recast": 0.0 + }, + "cage": { + "uncut": { + "faces": 1344, + "volume": 0.387534911, + "nonManifoldEdges": 0 + }, + "Bay": { + "faces": 1340, + "volume": 0.382961784, + "nonManifoldEdges": 0 + }, + "Recess": { + "faces": 1373, + "volume": 0.382415225, + "nonManifoldEdges": 0 + }, + "Gills": { + "faces": 1591, + "volume": 0.381816176, + "nonManifoldEdges": 0 + }, + "Break": { + "faces": 1596, + "volume": 0.381252326, + "nonManifoldEdges": 0 + }, + "deeper": { + "faces": 1597, + "volume": 0.380943949, + "nonManifoldEdges": 0 + } + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index fc9fd43..56e405a 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -222,7 +222,7 @@ class CheckKitTests(unittest.TestCase): for name in ("../x", "mechanical.v0", "Mechanical", "", "a/b", "x" * 33, 3): with self.assertRaisesRegex(core.KitError, "must be 1 to 32 of"): core.load_kit(name) - with self.assertRaisesRegex(core.KitError, "no kit named 'absent'; kits: mechanical"): + with self.assertRaisesRegex(core.KitError, "no kit named 'absent'; kits: cutters, mechanical"): core.load_kit("absent") with self.assertRaisesRegex(core.KitError, "has no part 'wing'; its parts: nozzle, tank"): core.part(core.load_kit("mechanical"), "wing") @@ -552,6 +552,150 @@ class MechanicalKitTests(unittest.TestCase): self.assertEqual(described["parts"][0]["params"][0], {"name": "radius", "type": "number", "min": 0.12, "max": 0.35, "default": 0.22, "doc": "shell radius"}) +@unittest.skipIf(np is None, "numpy is not installed") +class CuttersKitTests(unittest.TestCase): + """The cutters kit: what brokkr_kitbash.cut places. A cutter spans z from -depth to +lift; its floor socket is the + bottom of the recess seen from outside, so its z is +z where the cutter's own bottom face looks along -z.""" + + @classmethod + def setUpClass(cls): + cls.kit = core.load_kit("cutters") + + def draws(self, name): + part = self.kit["parts"][name] + rng = random.Random(f"cutters.{name}") + draws = [{p["name"]: p[key] for p in part["params"]} for key in ("default", "min", "max")] + for _ in range(16): + draws.append({p["name"]: rng.randint(p["min"], p["max"]) if p["type"] == "integer" else rng.uniform(p["min"], p["max"]) for p in part["params"]}) + return part, draws + + def test_the_kit_is_four_cutters_and_three_floors(self): + self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, + {"box": [("floor", "mount")], "cyl": [("floor", "mount")], "slot": [("floor", "mount")], "slab": []}) + self.assertEqual(self.kit["socketTypes"]["mount"], core.load_kit("mechanical")["socketTypes"]["mount"]) + self.assertTrue(all(part["bevel"] is None for part in self.kit["parts"].values())) + + def test_every_cutter_holds_everywhere(self): + """cutters-kit. Mutant S3 (the floor socket at z=+depth): the floor is not on the cutter's bottom.""" + built = refused = 0 + for name in self.kit["parts"]: + part, draws = self.draws(name) + for given in draws: + if name == "slot" and given["width"] <= given["height"]: + with self.assertRaisesRegex(core.KitError, r"part 'slot' shape 0 \(repeat\) of \(box\): every size must be above 0"): + core.build(part, given) + refused += 1 + continue + b = core.build(part, given) + built += 1 + self.assertTrue(closed_and_oriented(b), f"{name} {given}") + self.assertGreater(signed_volume(b), 0.0) + depth, lift = b.params["depth"], b.params["lift"] + self.assertAlmostEqual(float(b.V[:, 2].min()), -depth, places=12) + self.assertAlmostEqual(float(b.V[:, 2].max()), lift, places=12) + for socket in b.sockets: + self.assertEqual(socket["matrix"][:, 3].tolist(), [0.0, 0.0, -depth, 1.0]) + self.assertEqual(socket["matrix"][:3, :3].tolist(), np.eye(3).tolist()) + self.assertGreater(socket["size"], 0.0) + self.assertGreater(built, 60) + self.assertGreater(refused, 0) + + def test_the_floor_is_the_bottom_of_every_copy(self): + """Every copy's bottom face lies in the floor socket's plane looking the other way, the row is centred on the + frame, and the socket's origin is on a copy's bottom whenever the count is odd.""" + for name, size in (("box", {"width": 0.1, "height": 0.06}), ("cyl", {"r": 0.03}), ("slot", {"width": 0.1, "height": 0.06})): + part = self.kit["parts"][name] + for count in (1, 2, 3, 4, 7, 64): + b = core.build(part, {**size, "count": count, "pitch": 0.09, "depth": 0.03}) + floor = dict(b.sockets[0], matrix=b.sockets[0]["matrix"] @ core.FLIP) # the bottom face looks along -z + self.assertEqual(b.shell_count, count * (3 if name == "slot" else 1)) + bottoms = [b.V[face] for face in faces_of(b) if np.abs(b.V[face][:, 2] + 0.03).max() < 1e-12] + self.assertEqual(len(bottoms), b.shell_count) + self.assertAlmostEqual(float(b.V[:, 1].max() + b.V[:, 1].min()), 0.0, places=12) + self.assertAlmostEqual(float(b.V[:, 1].max() - b.V[:, 1].min()), (count - 1) * 0.09 + 0.06, places=12) + seat = socket_seat(b, floor) + self.assertTrue(seat < 1e-12 if count % 2 else abs(seat - 0.015) < 1e-12, f"{name} x{count}: {seat}") # even: 0.015 from each middle copy + + def test_a_slot_is_a_stadium_of_its_width(self): + """Mutant S9 (the end tubes at x = +-width/2): the slot is width + height long and the rounds stand off the box.""" + b = core.build(self.kit["parts"]["slot"], {"width": 0.3, "height": 0.05, "depth": 0.02, "lift": 0.05}) + self.assertAlmostEqual(float(b.V[:, 0].max()), 0.15, places=12) + self.assertAlmostEqual(float(b.V[:, 0].min()), -0.15, places=12) + self.assertAlmostEqual(float(np.abs(b.V[:, 1]).max()), 0.025, places=12) + corners = {(round(float(x), 9), round(float(y), 9)) for x, y in b.V[:8, :2]} # shape 0, the box + self.assertEqual(corners, {(-0.125, -0.025), (0.125, -0.025), (0.125, 0.025), (-0.125, 0.025)}) + rounds = {(round(float(x), 9), round(float(y), 9)) for x, y in b.V[8:, :2]} + self.assertTrue(corners <= rounds) # each round's quarter points are the box's corners: one outline + gon = 0.5 * 32 * 0.025 ** 2 * math.sin(2 * math.pi / 32) + self.assertAlmostEqual(signed_volume(b), (0.25 * 0.05 + 2 * gon) * 0.07, places=12) # shells counted where they overlap: the stadium and one more 32-gon + + def test_a_slab_has_no_socket_and_stands_on_the_normal(self): + b = core.build(self.kit["parts"]["slab"], {"depth": 0.1}) + self.assertEqual((b.sockets, len(b.counts)), ([], 6)) + self.assertEqual([round(float(b.V[:, k].max() - b.V[:, k].min()), 12) for k in range(3)], [0.02, 2.0, 0.15]) + with self.assertRaisesRegex(core.KitError, "part 'slab' has no param 'count'"): + core.build(self.kit["parts"]["slab"], {"count": 2}) + + def test_a_floor_takes_a_part_of_the_mechanical_kit(self): + """cross-kit-types: a mechanical vent's back on a cutter's floor, and what does not fit.""" + mechanical = core.load_kit("mechanical") + names = ("cutters", "mechanical") + recess = core.build(self.kit["parts"]["box"], {"width": 0.3, "height": 0.25}) + vent = core.build(mechanical["parts"]["vent"], {"width": 0.2, "height": 0.15}) + floor, back = core.joint(self.kit["parts"]["box"], recess, "floor", mechanical["parts"]["vent"], vent, "back") + self.assertIsNone(core.mate_refusal(self.kit["socketTypes"], floor, back, mechanical["socketTypes"], names)) + seated = core.mate(floor, back) @ back["matrix"] + self.assertLess(float(np.abs(seated[:3, 3] - [0.0, 0.0, -0.02]).max()), 1e-12) + self.assertLess(float(np.abs(seated[:3, 2] + [0.0, 0.0, 1.0]).max()), 1e-12) # the vent's back faces the floor: the vent breathes out of the recess + big = core.build(mechanical["parts"]["vent"], {"width": 0.8, "height": 0.6}) + self.assertIn("it is larger", core.mate_refusal(self.kit["socketTypes"], floor, big.sockets[0], mechanical["socketTypes"], names)) + nozzle = core.build(mechanical["parts"]["nozzle"]) + self.assertIn("are of different types", core.mate_refusal(self.kit["socketTypes"], floor, nozzle.sockets[0], mechanical["socketTypes"], names)) + + +@unittest.skipIf(np is None, "numpy is not installed") +class SurfaceFrameTests(unittest.TestCase): + """surface-frame: the frame brokkr_kitbash.cut gives a cutter. Bounds: a shipped reading is float rounding (worst + 4.4e-16 over the draws) and the least mutant's is 0.31 (S4, the roll dropped, at roll 18); 1e-9 separates them by + 2e6 and 3e8 (lodur:ruling:deterministic-bound-margin, geometric mean 1.2e-8).""" + EXACT = 1.2e-8 + + def test_z_is_the_normal_y_is_up_s_projection_and_the_frame_is_right_handed(self): + rng = random.Random("surface-frame") + for _ in range(64): + point, normal, up = ([rng.uniform(-3, 3) for _ in range(3)] for _ in range(3)) + frame = core.surface_frame(point, normal, up) + turn, n = frame[:3, :3], np.array(normal) / np.linalg.norm(normal) + self.assertLess(np.abs(turn.T @ turn - np.eye(3)).max(), self.EXACT) + self.assertLess(abs(np.linalg.det(turn) - 1.0), self.EXACT) + self.assertLess(np.abs(frame[:3, 2] - n).max(), self.EXACT) + self.assertLess(np.abs(frame[:3, 3] - point).max(), self.EXACT) + self.assertGreater(float(frame[:3, 1] @ up), 0.0) + self.assertLess(abs(float(np.cross(n, up) @ frame[:3, 1])), self.EXACT * 10) # y lies in the plane of up and the normal + self.assertEqual(frame[3].tolist(), [0.0, 0.0, 0.0, 1.0]) + self.assertLess(np.abs(core.surface_frame((1, 2, 3), (0, 0, 5), (0, 2, 9)) - [[1, 0, 0, 1], [0, 1, 0, 2], [0, 0, 1, 3], [0, 0, 0, 1]]).max(), self.EXACT) + + def test_roll_turns_the_frame_about_the_normal_right_handed(self): + """Mutant S4 (surface_frame without the roll).""" + rng = random.Random("surface-roll") + for roll in (18.0, 90.0, -37.0, 180.0, 360.0): + point, normal, up = ([rng.uniform(-3, 3) for _ in range(3)] for _ in range(3)) + flat, turned = core.surface_frame(point, normal, up), core.surface_frame(point, normal, up, roll) + read = math.degrees(math.atan2(np.cross(flat[:3, 1], turned[:3, 1]) @ flat[:3, 2], flat[:3, 1] @ turned[:3, 1])) + self.assertLess(abs((read - roll + 180.0) % 360.0 - 180.0), 1e-6) + self.assertLess(np.abs(turned[:, 2:] - flat[:, 2:]).max(), self.EXACT) + quarter = core.surface_frame((0, 0, 0), (0, 0, 1), (0, 1, 0), 90.0) + self.assertLess(np.abs(quarter[:3, 1] - [-1.0, 0.0, 0.0]).max(), self.EXACT) # as mate's roll: y turns toward -x + + def test_a_zero_normal_and_an_up_along_the_normal_are_refused(self): + with self.assertRaisesRegex(core.KitError, r"normal \(0, 0, 0\) has no direction"): + core.surface_frame((0, 0, 0), (0, 0, 0), (0, 0, 1)) + for up in ((0, 0, 1), (0, 0, -4), (0, 0, 0), (1e-7, 0, 1)): + with self.assertRaisesRegex(core.KitError, r"up \[.*\] runs along the surface normal \[0\.0, 0\.0, 1\.0\]"): + core.surface_frame((0, 0, 0), (0, 0, 2), up) + core.surface_frame((0, 0, 0), (0, 0, 2), (1e-5, 0, 1)) + + @unittest.skipIf(np is None, "numpy is not installed") class MateTests(unittest.TestCase): """core.mate, residual, mate_refusal and joint. The four bounds sit at the geometric mean of the shipped worst @@ -792,7 +936,7 @@ class MateTests(unittest.TestCase): ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", - "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.apply"] + "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.apply"] class HostFileTests(unittest.TestCase): @@ -843,6 +987,14 @@ class HostFileTests(unittest.TestCase): {k: v for k, v in close.items() if k != "other_socket"}): with self.assertRaises(at.IntentInvalid, msg=str(bad)): at.validate(bad, host) + cut = {**envelope, "action": "brokkr_kitbash.cut", "object_name": "Cage", "cutter_name": "Bay", "part": "box", + "origin_x": 3, "origin_y": 0, "origin_z": 0.5, "direction_x": -1, "direction_y": 0, "direction_z": 0} + admitted = at.validate(cut, host) + self.assertEqual([admitted[k] for k in ("up_x", "up_y", "up_z", "roll", "params")], [0, 0, 1, 0, ""]) + for bad in ({**cut, "part": "sphere"}, {**cut, "roll": 361}, {**cut, "origin_x": 1e4}, {k: v for k, v in cut.items() if k != "direction_z"}, + {**cut, "up_z": -1001}, {**cut, "cutter_name": ""}, {**cut, "operation": "UNION"}, {**cut, "params": "a=1;" * 1000 + "b"}): + with self.assertRaises(at.IntentInvalid, msg=str(bad)): + at.validate(bad, host) for row in self.document["actions"][4:]: self.assertTrue(all(field["type"] in ("string", "number") for field in row["fields"]), row["name"]) @@ -863,7 +1015,7 @@ class OwnershipTests(unittest.TestCase): return {p.name: p.read_text(encoding="utf-8") for p in sorted((SURFACE / "brokkr_kitbash").rglob("*")) if p.suffix in (".py", ".json")} def test_no_pattern_matches(self): - self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "mechanical.v0.json"]) + self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "mechanical.v0.json"]) for pattern in self.PACKAGE: for name, text in self.sources().items(): self.assertIsNone(re.search(pattern, text), f"{pattern} in {name}") @@ -873,14 +1025,19 @@ class OwnershipTests(unittest.TestCase): for path in schemas: self.assertIsNone(re.search(self.SCHEMAS, path.read_text(encoding="utf-8", errors="replace")), path.name) - def test_only_boolean_and_apply_evaluate_a_modifier_stack(self): - """An Exact Boolean costs about a second a part: report, attach, detach and set_params read stored state only.""" + def test_only_cut_boolean_and_apply_evaluate_a_modifier_stack(self): + """An Exact Boolean costs from tenths of a second to seconds: report, attach, detach and set_params read stored + state only, and cut evaluates its target with the Booleans off.""" source = self.sources()["__init__.py"] self.assertEqual(source.count("evaluated_get("), 1) self.assertIn("evaluated_get(", source.split("def evaluated_of(")[1].split("\n\n\n")[0]) callers = [body.split("(")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:] if "evaluated_of(" in body] - self.assertEqual(callers, ["boolean", "apply"]) - self.assertEqual(source.count("evaluated_of("), 3) + self.assertEqual(callers, ["boolean", "cut", "apply"]) + self.assertEqual(source.count("evaluated_of("), 4) + cut = source.split("class BROKKR_KITBASH_OT_cut")[1].split("class BROKKR_KITBASH_OT_")[0] + self.assertLess(cut.index("modifier.show_viewport = False"), cut.index("evaluated_of(")) + self.assertLess(cut.index("evaluated_of("), cut.index("modifier.show_viewport = True")) + self.assertNotIn("view_layer.update", cut) # an update after the cutter joins would evaluate the Boolean self.assertEqual(source.count("to_mesh("), 1) def test_only_attach_writes_the_roll(self): From 889f54954840e60558a7dfa54dae1a8f0b3d6814 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 02:53:42 +0100 Subject: [PATCH 085/223] docs/kitbash.md: what a cut costs on a pod with 15 cutters Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 26829ce..e127385 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -308,7 +308,11 @@ socket holds one part. `cut` reports `{object, cutter, booleans}`, the cutter as `report` would give it, with its `floor` in the world. It does not evaluate the Boolean (its own work is a few milliseconds), but Blender evaluates the changed target -after the action as after any other: on the shell above each cut cost 1.4 to 1.9 s, one cutter to eight. +after the action as after any other: on the shell above each cut cost 1.4 to 1.9 s, one cutter to eight. On a pod +with a Bevel under the Boolean and 15 cutters (two of them slabs through the whole shell) one evaluation took +5.4 s, and the 15 cuts took 113 s in a script that also hid each cutter before the next cut, which made Blender +evaluate the pod twice an action; the same cuts as one joined cutter, evaluated once, took 4.7 s. Cutting a shell +through actions costs an evaluation a cut. ## Expressions From 513b89fd35e56c113e76b7f1c2c303169dfff052 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 03:16:14 +0100 Subject: [PATCH 086/223] brokkr_kitbash.cut_many, a cutter axis, three floors on a slot A cut costs one Boolean evaluation of its target, because Blender evaluates a changed target after every action; cut_many places many cutters in one action, all or none, for one evaluation (Heron's pod: 4.9 s for 13 cutters against 113 s for 15 cut actions). cut and cut_many place through one function, place_cutters. axis states a cutter's z in place of the surface normal, so a panel break does not lean with a sloping roof. A slot carries floor_l and floor_r beside floor. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 142 +++++++++++++----- .../brokkr_kitbash/brokkr_actions.json | 49 +++++- .../brokkr_kitbash/kits/cutters.v0.json | 6 +- surfaces/blender/docs/kitbash.md | 34 +++-- surfaces/blender/tests/live/kitbash.py | 2 +- .../blender/tests/live/kitbash.result.json | 1 + .../blender/tests/live/kitbash_assembly.py | 2 +- surfaces/blender/tests/live/kitbash_shell.py | 74 ++++++++- .../tests/live/kitbash_shell.result.json | 92 +++++++++++- surfaces/blender/tests/test_kitbash.py | 40 +++-- 10 files changed, 375 insertions(+), 67 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 430fde2..a910f03 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -29,7 +29,8 @@ collection's name is a label, and it is linked to no scene. cut cuts a mesh where a ray meets it. The cut is a placed part of the cutters kit, parented to the target under an identity parent inverse: its matrix_basis is the recess frame and its params the recess size, so moving or resizing the cutter object moves the cut and its floor socket together, and nothing else stores either. Machinery attaches -to the floor socket with the ordinary attach. +to a floor socket with the ordinary attach. Blender evaluates a changed target after every action, so each cut costs +one Boolean evaluation; cut_many places many cutters for one. Connections are a tree. A loop (a brace from one branch to another) is closed by a closure: three ID properties on the closing part, kit_close_socket, kit_close_to (a pointer to the other part) and kit_close_to_socket. close @@ -395,6 +396,64 @@ def bounded(report: dict, advice: str) -> dict: return report +def place_cutters(context, target, specs, report=None) -> list: + """Place a cutters part for each spec ({name, part, origin, direction} and optionally params, up, roll, axis; the + vectors in the target's own frame) and add them to the target's difference Boolean; [(cutter, part, built)]. + Every refusal comes before any write. The rays are cast in one evaluation of the target with its Kit Booleans + off, the surface as designed and not as already cut: a second cut on the ray of a through bay lands where the + first did, and no Boolean is evaluated here. Blender evaluates the changed target once after the action, however + many cutters it placed. `report`, given the booleans rows to be, may refuse a report too long for a receipt.""" + rigid(target) + kit, made, names = core.load_kit(CUTTERS), [], set() + for spec in specs: + name = spec["name"] + if name in bpy.data.objects or name in names: + raise Refused(f"An object named {name!r} exists{' in this call' if name in names else ''}; nothing changed.") + names.add(name) + part = core.part(kit, spec["part"]) + built = core.build(part, core.parse_params(spec.get("params", ""))) + if Vector(spec["direction"]).length == 0.0: + raise Refused(f"{name!r}: the ray's direction is zero; nothing changed.") + made.append((part, built)) + cuts = [m for m in (target.modifiers.get("Kit " + operation.title()) for operation in OPERATIONS) if m is not None and m.show_viewport] + try: + for modifier in cuts: + modifier.show_viewport = False + depsgraph, _ = evaluated_of(context, target) + tree = BVHTree.FromObject(target, depsgraph) + finally: + for modifier in cuts: + modifier.show_viewport = True + frames = [] + for spec in specs: + origin, direction, axis = Vector(spec["origin"]), Vector(spec["direction"]), Vector(spec.get("axis", (0.0, 0.0, 0.0))) + hit, normal, _, _ = tree.ray_cast(origin, direction.normalized()) + if hit is None: + raise Refused(f"The ray from {tuple(round(v, 6) for v in origin)} along {tuple(round(v, 6) for v in direction)} misses {target.name!r}; nothing changed.") + if normal.dot(direction) > 0: + normal = -normal + if axis.length > 0.0 and axis.dot(normal) <= 0.0: + raise Refused(f"{spec['name']!r}: the axis {tuple(round(v, 6) for v in axis)} points into the surface (its normal there is " + f"{tuple(round(v, 6) for v in normal)}); nothing changed.") + frames.append(core.surface_frame(hit, axis if axis.length > 0.0 else normal, spec.get("up", (0.0, 0.0, 1.0)), spec.get("roll", 0.0))) + if report is not None: + report(booleans(target) + [{"cutter": spec["name"], "operation": "DIFFERENCE"} for spec in specs]) + placed = [] + for spec, (part, built), frame in zip(specs, made, frames): + mesh = bpy.data.meshes.new(spec["name"]) + write_mesh(mesh, built) + cutter = bpy.data.objects.new(spec["name"], mesh) + context.scene.collection.objects.link(cutter) + sync_bevel(cutter, built.bevel) + cutter[KIT], cutter[PART], cutter[PARAMS] = part["kit"], part["name"], json.dumps(built.params) + cutter.parent = target + cutter.matrix_world = target.matrix_world @ Matrix(frame.tolist()) # read by the report; no depsgraph update, which would evaluate the Boolean + seat(cutter, frame) + operation_collection(target, "DIFFERENCE", True).objects.link(cutter) + placed.append((cutter, part, built)) + return placed + + class BROKKR_KITBASH_OT_place_part(PolishOperator): """Place a kit part at the origin as a new mesh object: its geometry from the kit and params, a Bevel modifier when the part has a bevel, and the kit, part and params stored on the object""" @@ -593,8 +652,8 @@ class BROKKR_KITBASH_OT_boolean(PolishOperator): class BROKKR_KITBASH_OT_cut(PolishOperator): """Cut a mesh object, a kit part or any other, where a ray meets it: places a part of the cutters kit on the - surface there (z the surface normal, y the projection of up, turned by roll), parented to the target, and adds it - to the target's difference Boolean; the cutter's floor socket is where machinery attaches""" + surface there (z the surface normal or a stated axis, y the projection of up, turned by roll), parented to the + target, and adds it to the target's difference Boolean; the cutter's floor socket is where machinery attaches""" bl_idname = "brokkr_kitbash.cut" bl_label = "Cut At Ray" object_name: bpy.props.StringProperty(name="Object", description="The mesh that is cut: a kit part or any mesh") @@ -612,44 +671,55 @@ class BROKKR_KITBASH_OT_cut(PolishOperator): up_z: bpy.props.FloatProperty(name="Up Z", default=1.0) roll: bpy.props.FloatProperty(name="Roll", default=0.0, min=-360.0, max=360.0, description="Degrees about the surface normal, right-handed") + axis_x: bpy.props.FloatProperty(name="Axis X", default=0.0, description="The cutter's z, in the target's own frame; all zero: the surface normal") + axis_y: bpy.props.FloatProperty(name="Axis Y", default=0.0) + axis_z: bpy.props.FloatProperty(name="Axis Z", default=0.0) + @kit_work def work(self, context): target = mesh_object(self.object_name) - rigid(target) - if self.cutter_name in bpy.data.objects: - raise Refused(f"An object named {self.cutter_name!r} exists; nothing changed.") - part = core.part(core.load_kit(CUTTERS), self.part) - built = core.build(part, core.parse_params(self.params)) - origin, direction = Vector((self.origin_x, self.origin_y, self.origin_z)), Vector((self.direction_x, self.direction_y, self.direction_z)) - if direction.length == 0.0: - raise Refused("The ray's direction is zero; nothing changed.") - cuts = [m for m in (target.modifiers.get("Kit " + operation.title()) for operation in OPERATIONS) if m is not None and m.show_viewport] - try: # the surface as designed, not as already cut: a second cut on the ray of a through bay lands where the first did - for modifier in cuts: - modifier.show_viewport = False - depsgraph, _ = evaluated_of(context, target) - hit, normal, _, _ = BVHTree.FromObject(target, depsgraph).ray_cast(origin, direction.normalized()) - finally: - for modifier in cuts: - modifier.show_viewport = True - if hit is None: - raise Refused(f"The ray from {tuple(round(v, 6) for v in origin)} along {tuple(round(v, 6) for v in direction)} misses {target.name!r}; nothing changed.") - if normal.dot(direction) > 0: - normal = -normal - frame = core.surface_frame(hit, normal, (self.up_x, self.up_y, self.up_z), self.roll) - mesh = bpy.data.meshes.new(self.cutter_name) - write_mesh(mesh, built) - cutter = bpy.data.objects.new(self.cutter_name, mesh) - context.scene.collection.objects.link(cutter) - sync_bevel(cutter, built.bevel) - cutter[KIT], cutter[PART], cutter[PARAMS] = part["kit"], part["name"], json.dumps(built.params) - cutter.parent = target - cutter.matrix_world = target.matrix_world @ Matrix(frame.tolist()) # read by the report below; no depsgraph update, which would evaluate the Boolean - seat(cutter, frame) - operation_collection(target, "DIFFERENCE", True).objects.link(cutter) + spec = {"name": self.cutter_name, "part": self.part, "params": self.params, "roll": self.roll, + "origin": (self.origin_x, self.origin_y, self.origin_z), "direction": (self.direction_x, self.direction_y, self.direction_z), + "up": (self.up_x, self.up_y, self.up_z), "axis": (self.axis_x, self.axis_y, self.axis_z)} + (cutter, part, built), = place_cutters(context, target, [spec]) return {"object": target.name, "cutter": part_report(cutter, part, built), "booleans": booleans(target)} +CUT_KEYS = {"name": str, "part": str, "params": str, "origin": list, "direction": list, "up": list, "axis": list, "roll": (int, float)} +CUTS_LIMIT = 64 # cutters in one cut_many + + +class BROKKR_KITBASH_OT_cut_many(PolishOperator): + """Cut a mesh object at several rays in one action: every cutter is checked and every ray cast before anything is + written, so the call places all of them or none, and Blender evaluates the target's Boolean once for the lot""" + bl_idname = "brokkr_kitbash.cut_many" + bl_label = "Cut At Rays" + object_name: bpy.props.StringProperty(name="Object", description="The mesh that is cut: a kit part or any mesh") + cuts: bpy.props.StringProperty(name="Cuts", description="A JSON array of cutters: name, part, origin and direction, and optionally params, up, roll and axis, as cut's fields") + + @kit_work + def work(self, context): + target = mesh_object(self.object_name) + try: + specs = json.loads(self.cuts) + except ValueError as error: + raise Refused(f"cuts is not JSON ({error}); nothing changed.") from None + if not isinstance(specs, list) or not 1 <= len(specs) <= CUTS_LIMIT: + raise Refused(f"cuts must be a JSON array of 1 to {CUTS_LIMIT} cutters; nothing changed.") + for index, spec in enumerate(specs): + where = f"cuts[{index}]" + if not isinstance(spec, dict) or not {"name", "part", "origin", "direction"} <= set(spec) <= set(CUT_KEYS): + raise Refused(f"{where} must be an object with name, part, origin and direction, and optionally params, up, roll and axis; nothing changed.") + for key, value in spec.items(): + vector = CUT_KEYS[key] is list + if not isinstance(value, CUT_KEYS[key]) or isinstance(value, bool) or (vector and (len(value) != 3 or not all(core.finite(v) for v in value))) \ + or (key == "roll" and not (core.finite(value) and -360.0 <= value <= 360.0)) or (key == "name" and not 1 <= len(value) <= 63): + raise Refused(f"{where}.{key} must be {'three numbers' if vector else 'a number from -360 to 360' if key == 'roll' else 'a string' + (' of 1 to 63 characters' if key == 'name' else '')}; nothing changed.") + placed = place_cutters(context, target, specs, report=lambda rows: bounded({"object": target.name, "cutters": [spec["name"] for spec in specs], "booleans": rows}, + "cut fewer at once")) + return {"object": target.name, "cutters": [cutter.name for cutter, _, _ in placed], "booleans": booleans(target)} + + class BROKKR_KITBASH_OT_apply(PolishOperator): """Bake a kit part: its mesh becomes its evaluated mesh (Booleans and Bevel applied), every modifier goes with the collections its Booleans held, its material slots stay, and it is marked baked; its sockets and connections @@ -718,7 +788,7 @@ class BROKKR_KITBASH_OT_report(PolishOperator): classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report, - BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, + BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index cf8de59..5fe8651 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -254,7 +254,7 @@ }, { "name": "brokkr_kitbash.cut", - "doc": "Cut a mesh, a kit part or any other, where a ray meets it: places a part of the cutters kit (box, cyl, slot or slab; brokkr_kitbash.describe with kit cutters) on the surface there, parented to the target, and adds it to the target's difference Boolean. The ray is cast at the target without its cuts. The cutter's floor socket (type mount, at the bottom of the recess, facing out) takes a part by brokkr_kitbash.attach; move the cut with setObjectTransform on the cutter, resize it with set_params, hide the cutter with setObjectVisibility. Does not evaluate the Boolean itself (boolean does, and reports it). Reports the cutter with its sockets, and booleans.", + "doc": "Cut a mesh, a kit part or any other, where a ray meets it: places a part of the cutters kit (box, cyl, slot or slab; brokkr_kitbash.describe with kit cutters) on the surface there, parented to the target, and adds it to the target's difference Boolean. The ray is cast at the target without its cuts. The cutter's floor socket (type mount, at the bottom of the recess, facing out) takes a part by brokkr_kitbash.attach; move the cut with setObjectTransform on the cutter, resize it with set_params, hide the cutter with setObjectVisibility. Blender evaluates the changed target after the action: one Boolean evaluation a cut; brokkr_kitbash.cut_many places several cutters for one. Reports the cutter with its sockets, and booleans.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -367,6 +367,53 @@ "maximum": 360, "default": 0, "doc": "degrees about the surface normal, right-handed" + }, + { + "name": "axis_x", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 0, + "doc": "the cutter's z, in the target's own frame, in place of the surface normal (a panel break that must not lean with a sloping surface); all zero: the surface normal; refused when it points into the surface" + }, + { + "name": "axis_y", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 0 + }, + { + "name": "axis_z", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 0 + } + ] + }, + { + "name": "brokkr_kitbash.cut_many", + "doc": "Cut a mesh at several rays in one action, as brokkr_kitbash.cut does at one: all the cutters are placed or none, every ray is cast at the target without its cuts, and Blender evaluates the target's Boolean once after the action instead of once a cut. Reports object, the cutters' names and booleans; brokkr_kitbash.report gives a cutter's sockets.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the mesh that is cut: a kit part or any mesh, not scaled" + }, + { + "name": "cuts", + "type": "string", + "required": true, + "minLength": 2, + "maxLength": 16000, + "doc": "a JSON array of 1 to 64 cutters, each {\"name\", \"part\", \"origin\": [x, y, z], \"direction\": [x, y, z]} and optionally \"params\" (name=value; ...), \"up\": [x, y, z] (default 0, 0, 1), \"roll\" (degrees) and \"axis\": [x, y, z], with the meanings of brokkr_kitbash.cut's fields" } ] }, diff --git a/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json b/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json index 0677a9e..e15261c 100644 --- a/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json @@ -43,7 +43,7 @@ }, { "name": "slot", - "doc": "Round-ended slot, long along x: a visor, a gill, a vent. width must exceed height. Its floor socket faces out of the recess at the frame's centre (between the two middle copies when count is even).", + "doc": "Round-ended slot, long along x: a visor, a gill, a vent. width must exceed height. Three floor sockets face out of the recess: floor at the frame's centre (between the two middle copies when count is even), floor_l and floor_r a third of the width to each side; each holds one part.", "params": [ {"name": "width", "type": "number", "min": 0.01, "max": 8, "default": 0.3, "doc": "end to end (x); more than height"}, {"name": "height", "type": "number", "min": 0.005, "max": 4, "default": 0.05, "doc": "across the slot (y); the ends are half-rounds of this diameter"}, @@ -58,7 +58,9 @@ {"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "tube", "r0": "height/2", "r1": "height/2", "length": "depth+lift", "segments": 32, "at": ["(width-height)/2", "-(count-1)*pitch/2", "-depth"]}} ], "sockets": [ - {"name": "floor", "type": "mount", "size": "height", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"} + {"name": "floor", "type": "mount", "size": "height", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"}, + {"name": "floor_l", "type": "mount", "size": "height", "at": ["-width/3", 0, "-depth"], "z": "+z", "y": "+y"}, + {"name": "floor_r", "type": "mount", "size": "height", "at": ["width/3", 0, "-depth"], "z": "+z", "y": "+y"} ] }, { diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index e127385..5c512d2 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -278,7 +278,7 @@ kit part, where a ray meets it, and what it places is itself a kit part, of the | --- | --- | --- | | `box` | `width` (x), `height` (y), `count`, `pitch` | `floor` (mount, size the smaller side) | | `cyl` | `r`, `count`, `pitch` | `floor` (mount, size `2*r`) | -| `slot` | `width` (x, end to end), `height` (across; less than `width`), `count`, `pitch` | `floor` (mount, size `height`) | +| `slot` | `width` (x, end to end), `height` (across; less than `width`), `count`, `pitch` | `floor`, `floor_l`, `floor_r` (mount, size `height`) | | `slab` | `gap` (x), `length` (y) | none | A cutter's frame has its origin where the ray met the surface, `z` along the surface normal (turned to face @@ -289,6 +289,10 @@ cut cleanly across the whole cutter (raise `lift` for a wide cutter on a tight c thickness opens a hole. `count` copies stand `pitch` apart along `y`, centred on the frame: a row of gills (roll 90 turns the row along `x`). A `slab` is a panel break: a thin slab standing on the normal, long along `y`. +`axis` (default all zero: the surface normal) states the cutter's `z` instead. A slab on a sloping roof leans +with the roof's normal; with an axis it stands where it is told, and the break's plane has the normal +`up` cross `axis`. An axis that points into the surface is refused. + The ray and `up` are given in the target's own frame, and the ray is cast at the target evaluated with its `Kit` Booleans off: a second cut on the ray of a through bay lands on the surface as designed, not on the far wall behind the bay. The target must not be scaled. @@ -299,20 +303,25 @@ recess size, and nothing else stores either. `setObjectTransform` on the cutter resizes it, and deleting the cutter removes the cut. `cut` does not hide the cutter: `setObjectVisibility` does, and a hidden cutter still cuts. -`box`, `cyl` and `slot` carry one socket, `floor`: on the bottom of the recess at `z = -depth`, at the frame's -centre, facing out of the recess. Machinery attaches there with the ordinary `attach` (a vent's `back`, a +`box`, `cyl` and `slot` carry a socket, `floor`: on the bottom of the recess at `z = -depth`, at the frame's +centre, facing out of the recess. A `slot` carries two more on the same floor, `floor_l` and `floor_r`, a third +of its width to each side: a visor with three eyes. Machinery attaches there with the ordinary `attach` (a vent's `back`, a sensor's `mount`), is a child of the cutter, and so follows the cut when the cutter moves and is seated again when `set_params` changes its `depth`. With an even `count` and a `pitch` wider than the copies, the centre lies between the two middle copies: use an odd count, or a cutter of its own, for a recess that carries a part. A socket holds one part. -`cut` reports `{object, cutter, booleans}`, the cutter as `report` would give it, with its `floor` in the world. -It does not evaluate the Boolean (its own work is a few milliseconds), but Blender evaluates the changed target -after the action as after any other: on the shell above each cut cost 1.4 to 1.9 s, one cutter to eight. On a pod -with a Bevel under the Boolean and 15 cutters (two of them slabs through the whole shell) one evaluation took -5.4 s, and the 15 cuts took 113 s in a script that also hid each cutter before the next cut, which made Blender -evaluate the pod twice an action; the same cuts as one joined cutter, evaluated once, took 4.7 s. Cutting a shell -through actions costs an evaluation a cut. +`cut` reports `{object, cutter, booleans}`, the cutter as `report` would give it, with its floors in the world. +Its own work is a few milliseconds and it evaluates no Boolean, but Blender evaluates a changed target after +every action, so each `cut` costs one Boolean evaluation of the target: on the shell above 1.4 to 1.9 s, one +cutter to eight. `cut_many` takes a JSON array of cutters (`name`, `part`, `origin`, `direction`, and optionally +`params`, `up`, `roll`, `axis`), checks them all and casts every ray before it writes anything, places all of +them or none, and costs one evaluation for the lot. On a pod with a Bevel under the Boolean (6500 faces once +cut; one evaluation 5.2 s), 13 cutters placed by one `cut_many` took 4.9 s, and 15 placed by 15 `cut` actions +took 113 s; the same cuts as one joined cutter, evaluated once and baked, took 4.6 s (Blender 5.3 on Starfire). +Any later action that changes the target or a cutter (hiding the cutters, attaching a part to a floor) costs an +evaluation again while the target is visible. `cut_many` reports `{object, cutters, booleans}` with the cutters +by name. ## Expressions @@ -340,7 +349,8 @@ vertices overflow. | `brokkr_kitbash.detach` | `object_name` | Clears the part's connection and the closure it states; it stays where it stands. Refuses a part that has neither. | | `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. | | `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added) and `evaluated`. | -| `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the surface normal and a scaled target. Reports `object`, the `cutter` with its `floor` socket, and `booleans`. | +| `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans`. | +| `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans`. | | `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers and a mesh another object shares. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored @@ -442,5 +452,5 @@ part of `mechanical` also joins the part and socket list in `test_the_kit_is_the frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may mate, within a kit and across two. The operators are exercised in a real Blender by `tests/live/kitbash.py` (placing and re-parameterising) and `tests/live/kitbash_assembly.py` (attach, detach, `set_params` on assemblies, a braced leg closed by `close`, boolean and apply) and `tests/live/kitbash_shell.py` -(`cut` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no +(`cut` and `cut_many` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no collection). diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 00e50c1..b1807b1 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -75,7 +75,7 @@ def extent(obj, axis=2): check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == [f"brokkr_kitbash.{name}" for name in ( - "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "cut", "apply")], [R["hostErrors"], R["hostRows"]]) + "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "cut", "cut_many", "apply")], [R["hostErrors"], R["hostRows"]]) # --- describe --------------------------------------------------------------------------------------------------------- kit = core.load_kit("mechanical") diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index f5f3cb1..88be33e 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -415,6 +415,7 @@ "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", + "brokkr_kitbash.cut_many", "brokkr_kitbash.apply" ], "placed": { diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 188d821..86a2197 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -177,7 +177,7 @@ def evaluated(obj): rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == [f"brokkr_kitbash.{n}" for n in ( - "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "cut", "apply")], [R["hostErrors"], rows]) + "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "cut", "cut_many", "apply")], [R["hostErrors"], rows]) # --- attach ------------------------------------------------------------------------------------------------------------- tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088 diff --git a/surfaces/blender/tests/live/kitbash_shell.py b/surfaces/blender/tests/live/kitbash_shell.py index 6dc28f3..f8dbb11 100644 --- a/surfaces/blender/tests/live/kitbash_shell.py +++ b/surfaces/blender/tests/live/kitbash_shell.py @@ -1,7 +1,7 @@ """Live proof, in a background Blender, of brokkr_kitbash shell cuts through run_intent: cut on a mesh that is not a kit part (a subdivided, solidified cage), the one Boolean modifier per operation and its collection, a cast at the surface without its cuts, machinery on a cutter's floor socket and what moves when the cutter moves or is resized, boolean on -any mesh, the refusals, an object in no collection, and the order of a set_params report's closures. Not part of the +any mesh, the refusals, cut_many, a cutter's axis, a slot's three floors, an object in no collection, and the order of a set_params report's closures. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_shell.py -- @@ -207,7 +207,7 @@ for name, part, origin, direction, params, more in CUTS: check(f"cut reports {name} as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", report and report["object"] == "Cage" and report["cutter"]["object"] == name and report["cutter"]["kit"] == "cutters" and "evaluated" not in report and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in [c[0] for c in CUTS][:len(frames)]] - and [s["name"] for s in report["cutter"]["sockets"]] == ([] if part == "slab" else ["floor"]) + and [s["name"] for s in report["cutter"]["sockets"]] == {"slab": [], "slot": ["floor", "floor_l", "floor_r"]}.get(part, ["floor"]) and (part == "slab" or np.abs(np.array(report["cutter"]["sockets"][0]["matrix"]) - wanted @ core.build(kits["cutters"]["parts"][part], report["cutter"]["params"]).sockets[0]["matrix"]).max() < 1e-4), report) shown, _ = evaluated(cage) @@ -275,6 +275,72 @@ check("set_params depth=0.04 on the cutter deepens the cut and seats the vent on [receipt["message"], sunk.tolist(), after, deeper]) R["cage"]["deeper"] = deeper +# --- cut_many: several cutters for one evaluation, all or none; an axis; a slot's three floors ----------------------------------- +def uncut_cast(origin, direction): + shown = [m for m in cage.modifiers if m.name.startswith("Kit ")] + for m in shown: + m.show_viewport = False + try: + return cast(cage, origin, direction) + finally: + for m in shown: + m.show_viewport = True + + +MANY = [{"name": "Visor", "part": "slot", "params": "width=0.6; height=0.14; depth=0.02; lift=0.2", "origin": [0.6, 3.0, 0.5], "direction": [0.0, -1.0, 0.0]}, + {"name": "Seam", "part": "slab", "params": "length=0.4; depth=0.1", "origin": [-0.5, -3.0, -0.7], "direction": [0.0, 1.0, 0.0], "up": [1.0, 0.0, 0.0], "axis": [0.0, -1.0, 0.0]}, + {"name": "Port", "part": "cyl", "params": "r=0.05", "origin": [-0.6, 3.0, -0.5], "direction": [0.0, -2.0, 0.0], "up": [1.0, 0.0, 0.0], "roll": 45.0}] +wanted = {} +for spec in MANY: + hit, normal = uncut_cast(spec["origin"], spec["direction"]) + wanted[spec["name"]] = core.surface_frame(hit, spec.get("axis", normal), spec.get("up", (0.0, 0.0, 1.0)), spec.get("roll", 0.0)) + if "axis" in spec: + lean = float(np.degrees(np.arccos(np.clip(normal @ np.array(spec["axis"]), -1.0, 1.0)))) +refused("cut_many whose second ray misses places none", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "origin": [0.0, -3.0, 5.0]}])}, + "The ray from (0.0, -3.0, 5.0) along (0.0, 1.0, 0.0) misses 'Cage'") +refused("cut_many with a name twice", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Visor"}])}, "An object named 'Visor' exists in this call") +refused("cut_many with a name an object has", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Bay"}])}, "An object named 'Bay' exists;") +refused("cut_many whose last cutter has a bad param", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps(MANY[:2] + [{**MANY[2], "params": "r=9"}])}, "param 'r' = 9.0 is outside") +refused("cut_many of text that is not JSON", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[{"}, "cuts is not JSON") +refused("cut_many of no cutters", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[]"}, "cuts must be a JSON array of 1 to 64 cutters") +refused("cut_many of a cutter with no direction", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{k: v for k, v in MANY[0].items() if k != "direction"}])}, + "cuts[0] must be an object with name, part, origin and direction") +refused("cut_many of a cutter with a key cut does not have", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "operation": "UNION"}])}, "cuts[0] must be an object") +refused("cut_many of an origin of two numbers", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "origin": [0.0, 1.0]}])}, "cuts[0].origin must be three numbers") +refused("cut_many of a roll of 400", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "roll": 400}])}, "cuts[0].roll must be a number from -360 to 360") +refused("an axis that points into the surface", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[1], "axis": [0.0, 1.0, 0.0]}])}, "'Seam': the axis (0.0, 1.0, 0.0) points into the surface") +addon = sys.modules["brokkr_kitbash"] +limit = addon.REPORT_LIMIT +addon.REPORT_LIMIT = 300 +refused("cut_many whose report would not fit a receipt places none", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps(MANY)}, "over the 300 a receipt carries: cut fewer at once") +addon.REPORT_LIMIT = limit +receipt, report = send("brokkr_kitbash.cut_many", object_name="Cage", cuts=json.dumps(MANY)) +placed = [bpy.data.objects.get(spec["name"]) for spec in MANY] +check("cut_many places three cutters in one action, each as cut would: parented under an identity inverse, its basis the surface frame at its own ray on the uncut cage, in the difference collection in order", + receipt["status"] == "accepted" and all(placed) and report == {"object": "Cage", "cutters": ["Visor", "Seam", "Port"], "booleans": report["booleans"]} + and [row["cutter"] for row in report["booleans"]] == ["Bay", "Recess", "Gills", "Break", "Bay2", "Visor", "Seam", "Port"] + and all(c.parent == cage and np.array_equal(np.array(c.matrix_parent_inverse), np.eye(4)) + and reading("framed", np.abs(np.array(c.matrix_basis) - wanted[c.name]).max()) < FRAMED for c in placed) + and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and all(m.show_viewport for m in cage.modifiers) and evaluated(cage)[0]["nonManifoldEdges"] == 0, + [receipt["message"], report]) +seam = bpy.data.objects["Seam"] +check("a slab with an axis stands on the axis, not on the wall's normal, which leans from it there", lean > 5.0 + and reading("framed", np.abs(np.array(seam.matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, [lean, np.array(seam.matrix_basis).tolist()]) +receipt, report = send("brokkr_kitbash.cut", object_name="Cage", cutter_name="Seam2", part="slab", params="length=0.3; depth=0.1", origin_x=0.5, origin_y=-3.0, origin_z=-0.7, + direction_x=0.0, direction_y=1.0, direction_z=0.0, up_x=1.0, up_y=0.0, up_z=0.0, axis_x=0.0, axis_y=-1.0, axis_z=0.0) +check("cut takes the same axis", receipt["status"] == "accepted" and reading("framed", np.abs(np.array(bpy.data.objects["Seam2"].matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, receipt["message"]) +visor = bpy.data.objects["Visor"] +eyes = {} +for socket, x in (("floor", 0.0), ("floor_l", -0.2), ("floor_r", 0.2)): + eye = place(f"Eye_{socket}", "vent", "width=0.2; height=0.15") # back size 0.135; each floor's is 0.14 + receipt, report = send("brokkr_kitbash.attach", object_name=eye.name, socket="back", parent_name="Visor", parent_socket=socket) + there = world @ wanted["Visor"] @ np.array(Matrix.Translation((x, 0.0, -0.02))) + eyes[socket] = receipt["status"] == "accepted" and held(report) and eye.parent == visor \ + and reading("floored", max(np.abs(frame(eye, "back")[:3, 3] - there[:3, 3]).max(), np.abs(frame(eye, "back")[:3, 2] + there[:3, 2]).max())) < FLOORED +check("a slot's three floors each take a part: at the centre and a third of the width to each side, all on the slot's one floor plane", all(eyes.values()) and len(eyes) == 3, eyes) +refused("a second part on a side floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Nozzle' on 'Visor'") +refused("a fourth eye on a floor that is taken", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Big' on 'Visor'") + # --- boolean on any mesh, and the order of the three operations ----------------------------------------------------------------- lump_at = world @ [0.0, 0.0, 1.0, 1.0] send("createObject", objectType="MESH", name="Lump", location=lump_at[:3].tolist(), size=0.2) @@ -282,7 +348,7 @@ receipt, report = send("brokkr_kitbash.boolean", object_name="Cage", cutter="Lum check("boolean on the cage, which is not a kit part, adds a second modifier after the difference and reports the object, what cuts it and the evaluated mesh", receipt["status"] == "accepted" and stack(cage) == ["Subsurf", "Solidify", "Kit Difference", "Kit Union"] and sorted(report) == ["booleans", "evaluated", "object"] and report["object"] == "Cage" and report["evaluated"] == evaluated(cage)[0] - and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in ("Bay", "Recess", "Gills", "Break", "Bay2")] + [{"cutter": "Lump", "operation": "UNION"}] + and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in ("Bay", "Recess", "Gills", "Break", "Bay2", "Visor", "Seam", "Port", "Seam2")] + [{"cutter": "Lump", "operation": "UNION"}] and report["evaluated"]["volume"] > deeper["volume"], [receipt["message"], report]) refused("cut-refusals: a cutter already in the target's union collection", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Lump"}, "'Lump' already cuts 'Cage' (its Kit Union modifier's collection)") @@ -306,7 +372,7 @@ refused("apply on the cage, which is not a kit part", "brokkr_kitbash.apply", {" # --- cut-refusals ----------------------------------------------------------------------------------------------------------- RAY = {"object_name": "Cage", "cutter_name": "New", "part": "box", "origin_x": 3.0, "origin_y": 0.0, "origin_z": 0.1, "direction_x": -1.0, "direction_y": 0.0, "direction_z": 0.0} refused("a ray that misses", "brokkr_kitbash.cut", {**RAY, "origin_z": 5.0}, "The ray from (3.0, 0.0, 5.0) along (-1.0, 0.0, 0.0) misses 'Cage'") -refused("a ray of no direction", "brokkr_kitbash.cut", {**RAY, "direction_x": 0.0}, "The ray's direction is zero") +refused("a ray of no direction", "brokkr_kitbash.cut", {**RAY, "direction_x": 0.0}, "'New': the ray's direction is zero") refused("a cutter name an object has", "brokkr_kitbash.cut", {**RAY, "cutter_name": "Bay"}, "An object named 'Bay' exists") refused("a param the cutter part does not have", "brokkr_kitbash.cut", {**RAY, "params": "radius=0.1"}, "kit 'cutters' part 'box' has no param 'radius'") refused("a slot wider across than along", "brokkr_kitbash.cut", {**RAY, "part": "slot", "params": "width=0.05; height=0.1"}, "every size must be above 0") diff --git a/surfaces/blender/tests/live/kitbash_shell.result.json b/surfaces/blender/tests/live/kitbash_shell.result.json index 90e7a0e..74a159c 100644 --- a/surfaces/blender/tests/live/kitbash_shell.result.json +++ b/surfaces/blender/tests/live/kitbash_shell.result.json @@ -106,6 +106,96 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: cut_many whose second ray misses places none", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many with a name twice", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many with a name an object has", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many whose last cutter has a bad param", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many of text that is not JSON", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many of no cutters", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many of a cutter with no direction", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many of a cutter with a key cut does not have", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many of an origin of two numbers", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many of a roll of 400", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an axis that points into the surface", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many whose report would not fit a receipt places none", + "ok": true, + "detail": null + }, + { + "name": "cut_many places three cutters in one action, each as cut would: parented under an identity inverse, its basis the surface frame at its own ray on the uncut cage, in the difference collection in order", + "ok": true, + "detail": null + }, + { + "name": "a slab with an axis stands on the axis, not on the wall's normal, which leans from it there", + "ok": true, + "detail": null + }, + { + "name": "cut takes the same axis", + "ok": true, + "detail": null + }, + { + "name": "a slot's three floors each take a part: at the centre and a third of the width to each side, all on the slot's one floor plane", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a second part on a side floor", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a fourth eye on a floor that is taken", + "ok": true, + "detail": null + }, { "name": "boolean on the cage, which is not a kit part, adds a second modifier after the difference and reports the object, what cuts it and the evaluated mesh", "ok": true, @@ -239,7 +329,7 @@ ], "hostErrors": [], "readings": { - "floored": 1.8e-07, + "floored": 2.6e-07, "framed": 5.1e-07, "recast": 0.0 }, diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 56e405a..b0c9404 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -569,9 +569,9 @@ class CuttersKitTests(unittest.TestCase): draws.append({p["name"]: rng.randint(p["min"], p["max"]) if p["type"] == "integer" else rng.uniform(p["min"], p["max"]) for p in part["params"]}) return part, draws - def test_the_kit_is_four_cutters_and_three_floors(self): + def test_the_kit_is_four_cutters_and_their_floors(self): self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, - {"box": [("floor", "mount")], "cyl": [("floor", "mount")], "slot": [("floor", "mount")], "slab": []}) + {"box": [("floor", "mount")], "cyl": [("floor", "mount")], "slot": [("floor", "mount"), ("floor_l", "mount"), ("floor_r", "mount")], "slab": []}) self.assertEqual(self.kit["socketTypes"]["mount"], core.load_kit("mechanical")["socketTypes"]["mount"]) self.assertTrue(all(part["bevel"] is None for part in self.kit["parts"].values())) @@ -594,7 +594,8 @@ class CuttersKitTests(unittest.TestCase): self.assertAlmostEqual(float(b.V[:, 2].min()), -depth, places=12) self.assertAlmostEqual(float(b.V[:, 2].max()), lift, places=12) for socket in b.sockets: - self.assertEqual(socket["matrix"][:, 3].tolist(), [0.0, 0.0, -depth, 1.0]) + side = {"floor": 0.0, "floor_l": -1.0, "floor_r": 1.0}[socket["name"]] * b.params.get("width", 0.0) / 3 + self.assertEqual(socket["matrix"][:, 3].tolist(), [side, 0.0, -depth, 1.0]) self.assertEqual(socket["matrix"][:3, :3].tolist(), np.eye(3).tolist()) self.assertGreater(socket["size"], 0.0) self.assertGreater(built, 60) @@ -616,6 +617,17 @@ class CuttersKitTests(unittest.TestCase): seat = socket_seat(b, floor) self.assertTrue(seat < 1e-12 if count % 2 else abs(seat - 0.015) < 1e-12, f"{name} x{count}: {seat}") # even: 0.015 from each middle copy + def test_a_slot_has_three_floors_on_its_bottom(self): + """A visor carries three eyes: floor_l and floor_r lie a third of the width to each side, on the slot's own + bottom, each the size of the slot's height. Mutant B4 (the two side floors swapped).""" + part = self.kit["parts"]["slot"] + for given in ({"width": 0.66, "height": 0.12, "depth": 0.045}, {"width": 0.3, "height": 0.25}, {"width": 0.3, "height": 0.05, "count": 3, "pitch": 0.2}): + b = core.build(part, given) + self.assertEqual([(s["name"], round(float(s["matrix"][0, 3]), 12), s["size"]) for s in b.sockets], + [("floor", 0.0, given["height"]), ("floor_l", round(-given["width"] / 3, 12), given["height"]), ("floor_r", round(given["width"] / 3, 12), given["height"])]) + for socket in b.sockets: + self.assertLess(socket_seat(b, dict(socket, matrix=socket["matrix"] @ core.FLIP)), 1e-12, socket["name"]) + def test_a_slot_is_a_stadium_of_its_width(self): """Mutant S9 (the end tubes at x = +-width/2): the slot is width + height long and the rounds stand off the box.""" b = core.build(self.kit["parts"]["slot"], {"width": 0.3, "height": 0.05, "depth": 0.02, "lift": 0.05}) @@ -936,7 +948,7 @@ class MateTests(unittest.TestCase): ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", - "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.apply"] + "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply"] class HostFileTests(unittest.TestCase): @@ -995,6 +1007,12 @@ class HostFileTests(unittest.TestCase): {**cut, "up_z": -1001}, {**cut, "cutter_name": ""}, {**cut, "operation": "UNION"}, {**cut, "params": "a=1;" * 1000 + "b"}): with self.assertRaises(at.IntentInvalid, msg=str(bad)): at.validate(bad, host) + self.assertEqual([at.validate(cut, host)[k] for k in ("axis_x", "axis_y", "axis_z")], [0, 0, 0]) + many = {**envelope, "action": "brokkr_kitbash.cut_many", "object_name": "Cage", "cuts": '[{"name": "Bay", "part": "box", "origin": [3, 0, 0], "direction": [-1, 0, 0]}]'} + self.assertEqual(at.validate(many, host)["cuts"], many["cuts"]) + for bad in ({**cut, "axis_y": 1001}, {**many, "cuts": ""}, {**many, "cuts": "[" + " " * 16000}, {k: v for k, v in many.items() if k != "cuts"}, {**many, "cutter_name": "Bay"}): + with self.assertRaises(at.IntentInvalid, msg=str(bad)): + at.validate(bad, host) for row in self.document["actions"][4:]: self.assertTrue(all(field["type"] in ("string", "number") for field in row["fields"]), row["name"]) @@ -1032,12 +1050,16 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(source.count("evaluated_get("), 1) self.assertIn("evaluated_get(", source.split("def evaluated_of(")[1].split("\n\n\n")[0]) callers = [body.split("(")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:] if "evaluated_of(" in body] - self.assertEqual(callers, ["boolean", "cut", "apply"]) + self.assertEqual(callers, ["boolean", "apply"]) self.assertEqual(source.count("evaluated_of("), 4) - cut = source.split("class BROKKR_KITBASH_OT_cut")[1].split("class BROKKR_KITBASH_OT_")[0] - self.assertLess(cut.index("modifier.show_viewport = False"), cut.index("evaluated_of(")) - self.assertLess(cut.index("evaluated_of("), cut.index("modifier.show_viewport = True")) - self.assertNotIn("view_layer.update", cut) # an update after the cutter joins would evaluate the Boolean + place = source.split("def place_cutters(")[1].split("\n\n\n")[0] # cut and cut_many place through it: one evaluation, with the Booleans off + self.assertEqual(place.count("evaluated_of("), 1) + self.assertLess(place.index("modifier.show_viewport = False"), place.index("evaluated_of(")) + self.assertLess(place.index("evaluated_of("), place.index("modifier.show_viewport = True")) + self.assertLess(place.index("report(booleans(target)"), place.index("bpy.data.meshes.new(")) # every refusal before any write + for body in (place, *(source.split(f"class BROKKR_KITBASH_OT_{name}(")[1].split("class BROKKR_KITBASH_OT_")[0] for name in ("cut", "cut_many"))): + self.assertNotIn("view_layer.update", body) # an update after a cutter joins would evaluate the Boolean + self.assertEqual(body.count("place_cutters("), 0 if body is place else 1) self.assertEqual(source.count("to_mesh("), 1) def test_only_attach_writes_the_roll(self): From bff51e887fbdf8731370c00679d9ccd7b030bdc6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 02:08:31 +0100 Subject: [PATCH 087/223] brokkr_kitbash: roll, aim and reach pose an attached part in place, the roll solved in closed form write_connection is the one writer of a connection (parent, seat, kit_socket, kit_parent_socket, kit_roll); attach's inline write moves into it. roll states an attached part's roll where it hangs; aim and reach solve it from core.roll_terms (d . p = A cos + B sin + C): aim_roll = atan2(B, A), reach_roll = atan2(B, A) +- acos, the root nearer the current roll. Each reports closures as set_params does and never seats one. PoseTests pin the solves against core.mate; tests/live/kitbash_pose.py exercises the three operators and their refusals through run_intent. Cut kit-roll-aim (aetheria-release:cut_spec:cut-kit-roll-aim.r1). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 112 ++++++- .../brokkr_kitbash/brokkr_actions.json | 134 ++++++++ surfaces/blender/brokkr_kitbash/core.py | 57 ++++ surfaces/blender/docs/kitbash.md | 52 +++- surfaces/blender/tests/live/kitbash.py | 2 +- .../blender/tests/live/kitbash_assembly.py | 2 +- surfaces/blender/tests/live/kitbash_pose.py | 291 ++++++++++++++++++ surfaces/blender/tests/test_kitbash.py | 182 ++++++++++- 8 files changed, 807 insertions(+), 25 deletions(-) create mode 100644 surfaces/blender/tests/live/kitbash_pose.py diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index a910f03..105b694 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -15,7 +15,9 @@ params). A connection belongs to the child: its parent pointer (under an identity parent inverse) and three more ID properties, kit_socket, kit_parent_socket and kit_roll. Its matrix_basis is derived from them and both parts' -params by core.mate; attach and set_params write it, and a report says how far the child stands from it. kit_baked +params by core.mate; attach and set_params write it, and a report says how far the child stands from it. +write_connection is the one writer of a connection. roll, aim and reach rewrite an attached part's roll through it, +in place: roll states the roll, aim and reach solve it in closed form (core.aim_roll, core.reach_roll). kit_baked says apply replaced the mesh with the evaluated one: the params then only place the part's sockets. Placing a loose part, hiding a cutter, materials and export are Brokkr's own rows (setObjectTransform, setObjectVisibility, assignMaterial, exportGltf). @@ -231,6 +233,15 @@ def seat(child, basis) -> None: child.matrix_basis = Matrix(np.asarray(basis).tolist()) +def write_connection(child, parent, sockets, stated) -> None: + """State a connection and seat it: the child's parent, its derived matrix_basis and its three properties. + `sockets` is mated()'s answer for `stated`. attach, roll, aim and reach write a connection here and nowhere + else.""" + child.parent = parent + seat(child, core.mate(*sockets, stated[2])) + child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated + + def connection_report(obj, part, built): """None for a part that states no connection, else what it states and whether it holds: the parent is a kit part, both sockets exist, the roll is a number, the parent inverse is the identity and the child @@ -563,9 +574,7 @@ class BROKKR_KITBASH_OT_attach(PolishOperator): sockets = mated(parent, parent_part, parent_built, child, part, built, stated) free(parent, self.parent_socket) free(child, self.socket) - child.parent = parent - seat(child, core.mate(*sockets, stated[2])) - child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated + write_connection(child, parent, sockets, stated) context.view_layer.update() return part_report(child, part, built) @@ -593,6 +602,97 @@ class BROKKR_KITBASH_OT_detach(PolishOperator): return part_report(obj, part, built) +def pose(context, name: str, solve) -> dict: + """Give an attached part a new roll where it hangs: its parent and both sockets stay, and what is attached to + it follows. `solve(child, built, sockets, stated)` answers (the roll, what to add to the report), or refuses. + Refuses a part that states no connection or has no parent, and what mated() refuses. The report is the part's + and, as set_params', every closure in the scene with the part's own first: a roll can open one, and never + seats one.""" + child = mesh_object(name) + part, built = built_part(child) + stated = link(child) + if stated is None: + raise Refused(f"{child.name!r} is not attached (it has no {SOCKET} property): attach gives it a connection to pose; nothing changed.") + if child.parent is None: + raise Refused(f"{child.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.") + sockets = mated(child.parent, *built_part(child.parent), child, part, built, stated) + try: + roll, solved = solve(child, built, sockets, stated) + except core.KitError as error: + raise Refused(f"{child.name!r} on {child.parent.name!r}: {error}; nothing changed.") from None + write_connection(child, child.parent, sockets, (stated[0], stated[1], float(roll))) + context.view_layer.update() + report = {**part_report(child, part, built), **solved} + report["closures"] = scene_closures(context, report, (child,)) + return report + + +def unit(operator) -> np.ndarray: + """An operator's direction_x, direction_y and direction_z as a unit vector; zero is refused.""" + direction = np.array([operator.direction_x, operator.direction_y, operator.direction_z], dtype=np.float64) + if not np.linalg.norm(direction) > 0: + raise Refused("The direction is zero: give direction_x, direction_y and direction_z a world direction; nothing changed.") + return direction / np.linalg.norm(direction) + + +class BROKKR_KITBASH_OT_roll(PolishOperator): + """Turn an attached kit part to a roll about its parent socket's normal, in place: its parent and sockets stay + and what hangs from it follows""" + bl_idname = "brokkr_kitbash.roll" + bl_label = "Roll Kit Part" + object_name: bpy.props.StringProperty(name="Object", description="An attached part") + roll: bpy.props.FloatProperty(name="Roll", default=0.0, min=-360.0, max=360.0, + description="Degrees about the parent socket's normal, right-handed; at 0 the two sockets' ys line up") + + @kit_work + def work(self, context): + return pose(context, self.object_name, lambda child, built, sockets, stated: (self.roll, {})) + + +class BROKKR_KITBASH_OT_aim(PolishOperator): + """Turn an attached kit part about its pin until one of its own axes points as near a world direction as the + pin lets it: the roll is solved, not searched""" + bl_idname = "brokkr_kitbash.aim" + bl_label = "Aim Kit Part" + object_name: bpy.props.StringProperty(name="Object", description="An attached part") + axis: bpy.props.EnumProperty(name="Axis", description="An axis of the part's own frame", default="+z", + items=[(name, name, "") for name in core.AXES]) + direction_x: bpy.props.FloatProperty(name="Direction X", default=0.0, description="World direction, any length") + direction_y: bpy.props.FloatProperty(name="Direction Y", default=0.0) + direction_z: bpy.props.FloatProperty(name="Direction Z", default=0.0) + + @kit_work + def work(self, context): + def solve(child, built, sockets, stated): + roll, dot = core.aim_roll(child.parent.matrix_world, *sockets, core.AXES[self.axis], unit(self)) + return roll, {"aimed": {"roll": round(roll, 6), "dot": round(dot, 9)}} + return pose(context, self.object_name, solve) + + +class BROKKR_KITBASH_OT_reach(PolishOperator): + """Turn an attached kit part about its pin until one of its sockets stands at a height along a world direction: + of the two rolls that do it, the one nearer the roll it has""" + bl_idname = "brokkr_kitbash.reach" + bl_label = "Reach With Kit Part" + object_name: bpy.props.StringProperty(name="Object", description="An attached part") + socket: bpy.props.StringProperty(name="Socket", description="The socket of the part whose origin is brought to the plane") + direction_x: bpy.props.FloatProperty(name="Direction X", default=0.0, description="World direction, any length") + direction_y: bpy.props.FloatProperty(name="Direction Y", default=0.0) + direction_z: bpy.props.FloatProperty(name="Direction Z", default=1.0) + height: bpy.props.FloatProperty(name="Height", default=0.0, min=-1000.0, max=1000.0, + description="Metres along the unit direction, in the world: the plane is direction . x = height") + + @kit_work + def work(self, context): + def solve(child, built, sockets, stated): + found = [s for s in built.sockets if s["name"] == self.socket] + if not found: + raise Refused(f"{child.name!r} has no socket {self.socket!r}; its sockets: {', '.join(s['name'] for s in built.sockets)}; nothing changed.") + roll, residual = core.reach_roll(child.parent.matrix_world, *sockets, found[0]["matrix"][:3, 3], unit(self), self.height, stated[2]) + return roll, {"reached": {"roll": round(roll, 6), "residual": round(residual, 9)}} + return pose(context, self.object_name, solve) + + class BROKKR_KITBASH_OT_close(PolishOperator): """State that a socket of a kit part meets a socket of another part, of its kit or of any kit whose socket types agree, closing a loop the tree of connections cannot: accepted only when the two already meet, origins together and normals opposed, and it @@ -788,8 +888,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_cut, BROKKR_KITBASH_OT_cut_many, - BROKKR_KITBASH_OT_apply) + BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach, + BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply) def register(): diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 5fe8651..e134ef2 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -174,6 +174,140 @@ } ] }, + { + "name": "brokkr_kitbash.roll", + "doc": "Turn an attached kit part to a roll about its parent socket's normal, in place: its parent and both sockets stay, and what is attached to it follows. Refuses a part that is not attached. Reports the part and closures, every closure in the scene as {part, to, holds}, its own first: a roll can open one and never seats one.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "an attached part" + }, + { + "name": "roll", + "type": "number", + "required": true, + "minimum": -360, + "maximum": 360, + "doc": "degrees about the parent socket's normal, right-handed; at 0 the two sockets' up axes line up" + } + ] + }, + { + "name": "brokkr_kitbash.aim", + "doc": "Turn an attached kit part about its pin until one of its own axes points as near a world direction as the pin lets it. The roll is solved exactly, not searched. Refuses an axis or a direction that lies along the pin, and a zero direction. Reports the part, aimed: {roll, dot} (dot 1 when the axis reaches the direction) and closures as roll does.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "an attached part" + }, + { + "name": "axis", + "type": "string", + "required": true, + "enum": [ + "+x", + "-x", + "+y", + "-y", + "+z", + "-z" + ], + "doc": "an axis of the part's own frame" + }, + { + "name": "direction_x", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true, + "doc": "the world direction to aim at, any length" + }, + { + "name": "direction_y", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true + }, + { + "name": "direction_z", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "required": true + } + ] + }, + { + "name": "brokkr_kitbash.reach", + "doc": "Turn an attached kit part about its pin until one of its sockets' origins stands at a height along a world direction (by default world z): of the two rolls that do it, the one nearer the roll it has. Solved exactly. Refuses a height the socket cannot reach, naming the range it can. Reports the part, reached: {roll, residual} and closures as roll does.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "an attached part" + }, + { + "name": "socket", + "type": "string", + "required": true, + "chars": "id", + "minLength": 1, + "maxLength": 32, + "doc": "the socket of the part that is brought to the plane; brokkr_kitbash.report lists a part's sockets" + }, + { + "name": "direction_x", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 0, + "doc": "the world direction the height is measured along, any length" + }, + { + "name": "direction_y", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 0 + }, + { + "name": "direction_z", + "type": "number", + "minimum": -1000, + "maximum": 1000, + "default": 1 + }, + { + "name": "height", + "type": "number", + "required": true, + "minimum": -1000, + "maximum": 1000, + "doc": "metres along the unit direction, in the world" + } + ] + }, { "name": "brokkr_kitbash.close", "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.", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 066f233..736fbff 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -17,6 +17,10 @@ both kits declare the socket's type with the same match rule. surface_frame is t 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. +A pin's roll is its one degree of freedom, and it is solved in closed form: roll_terms gives how a point or an axis +of the child moves along a world direction as the roll turns (a cosine, a sine and a constant), aim_roll the roll +that points an axis of the child at a direction, reach_roll the roll that brings a point of the child to a plane. + Every refusal is a KitError whose message names the kit, part and field. """ from __future__ import annotations @@ -640,6 +644,59 @@ def residual(parent_world, parent_socket: dict, child_world, child_socket: dict, return float(np.abs(wanted - np.asarray(child_world, dtype=np.float64) @ child_socket["matrix"]).max()) +def roll_terms(parent_world, parent_socket: dict, child_socket: dict, local, w: float, direction) -> tuple[float, float, float]: + """(A, B, C) with direction . (the child's `local`, in the world) = A cos(roll) + B sin(roll) + C when the child + is mated on parent_socket at that roll. `local` is in the child's own frame: a point with w 1, an axis with w 0. + Everything but the roll is held: the parent's world matrix and both sockets.""" + M = np.asarray(parent_world, dtype=np.float64) @ parent_socket["matrix"] + q = FLIP @ np.linalg.inv(child_socket["matrix"]) @ np.array([*local, w], dtype=np.float64) + direction = np.asarray(direction, dtype=np.float64) + e = M[:3, :3].T @ direction + return (float(e[0] * q[0] + e[1] * q[1]), float(e[1] * q[0] - e[0] * q[1]), float(e[2] * q[2] + w * (direction @ M[:3, 3]))) + + +# The least hypot(A, B) aim_roll solves for: below it the axis or the direction lies along the pin and no roll turns +# one toward the other. Least aimable case of the tests 0.0175 (a direction 1 degree off the pin); a degenerate case +# reads at most 1.2e-16 (float rounding of an axis along the pin); the geometric mean, separation 1.2e7 each side. +AIM_FLOOR = 1.5e-9 + + +def _wrapped(degrees: float) -> float: + """An angle in (-180, 180].""" + return 180.0 - (180.0 - degrees) % 360.0 + + +def aim_roll(parent_world, parent_socket: dict, child_socket: dict, axis, direction) -> tuple[float, float]: + """(roll in degrees in (-180, 180], the dot it achieves) that turns the child's own `axis` as far toward the + world `direction` as its pin lets it: roll = atan2(B, A), dot = C + hypot(A, B), for unit vectors. Refuses an + axis or a direction along the pin, which no roll turns.""" + direction = np.asarray(direction, dtype=np.float64) + direction = direction / np.linalg.norm(direction) + A, B, C = roll_terms(parent_world, parent_socket, child_socket, axis, 0.0, direction) + if math.hypot(A, B) <= AIM_FLOOR: + raise KitError(f"socket {child_socket['name']!r} on parent socket {parent_socket['name']!r}: the axis {tuple(float(v) for v in axis)} of the part " + f"or the direction {tuple(round(float(v), 6) for v in direction)} lies along the pin, so no roll turns one toward the other") + return _wrapped(math.degrees(math.atan2(B, A))), C + math.hypot(A, B) + + +def reach_roll(parent_world, parent_socket: dict, child_socket: dict, point, direction, height: float, current_roll: float) -> tuple[float, float]: + """(roll in degrees in (-180, 180], residual |direction . p - height| in metres) that brings the child's own + `point` to the plane direction . x = height, for a unit direction: atan2(B, A) +- acos((height - C) / hypot(A, B)), + of the two the one nearer current_roll round the circle (a tie takes the smaller roll). Refuses a height the + point cannot reach, naming the range it can.""" + direction = np.asarray(direction, dtype=np.float64) + direction = direction / np.linalg.norm(direction) + A, B, C = roll_terms(parent_world, parent_socket, child_socket, point, 1.0, direction) + swing = math.hypot(A, B) + if abs(height - C) > swing: + raise KitError(f"socket {child_socket['name']!r} on parent socket {parent_socket['name']!r}: no roll brings the point to {height:.6g} m along " + f"{tuple(round(float(v), 6) for v in direction)}; it reaches {C - swing:.6g} m to {C + swing:.6g} m") + middle, spread = math.degrees(math.atan2(B, A)), math.degrees(math.acos((height - C) / swing)) if swing > 0 else 0.0 + roots = sorted({_wrapped(middle - spread), _wrapped(middle + spread)}) + roll = min(roots, key=lambda root: (round(abs(_wrapped(root - current_roll)), 9), root)) + return roll, abs(A * math.cos(math.radians(roll)) + B * math.sin(math.radians(roll)) + C - height) + + def closure_residual(world_a, socket_a: dict, world_b, socket_b: dict) -> float: """How far two sockets of two placed parts stand from meeting as a pin: the larger of the largest difference between their origins (metres) and the largest entry of the sum of their normals (0 when opposed). Roll is not diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 5c512d2..a90d1d8 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -6,7 +6,7 @@ actuators, housings and plumbing an agent assembles offline under a hand-fit arm add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish` and `brokkr_rig`: it imports the polish package's operator base, `Refused` and `mesh_object`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish` first; `brokkr_kitbash` refuses to register without it. `brokkr_actions.json` beside -its `__init__.py` lists the nine operators agents may run. Every action writes a JSON report to +its `__init__.py` lists the fourteen operators agents may run. Every action writes a JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. Who owns what: @@ -136,8 +136,8 @@ Nothing else stores it: no parent name, no world matrix, no empties. The child's matrix_basis = S_parent @ Rz(roll) @ FLIP @ inverse(S_child) FLIP = half a turn about y ``` -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. +with `S` each socket's frame in its own part at that part's stored params (`core.mate`). `attach`, `set_params`, +`roll`, `aim` and `reach` write it; nothing else should. **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 @@ -155,8 +155,8 @@ refuses, changing nothing: - a part that is not a kit part, or is scaled in the world. A part may carry a child on every socket but the one it hangs by. Connections are a tree: tank, then a tee on -its port, then a nozzle on each free flange of the tee. Nothing moves a part but `attach` and `set_params`, -through that tree. +its port, then a nozzle on each free flange of the tee. Nothing moves a part but `attach`, `set_params` and the +three that pose a hinge, through that tree. **A closure** states the one thing a tree cannot: that a part's second socket also meets something. A brace hangs from its own bracket by one pin (a connection); its other pin meets the leg's rod (a closure), and the @@ -185,6 +185,34 @@ which gives the point where the free pins meet. Each member's roll is then the a `z`, from that socket's `y` to the direction of the meeting point. `report` gives every socket's world frame to read these from. +**Posing a hinge.** The roll is a connection's one degree of freedom, and three actions change it where the part +hangs: its parent and both sockets stay, the part is seated again at the new roll, and what is attached to it +follows through parenting. None of them detaches anything. `roll` states the roll. `aim` and `reach` solve it: +with everything but the roll held, a point or an axis of the child moves on a circle as the roll turns, so along +a world direction `d` it reads + +```text +d . p(roll) = A cos(roll) + B sin(roll) + C +``` + +with `A`, `B` and `C` from the parent's world frame, the two sockets and the point or axis in the child's own +frame (`core.roll_terms`). `aim` turns one of the child's own axes (`+x` to `-z`) as far toward `d` as the pin +lets it: `roll = atan2(B, A)`, and the dot it reaches is `C + hypot(A, B)`, reported as `aimed: {roll, dot}`; a +dot under 1 says the pin does not let the axis reach the direction. `reach` brings the origin of one of the +child's sockets to the plane `d . x = height`: `roll = atan2(B, A) ± acos((height - C) / hypot(A, B))`, of the two +the one nearer the roll the part has (a tie takes the smaller), reported as `reached: {roll, residual}`. Both are +exact: nothing is searched. The roll they write is in (-180, 180] and is stored as `kit_roll`; the direction or +plane it was solved for is stored nowhere, so a parent that moves afterwards carries the part with it and nothing +re-aims it. + +They refuse, changing nothing: a part that states no connection (`attach` it first), one whose parent was +cleared, a connection `attach` would refuse now (sockets that no longer mate), a zero direction, an `aim` whose +axis or direction lies along the pin (no roll turns one toward the other), and a `reach` to a height the socket's +circle does not cross, naming the range it does. A leg is posed with them from the hip down: `aim` the yoke's +front at where the leg should point, `reach` the last link's clevis to the ground plus the foot's drop, `aim` +the foot's sole at the ground. Each reports `closures` as `set_params` does, the part's own first: a roll moves +everything below the part, can open a closure anywhere there, and never seats one. + A part's report carries `closure`: `null`, or ```json @@ -201,7 +229,7 @@ after which the two sockets may no longer mate (a pin of another size), naming t moves a socket (an actuator's `extension` under a closed brace) is accepted and opens the closure: the report of `set_params` lists every closure in the scene as `closures: [{part, to, holds}]`, those its own part is an end of first, then those that do not hold, then the rest, so the caller sees which -ones it opened and can solve the rolls again, `detach` and `attach` the members, and find the closure holding. +ones it opened and can solve the rolls again, turn the members with `roll` or `reach`, and find the closure holding. `detach` clears the closing part's closure together with its connection. **`set_params` keeps an assembly together.** Sockets move with params (an actuator's `rod_end` with `extension`, a @@ -347,6 +375,9 @@ vertices overflow. | `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; 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.roll` | `object_name`, `roll` (degrees, -360 to 360) | Turns an attached part to that roll where it hangs. Refuses a part that is not attached. Reports the part and `closures` as `set_params` does. | +| `brokkr_kitbash.aim` | `object_name`, `axis` (`+x`, `-x`, `+y`, `-y`, `+z` or `-z`, the part's own), `direction_x`, `direction_y`, `direction_z` (world, any length) | Solves the roll that turns the axis as far toward the direction as the pin lets it, and turns the part to it. Refuses an axis or direction along the pin. Reports the part, `aimed: {roll, dot}` and `closures`. | +| `brokkr_kitbash.reach` | `object_name`, `socket` (one of the part's), `height` (metres, -1000 to 1000), `direction_x`, `direction_y`, `direction_z` (world; default 0, 0, 1) | Solves the roll that brings the socket's origin to `height` along the direction, the nearer of the two, and turns the part to it. Refuses a height out of reach, naming the range. Reports the part, `reached: {roll, residual}` and `closures`. | | `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. | | `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added) and `evaluated`. | | `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans`. | @@ -449,8 +480,9 @@ seated on a face that faces its `z`, and no build passes 20000 faces. Choose par 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`. `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) and `tests/live/kitbash_shell.py` +frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may mate, within a kit and across two, +`PoseTests` the closed-form rolls. The operators are exercised in a real Blender by +`tests/live/kitbash.py` (placing and re-parameterising), `tests/live/kitbash_assembly.py` (attach, detach, +`set_params` on assemblies, a braced leg closed by `close`, boolean and apply), `tests/live/kitbash_shell.py` (`cut` and `cut_many` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no -collection). +collection) and `tests/live/kitbash_pose.py` (roll, aim and reach). diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index b1807b1..3b100a4 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -75,7 +75,7 @@ def extent(obj, axis=2): check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == [f"brokkr_kitbash.{name}" for name in ( - "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "cut", "cut_many", "apply")], [R["hostErrors"], R["hostRows"]]) + "place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply")], [R["hostErrors"], R["hostRows"]]) # --- describe --------------------------------------------------------------------------------------------------------- kit = core.load_kit("mechanical") diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 86a2197..c14b342 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -177,7 +177,7 @@ def evaluated(obj): rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == [f"brokkr_kitbash.{n}" for n in ( - "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "cut", "cut_many", "apply")], [R["hostErrors"], rows]) + "place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply")], [R["hostErrors"], rows]) # --- attach ------------------------------------------------------------------------------------------------------------- tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088 diff --git a/surfaces/blender/tests/live/kitbash_pose.py b/surfaces/blender/tests/live/kitbash_pose.py new file mode 100644 index 0000000..1e58074 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_pose.py @@ -0,0 +1,291 @@ +"""Live proof, in a background Blender, of brokkr_kitbash posing through run_intent: roll turns an attached part +where it hangs, aim and reach solve the roll (core.aim_roll, core.reach_roll), each reports the closures it opened, +and each refusal changes nothing. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_pose.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). is an absolute path; writes .result.json and exits 1 when a check failed. + +The scene: a tank, a bracket on its lug, a strut pinned in the bracket, an actuator pinned on the strut's far end, +and a loose strut whose closure names the actuator's rod pin. Bounds follow lodur:ruling:deterministic-bound-margin: +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 bpy +import numpy as np +from mathutils import Matrix + +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-pose-")) +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] +kit = core.load_kit("mechanical") +# Metres (or a difference of unit vectors) between where a posed part's socket is and where its mate puts it, read +# from the two world matrices. Shipped worst 2.4e-07 (float32 matrices); least claimed mutant 0.24 (R3, roll writes +# kit_roll without seating: the actuator, read against the roll its strut states); separation 1.0e6. +SEATED = 2.4e-4 +# Degrees between the roll read from the two world frames and the roll stated. Shipped worst 1.4e-05; least claimed +# mutant 15 (R3, at the smallest turn here); separation 1.1e6. +ROLL = 1.4e-2 +# Metres between how far the actuator's pin moved and how far the strut's socket that carries it moved. Shipped +# worst 2.4e-07; least claimed mutant 0.38 (R3: the strut's socket is read at the stated roll, the actuator stays). +CARRIED = 3.0e-4 +# The dot aim reports against the dot read from the scene, and its roll (degrees) against core.aim_roll on the +# scene's float32 matrices. Shipped worst 6.0e-08 and 3.4e-06; least claimed mutant 1.0 and 90 (R1); the roll's +# bound is ROLL's. +AIMED = 2.4e-4 +# Metres between the socket reach moved and the plane asked for, read from the scene. Shipped worst 2.4e-07; least +# claimed mutant 0.36 (R6, a left-handed roll_terms: the root it solves is the mirror's). +REACHED = 2.9e-4 + + +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 socket(obj, name): + built = core.build(core.part(kit, obj["kit_part"]), json.loads(obj["kit_params"])) + return next(s for s in built.sockets if s["name"] == name) + + +def frame(obj, name): + """A socket's world frame, from the object's matrix_world and core's build of its stored params.""" + return np.array(obj.matrix_world, dtype=np.float64) @ socket(obj, name)["matrix"] + + +def seated(child, name, parent, parent_socket, roll=None): + """How far a child's socket is from seated on its parent's: origins apart, or normals not opposed. With a roll, + also records the degrees between it and the roll read from the two frames.""" + a, b = frame(parent, parent_socket), frame(child, name) + if roll is not None: + read = math.degrees(math.atan2(np.cross(a[:3, 1], b[:3, 1]) @ a[:3, 2], a[:3, 1] @ b[:3, 1])) + reading("roll", abs((read - roll + 180.0) % 360.0 - 180.0)) + return max(float(np.abs(a[:3, 3] - b[:3, 3]).max()), float(np.abs(a[:3, 2] + b[:3, 2]).max())) + + +def connection(name): + receipt, report = send("brokkr_kitbash.report", object_name=name) + return report["parts"][0]["connection"] if report else {"error": receipt["message"]} + + +def holds(found, parent, name, parent_socket, roll): + """A connection row that states this connection and holds.""" + found = found or {} + return found == {**found, "parent": parent, "socket": name, "parentSocket": parent_socket, "roll": roll, "holds": True} and found.get("residual", 1.0) <= 1e-5 + + +def stated(obj): + return obj.parent and obj.parent.name, {k: obj[k] for k in sorted(obj.keys()) if k.startswith("kit_") and k != "kit_roll"}, np.array(obj.matrix_parent_inverse).tolist() + + +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_")}) for o in bpy.data.objects} + + +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"]]) + + +rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] +check("roll, aim and reach load as host actions after detach, with no errors", not R["hostErrors"] and "brokkr_kitbash.detach" in rows + and rows[rows.index("brokkr_kitbash.detach") + 1:][:3] == ["brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach"], [R["hostErrors"], rows]) + +# --- the scene ---------------------------------------------------------------------------------------------------------- +tank = place("Tank", "tank", "radius=0.3; length=1.2", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # lug size 0.09 +mount = place("Mount", "bracket") # pin 0.054, plate 0.09 +strut, ram = place("Strut", "strut", "width=0.09"), place("Ram", "actuator") +spare, orphan = place("Spare", "strut", "width=0.09", location=[0.0, 6.0, 0.0]), place("Orphan", "bracket") +send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3) +send("brokkr_kitbash.attach", object_name="Mount", socket="mount", parent_name="Tank", parent_socket="lug_b") +send("brokkr_kitbash.attach", object_name="Orphan", socket="mount", parent_name="Tank", parent_socket="lug_a") +send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Mount", parent_socket="pivot", roll=20.0) +receipt, report = send("brokkr_kitbash.attach", object_name="Ram", socket="base", parent_name="Strut", parent_socket="end_b", roll=-35.0) +check("the chain stands: tank, bracket, strut, actuator", receipt["status"] == "accepted" and holds(connection("Strut"), "Mount", "end_a", "pivot", 20.0) + and holds(report["connection"], "Strut", "base", "end_b", -35.0), [receipt["message"], connection("Strut")]) + + +def meeting(name, other, other_socket, roll): + """Place a loose strut so its end_a meets a socket of another part, and close it there.""" + loose = place(name, "strut", "width=0.09") + meet = Matrix((np.array(other.matrix_world) @ core.mate(socket(other, other_socket), socket(loose, "end_a"), roll)).tolist()) + send("setObjectTransform", targetObjectName=name, location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) + return send("brokkr_kitbash.close", object_name=name, socket="end_a", other_name=other.name, other_socket=other_socket) + + +anchor = place("Aa_Anchor", "strut", "width=0.09", location=[0.0, -20.0, 0.0]) +receipt, report = meeting("Brace", ram, "rod_end", 50.0) +check("a brace closes on the actuator's rod pin", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) +receipt, report = meeting("Aa_Loose", anchor, "end_b", 40.0) +check("and a second closure, named to sort first, holds far from it", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) +brace = bpy.data.objects["Brace"] +closing = {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} + +# --- roll: in place ----------------------------------------------------------------------------------------------------- +for turn in (65.0, -160.0, 35.0): # from the 20 it was attached at + was, pin, before = stated(strut), frame(ram, "base")[:3, 3].copy(), (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) + sent = COUNT[0] + receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=turn) + carried = frame(strut, "end_b")[:3, 3] - pin # where the socket that carries the actuator stands now, from where the actuator's pin was + check(f"roll {turn:g} turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated", + receipt["status"] == "accepted" and COUNT[0] == sent + 1 and stated(strut) == was and strut["kit_roll"] == turn + and reading("seated", seated(strut, "end_a", mount, "pivot", turn)) < SEATED and R["readings"]["roll"] < ROLL + and report and report["object"] == "Strut" and holds(report["connection"], "Mount", "end_a", "pivot", turn) and holds(connection("Strut"), "Mount", "end_a", "pivot", turn), + [receipt["message"], report and report["connection"], R["readings"]]) + check(f"and the actuator follows through its own connection, which nothing rewrote (roll {turn:g})", + (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) == before and float(np.linalg.norm(carried)) > 0.1 + and reading("carried", np.abs(frame(ram, "base")[:3, 3] - pin - carried).max()) < CARRIED + and reading("seated", seated(ram, "base", strut, "end_b", -35.0)) < SEATED and R["readings"]["roll"] < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -35.0), + [carried.tolist(), connection("Ram"), R["readings"]]) + reading("turned", float(np.linalg.norm(carried))) + +# --- roll: the closures it opens ---------------------------------------------------------------------------------------- +check("the rolls above opened the brace's closure and reported it before the one that holds, whatever its name", report and report.get("closures") == [ + {"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] and report["closure"] is None, report and report.get("closures")) +receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=20.0) +check("rolled back to where the brace met it, the closure holds again: read from where the parts stand", receipt["status"] == "accepted" and report["closures"] == [ + {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}, {"part": "Brace", "to": "Ram", "holds": True}], report and report.get("closures")) +send("setObjectTransform", targetObjectName="Aa_Loose", location=[0.0, -25.0, 0.0], rotationEuler=[0.0, 0.0, 0.0]) +receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-35.0) +check("a roll lists the closures its own part is an end of first, before a broken one elsewhere", receipt["status"] == "accepted" and report["closures"] == [ + {"part": "Brace", "to": "Ram", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}], report and report.get("closures")) +receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-36.0) +check("and a roll of the part a closure names opens it; no roll seats or rewrites a closure", receipt["status"] == "accepted" and report["closures"] == [ + {"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}] + and {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} == closing and brace.parent is None, [report and report.get("closures"), dict(brace.items())]) + +# --- aim ---------------------------------------------------------------------------------------------------------------- +for axis, direction in (("+z", (1.0, 0.0, 0.0)), ("-x", (0.0, -3.0, 4.0)), ("+z", (0.2, 0.1, -2.0))): + world = np.array(mount.matrix_world, dtype=np.float64) + want, dot = core.aim_roll(world, socket(mount, "pivot"), socket(strut, "end_a"), core.AXES[axis], direction) + receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis=axis, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2]) + aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9} + read = float(np.array(strut.matrix_world, dtype=np.float64)[:3, :3] @ np.array(core.AXES[axis]) @ (np.array(direction) / np.linalg.norm(direction))) + grid = max(float((world @ core.mate(socket(mount, "pivot"), socket(strut, "end_a"), float(r)))[:3, :3] @ np.array(core.AXES[axis]) @ (np.array(direction) / np.linalg.norm(direction))) + for r in range(-180, 180)) + check(f"aim points the strut's {axis} at {direction} as far as its pin lets it: the dot core solves, the dot the scene reads, and no roll on a 1-degree grid passes it", + receipt["status"] == "accepted" and reading("aimed roll", abs((aimed["roll"] - want + 180.0) % 360.0 - 180.0)) < ROLL + and reading("aimed dot", max(abs(aimed["dot"] - dot), abs(aimed["dot"] - read))) < AIMED and grid < aimed["dot"] + AIMED and 0.2 < aimed["dot"] < 0.999, + [receipt["message"], aimed, want, dot, read, grid]) + check(f"and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported ({axis})", + aimed["roll"] == round(strut["kit_roll"], 6) and -180.0 < aimed["roll"] <= 180.0 + and holds(report and report["connection"], "Mount", "end_a", "pivot", aimed["roll"]) and reading("seated", seated(strut, "end_a", mount, "pivot", aimed["roll"])) < SEATED + and R["readings"]["roll"] < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len(report.get("closures", [])) == 2, + [dict(strut.items()), report and report["connection"], report and report.get("closures")]) + +# --- reach -------------------------------------------------------------------------------------------------------------- +for direction, part, offset in (((0.0, 0.0, 1.0), 0.5, 40.0), ((0.0, 0.0, 1.0), 0.5, -40.0), ((1.0, 2.0, -0.5), -0.8, 100.0)): + world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction) + A, B, C = core.roll_terms(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], 1.0, unit) + current = float(round(math.degrees(math.atan2(B, A)) + offset)) # the two rolls that reach stand either side of the middle: start nearer one + send("brokkr_kitbash.roll", object_name="Strut", roll=current) + height = round(C + part * math.hypot(A, B), 3) + want, _ = core.reach_roll(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], unit, height, current) + other = (2.0 * math.degrees(math.atan2(B, A)) - want + 180.0) % 360.0 - 180.0 + fields = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} if direction != (0.0, 0.0, 1.0) else {} # world z is the default + receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=height, **fields) + reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9} + check(f"reach brings the strut's end_b to {height} m along {direction} from roll {current:g}, by the nearer of the two rolls that do", + receipt["status"] == "accepted" and reading("reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - height)) < REACHED and reached["residual"] < REACHED + and reading("reached roll", abs((reached["roll"] - want + 180.0) % 360.0 - 180.0)) < ROLL + and abs((want - current + 180.0) % 360.0 - 180.0) + 10.0 < abs((other - current + 180.0) % 360.0 - 180.0), + [receipt["message"], reached, want, other, float(frame(strut, "end_b")[:3, 3] @ unit)]) + check(f"and it is stated and seated as roll's ({direction}, from {current:g})", reached["roll"] == round(strut["kit_roll"], 6) and -180.0 < reached["roll"] <= 180.0 + and holds(report and report["connection"], "Mount", "end_a", "pivot", reached["roll"]) and reading("seated", seated(strut, "end_a", mount, "pivot", reached["roll"])) < SEATED + and R["readings"]["roll"] < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len(report.get("closures", [])) == 2, + [dict(strut.items()), report and report["connection"]]) + +# --- refusals ----------------------------------------------------------------------------------------------------------- +send("setObjectParent", targetObjectName="Orphan", parentObjectName="") +low, high = C - math.hypot(A, B), C + math.hypot(A, B) +refused("roll of a part nobody attached", "brokkr_kitbash.roll", {"object_name": "Spare", "roll": 10.0}, "'Spare' is not attached (it has no kit_socket property)") +refused("aim of a part nobody attached", "brokkr_kitbash.aim", {"object_name": "Spare", "axis": "+z", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "'Spare' is not attached") +refused("reach of a part nobody attached", "brokkr_kitbash.reach", {"object_name": "Spare", "socket": "end_b", "height": 0.0}, "'Spare' is not attached") +refused("roll of a part whose parent was cleared", "brokkr_kitbash.roll", {"object_name": "Orphan", "roll": 10.0}, "'Orphan' states a connection and has no parent: detach it") +refused("roll of a mesh that is not a kit part", "brokkr_kitbash.roll", {"object_name": "Plain", "roll": 10.0}, "'Plain' is not a kit part") +refused("aim of the axis along the pin", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+y", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, + "'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': the axis (0.0, 1.0, 0.0) of the part or the direction (1.0, 0.0, 0.0) lies along the pin") +refused("aim at no direction", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+z", "direction_x": 0.0, "direction_y": 0.0, "direction_z": 0.0}, "The direction is zero") +refused("reach past the circle the socket turns on, naming what it reaches", "brokkr_kitbash.reach", + {"object_name": "Strut", "socket": "end_b", "height": 900.0, "direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]}, + f"no roll brings the point to 900 m along ({unit[0]:.6f}".rstrip("0")) +receipt, _ = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=900.0, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2]) +check("and the range it names is the one core solves", f"it reaches {low:.6g} m to {high:.6g} m" in str(receipt["message"]) and high - low > 1.0, [receipt["message"], low, high]) +refused("reach with a socket the part does not have", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_c", "height": 0.0}, + "'Strut' has no socket 'end_c'; its sockets: end_a, end_a_back, end_b, end_b_back") +refused("reach along no direction", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": 0.0, "direction_z": 0.0}, "The direction is zero") +refused("a roll past a turn, by the action table", "brokkr_kitbash.roll", {"object_name": "Strut", "roll": 361.0}, "roll") +refused("an axis that is not one of the six, by the action table", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "x", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "axis") + +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/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index b0c9404..4f14425 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -2,7 +2,8 @@ corner of its params, and the host action file against Brokkr's own checker. Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) -The operators are exercised in a real Blender by tests/live/kitbash.py and tests/live/kitbash_assembly.py. +The operators are exercised in a real Blender by tests/live/kitbash.py, tests/live/kitbash_assembly.py and +tests/live/kitbash_pose.py. Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is the built value, and each names the mutant it kills. @@ -947,8 +948,145 @@ class MateTests(unittest.TestCase): core.joint(parts["tank"], tank, "port_b", parts["pipe_fitting"], fitting, "d") +@unittest.skipIf(np is None, "numpy is not installed") +class PoseTests(unittest.TestCase): + """core.roll_terms, aim_roll and reach_roll: a pin's roll solved in closed form, read back through core.mate. The + bounds sit at the geometric mean of the shipped worst reading and the least claimed mutant's + (lodur:ruling:deterministic-bound-margin).""" + PAIRS = MateTests.PAIRS + AIMED = 2.1e-8 # shipped 2.2e-16; least mutant 1.91 (R1, atan2(A, B)); R6 (roll_terms' B with its sign flipped) reads 1.97; separation 8.6e15 + BEATEN = 5.0e-9 # how far a roll on the 1-degree grid may pass the solved dot. shipped 0, taken as one float step; least mutant 0.114 (R8, the dot reported without its hypot); separation 5.1e14 + REACHED = 6.6e-8 # metres off the plane. shipped 1.8e-15; least mutant 2.44 (R6); separation 1.4e15 + NEARER = 2.2e-6 # degrees the chosen root may stand farther from the current roll than the other. shipped 0, taken as 2.8e-14; least mutant 172 (R2, the farther root) + + @classmethod + def setUpClass(cls): + cls.kit = core.load_kit("mechanical") + + def joints(self, seed): + """Each PAIRS joint under four seeded random parent frames: (parent world, parent socket, child socket, rng).""" + rng, parts = random.Random(seed), self.kit["parts"] + for parent, parent_params, parent_socket, child, child_params, child_socket in self.PAIRS: + sp, sc = core.joint(parts[parent], core.build(parts[parent], parent_params), parent_socket, + parts[child], core.build(parts[child], child_params), child_socket) + for _ in range(4): + world = np.eye(4) + world[:3, :3] = core._rotation([rng.uniform(-180, 180) for _ in range(3)]) + world[:3, 3] = [rng.uniform(-5, 5) for _ in range(3)] + yield world, sp, sc, rng + + @staticmethod + def direction(rng): + d = np.array([rng.gauss(0, 1) for _ in range(3)]) + return d / np.linalg.norm(d) + + def aim_readings(self): + worst = {"aimed": 0.0, "terms": 0.0, "beaten": 0.0, "least": math.inf, "cases": 0} + for world, sp, sc, rng in self.joints("aim"): + for name, axis in core.AXES.items(): + if abs(np.array(axis) @ sc["matrix"][:3, 2]) == 1.0: + continue # the socket's own normal: the pin + d = self.direction(rng) + roll, dot = core.aim_roll(world, sp, sc, axis, 3.0 * d) # any length + A, B, C = core.roll_terms(world, sp, sc, axis, 0.0, d) + turned = lambda r: float(d @ (world @ core.mate(sp, sc, r))[:3, :3] @ np.array(axis)) # noqa: E731 + self.assertTrue(-180.0 < roll <= 180.0, roll) + worst["aimed"] = max(worst["aimed"], abs(dot - turned(roll))) + worst["terms"] = max(worst["terms"], abs(dot - (C + math.hypot(A, B)))) + worst["beaten"] = max(worst["beaten"], max(turned(float(r)) for r in range(-180, 180)) - dot) + worst["least"] = min(worst["least"], math.hypot(A, B)) + worst["cases"] += 1 + return worst + + def test_aim_is_the_roll_no_other_roll_beats(self): + """aim-closed-form. The dot aim_roll reports is the axis's world dot after core.mate at that roll, is C + hypot(A, B), + and no roll on a 1-degree grid passes it. Mutants R1 (atan2(A, B)) and R6 (B's sign flipped: a left-handed roll).""" + ident = {"name": "s", "matrix": np.eye(4)} + roll, dot = core.aim_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (1.0, 0.0, 0.0)) # the child's y stands at (-sin, cos, 0) + self.assertEqual((round(roll, 9), round(dot, 12)), (-90.0, 1.0)) + roll, dot = core.aim_roll(np.eye(4), ident, ident, (1.0, 0.0, 0.0), (1.0, 1.0, 5.0)) # its x at (-cos, -sin, 0): the pin lets it reach 0.272 of the way + self.assertEqual((round(roll, 9), round(dot, 12)), (-135.0, round(math.sqrt(2.0 / 27.0), 12))) + worst = self.aim_readings() + self.assertEqual(worst["cases"], 80) + self.assertLess(worst["aimed"], self.AIMED) + self.assertLess(worst["terms"], self.AIMED) + self.assertLess(worst["beaten"], self.BEATEN) + + def reach_readings(self): + worst = {"reached": 0.0, "residual": 0.0, "nearer": 0.0, "cases": 0} + for world, sp, sc, rng in self.joints("reach"): + for _ in range(3): + point, d = [rng.uniform(-1, 1) for _ in range(3)], self.direction(rng) + A, B, C = core.roll_terms(world, sp, sc, point, 1.0, d) + swing, middle = math.hypot(A, B), math.degrees(math.atan2(B, A)) + for part in (-0.999, -0.4, 0.0, 0.6, 0.999): + height, current = C + part * swing, rng.uniform(-360, 360) + roll, residual = core.reach_roll(world, sp, sc, point, 2.0 * d, height, current) + stands = float(d @ (world @ core.mate(sp, sc, roll) @ np.array([*point, 1.0]))[:3]) + apart = lambda r: abs((r - current + 180.0) % 360.0 - 180.0) # noqa: E731 + self.assertTrue(-180.0 < roll <= 180.0, roll) + worst["reached"] = max(worst["reached"], abs(stands - height)) + worst["residual"] = max(worst["residual"], abs(residual - abs(stands - height))) + worst["nearer"] = max(worst["nearer"], apart(roll) - apart(2.0 * middle - roll)) # the other root mirrors it about the middle + worst["cases"] += 1 + for beyond in (-1.01, 1.01): + with self.assertRaisesRegex(core.KitError, re.escape(f"it reaches {C - swing:.6g} m to {C + swing:.6g} m")): + core.reach_roll(world, sp, sc, point, d, C + beyond * swing, 0.0) + return worst + + def test_reach_lands_on_the_plane_by_the_nearer_root(self): + """reach-closed-form. The chosen roll puts the point on the plane, it is the root nearer the current roll (a tie takes + the smaller), and a height past the circle is refused with the range. Mutants R2 (the farther root) and R6.""" + ident = {"name": "s", "matrix": np.eye(4)} + reach = lambda height, current: tuple(round(v, 9) for v in core.reach_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (1.0, 0.0, 0.0), height, current)) # noqa: E731 + self.assertEqual(reach(0.5, 0.0), (-30.0, 0.0)) # the point stands at x = -sin(roll): rolls -30 and -150 + self.assertEqual(reach(0.5, 170.0), (-150.0, 0.0)) + self.assertEqual(reach(0.5, -90.0), (-150.0, 0.0)) # a tie + self.assertEqual(reach(0.5, 90.0), (-150.0, 0.0)) # and the tie across the circle + self.assertEqual(reach(0.5, 330.0), (-30.0, 0.0)) # the current roll is read round the circle + with self.assertRaisesRegex(core.KitError, r"no roll brings the point to 1\.5 m along \(1\.0, 0\.0, 0\.0\); it reaches -1 m to 1 m"): + reach(1.5, 0.0) + worst = self.reach_readings() + self.assertEqual(worst["cases"], 300) + self.assertLess(worst["reached"], self.REACHED) + self.assertLess(worst["residual"], self.REACHED) + self.assertLess(worst["nearer"], self.NEARER) + + def floor_readings(self): + """(the largest hypot(A, B) of an axis or a direction along the pin, the least of an axis 1 degree off it).""" + along, least = 0.0, math.inf + for world, sp, sc, rng in self.joints("floor"): + pin_local, pin_world = sc["matrix"][:3, 2], (world @ sp["matrix"])[:3, 2] + side = (world @ sp["matrix"])[:3, 0] + near = math.cos(math.radians(1.0)) * pin_world + math.sin(math.radians(1.0)) * side + for axis, d, refused in ((pin_local, self.direction(rng), True), ((1.0, 0.0, 0.0) if abs(pin_local[0]) < 0.5 else (0.0, 1.0, 0.0), pin_world, True), + ((1.0, 0.0, 0.0) if abs(pin_local[0]) < 0.5 else (0.0, 1.0, 0.0), near, False)): + A, B, _ = core.roll_terms(world, sp, sc, axis, 0.0, d) + if refused: + along = max(along, math.hypot(A, B)) + with self.assertRaisesRegex(core.KitError, "lies along the pin, so no roll turns one toward the other"): + core.aim_roll(world, sp, sc, axis, d) + else: + least = min(least, math.hypot(A, B)) + core.aim_roll(world, sp, sc, axis, d) + return along, least + + def test_aim_along_the_pin_is_refused(self): + """aim-floor. An axis along the pin, or a direction along it, is refused; a direction 1 degree off it is solved. + AIM_FLOOR sits between the two readings by the margin rule. Mutant R5 (no floor: aim along the pin returns a roll).""" + along, least = self.floor_readings() + self.assertLess(along * 1.2, core.AIM_FLOOR) + self.assertGreater(least, core.AIM_FLOOR * 1.2) + self.assertLess(least, 0.0175) # sin(1 degree): the least case the floor is set against + self.assertGreater(min(self.aim_readings()["least"], least), core.AIM_FLOOR * 1.2) + ident = {"name": "s", "matrix": np.eye(4)} + with self.assertRaisesRegex(core.KitError, r"socket 's' on parent socket 's': the axis \(0\.0, 0\.0, 1\.0\) of the part or the direction \(1\.0, 0\.0, 0\.0\) lies along the pin"): + core.aim_roll(np.eye(4), ident, ident, (0.0, 0.0, 1.0), (1.0, 0.0, 0.0)) + + ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", - "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply"] + "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", + "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply"] class HostFileTests(unittest.TestCase): @@ -1016,6 +1154,22 @@ class HostFileTests(unittest.TestCase): for row in self.document["actions"][4:]: self.assertTrue(all(field["type"] in ("string", "number") for field in row["fields"]), row["name"]) + def test_the_pose_rows_take_scalars_inside_their_bounds(self): + host = [{**row, "host": "brokkr_kitbash"} for row in self.document["actions"]] + envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver", "object_name": "Strut"} + roll = {**envelope, "action": "brokkr_kitbash.roll", "roll": -360} + aim = {**envelope, "action": "brokkr_kitbash.aim", "axis": "-y", "direction_x": 0, "direction_y": 0.5, "direction_z": -1} + reach = {**envelope, "action": "brokkr_kitbash.reach", "socket": "end_b", "height": 0.3} + self.assertEqual(at.validate(roll, host)["roll"], -360) + self.assertEqual(at.validate(aim, host)["axis"], "-y") + admitted = at.validate(reach, host) + self.assertEqual((admitted["direction_x"], admitted["direction_y"], admitted["direction_z"], admitted["height"]), (0, 0, 1, 0.3)) + for bad in ({**roll, "roll": 361}, {k: v for k, v in roll.items() if k != "roll"}, {**aim, "axis": "x"}, + {k: v for k, v in aim.items() if k != "direction_z"}, {**aim, "roll": 10}, {**reach, "height": 1e4}, + {**reach, "socket": "end b"}, {k: v for k, v in reach.items() if k != "height"}, {**reach, "direction_z": "up"}): + with self.assertRaises(at.IntentInvalid, msg=str(bad)): + at.validate(bad, host) + class OwnershipTests(unittest.TestCase): """The negative patterns of the cut: expressions are walked and never run, the bridge stays out, core needs no @@ -1062,12 +1216,26 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(body.count("place_cutters("), 0 if body is place else 1) self.assertEqual(source.count("to_mesh("), 1) - def test_only_attach_writes_the_roll(self): - """kit_roll is the one statement of a connection's roll: set_params and the reports read it and never write it back.""" + def test_only_write_connection_writes_the_roll(self): + """one-writer. kit_roll is the one statement of a connection's roll, and write_connection its one writer: attach + and pose (roll, aim and reach) call it; set_params and the reports read the roll and never write it back. + Mutant R7 (attach keeps its own inline write beside write_connection).""" source = self.sources()["__init__.py"] writes = re.findall(r'[^\n]*(?:\[ROLL\]|\["kit_roll"\])\s*=(?!=)[^\n]*', source) - self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated"]) - self.assertIn(writes[0], source.split("class BROKKR_KITBASH_OT_attach")[1].split("class BROKKR_KITBASH_OT_")[0]) + self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated"]) + self.assertIn(writes[0], source.split("def write_connection(")[1].split("\n\n\n")[0]) + bodies = {body.split("(")[0]: body.split("\n\n\n")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:]} + callers = [name for name, body in bodies.items() if "write_connection(" in body] + self.assertEqual((callers, source.count("write_connection("), source.split("def pose(")[1].split("\n\n\n")[0].count("write_connection(")), (["attach"], 3, 1)) + for name in ("roll", "aim", "reach"): + self.assertEqual((bodies[name].count("pose(context, self.object_name, "), bool(re.search(r"\.parent\s*=(?!=)|\bseat\(|matrix_basis", bodies[name]))), (1, False), name) + self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|matrix_basis", bodies["attach"])) + + def test_no_roll_is_searched(self): + """A roll is solved, never scanned: no loop in the package steps a roll.""" + for name in ("__init__.py", "core.py"): + self.assertIsNone(re.search(r"for [^\n]* in range\([^\n]*\):\s*\n[^\n]*roll", self.sources()[name]), name) + self.assertIsNotNone(re.search(r"for [^\n]* in range\([^\n]*\):\s*\n[^\n]*roll", "for k in range(72):\n reroll(child, k * 5)")) def test_only_close_writes_a_closure(self): """A closure is the closing part's three properties: close assigns them, detach deletes them, nothing else does @@ -1085,7 +1253,7 @@ class OwnershipTests(unittest.TestCase): self.assertIsNone(re.search(placing, bodies["close"])) for text in ("child.matrix_basis = basis", "obj.matrix_world = world", "obj.parent = other", "seat(obj, basis)"): self.assertIsNotNone(re.search(placing, text)) - self.assertIsNotNone(re.search(placing, bodies["attach"])) + self.assertIsNotNone(re.search(placing, source.split("def write_connection(")[1].split("\n\n\n")[0])) def test_the_patterns_bite(self): planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name', From c788b9d9b646b2536add275e03f63f74bcb57b47 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 02:25:44 +0100 Subject: [PATCH 088/223] kitbash_pose.py: each metric read before its check, bounds by the margin rule; live result files Bounds set from the shipped readings and nine mutants applied once each to a scratch copy (R1 atan2(A, B), R2 the farther root, R3 roll without the seat, R4 no closures, R5 no aim floor, R6 left-handed roll_terms, R7 attach's inline write kept, R8 the dot without its hypot, R9 sockets swapped in write_connection): every one fails a unit test or a live check by name. kitbash, kitbash_assembly and kitbash_pose result files from Blender 5.3. Co-Authored-By: Claude Fable 5.2 --- .../blender/tests/live/kitbash.result.json | 3 + surfaces/blender/tests/live/kitbash_pose.py | 105 ++++----- .../tests/live/kitbash_pose.result.json | 211 ++++++++++++++++++ 3 files changed, 268 insertions(+), 51 deletions(-) create mode 100644 surfaces/blender/tests/live/kitbash_pose.result.json diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 88be33e..e95d92c 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -412,6 +412,9 @@ "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", + "brokkr_kitbash.roll", + "brokkr_kitbash.aim", + "brokkr_kitbash.reach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", diff --git a/surfaces/blender/tests/live/kitbash_pose.py b/surfaces/blender/tests/live/kitbash_pose.py index 1e58074..8f85a31 100644 --- a/surfaces/blender/tests/live/kitbash_pose.py +++ b/surfaces/blender/tests/live/kitbash_pose.py @@ -57,23 +57,27 @@ target.reload_host_actions() R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}} COUNT = [0] kit = core.load_kit("mechanical") +# Each mutant's reading below is its least over the cases here that it changes; the shipped reading is the worst. # Metres (or a difference of unit vectors) between where a posed part's socket is and where its mate puts it, read -# from the two world matrices. Shipped worst 2.4e-07 (float32 matrices); least claimed mutant 0.24 (R3, roll writes -# kit_roll without seating: the actuator, read against the roll its strut states); separation 1.0e6. -SEATED = 2.4e-4 -# Degrees between the roll read from the two world frames and the roll stated. Shipped worst 1.4e-05; least claimed -# mutant 15 (R3, at the smallest turn here); separation 1.1e6. -ROLL = 1.4e-2 -# Metres between how far the actuator's pin moved and how far the strut's socket that carries it moved. Shipped -# worst 2.4e-07; least claimed mutant 0.38 (R3: the strut's socket is read at the stated roll, the actuator stays). -CARRIED = 3.0e-4 -# The dot aim reports against the dot read from the scene, and its roll (degrees) against core.aim_roll on the -# scene's float32 matrices. Shipped worst 6.0e-08 and 3.4e-06; least claimed mutant 1.0 and 90 (R1); the roll's -# bound is ROLL's. -AIMED = 2.4e-4 -# Metres between the socket reach moved and the plane asked for, read from the scene. Shipped worst 2.4e-07; least -# claimed mutant 0.36 (R6, a left-handed roll_terms: the root it solves is the mirror's). -REACHED = 2.9e-4 +# from the two world matrices. Shipped worst 1.1e-06 (float32 matrices); least claimed mutant 0.25 (R9, +# write_connection seats with the two sockets swapped); separation 2.3e5. +SEATED = 5.2e-4 +# Degrees between the roll read from the two world frames and the roll stated. Shipped worst 8.4e-06; least claimed +# mutant 15 (R3, roll writes kit_roll without seating, at the smallest turn here); separation 1.8e6. +ROLL = 1.1e-2 +# Metres the actuator's pin moves when the strut it hangs from is rolled. Shipped least 0.55 (the 45 degree turn); +# least claimed mutant reads at most 5e-08 (R3: nothing moves); separation 1.1e7. +TURNED = 1.7e-4 +# The dot aim reports against the dot read from the scene, and how far a roll on the 1-degree grid passes the dot +# read. Shipped worst 3.3e-07; least claimed mutant 0.0014 (R6, a left-handed roll_terms, at the aim nearest its +# mirror); R1 (atan2(A, B)) reads 0.81 and R8 (the dot without its hypot) 0.86; separation 4.2e3. +AIMED = 2.1e-5 +# Metres between the socket reach moved and the plane asked for, read from the scene. Shipped worst 2.1e-07; least +# claimed mutant 0.42 (R6); separation 2.0e6. +REACHED = 3.0e-4 +# Degrees the other root stands farther from the roll the part had than the root reach took. A rule, the sign: shipped +# least 74; R2 (the farther root) reads -74. +NEARER = 0.0 def check(name, ok, detail=None): @@ -85,6 +89,11 @@ def reading(name, value): return float(value) +def least(name, value): + R["readings"][name] = min(R["readings"].get(name, math.inf), 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}) @@ -191,52 +200,46 @@ for turn in (65.0, -160.0, 35.0): # from the 20 it was attached at was, pin, before = stated(strut), frame(ram, "base")[:3, 3].copy(), (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) sent = COUNT[0] receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=turn) - carried = frame(strut, "end_b")[:3, 3] - pin # where the socket that carries the actuator stands now, from where the actuator's pin was + gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", turn)), R["readings"]["roll"] check(f"roll {turn:g} turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated", - receipt["status"] == "accepted" and COUNT[0] == sent + 1 and stated(strut) == was and strut["kit_roll"] == turn - and reading("seated", seated(strut, "end_a", mount, "pivot", turn)) < SEATED and R["readings"]["roll"] < ROLL + receipt["status"] == "accepted" and COUNT[0] == sent + 1 and stated(strut) == was and strut["kit_roll"] == turn and gap < SEATED and off < ROLL and report and report["object"] == "Strut" and holds(report["connection"], "Mount", "end_a", "pivot", turn) and holds(connection("Strut"), "Mount", "end_a", "pivot", turn), - [receipt["message"], report and report["connection"], R["readings"]]) + [receipt["message"], report and report["connection"], gap, off]) + moved, gap = least("turned", float(np.linalg.norm(frame(ram, "base")[:3, 3] - pin))), reading("seated", seated(ram, "base", strut, "end_b", -35.0)) check(f"and the actuator follows through its own connection, which nothing rewrote (roll {turn:g})", - (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) == before and float(np.linalg.norm(carried)) > 0.1 - and reading("carried", np.abs(frame(ram, "base")[:3, 3] - pin - carried).max()) < CARRIED - and reading("seated", seated(ram, "base", strut, "end_b", -35.0)) < SEATED and R["readings"]["roll"] < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -35.0), - [carried.tolist(), connection("Ram"), R["readings"]]) - reading("turned", float(np.linalg.norm(carried))) + (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) == before and moved > TURNED and gap < SEATED and R["readings"]["roll"] < ROLL + and holds(connection("Ram"), "Strut", "base", "end_b", -35.0), [moved, gap, connection("Ram"), R["readings"]]) # --- roll: the closures it opens ---------------------------------------------------------------------------------------- -check("the rolls above opened the brace's closure and reported it before the one that holds, whatever its name", report and report.get("closures") == [ +check("the rolls above opened the brace's closure and reported it before the one that holds, whatever its name", (report or {}).get("closures") == [ {"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] and report["closure"] is None, report and report.get("closures")) receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=20.0) -check("rolled back to where the brace met it, the closure holds again: read from where the parts stand", receipt["status"] == "accepted" and report["closures"] == [ +check("rolled back to where the brace met it, the closure holds again: read from where the parts stand", receipt["status"] == "accepted" and (report or {}).get("closures") == [ {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}, {"part": "Brace", "to": "Ram", "holds": True}], report and report.get("closures")) send("setObjectTransform", targetObjectName="Aa_Loose", location=[0.0, -25.0, 0.0], rotationEuler=[0.0, 0.0, 0.0]) receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-35.0) -check("a roll lists the closures its own part is an end of first, before a broken one elsewhere", receipt["status"] == "accepted" and report["closures"] == [ +check("a roll lists the closures its own part is an end of first, before a broken one elsewhere", receipt["status"] == "accepted" and (report or {}).get("closures") == [ {"part": "Brace", "to": "Ram", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}], report and report.get("closures")) receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-36.0) -check("and a roll of the part a closure names opens it; no roll seats or rewrites a closure", receipt["status"] == "accepted" and report["closures"] == [ +check("and a roll of the part a closure names opens it; no roll seats or rewrites a closure", receipt["status"] == "accepted" and (report or {}).get("closures") == [ {"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}] and {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} == closing and brace.parent is None, [report and report.get("closures"), dict(brace.items())]) # --- aim ---------------------------------------------------------------------------------------------------------------- for axis, direction in (("+z", (1.0, 0.0, 0.0)), ("-x", (0.0, -3.0, 4.0)), ("+z", (0.2, 0.1, -2.0))): - world = np.array(mount.matrix_world, dtype=np.float64) - want, dot = core.aim_roll(world, socket(mount, "pivot"), socket(strut, "end_a"), core.AXES[axis], direction) + world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction) receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis=axis, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2]) aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9} - read = float(np.array(strut.matrix_world, dtype=np.float64)[:3, :3] @ np.array(core.AXES[axis]) @ (np.array(direction) / np.linalg.norm(direction))) - grid = max(float((world @ core.mate(socket(mount, "pivot"), socket(strut, "end_a"), float(r)))[:3, :3] @ np.array(core.AXES[axis]) @ (np.array(direction) / np.linalg.norm(direction))) - for r in range(-180, 180)) - check(f"aim points the strut's {axis} at {direction} as far as its pin lets it: the dot core solves, the dot the scene reads, and no roll on a 1-degree grid passes it", - receipt["status"] == "accepted" and reading("aimed roll", abs((aimed["roll"] - want + 180.0) % 360.0 - 180.0)) < ROLL - and reading("aimed dot", max(abs(aimed["dot"] - dot), abs(aimed["dot"] - read))) < AIMED and grid < aimed["dot"] + AIMED and 0.2 < aimed["dot"] < 0.999, - [receipt["message"], aimed, want, dot, read, grid]) + read = float(np.array(strut.matrix_world, dtype=np.float64)[:3, :3] @ np.array(core.AXES[axis]) @ unit) + grid = max(float((world @ core.mate(socket(mount, "pivot"), socket(strut, "end_a"), float(r)))[:3, :3] @ np.array(core.AXES[axis]) @ unit) for r in range(-180, 180)) + apart, short = reading("aimed", abs(aimed["dot"] - read)), reading("aimed short", max(grid - read, 0.0)) + check(f"aim points the strut's {axis} at {direction} as far as its pin lets it: the dot it reports is the dot the scene reads, and no roll on a 1-degree grid passes it", + receipt["status"] == "accepted" and apart < AIMED and short < AIMED and 0.2 < aimed["dot"] < 0.999, [receipt["message"], aimed, read, grid]) + gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", aimed["roll"])), R["readings"]["roll"] check(f"and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported ({axis})", - aimed["roll"] == round(strut["kit_roll"], 6) and -180.0 < aimed["roll"] <= 180.0 - and holds(report and report["connection"], "Mount", "end_a", "pivot", aimed["roll"]) and reading("seated", seated(strut, "end_a", mount, "pivot", aimed["roll"])) < SEATED - and R["readings"]["roll"] < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len(report.get("closures", [])) == 2, - [dict(strut.items()), report and report["connection"], report and report.get("closures")]) + aimed["roll"] == round(strut["kit_roll"], 6) and -180.0 < aimed["roll"] <= 180.0 and holds(report and report["connection"], "Mount", "end_a", "pivot", aimed["roll"]) + and gap < SEATED and off < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2, + [dict(strut.items()), report and report["connection"], report and report.get("closures"), gap, off]) # --- reach -------------------------------------------------------------------------------------------------------------- for direction, part, offset in (((0.0, 0.0, 1.0), 0.5, 40.0), ((0.0, 0.0, 1.0), 0.5, -40.0), ((1.0, 2.0, -0.5), -0.8, 100.0)): @@ -245,20 +248,20 @@ for direction, part, offset in (((0.0, 0.0, 1.0), 0.5, 40.0), ((0.0, 0.0, 1.0), current = float(round(math.degrees(math.atan2(B, A)) + offset)) # the two rolls that reach stand either side of the middle: start nearer one send("brokkr_kitbash.roll", object_name="Strut", roll=current) height = round(C + part * math.hypot(A, B), 3) - want, _ = core.reach_roll(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], unit, height, current) - other = (2.0 * math.degrees(math.atan2(B, A)) - want + 180.0) % 360.0 - 180.0 fields = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} if direction != (0.0, 0.0, 1.0) else {} # world z is the default receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=height, **fields) reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9} + apart = lambda roll: abs((roll - current + 180.0) % 360.0 - 180.0) # noqa: E731 + off_plane = reading("reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - height)) + farther = least("reach other root", apart(2.0 * math.degrees(math.atan2(B, A)) - reached["roll"]) - apart(reached["roll"])) # the other root mirrors it about the middle check(f"reach brings the strut's end_b to {height} m along {direction} from roll {current:g}, by the nearer of the two rolls that do", - receipt["status"] == "accepted" and reading("reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - height)) < REACHED and reached["residual"] < REACHED - and reading("reached roll", abs((reached["roll"] - want + 180.0) % 360.0 - 180.0)) < ROLL - and abs((want - current + 180.0) % 360.0 - 180.0) + 10.0 < abs((other - current + 180.0) % 360.0 - 180.0), - [receipt["message"], reached, want, other, float(frame(strut, "end_b")[:3, 3] @ unit)]) + receipt["status"] == "accepted" and off_plane < REACHED and reached["residual"] < REACHED and farther > NEARER, + [receipt["message"], reached, off_plane, farther]) + gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", reached["roll"])), R["readings"]["roll"] check(f"and it is stated and seated as roll's ({direction}, from {current:g})", reached["roll"] == round(strut["kit_roll"], 6) and -180.0 < reached["roll"] <= 180.0 - and holds(report and report["connection"], "Mount", "end_a", "pivot", reached["roll"]) and reading("seated", seated(strut, "end_a", mount, "pivot", reached["roll"])) < SEATED - and R["readings"]["roll"] < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len(report.get("closures", [])) == 2, - [dict(strut.items()), report and report["connection"]]) + and holds(report and report["connection"], "Mount", "end_a", "pivot", reached["roll"]) and gap < SEATED and off < ROLL + and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2, + [dict(strut.items()), report and report["connection"], gap, off]) # --- refusals ----------------------------------------------------------------------------------------------------------- send("setObjectParent", targetObjectName="Orphan", parentObjectName="") diff --git a/surfaces/blender/tests/live/kitbash_pose.result.json b/surfaces/blender/tests/live/kitbash_pose.result.json new file mode 100644 index 0000000..828054c --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_pose.result.json @@ -0,0 +1,211 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "roll, aim and reach load as host actions after detach, with no errors", + "ok": true, + "detail": null + }, + { + "name": "the chain stands: tank, bracket, strut, actuator", + "ok": true, + "detail": null + }, + { + "name": "a brace closes on the actuator's rod pin", + "ok": true, + "detail": null + }, + { + "name": "and a second closure, named to sort first, holds far from it", + "ok": true, + "detail": null + }, + { + "name": "roll 65 turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated", + "ok": true, + "detail": null + }, + { + "name": "and the actuator follows through its own connection, which nothing rewrote (roll 65)", + "ok": true, + "detail": null + }, + { + "name": "roll -160 turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated", + "ok": true, + "detail": null + }, + { + "name": "and the actuator follows through its own connection, which nothing rewrote (roll -160)", + "ok": true, + "detail": null + }, + { + "name": "roll 35 turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated", + "ok": true, + "detail": null + }, + { + "name": "and the actuator follows through its own connection, which nothing rewrote (roll 35)", + "ok": true, + "detail": null + }, + { + "name": "the rolls above opened the brace's closure and reported it before the one that holds, whatever its name", + "ok": true, + "detail": null + }, + { + "name": "rolled back to where the brace met it, the closure holds again: read from where the parts stand", + "ok": true, + "detail": null + }, + { + "name": "a roll lists the closures its own part is an end of first, before a broken one elsewhere", + "ok": true, + "detail": null + }, + { + "name": "and a roll of the part a closure names opens it; no roll seats or rewrites a closure", + "ok": true, + "detail": null + }, + { + "name": "aim points the strut's +z at (1.0, 0.0, 0.0) as far as its pin lets it: the dot it reports is the dot the scene reads, and no roll on a 1-degree grid passes it", + "ok": true, + "detail": null + }, + { + "name": "and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported (+z)", + "ok": true, + "detail": null + }, + { + "name": "aim points the strut's -x at (0.0, -3.0, 4.0) as far as its pin lets it: the dot it reports is the dot the scene reads, and no roll on a 1-degree grid passes it", + "ok": true, + "detail": null + }, + { + "name": "and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported (-x)", + "ok": true, + "detail": null + }, + { + "name": "aim points the strut's +z at (0.2, 0.1, -2.0) as far as its pin lets it: the dot it reports is the dot the scene reads, and no roll on a 1-degree grid passes it", + "ok": true, + "detail": null + }, + { + "name": "and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported (+z)", + "ok": true, + "detail": null + }, + { + "name": "reach brings the strut's end_b to 4.23 m along (0.0, 0.0, 1.0) from roll -38, by the nearer of the two rolls that do", + "ok": true, + "detail": null + }, + { + "name": "and it is stated and seated as roll's ((0.0, 0.0, 1.0), from -38)", + "ok": true, + "detail": null + }, + { + "name": "reach brings the strut's end_b to 4.23 m along (0.0, 0.0, 1.0) from roll -118, by the nearer of the two rolls that do", + "ok": true, + "detail": null + }, + { + "name": "and it is stated and seated as roll's ((0.0, 0.0, 1.0), from -118)", + "ok": true, + "detail": null + }, + { + "name": "reach brings the strut's end_b to 0.885 m along (1.0, 2.0, -0.5) from roll 135, by the nearer of the two rolls that do", + "ok": true, + "detail": null + }, + { + "name": "and it is stated and seated as roll's ((1.0, 2.0, -0.5), from 135)", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: roll of a part nobody attached", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: aim of a part nobody attached", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: reach of a part nobody attached", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: roll of a part whose parent was cleared", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: roll of a mesh that is not a kit part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: aim of the axis along the pin", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: aim at no direction", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: reach past the circle the socket turns on, naming what it reaches", + "ok": true, + "detail": null + }, + { + "name": "and the range it names is the one core solves", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: reach with a socket the part does not have", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: reach along no direction", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a roll past a turn, by the action table", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an axis that is not one of the six, by the action table", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "readings": { + "aimed": 3.3e-07, + "aimed short": 0.0, + "reach other root": 74.0, + "reached": 2.1e-07, + "roll": 8.4e-06, + "seated": 1.1e-06, + "turned": 0.55 + }, + "ok": true +} \ No newline at end of file From fb3382a923fda5d0748e0acb9cf78370ca9cfa45 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 04:31:37 +0100 Subject: [PATCH 089/223] brokkr_kitbash: aim's floor matched to float32 scenes; reach takes the edge of its circle and refuses a socket on the pin AIM_FLOOR 1.5e-9 was set against float64 rounding, but a scene's matrices and an action's fields are float32: the pin's own direction, as the scene holds it or typed at 6 or 4 decimals, was aimed at and swung the part to an arbitrary roll. The floor is 1e-3, the geometric mean of the 4 decimal reading (6.2e-5) and a direction 1 degree off the pin (0.0175). reach takes a height up to REACH_EDGE (1e-5 m, HELD) past the top or bottom of the circle as the top or bottom, so the range a refusal names (now 6 decimals) can be typed back; a socket on the pin, or a direction along it, is refused instead of dividing by a zero swing. Half a turn is pinned as 180. Soul's verdict cut-kit-roll-aim.s1: findings aim-floor-below-float32-noise and reach-exact-edge-refused-and-unpinned; survivors S6, S7, S8. Co-Authored-By: Claude Fable 5.2 --- .../brokkr_kitbash/brokkr_actions.json | 4 +- surfaces/blender/brokkr_kitbash/core.py | 38 ++++-- surfaces/blender/docs/kitbash.md | 13 +- surfaces/blender/tests/live/kitbash_pose.py | 21 +++- .../tests/live/kitbash_pose.result.json | 37 ++++++ surfaces/blender/tests/test_kitbash.py | 114 ++++++++++++++---- 6 files changed, 188 insertions(+), 39 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index e134ef2..99fd330 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -201,7 +201,7 @@ }, { "name": "brokkr_kitbash.aim", - "doc": "Turn an attached kit part about its pin until one of its own axes points as near a world direction as the pin lets it. The roll is solved exactly, not searched. Refuses an axis or a direction that lies along the pin, and a zero direction. Reports the part, aimed: {roll, dot} (dot 1 when the axis reaches the direction) and closures as roll does.", + "doc": "Turn an attached kit part about its pin until one of its own axes points as near a world direction as the pin lets it. The roll is solved exactly, not searched. Refuses an axis or a direction that lies along the pin (within about 0.06 degrees), and a zero direction. Reports the part, aimed: {roll, dot} (dot 1 when the axis reaches the direction) and closures as roll does.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -254,7 +254,7 @@ }, { "name": "brokkr_kitbash.reach", - "doc": "Turn an attached kit part about its pin until one of its sockets' origins stands at a height along a world direction (by default world z): of the two rolls that do it, the one nearer the roll it has. Solved exactly. Refuses a height the socket cannot reach, naming the range it can. Reports the part, reached: {roll, residual} and closures as roll does.", + "doc": "Turn an attached kit part about its pin until one of its sockets' origins stands at a height along a world direction (by default world z): of the two rolls that do it, the one nearer the roll it has. Solved exactly. Refuses a height the socket cannot reach, naming the range it can (either end of the range is taken), and a socket that lies on the pin. Reports the part, reached: {roll, residual} and closures as roll does.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 736fbff..f41c8a8 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -655,10 +655,19 @@ def roll_terms(parent_world, parent_socket: dict, child_socket: dict, local, w: return (float(e[0] * q[0] + e[1] * q[1]), float(e[1] * q[0] - e[0] * q[1]), float(e[2] * q[2] + w * (direction @ M[:3, 3]))) -# The least hypot(A, B) aim_roll solves for: below it the axis or the direction lies along the pin and no roll turns -# one toward the other. Least aimable case of the tests 0.0175 (a direction 1 degree off the pin); a degenerate case -# reads at most 1.2e-16 (float rounding of an axis along the pin); the geometric mean, separation 1.2e7 each side. -AIM_FLOOR = 1.5e-9 +# The least hypot(A, B) aim_roll solves for: at or below it the axis or the direction lies along the pin, as nearly as +# the scene can say, and no roll turns one toward the other. A scene's matrices and an action's fields are float32 +# and a direction read from a report has 6 decimals or fewer, so "along the pin" is never exact: the worst reading +# of the tests for a pin direction through a float32 world, as float32, at 6 and at 4 decimals is 6.2e-05 (the 4 +# decimal case); the least aimable case is 0.0175 (a direction 1 degree off the pin). The geometric mean, +# separation 17 each side: a direction within about 0.06 degrees of the pin is refused. +AIM_FLOOR = 1e-3 +# How far past the top or bottom of its circle a reach may ask, in metres: such a height is taken as the top or +# bottom, and the residual says how far off the socket stands. A rule, the add-on's HELD: a height typed back from +# the range a refusal names (6 decimals, through a float32 field) is within 6.5e-07 of it in the tests, and float32 +# steps 1e-06 for parts within 16 m of the origin. A socket whose circle is this small lies on the pin: no roll +# moves it. +REACH_EDGE = 1e-5 def _wrapped(degrees: float) -> float: @@ -669,7 +678,7 @@ def _wrapped(degrees: float) -> float: def aim_roll(parent_world, parent_socket: dict, child_socket: dict, axis, direction) -> tuple[float, float]: """(roll in degrees in (-180, 180], the dot it achieves) that turns the child's own `axis` as far toward the world `direction` as its pin lets it: roll = atan2(B, A), dot = C + hypot(A, B), for unit vectors. Refuses an - axis or a direction along the pin, which no roll turns.""" + axis or a direction along the pin (hypot(A, B) at most AIM_FLOOR), which no roll turns.""" direction = np.asarray(direction, dtype=np.float64) direction = direction / np.linalg.norm(direction) A, B, C = roll_terms(parent_world, parent_socket, child_socket, axis, 0.0, direction) @@ -682,16 +691,21 @@ def aim_roll(parent_world, parent_socket: dict, child_socket: dict, axis, direct def reach_roll(parent_world, parent_socket: dict, child_socket: dict, point, direction, height: float, current_roll: float) -> tuple[float, float]: """(roll in degrees in (-180, 180], residual |direction . p - height| in metres) that brings the child's own `point` to the plane direction . x = height, for a unit direction: atan2(B, A) +- acos((height - C) / hypot(A, B)), - of the two the one nearer current_roll round the circle (a tie takes the smaller roll). Refuses a height the - point cannot reach, naming the range it can.""" + of the two the one nearer current_roll round the circle (a tie takes the smaller roll). A height up to REACH_EDGE + past the top or bottom of the circle is taken as the top or bottom. Refuses a height farther out, naming the + range the point reaches, and a point no roll moves along the direction (it lies on the pin, or the direction + does).""" direction = np.asarray(direction, dtype=np.float64) direction = direction / np.linalg.norm(direction) A, B, C = roll_terms(parent_world, parent_socket, child_socket, point, 1.0, direction) - swing = math.hypot(A, B) - if abs(height - C) > swing: - raise KitError(f"socket {child_socket['name']!r} on parent socket {parent_socket['name']!r}: no roll brings the point to {height:.6g} m along " - f"{tuple(round(float(v), 6) for v in direction)}; it reaches {C - swing:.6g} m to {C + swing:.6g} m") - middle, spread = math.degrees(math.atan2(B, A)), math.degrees(math.acos((height - C) / swing)) if swing > 0 else 0.0 + swing, here = math.hypot(A, B), f"socket {child_socket['name']!r} on parent socket {parent_socket['name']!r}" + if swing <= REACH_EDGE: + raise KitError(f"{here}: no roll moves the point along {tuple(round(float(v), 6) for v in direction)}: it lies on the pin, or the direction " + f"runs along it; it stays at {C:.6f} m") + if abs(height - C) > swing + REACH_EDGE: + raise KitError(f"{here}: no roll brings the point to {height:.6f} m along {tuple(round(float(v), 6) for v in direction)}; " + f"it reaches {C - swing:.6f} m to {C + swing:.6f} m") + middle, spread = math.degrees(math.atan2(B, A)), math.degrees(math.acos(max(-1.0, min(1.0, (height - C) / swing)))) roots = sorted({_wrapped(middle - spread), _wrapped(middle + spread)}) roll = min(roots, key=lambda root: (round(abs(_wrapped(root - current_roll)), 9), root)) return roll, abs(A * math.cos(math.radians(roll)) + B * math.sin(math.radians(roll)) + C - height) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index a90d1d8..f6070d6 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -207,8 +207,17 @@ re-aims it. They refuse, changing nothing: a part that states no connection (`attach` it first), one whose parent was cleared, a connection `attach` would refuse now (sockets that no longer mate), a zero direction, an `aim` whose -axis or direction lies along the pin (no roll turns one toward the other), and a `reach` to a height the socket's -circle does not cross, naming the range it does. A leg is posed with them from the hip down: `aim` the yoke's +axis or direction lies along the pin (no roll turns one toward the other), a `reach` with a socket that lies on +the pin or a direction along it (no roll moves it), and a `reach` to a height the socket's circle does not cross, +naming the range it does. + +A scene's matrices and an action's fields are float32, and a direction read from a report has 6 decimals, so +neither test is exact. "Along the pin" is `hypot(A, B)` at most 1e-3 (`core.AIM_FLOOR`): a direction within about +0.06 degrees of the pin, which covers the pin's own direction read from a report and typed at 4 decimals. A +`reach` to a height up to 1e-5 m past the top or bottom of the circle (`core.REACH_EDGE`) is taken as the top or +bottom, so the range a refusal names can be typed back; `residual` then says how far short the socket stands. + +A leg is posed with them from the hip down: `aim` the yoke's front at where the leg should point, `reach` the last link's clevis to the ground plus the foot's drop, `aim` the foot's sole at the ground. Each reports `closures` as `set_params` does, the part's own first: a roll moves everything below the part, can open a closure anywhere there, and never seats one. diff --git a/surfaces/blender/tests/live/kitbash_pose.py b/surfaces/blender/tests/live/kitbash_pose.py index 8f85a31..95d0b3d 100644 --- a/surfaces/blender/tests/live/kitbash_pose.py +++ b/surfaces/blender/tests/live/kitbash_pose.py @@ -78,6 +78,9 @@ REACHED = 3.0e-4 # Degrees the other root stands farther from the roll the part had than the root reach took. A rule, the sign: shipped # least 74; R2 (the farther root) reads -74. NEARER = 0.0 +# Metres past the top of its circle a reach may ask (core.REACH_EDGE, a rule: HELD). A height typed back from a +# refusal's range overshoots by at most 3.2e-07 here and is taken; PAST is refused. The two sit sqrt(10) either side. +EDGE, PAST = 1e-5, 3.2e-5 def check(name, ok, detail=None): @@ -276,9 +279,23 @@ refused("aim of the axis along the pin", "brokkr_kitbash.aim", {"object_name": " refused("aim at no direction", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+z", "direction_x": 0.0, "direction_y": 0.0, "direction_z": 0.0}, "The direction is zero") refused("reach past the circle the socket turns on, naming what it reaches", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": 900.0, "direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]}, - f"no roll brings the point to 900 m along ({unit[0]:.6f}".rstrip("0")) + f"no roll brings the point to 900.000000 m along ({unit[0]:.6f}".rstrip("0")) receipt, _ = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=900.0, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2]) -check("and the range it names is the one core solves", f"it reaches {low:.6g} m to {high:.6g} m" in str(receipt["message"]) and high - low > 1.0, [receipt["message"], low, high]) +check("and the range it names is the one core solves", f"it reaches {low:.6f} m to {high:.6f} m" in str(receipt["message"]) and high - low > 1.0, [receipt["message"], low, high]) +skew = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} +refused("reach a little past the top it names", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": float(f"{high:.6f}") + PAST, **skew}, "no roll brings the point to") +receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=float(f"{high:.6f}"), **skew) +reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9} +over, stands = reading("edge typed past", max(float(np.float32(f"{high:.6f}")) - high, 0.0)), reading("edge reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - high)) +check("reach to the top of the circle, typed back from the range the refusal named, is taken: the socket stands at the top", receipt["status"] == "accepted" + and reached["residual"] <= EDGE and over <= EDGE and stands < REACHED and holds(report["connection"], "Mount", "end_a", "pivot", reached["roll"]), + [receipt["message"], reached, over, stands, high]) +refused("reach with the socket the part hangs by: it lies on the pin", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_a", "height": 0.0}, + "'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': no roll moves the point along (0.0, 0.0, 1.0): it lies on the pin") +pin = np.array(mount.matrix_world, dtype=np.float64) @ socket(mount, "pivot")["matrix"] +for label, along in (("as the scene holds it", pin[:3, 2]), ("to 6 decimals", np.round(pin[:3, 2], 6)), ("to 4 decimals", np.round(pin[:3, 2], 4)), ("reversed, to 4 decimals", -np.round(pin[:3, 2], 4))): + refused(f"aim at the pin's own direction {label}", "brokkr_kitbash.aim", + {"object_name": "Strut", "axis": "+z", "direction_x": float(along[0]), "direction_y": float(along[1]), "direction_z": float(along[2])}, "lies along the pin, so no roll turns one toward the other") refused("reach with a socket the part does not have", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_c", "height": 0.0}, "'Strut' has no socket 'end_c'; its sockets: end_a, end_a_back, end_b, end_b_back") refused("reach along no direction", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": 0.0, "direction_z": 0.0}, "The direction is zero") diff --git a/surfaces/blender/tests/live/kitbash_pose.result.json b/surfaces/blender/tests/live/kitbash_pose.result.json index 828054c..ea72302 100644 --- a/surfaces/blender/tests/live/kitbash_pose.result.json +++ b/surfaces/blender/tests/live/kitbash_pose.result.json @@ -176,6 +176,41 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: reach a little past the top it names", + "ok": true, + "detail": null + }, + { + "name": "reach to the top of the circle, typed back from the range the refusal named, is taken: the socket stands at the top", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: reach with the socket the part hangs by: it lies on the pin", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: aim at the pin's own direction as the scene holds it", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: aim at the pin's own direction to 6 decimals", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: aim at the pin's own direction to 4 decimals", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: aim at the pin's own direction reversed, to 4 decimals", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: reach with a socket the part does not have", "ok": true, @@ -201,6 +236,8 @@ "readings": { "aimed": 3.3e-07, "aimed short": 0.0, + "edge reached": 2.6e-08, + "edge typed past": 3.2e-07, "reach other root": 74.0, "reached": 2.1e-07, "roll": 8.4e-06, diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 4f14425..e29e1d3 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1006,6 +1006,7 @@ class PoseTests(unittest.TestCase): self.assertEqual((round(roll, 9), round(dot, 12)), (-90.0, 1.0)) roll, dot = core.aim_roll(np.eye(4), ident, ident, (1.0, 0.0, 0.0), (1.0, 1.0, 5.0)) # its x at (-cos, -sin, 0): the pin lets it reach 0.272 of the way self.assertEqual((round(roll, 9), round(dot, 12)), (-135.0, round(math.sqrt(2.0 / 27.0), 12))) + self.assertEqual(core.aim_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (0.0, -1.0, 0.0)), (180.0, 1.0)) # half a turn is 180, never -180 (S6) worst = self.aim_readings() self.assertEqual(worst["cases"], 80) self.assertLess(worst["aimed"], self.AIMED) @@ -1030,7 +1031,7 @@ class PoseTests(unittest.TestCase): worst["nearer"] = max(worst["nearer"], apart(roll) - apart(2.0 * middle - roll)) # the other root mirrors it about the middle worst["cases"] += 1 for beyond in (-1.01, 1.01): - with self.assertRaisesRegex(core.KitError, re.escape(f"it reaches {C - swing:.6g} m to {C + swing:.6g} m")): + with self.assertRaisesRegex(core.KitError, re.escape(f"it reaches {C - swing:.6f} m to {C + swing:.6f} m")): core.reach_roll(world, sp, sc, point, d, C + beyond * swing, 0.0) return worst @@ -1044,7 +1045,10 @@ class PoseTests(unittest.TestCase): self.assertEqual(reach(0.5, -90.0), (-150.0, 0.0)) # a tie self.assertEqual(reach(0.5, 90.0), (-150.0, 0.0)) # and the tie across the circle self.assertEqual(reach(0.5, 330.0), (-30.0, 0.0)) # the current roll is read round the circle - with self.assertRaisesRegex(core.KitError, r"no roll brings the point to 1\.5 m along \(1\.0, 0\.0, 0\.0\); it reaches -1 m to 1 m"): + self.assertEqual(reach(0.0, 170.0), (180.0, 0.0)) # rolls 0 and 180: half a turn is 180, never -180 (mutant S6, the wrap's other end) + self.assertEqual(reach(0.0, -170.0), (180.0, 0.0)) + self.assertEqual([core._wrapped(v) for v in (-180.0, 180.0, 540.0, -179.0, 0.0, 359.0)], [180.0, 180.0, 180.0, -179.0, 0.0, -1.0]) + with self.assertRaisesRegex(core.KitError, r"no roll brings the point to 1\.500000 m along \(1\.0, 0\.0, 0\.0\); it reaches -1\.000000 m to 1\.000000 m"): reach(1.5, 0.0) worst = self.reach_readings() self.assertEqual(worst["cases"], 300) @@ -1053,36 +1057,104 @@ class PoseTests(unittest.TestCase): self.assertLess(worst["nearer"], self.NEARER) def floor_readings(self): - """(the largest hypot(A, B) of an axis or a direction along the pin, the least of an axis 1 degree off it).""" - along, least = 0.0, math.inf + """(the largest hypot(A, B) of an axis along the pin or a direction along it in doubles; the largest for the pin's + direction as a scene gives it: through a float32 world, as float32, at 6 and at 4 decimals; the least of a + direction 1 degree off the pin, through the same float32 world).""" + along, scene, least = 0.0, 0.0, math.inf for world, sp, sc, rng in self.joints("floor"): pin_local, pin_world = sc["matrix"][:3, 2], (world @ sp["matrix"])[:3, 2] - side = (world @ sp["matrix"])[:3, 0] - near = math.cos(math.radians(1.0)) * pin_world + math.sin(math.radians(1.0)) * side - for axis, d, refused in ((pin_local, self.direction(rng), True), ((1.0, 0.0, 0.0) if abs(pin_local[0]) < 0.5 else (0.0, 1.0, 0.0), pin_world, True), - ((1.0, 0.0, 0.0) if abs(pin_local[0]) < 0.5 else (0.0, 1.0, 0.0), near, False)): - A, B, _ = core.roll_terms(world, sp, sc, axis, 0.0, d) - if refused: - along = max(along, math.hypot(A, B)) - with self.assertRaisesRegex(core.KitError, "lies along the pin, so no roll turns one toward the other"): - core.aim_roll(world, sp, sc, axis, d) - else: + other = (1.0, 0.0, 0.0) if abs(pin_local[0]) < 0.5 else (0.0, 1.0, 0.0) # an axis of the child across its pin + single = world.astype(np.float32).astype(np.float64) # the parent's matrix_world as Blender holds it + near = math.cos(math.radians(1.0)) * pin_world + math.sin(math.radians(1.0)) * (world @ sp["matrix"])[:3, 0] + for frame, axis, d, kind in ((world, pin_local, self.direction(rng), "along"), (world, other, pin_world, "along"), + (single, other, pin_world.astype(np.float32).astype(np.float64), "scene"), + (single, other, np.round(pin_world, 6).astype(np.float32).astype(np.float64), "scene"), + (single, other, np.round(pin_world, 4).astype(np.float32).astype(np.float64), "scene"), + (single, other, near.astype(np.float32).astype(np.float64), "near")): + A, B, _ = core.roll_terms(frame, sp, sc, axis, 0.0, d / np.linalg.norm(d)) + if kind == "near": least = min(least, math.hypot(A, B)) - core.aim_roll(world, sp, sc, axis, d) - return along, least + core.aim_roll(frame, sp, sc, axis, d) + continue + along, scene = (max(along, math.hypot(A, B)), scene) if kind == "along" else (along, max(scene, math.hypot(A, B))) + with self.assertRaisesRegex(core.KitError, "lies along the pin, so no roll turns one toward the other", msg=f"{kind} {d}"): + core.aim_roll(frame, sp, sc, axis, d) + return along, scene, least def test_aim_along_the_pin_is_refused(self): - """aim-floor. An axis along the pin, or a direction along it, is refused; a direction 1 degree off it is solved. - AIM_FLOOR sits between the two readings by the margin rule. Mutant R5 (no floor: aim along the pin returns a roll).""" - along, least = self.floor_readings() - self.assertLess(along * 1.2, core.AIM_FLOOR) + """aim-floor. An axis along the pin, or a direction along it as a scene can give it (a float32 world, the pin as + float32, at 6 and at 4 decimals), is refused; a direction 1 degree off it is solved. AIM_FLOOR sits between the + two readings by the margin rule. Mutants R5 (no floor) and E4 (the floor at float64 rounding, 1.5e-9).""" + along, scene, least = self.floor_readings() + self.assertLess(along, 1e-15) + self.assertGreater(scene, 2e-5) # the 4 decimal pin: far above float64 rounding, so the floor is set against it + self.assertLess(scene * 1.2, core.AIM_FLOOR) self.assertGreater(least, core.AIM_FLOOR * 1.2) - self.assertLess(least, 0.0175) # sin(1 degree): the least case the floor is set against + self.assertLess(least, 0.0175) # sin(1 degree): the least case the floor is set against self.assertGreater(min(self.aim_readings()["least"], least), core.AIM_FLOOR * 1.2) ident = {"name": "s", "matrix": np.eye(4)} with self.assertRaisesRegex(core.KitError, r"socket 's' on parent socket 's': the axis \(0\.0, 0\.0, 1\.0\) of the part or the direction \(1\.0, 0\.0, 0\.0\) lies along the pin"): core.aim_roll(np.eye(4), ident, ident, (0.0, 0.0, 1.0), (1.0, 0.0, 0.0)) + def edge_readings(self): + """Reach asked for the top and bottom of its circle: exactly, as typed back from a refusal (6 decimals through + float32), 0.32 of REACH_EDGE past and 3.2 of it past (the two sit sqrt(10) either side of the rule).""" + worst = {"exact": 0.0, "typed": 0.0, "typed past": 0.0, "inside": 0.0, "cases": 0} + for world, sp, sc, rng in self.joints("edge"): + for _ in range(3): + point, d = [rng.uniform(-1, 1) for _ in range(3)], self.direction(rng) + A, B, C = core.roll_terms(world, sp, sc, point, 1.0, d) + swing, middle = math.hypot(A, B), math.degrees(math.atan2(B, A)) + for sign in (1.0, -1.0): + end = core._wrapped(middle if sign > 0 else middle + 180.0) # the one roll at the top, or at the bottom + roll, residual = core.reach_roll(world, sp, sc, point, d, C + sign * swing, rng.uniform(-360, 360)) + worst["exact"] = max(worst["exact"], residual, abs(core._wrapped(roll - end)) * 1e-9) + typed = float(np.float32(f"{C + sign * swing:.6f}")) + roll, residual = core.reach_roll(world, sp, sc, point, d, typed, 0.0) + worst["typed"] = max(worst["typed"], residual) + worst["typed past"] = max(worst["typed past"], sign * (typed - C) - swing) + roll, residual = core.reach_roll(world, sp, sc, point, d, C + sign * (swing + 0.32 * core.REACH_EDGE), 0.0) + worst["inside"] = max(worst["inside"], abs(residual - 0.32 * core.REACH_EDGE), abs(core._wrapped(roll - end)) * 1e-9) + with self.assertRaisesRegex(core.KitError, re.escape(f"it reaches {C - swing:.6f} m to {C + swing:.6f} m")): + core.reach_roll(world, sp, sc, point, d, C + sign * (swing + 3.2 * core.REACH_EDGE), 0.0) + worst["cases"] += 1 + return worst + + def test_reach_takes_the_edge_of_its_circle(self): + """reach-edge. A height at the top or bottom of the circle is reached, exactly and as typed back from the range a + refusal names; one within REACH_EDGE past it is taken as the edge and the residual says how far off the point + stands; one farther is refused. Mutants E1 (no tolerance: the edge refused a quarter of the time), E2 (the + ratio not clamped into acos) and S7 (Soul's >= at the edge).""" + worst = self.edge_readings() + self.assertEqual(worst["cases"], 120) + self.assertLess(worst["exact"], 6.6e-8) # PoseTests.REACHED: the edge is on the plane as any other height is + self.assertLess(worst["typed"], core.REACH_EDGE / 1.2) + self.assertLess(worst["typed past"], core.REACH_EDGE / 1.2) # a typed edge overshoots by at most a rounding: inside the rule + self.assertGreater(worst["typed past"], 1e-7) # and it does overshoot: without the tolerance these are refused + self.assertLess(worst["inside"], 1e-12) + ident = {"name": "s", "matrix": np.eye(4)} + reach = lambda height, current: tuple(round(v, 9) for v in core.reach_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (1.0, 0.0, 0.0), height, current)) # noqa: E731 + self.assertEqual((reach(1.0, 0.0), reach(-1.0, 0.0)), ((-90.0, 0.0), (90.0, 0.0))) # the point stands at x = -sin(roll) + self.assertEqual(reach(1.000003, 0.0), (-90.0, 3e-06)) + + def test_reach_refuses_a_point_no_roll_moves(self): + """reach-on-the-pin. A point on the pin's axis, or a direction along the pin, is refused whatever the height: no + roll moves the point along the direction, and solving would divide by its swing. Mutant E3 (the guard dropped: + Soul's S8, zero swing with the point on the pin).""" + ident = {"name": "s", "matrix": np.eye(4)} + for point, d, height in (((0.0, 0.0, 2.0), (1.0, 0.0, 0.0), 0.0), ((0.0, 0.0, 2.0), (1.0, 0.0, 0.0), 0.5), ((0.3, 0.4, 2.0), (0.0, 0.0, 1.0), -2.0), + ((0.3, 0.4, 2.0), (0.0, 0.0, 1.0), 1.0), ((0.0, 3e-6, 2.0), (1.0, 0.0, 0.0), 0.0)): + with self.assertRaisesRegex(core.KitError, r"socket 's' on parent socket 's': no roll moves the point along .*: it lies on the pin, or the direction runs along it; it stays at -?\d+\.\d{6} m"): + core.reach_roll(np.eye(4), ident, ident, point, d, height, 0.0) + self.assertEqual(round(core.reach_roll(np.eye(4), ident, ident, (0.0, 3.2e-5, 2.0), (1.0, 0.0, 0.0), 0.0, 10.0)[0], 9), 0.0) # sqrt(10) past REACH_EDGE off the pin: solved + for world, sp, sc, rng in self.joints("pin"): + on_pin = sc["matrix"] @ np.array([0.0, 0.0, rng.uniform(-1, 1), 1.0]) # on the child socket's own normal + _, _, C = core.roll_terms(world, sp, sc, on_pin[:3], 1.0, self.direction(rng)) + with self.assertRaisesRegex(core.KitError, "no roll moves the point"): + core.reach_roll(world, sp, sc, on_pin[:3], self.direction(rng), C, 0.0) + with self.assertRaisesRegex(core.KitError, "no roll moves the point"): + core.reach_roll(world, sp, sc, [rng.uniform(-1, 1) for _ in range(3)], (world @ sp["matrix"])[:3, 2], 0.0, 0.0) + ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", From cc98d36f4e8daf8db5927b35c9669b33b0258174 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 05:56:08 +0100 Subject: [PATCH 090/223] brokkr_kitbash: the shell-cuts Lows: evaluable, fitted receipts, slot floors at the round ends, live checks that name what died evaluable refuses, before any write, an object the evaluated depsgraph does not hold (disabled in viewports with nothing depending on it, or in a collection outside the view layer): boolean, cut, cut_many and apply call it. fitted trims a report's rows to a receipt and counts the rest in Omitted: scene_closures, cut, cut_many and boolean use it, so place_cutters loses its report hook and cut_many its refusal of a long report. The slot's floor_l and floor_r move to the centres of its round ends, sized so the three never overlap. kitbash_shell.py runs inside one try: an uncaught error is a failed check naming its section and the result file is always written. It pins M1, M3, M6, M7, M16, hidden and unlinked targets, and trimmed receipts. docs: like-for-like cost (13 cutters: cut_many 6.1 s, 13 cuts 51.3 s, 105 s with hides). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 64 +- .../brokkr_kitbash/brokkr_actions.json | 8 +- .../brokkr_kitbash/kits/cutters.v0.json | 8 +- surfaces/blender/docs/kitbash.md | 34 +- surfaces/blender/tests/live/kitbash_shell.py | 617 ++++++++++-------- .../tests/live/kitbash_shell.result.json | 91 ++- surfaces/blender/tests/test_kitbash.py | 38 +- 7 files changed, 546 insertions(+), 314 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 105b694..05b6129 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -32,7 +32,9 @@ cut cuts a mesh where a ray meets it. The cut is a placed part of the cutters ki 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 a floor socket with the ordinary attach. Blender evaluates a changed target after every action, so each cut costs -one Boolean evaluation; cut_many places many cutters for one. +one Boolean evaluation; cut_many places many cutters for one. Every action that evaluates an object (boolean, cut, +cut_many, apply) first refuses one Blender does not evaluate (evaluable). A report's list that would not fit a +receipt is trimmed by fitted, the rows left off counted beside it: the scene keeps what they would have said. 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 @@ -297,8 +299,7 @@ def closure_report(obj, part, built, held=None, kits=None): def scene_closures(context, report: dict, ends=()) -> list: """Every closure stated in the scene as {part, to, holds}, for a set_params report: a change of params can open a closure anywhere below the part. The closures `ends` are parts of come first, then those that do not hold, - then the rest, each by name; rows that would take the report past what a receipt carries are left off the end - and counted in closuresOmitted.""" + then the rest, each by name, trimmed to a receipt by fitted.""" held, kits, rows = closers(), {}, [] for obj in (o for o in context.scene.objects if o.type == "MESH" and CLOSE in o): try: @@ -306,14 +307,7 @@ def scene_closures(context, report: dict, ends=()) -> list: except (Refused, core.KitError): # the closing part itself cannot be read (scaled) found = {"to": closure(obj)[1].name if closure(obj)[1] else None, "holds": False} rows.append((obj not in ends and closure(obj)[1] not in ends, found["holds"], obj.name, {"part": obj.name, "to": found["to"], "holds": found["holds"]})) - kept, size = [], len(json.dumps(report, separators=(",", ":"))) + 40 - for *_, row in sorted(rows, key=lambda r: r[:3]): - size += len(json.dumps(row, separators=(",", ":"))) + 1 - if size > REPORT_LIMIT: - report["closuresOmitted"] = len(rows) - len(kept) - break - kept.append(row) - return kept + return fitted(report, "closures", [row for *_, row in sorted(rows, key=lambda r: r[:3])]) def part_report(obj, part, built) -> dict: @@ -375,6 +369,17 @@ def evaluated_of(context, obj): return depsgraph, obj.evaluated_get(depsgraph) +def evaluable(context, obj): + """evaluated_of, for an object Blender evaluates: refuses one the evaluated depsgraph does not hold, which has no + evaluated mesh to cast at, cut or bake. Membership of the depsgraph is the test, whatever keeps the object out + of it. Every action that evaluates calls this before its first write.""" + depsgraph, evaluated = evaluated_of(context, obj) + if not evaluated.is_evaluated: + raise Refused(f"Blender does not evaluate {obj.name!r} in this view layer: it is disabled in viewports, or in no collection the " + "view layer shows. Enable it, or link it to the scene; nothing changed.") + return depsgraph, evaluated + + def measured(mesh) -> dict: """Faces, signed volume (overlapping shells count twice) and edges that do not join exactly two faces.""" bm = bmesh.new() @@ -407,13 +412,27 @@ def bounded(report: dict, advice: str) -> dict: return report -def place_cutters(context, target, specs, report=None) -> list: +def fitted(report: dict, key: str, rows: list) -> list: + """The rows of one list of a report that fit what a receipt carries beside the rest of the report, in order; those + left off the end are counted in report[key + 'Omitted']. The one rule that trims a report's rows to a receipt: + the scene keeps what the rows would have said.""" + kept, size = [], len(json.dumps(report, separators=(",", ":"))) + 2 * len(key) + 24 + for row in rows: + size += len(json.dumps(row, separators=(",", ":"))) + 1 + if size > REPORT_LIMIT: + report[key + "Omitted"] = len(rows) - len(kept) + break + kept.append(row) + return kept + + +def place_cutters(context, target, specs) -> list: """Place a cutters part for each spec ({name, part, origin, direction} and optionally params, up, roll, axis; the vectors in the target's own frame) and add them to the target's difference Boolean; [(cutter, part, built)]. Every refusal comes before any write. The rays are cast in one evaluation of the target with its Kit Booleans off, the surface as designed and not as already cut: a second cut on the ray of a through bay lands where the first did, and no Boolean is evaluated here. Blender evaluates the changed target once after the action, however - many cutters it placed. `report`, given the booleans rows to be, may refuse a report too long for a receipt.""" + many cutters it placed.""" rigid(target) kit, made, names = core.load_kit(CUTTERS), [], set() for spec in specs: @@ -430,7 +449,7 @@ def place_cutters(context, target, specs, report=None) -> list: try: for modifier in cuts: modifier.show_viewport = False - depsgraph, _ = evaluated_of(context, target) + depsgraph, _ = evaluable(context, target) tree = BVHTree.FromObject(target, depsgraph) finally: for modifier in cuts: @@ -447,8 +466,6 @@ def place_cutters(context, target, specs, report=None) -> list: raise Refused(f"{spec['name']!r}: the axis {tuple(round(v, 6) for v in axis)} points into the surface (its normal there is " f"{tuple(round(v, 6) for v in normal)}); nothing changed.") frames.append(core.surface_frame(hit, axis if axis.length > 0.0 else normal, spec.get("up", (0.0, 0.0, 1.0)), spec.get("roll", 0.0))) - if report is not None: - report(booleans(target) + [{"cutter": spec["name"], "operation": "DIFFERENCE"} for spec in specs]) placed = [] for spec, (part, built), frame in zip(specs, made, frames): mesh = bpy.data.meshes.new(spec["name"]) @@ -743,10 +760,12 @@ class BROKKR_KITBASH_OT_boolean(PolishOperator): report = part_report(obj, *built_part(obj)) if PART in obj else {"object": obj.name} rigid(obj) uncut(obj, cutter) + evaluable(context, obj) operation_collection(obj, self.operation, True).objects.link(cutter) _, evaluated = evaluated_of(context, obj) - report["booleans"], report["evaluated"] = booleans(obj), measured(evaluated.to_mesh()) + report["evaluated"] = measured(evaluated.to_mesh()) evaluated.to_mesh_clear() + report["booleans"] = fitted(report, "booleans", booleans(obj)) return report @@ -782,7 +801,9 @@ class BROKKR_KITBASH_OT_cut(PolishOperator): "origin": (self.origin_x, self.origin_y, self.origin_z), "direction": (self.direction_x, self.direction_y, self.direction_z), "up": (self.up_x, self.up_y, self.up_z), "axis": (self.axis_x, self.axis_y, self.axis_z)} (cutter, part, built), = place_cutters(context, target, [spec]) - return {"object": target.name, "cutter": part_report(cutter, part, built), "booleans": booleans(target)} + report = {"object": target.name, "cutter": part_report(cutter, part, built)} + report["booleans"] = fitted(report, "booleans", booleans(target)) + return report CUT_KEYS = {"name": str, "part": str, "params": str, "origin": list, "direction": list, "up": list, "axis": list, "roll": (int, float)} @@ -815,9 +836,9 @@ class BROKKR_KITBASH_OT_cut_many(PolishOperator): if not isinstance(value, CUT_KEYS[key]) or isinstance(value, bool) or (vector and (len(value) != 3 or not all(core.finite(v) for v in value))) \ or (key == "roll" and not (core.finite(value) and -360.0 <= value <= 360.0)) or (key == "name" and not 1 <= len(value) <= 63): raise Refused(f"{where}.{key} must be {'three numbers' if vector else 'a number from -360 to 360' if key == 'roll' else 'a string' + (' of 1 to 63 characters' if key == 'name' else '')}; nothing changed.") - placed = place_cutters(context, target, specs, report=lambda rows: bounded({"object": target.name, "cutters": [spec["name"] for spec in specs], "booleans": rows}, - "cut fewer at once")) - return {"object": target.name, "cutters": [cutter.name for cutter, _, _ in placed], "booleans": booleans(target)} + report = {"object": target.name, "cutters": [cutter.name for cutter, _, _ in place_cutters(context, target, specs)]} + report["booleans"] = fitted(report, "booleans", booleans(target)) + return report class BROKKR_KITBASH_OT_apply(PolishOperator): @@ -831,6 +852,7 @@ class BROKKR_KITBASH_OT_apply(PolishOperator): @kit_work def work(self, context): obj = mesh_object(self.object_name) + evaluable(context, obj) part, built = built_part(obj) own_mesh(obj, "baking") if not obj.modifiers: diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 99fd330..1fe79d4 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -353,7 +353,7 @@ }, { "name": "brokkr_kitbash.boolean", - "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.", + "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, and booleans, what cuts the target (rows a receipt has no room for are left off the end and counted in booleansOmitted). Refuses a target Blender does not evaluate (disabled in viewports, or in no collection the view layer shows). The cutter is not changed; hide it with setObjectVisibility.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -388,7 +388,7 @@ }, { "name": "brokkr_kitbash.cut", - "doc": "Cut a mesh, a kit part or any other, where a ray meets it: places a part of the cutters kit (box, cyl, slot or slab; brokkr_kitbash.describe with kit cutters) on the surface there, parented to the target, and adds it to the target's difference Boolean. The ray is cast at the target without its cuts. The cutter's floor socket (type mount, at the bottom of the recess, facing out) takes a part by brokkr_kitbash.attach; move the cut with setObjectTransform on the cutter, resize it with set_params, hide the cutter with setObjectVisibility. Blender evaluates the changed target after the action: one Boolean evaluation a cut; brokkr_kitbash.cut_many places several cutters for one. Reports the cutter with its sockets, and booleans.", + "doc": "Cut a mesh, a kit part or any other, where a ray meets it: places a part of the cutters kit (box, cyl, slot or slab; brokkr_kitbash.describe with kit cutters) on the surface there, parented to the target, and adds it to the target's difference Boolean. The ray is cast at the target without its cuts. The cutter's floor socket (type mount, at the bottom of the recess, facing out) takes a part by brokkr_kitbash.attach; move the cut with setObjectTransform on the cutter, resize it with set_params, hide the cutter with setObjectVisibility. Blender evaluates the changed target after the action: one Boolean evaluation a cut; brokkr_kitbash.cut_many places several cutters for one. Reports the cutter with its sockets, and booleans (rows a receipt has no room for are counted in booleansOmitted). Refuses a target Blender does not evaluate.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -528,7 +528,7 @@ }, { "name": "brokkr_kitbash.cut_many", - "doc": "Cut a mesh at several rays in one action, as brokkr_kitbash.cut does at one: all the cutters are placed or none, every ray is cast at the target without its cuts, and Blender evaluates the target's Boolean once after the action instead of once a cut. Reports object, the cutters' names and booleans; brokkr_kitbash.report gives a cutter's sockets.", + "doc": "Cut a mesh at several rays in one action, as brokkr_kitbash.cut does at one: all the cutters are placed or none, every ray is cast at the target without its cuts, and Blender evaluates the target's Boolean once after the action instead of once a cut. Reports object, the cutters' names and booleans (rows a receipt has no room for are counted in booleansOmitted); brokkr_kitbash.report gives a cutter's sockets.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -553,7 +553,7 @@ }, { "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.", + "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, a mesh another object shares and a part Blender does not evaluate.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json b/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json index e15261c..57b5e1b 100644 --- a/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/cutters.v0.json @@ -43,7 +43,7 @@ }, { "name": "slot", - "doc": "Round-ended slot, long along x: a visor, a gill, a vent. width must exceed height. Three floor sockets face out of the recess: floor at the frame's centre (between the two middle copies when count is even), floor_l and floor_r a third of the width to each side; each holds one part.", + "doc": "Round-ended slot, long along x: a visor, a gill, a vent. width must exceed height. Three floor sockets face out of the recess: floor at the frame's centre (between the two middle copies when count is even), floor_l and floor_r at the centres of the two round ends; each holds one part and is as large as fits beside the next, min(height, (width-height)/2).", "params": [ {"name": "width", "type": "number", "min": 0.01, "max": 8, "default": 0.3, "doc": "end to end (x); more than height"}, {"name": "height", "type": "number", "min": 0.005, "max": 4, "default": 0.05, "doc": "across the slot (y); the ends are half-rounds of this diameter"}, @@ -58,9 +58,9 @@ {"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "tube", "r0": "height/2", "r1": "height/2", "length": "depth+lift", "segments": 32, "at": ["(width-height)/2", "-(count-1)*pitch/2", "-depth"]}} ], "sockets": [ - {"name": "floor", "type": "mount", "size": "height", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"}, - {"name": "floor_l", "type": "mount", "size": "height", "at": ["-width/3", 0, "-depth"], "z": "+z", "y": "+y"}, - {"name": "floor_r", "type": "mount", "size": "height", "at": ["width/3", 0, "-depth"], "z": "+z", "y": "+y"} + {"name": "floor", "type": "mount", "size": "min(height, (width-height)/2)", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"}, + {"name": "floor_l", "type": "mount", "size": "min(height, (width-height)/2)", "at": ["-(width-height)/2", 0, "-depth"], "z": "+z", "y": "+y"}, + {"name": "floor_r", "type": "mount", "size": "min(height, (width-height)/2)", "at": ["(width-height)/2", 0, "-depth"], "z": "+z", "y": "+y"} ] }, { diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index f6070d6..888fd4c 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -315,7 +315,7 @@ kit part, where a ray meets it, and what it places is itself a kit part, of the | --- | --- | --- | | `box` | `width` (x), `height` (y), `count`, `pitch` | `floor` (mount, size the smaller side) | | `cyl` | `r`, `count`, `pitch` | `floor` (mount, size `2*r`) | -| `slot` | `width` (x, end to end), `height` (across; less than `width`), `count`, `pitch` | `floor`, `floor_l`, `floor_r` (mount, size `height`) | +| `slot` | `width` (x, end to end), `height` (across; less than `width`), `count`, `pitch` | `floor`, `floor_l`, `floor_r` (mount, size the smaller of `height` and `(width-height)/2`) | | `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 @@ -341,8 +341,9 @@ resizes it, and deleting the cutter removes the cut. `cut` does not hide the cut and a hidden cutter still cuts. `box`, `cyl` and `slot` carry a socket, `floor`: on the bottom of the recess at `z = -depth`, at the frame's -centre, facing out of the recess. A `slot` carries two more on the same floor, `floor_l` and `floor_r`, a third -of its width to each side: a visor with three eyes. Machinery attaches there with the ordinary `attach` (a vent's `back`, a +centre, facing out of the recess. A `slot` carries two more on the same floor, `floor_l` and `floor_r`, at the +centres of its two round ends, `(width-height)/2` to each side: a visor with three eyes. The three are sized so +that neighbours never overlap and none passes the slot's ends. 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 @@ -354,11 +355,20 @@ every action, so each `cut` costs one Boolean evaluation of the target: on the s cutter to eight. `cut_many` takes a JSON array of cutters (`name`, `part`, `origin`, `direction`, and optionally `params`, `up`, `roll`, `axis`), checks them all and casts every ray before it writes anything, places all of them or none, and costs one evaluation for the lot. On a pod with a Bevel under the Boolean (6500 faces once -cut; one evaluation 5.2 s), 13 cutters placed by one `cut_many` took 4.9 s, and 15 placed by 15 `cut` actions -took 113 s; the same cuts as one joined cutter, evaluated once and baked, took 4.6 s (Blender 5.3 on Starfire). -Any later action that changes the target or a cutter (hiding the cutters, attaching a part to a floor) costs an -evaluation again while the target is visible. `cut_many` reports `{object, cutters, booleans}` with the cutters -by name. +cut), the same 13 cutters took 6.1 s placed by one `cut_many` and 51.3 s placed by 13 `cut` actions, about 8 +times as long (medians of 3, Blender 5.3 on Starfire); hiding each cutter after its `cut` is a second evaluation +each and brought the 13 to 105 s. Any later action that changes the target or a cutter (hiding the cutters, +attaching a part to a floor) costs an evaluation again while the target is visible. `cut_many` reports +`{object, cutters, booleans}` with the cutters by name. + +`booleans` in a report of `cut`, `cut_many` or `boolean` is trimmed to what a receipt carries: on a target with +more cutters than fit (about 150 of long names), the rows left off the end are counted in `booleansOmitted`. The +scene keeps every cutter; the target's `Kit` modifier collections list them. + +`cut`, `cut_many`, `boolean` and `apply` evaluate their object, and refuse one Blender does not evaluate in the +view layer: an object disabled in viewports that nothing evaluated depends on, or one whose collections no view +layer shows. A disabled object that an evaluated object needs (a parent of one, a cutter of one) is evaluated +all the same, and is cut. ## Expressions @@ -388,10 +398,10 @@ vertices overflow. | `brokkr_kitbash.aim` | `object_name`, `axis` (`+x`, `-x`, `+y`, `-y`, `+z` or `-z`, the part's own), `direction_x`, `direction_y`, `direction_z` (world, any length) | Solves the roll that turns the axis as far toward the direction as the pin lets it, and turns the part to it. Refuses an axis or direction along the pin. Reports the part, `aimed: {roll, dot}` and `closures`. | | `brokkr_kitbash.reach` | `object_name`, `socket` (one of the part's), `height` (metres, -1000 to 1000), `direction_x`, `direction_y`, `direction_z` (world; default 0, 0, 1) | Solves the roll that brings the socket's origin to `height` along the direction, the nearer of the two, and turns the part to it. Refuses a height out of reach, naming the range. Reports the part, `reached: {roll, residual}` and `closures`. | | `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. | -| `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added) and `evaluated`. | -| `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans`. | -| `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans`. | -| `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers and a mesh another object shares. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | +| `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; `booleansOmitted` counts rows a receipt had no room for) 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), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans` (with `booleansOmitted`, as `boolean`). | +| `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | +| `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored value (`set_params`). A value outside its bounds is refused with the bounds in the message. diff --git a/surfaces/blender/tests/live/kitbash_shell.py b/surfaces/blender/tests/live/kitbash_shell.py index f8dbb11..d5f8e20 100644 --- a/surfaces/blender/tests/live/kitbash_shell.py +++ b/surfaces/blender/tests/live/kitbash_shell.py @@ -1,8 +1,8 @@ """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, cut_many, a cutter's axis, a slot's three floors, an object in no collection, and the order of a set_params report's closures. Not part of the -unittest run: it needs Blender. +any mesh, the refusals, cut_many, a cutter's axis, a slot's three floors, an object in no collection or one Blender does not evaluate, a receipt's rows trimmed +to fit, 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 -- @@ -11,6 +11,9 @@ without them). is an absolute path; writes .result.json and exits 1 w 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. + +The checks run inside one try: an uncaught error is a failed check that names the section it happened in, and the +result file is written and the checks printed whatever happened. """ import importlib.util import json @@ -18,6 +21,7 @@ import math import os import sys import tempfile +import traceback import types from pathlib import Path @@ -160,123 +164,15 @@ 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} +SECTION = ["setup"] -# --- 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"]] == {"slab": [], "slot": ["floor", "floor_l", "floor_r"]}.get(part, ["floor"]) - and (part == "slab" or np.abs(np.array(report["cutter"]["sockets"][0]["matrix"]) - wanted @ core.build(kits["cutters"]["parts"][part], report["cutter"]["params"]).sockets[0]["matrix"]).max() < 1e-4), - report) - shown, _ = evaluated(cage) - 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)]) +def section(name): + SECTION[0] = name -# --- 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 -# --- cut_many: several cutters for one evaluation, all or none; an axis; a slot's three floors ----------------------------------- def uncut_cast(origin, direction): + """cast at the cage with its Kit Booleans off: the surface as designed.""" shown = [m for m in cage.modifiers if m.name.startswith("Kit ")] for m in shown: m.show_viewport = False @@ -287,151 +183,358 @@ def uncut_cast(origin, direction): m.show_viewport = True -MANY = [{"name": "Visor", "part": "slot", "params": "width=0.6; height=0.14; depth=0.02; lift=0.2", "origin": [0.6, 3.0, 0.5], "direction": [0.0, -1.0, 0.0]}, - {"name": "Seam", "part": "slab", "params": "length=0.4; depth=0.1", "origin": [-0.5, -3.0, -0.7], "direction": [0.0, 1.0, 0.0], "up": [1.0, 0.0, 0.0], "axis": [0.0, -1.0, 0.0]}, - {"name": "Port", "part": "cyl", "params": "r=0.05", "origin": [-0.6, 3.0, -0.5], "direction": [0.0, -2.0, 0.0], "up": [1.0, 0.0, 0.0], "roll": 45.0}] -wanted = {} -for spec in MANY: - hit, normal = uncut_cast(spec["origin"], spec["direction"]) - wanted[spec["name"]] = core.surface_frame(hit, spec.get("axis", normal), spec.get("up", (0.0, 0.0, 1.0)), spec.get("roll", 0.0)) - if "axis" in spec: - lean = float(np.degrees(np.arccos(np.clip(normal @ np.array(spec["axis"]), -1.0, 1.0)))) -refused("cut_many whose second ray misses places none", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "origin": [0.0, -3.0, 5.0]}])}, - "The ray from (0.0, -3.0, 5.0) along (0.0, 1.0, 0.0) misses 'Cage'") -refused("cut_many with a name twice", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Visor"}])}, "An object named 'Visor' exists in this call") -refused("cut_many with a name an object has", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Bay"}])}, "An object named 'Bay' exists;") -refused("cut_many whose last cutter has a bad param", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps(MANY[:2] + [{**MANY[2], "params": "r=9"}])}, "param 'r' = 9.0 is outside") -refused("cut_many of text that is not JSON", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[{"}, "cuts is not JSON") -refused("cut_many of no cutters", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[]"}, "cuts must be a JSON array of 1 to 64 cutters") -refused("cut_many of a cutter with no direction", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{k: v for k, v in MANY[0].items() if k != "direction"}])}, - "cuts[0] must be an object with name, part, origin and direction") -refused("cut_many of a cutter with a key cut does not have", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "operation": "UNION"}])}, "cuts[0] must be an object") -refused("cut_many of an origin of two numbers", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "origin": [0.0, 1.0]}])}, "cuts[0].origin must be three numbers") -refused("cut_many of a roll of 400", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "roll": 400}])}, "cuts[0].roll must be a number from -360 to 360") -refused("an axis that points into the surface", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[1], "axis": [0.0, 1.0, 0.0]}])}, "'Seam': the axis (0.0, 1.0, 0.0) points into the surface") -addon = sys.modules["brokkr_kitbash"] -limit = addon.REPORT_LIMIT -addon.REPORT_LIMIT = 300 -refused("cut_many whose report would not fit a receipt places none", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps(MANY)}, "over the 300 a receipt carries: cut fewer at once") -addon.REPORT_LIMIT = limit -receipt, report = send("brokkr_kitbash.cut_many", object_name="Cage", cuts=json.dumps(MANY)) -placed = [bpy.data.objects.get(spec["name"]) for spec in MANY] -check("cut_many places three cutters in one action, each as cut would: parented under an identity inverse, its basis the surface frame at its own ray on the uncut cage, in the difference collection in order", - receipt["status"] == "accepted" and all(placed) and report == {"object": "Cage", "cutters": ["Visor", "Seam", "Port"], "booleans": report["booleans"]} - and [row["cutter"] for row in report["booleans"]] == ["Bay", "Recess", "Gills", "Break", "Bay2", "Visor", "Seam", "Port"] - and all(c.parent == cage and np.array_equal(np.array(c.matrix_parent_inverse), np.eye(4)) - and reading("framed", np.abs(np.array(c.matrix_basis) - wanted[c.name]).max()) < FRAMED for c in placed) - and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and all(m.show_viewport for m in cage.modifiers) and evaluated(cage)[0]["nonManifoldEdges"] == 0, - [receipt["message"], report]) -seam = bpy.data.objects["Seam"] -check("a slab with an axis stands on the axis, not on the wall's normal, which leans from it there", lean > 5.0 - and reading("framed", np.abs(np.array(seam.matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, [lean, np.array(seam.matrix_basis).tolist()]) -receipt, report = send("brokkr_kitbash.cut", object_name="Cage", cutter_name="Seam2", part="slab", params="length=0.3; depth=0.1", origin_x=0.5, origin_y=-3.0, origin_z=-0.7, - direction_x=0.0, direction_y=1.0, direction_z=0.0, up_x=1.0, up_y=0.0, up_z=0.0, axis_x=0.0, axis_y=-1.0, axis_z=0.0) -check("cut takes the same axis", receipt["status"] == "accepted" and reading("framed", np.abs(np.array(bpy.data.objects["Seam2"].matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, receipt["message"]) -visor = bpy.data.objects["Visor"] -eyes = {} -for socket, x in (("floor", 0.0), ("floor_l", -0.2), ("floor_r", 0.2)): - eye = place(f"Eye_{socket}", "vent", "width=0.2; height=0.15") # back size 0.135; each floor's is 0.14 - receipt, report = send("brokkr_kitbash.attach", object_name=eye.name, socket="back", parent_name="Visor", parent_socket=socket) - there = world @ wanted["Visor"] @ np.array(Matrix.Translation((x, 0.0, -0.02))) - eyes[socket] = receipt["status"] == "accepted" and held(report) and eye.parent == visor \ - and reading("floored", max(np.abs(frame(eye, "back")[:3, 3] - there[:3, 3]).max(), np.abs(frame(eye, "back")[:3, 2] + there[:3, 2]).max())) < FLOORED -check("a slot's three floors each take a part: at the centre and a third of the width to each side, all on the slot's one floor plane", all(eyes.values()) and len(eyes) == 3, eyes) -refused("a second part on a side floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Nozzle' on 'Visor'") -refused("a fourth eye on a floor that is taken", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Big' on 'Visor'") +def quad(name, location): + """A single square face, 1 m, normal +z: a surface with one side.""" + made = bpy.data.objects.new(name, bpy.data.meshes.new(name)) + made.data.from_pydata([(-0.5, -0.5, 0.0), (0.5, -0.5, 0.0), (0.5, 0.5, 0.0), (-0.5, 0.5, 0.0)], [], [(0, 1, 2, 3)]) + bpy.context.scene.collection.objects.link(made) + made.location = location + bpy.context.view_layer.update() + return made -# --- 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", "Visor", "Seam", "Port", "Seam2")] + [{"cutter": "Lump", "operation": "UNION"}] - and report["evaluated"]["volume"] > deeper["volume"], [receipt["message"], report]) -refused("cut-refusals: a cutter already in the target's union collection", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Lump"}, - "'Lump' already cuts 'Cage' (its Kit Union modifier's collection)") -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}, "'New': the ray's direction is zero") -refused("a cutter name an object has", "brokkr_kitbash.cut", {**RAY, "cutter_name": "Bay"}, "An object named 'Bay' exists") -refused("a param the cutter part does not have", "brokkr_kitbash.cut", {**RAY, "params": "radius=0.1"}, "kit 'cutters' part 'box' has no param 'radius'") -refused("a slot wider across than along", "brokkr_kitbash.cut", {**RAY, "part": "slot", "params": "width=0.05; height=0.1"}, "every size must be above 0") -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()]) +try: + # --- a cage: not a kit part. A closed loft of 6 rings of 8, subdivided and given a wall ---------------------------------- + section('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-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) + # --- cut-at-ray: a through bay, a blind round recess, a row of gills and a panel break -------------------------------------- + section('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"]] == {"slab": [], "slot": ["floor", "floor_l", "floor_r"]}.get(part, ["floor"]) + and (part == "slab" or np.abs(np.array(report["cutter"]["sockets"][0]["matrix"]) - wanted @ core.build(kits["cutters"]["parts"][part], report["cutter"]["params"]).sockets[0]["matrix"]).max() < 1e-4), + report) + shown, _ = evaluated(cage) + 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"]]) -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) + # --- cut-casts-the-uncut-surface -------------------------------------------------------------------------------------------- + section('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 ------------------------------------------------------------------------------------------------ + section('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 + + # --- cut_many: several cutters for one evaluation, all or none; an axis; a slot's three floors ----------------------------------- + section("cut_many: several cutters for one evaluation, all or none; an axis; a slot's three floors") + MANY = [{"name": "Visor", "part": "slot", "params": "width=0.6; height=0.14; depth=0.02; lift=0.2", "origin": [0.6, 3.0, 0.5], "direction": [0.0, -1.0, 0.0]}, + {"name": "Seam", "part": "slab", "params": "length=0.4; depth=0.1", "origin": [-0.5, -3.0, -0.7], "direction": [0.0, 1.0, 0.0], "up": [1.0, 0.0, 0.0], "axis": [0.0, -1.0, 0.0]}, + {"name": "Port", "part": "cyl", "params": "r=0.05", "origin": [-0.6, 3.0, -0.5], "direction": [0.0, -2.0, 0.0], "up": [1.0, 0.0, 0.0], "roll": 45.0}] + wanted = {} + for spec in MANY: + hit, normal = uncut_cast(spec["origin"], spec["direction"]) + wanted[spec["name"]] = core.surface_frame(hit, spec.get("axis", normal), spec.get("up", (0.0, 0.0, 1.0)), spec.get("roll", 0.0)) + if "axis" in spec: + lean = float(np.degrees(np.arccos(np.clip(normal @ np.array(spec["axis"]), -1.0, 1.0)))) + refused("cut_many whose second ray misses places none", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "origin": [0.0, -3.0, 5.0]}])}, + "The ray from (0.0, -3.0, 5.0) along (0.0, 1.0, 0.0) misses 'Cage'") + refused("cut_many with a name twice", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Visor"}])}, "An object named 'Visor' exists in this call") + refused("cut_many with a name an object has", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Bay"}])}, "An object named 'Bay' exists;") + refused("cut_many whose last cutter has a bad param", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps(MANY[:2] + [{**MANY[2], "params": "r=9"}])}, "param 'r' = 9.0 is outside") + refused("cut_many of text that is not JSON", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[{"}, "cuts is not JSON") + refused("cut_many of no cutters", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[]"}, "cuts must be a JSON array of 1 to 64 cutters") + refused("cut_many of a cutter with no direction", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{k: v for k, v in MANY[0].items() if k != "direction"}])}, + "cuts[0] must be an object with name, part, origin and direction") + refused("cut_many of a cutter with a key cut does not have", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "operation": "UNION"}])}, "cuts[0] must be an object") + refused("cut_many of an origin of two numbers", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "origin": [0.0, 1.0]}])}, "cuts[0].origin must be three numbers") + refused("cut_many of a roll of 400", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "roll": 400}])}, "cuts[0].roll must be a number from -360 to 360") + refused("an axis that points into the surface", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[1], "axis": [0.0, 1.0, 0.0]}])}, "'Seam': the axis (0.0, 1.0, 0.0) points into the surface") + quad("Many", (0.0, -27.0, 0.0)) # a target of its own, cheap to evaluate should the 65 ever be placed + refused("M7: cut_many of 65 cutters, one over the limit", "brokkr_kitbash.cut_many", + {"object_name": "Many", "cuts": json.dumps([{"name": f"Over{k}", "part": "cyl", "params": "r=0.005", "origin": [0.4 - k * 0.012, 0.0, 3.0], "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]} + for k in range(65)])}, "cuts must be a JSON array of 1 to 64 cutters") + receipt, report = send("brokkr_kitbash.cut_many", object_name="Cage", cuts=json.dumps(MANY)) + placed = [bpy.data.objects.get(spec["name"]) for spec in MANY] + check("cut_many places three cutters in one action, each as cut would: parented under an identity inverse, its basis the surface frame at its own ray on the uncut cage, in the difference collection in order", + receipt["status"] == "accepted" and all(placed) and report == {"object": "Cage", "cutters": ["Visor", "Seam", "Port"], "booleans": report["booleans"]} + and [row["cutter"] for row in report["booleans"]] == ["Bay", "Recess", "Gills", "Break", "Bay2", "Visor", "Seam", "Port"] + and all(c.parent == cage and np.array_equal(np.array(c.matrix_parent_inverse), np.eye(4)) + and reading("framed", np.abs(np.array(c.matrix_basis) - wanted[c.name]).max()) < FRAMED for c in placed) + and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and all(m.show_viewport for m in cage.modifiers) and evaluated(cage)[0]["nonManifoldEdges"] == 0, + [receipt["message"], report]) + seam = bpy.data.objects["Seam"] + check("a slab with an axis stands on the axis, not on the wall's normal, which leans from it there", lean > 5.0 + and reading("framed", np.abs(np.array(seam.matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, [lean, np.array(seam.matrix_basis).tolist()]) + receipt, report = send("brokkr_kitbash.cut", object_name="Cage", cutter_name="Seam2", part="slab", params="length=0.3; depth=0.1", origin_x=0.5, origin_y=-3.0, origin_z=-0.7, + direction_x=0.0, direction_y=1.0, direction_z=0.0, up_x=1.0, up_y=0.0, up_z=0.0, axis_x=0.0, axis_y=-1.0, axis_z=0.0) + check("cut takes the same axis", receipt["status"] == "accepted" and reading("framed", np.abs(np.array(bpy.data.objects["Seam2"].matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, receipt["message"]) + visor = bpy.data.objects["Visor"] + eyes = {} + for socket, x in (("floor", 0.0), ("floor_l", -0.23), ("floor_r", 0.23)): # the round ends' centres: -+(0.6 - 0.14) / 2 + eye = place(f"Eye_{socket}", "vent", "width=0.2; height=0.15") # back size 0.135; each floor's is 0.14 + receipt, report = send("brokkr_kitbash.attach", object_name=eye.name, socket="back", parent_name="Visor", parent_socket=socket) + there = world @ wanted["Visor"] @ np.array(Matrix.Translation((x, 0.0, -0.02))) + eyes[socket] = receipt["status"] == "accepted" and held(report) and eye.parent == visor \ + and reading("floored", max(np.abs(frame(eye, "back")[:3, 3] - there[:3, 3]).max(), np.abs(frame(eye, "back")[:3, 2] + there[:3, 2]).max())) < FLOORED + check("slot-floors: a slot's three floors each take a part: at the centre and at the round ends, all on the slot's one floor plane", all(eyes.values()) and len(eyes) == 3, eyes) + refused("a second part on a side floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Nozzle' on 'Visor'") + refused("a fourth eye on a floor that is taken", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Big' on 'Visor'") + + # --- boolean on any mesh, and the order of the three operations ----------------------------------------------------------------- + section('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", "Visor", "Seam", "Port", "Seam2")] + [{"cutter": "Lump", "operation": "UNION"}] + and report["evaluated"]["volume"] > deeper["volume"], [receipt["message"], report]) + refused("cut-refusals: a cutter already in the target's union collection", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Lump"}, + "'Lump' already cuts 'Cage' (its Kit Union modifier's collection)") + 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)") + blocked = cast(cage, (-0.3, 0.0, 0.95), (1.0, 0.0, 0.0))[0] # as evaluated now: the ray meets Lump, which the union added inside the cage's mouth + hit, normal = uncut_cast((-0.3, 0.0, 0.95), (1.0, 0.0, 0.0)) + receipt, report = cut("Past", "cyl", (-0.3, 0.0, 0.95), (1.0, 0.0, 0.0), "r=0.02; depth=0.01") + past = bpy.data.objects.get("Past") + check("M3: a cut whose ray meets what a union added lands on the surface as designed: the cast has the Kit Union off too", + receipt["status"] == "accepted" and past is not None and np.linalg.norm(blocked - hit) > 0.3 + and reading("framed", np.abs(np.array(past.matrix_basis) - core.surface_frame(hit, normal, (0.0, 0.0, 1.0))).max()) < FRAMED + and all(m.show_viewport for m in cage.modifiers), [receipt["message"], blocked.tolist(), hit.tolist(), past and list(past.matrix_basis.translation)]) + 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") + twin = place("Twin", "plate", location=[0.0, -15.0, 0.0]) + send("createObject", objectType="MESH", name="TwinHole", location=[0.0, -15.0, 0.0], size=0.05) + send("brokkr_kitbash.boolean", object_name="Twin", cutter="TwinHole") + copied = twin.copy() # a copied part: its own mesh, and a Kit Difference modifier that reads the same collection + copied.data = twin.data.copy() + bpy.context.scene.collection.objects.link(copied) + receipt, baked = send("brokkr_kitbash.apply", object_name="Twin") + kept = bpy.data.collections.get("Twin difference") + check("M6: apply keeps a collection a copied part's modifier still reads", receipt["status"] == "accepted" and len(twin.modifiers) == 0 and kept is not None + and copied.modifiers["Kit Difference"].collection == kept and [o.name for o in kept.objects] == ["TwinHole"], [receipt["message"], [c.name for c in bpy.data.collections]]) + + # --- cut-refusals ----------------------------------------------------------------------------------------------------------- + section('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}, "'New': the ray's direction is zero") + refused("a cutter name an object has", "brokkr_kitbash.cut", {**RAY, "cutter_name": "Bay"}, "An object named 'Bay' exists") + refused("a param the cutter part does not have", "brokkr_kitbash.cut", {**RAY, "params": "radius=0.1"}, "kit 'cutters' part 'box' has no param 'radius'") + refused("a slot wider across than along", "brokkr_kitbash.cut", {**RAY, "part": "slot", "params": "width=0.05; height=0.1"}, "every size must be above 0") + 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()]) + + # --- lows-pinned: the surface's side, an axis along it, and an object Blender does not evaluate -------------------------------- + section("lows-pinned: the surface's side, an axis along it, and an object Blender does not evaluate") + sheet = quad("Sheet", (0.0, -12.0, 0.0)) + UNDER = {"object_name": "Sheet", "cutter_name": "Under", "part": "cyl", "origin_x": 0.1, "origin_y": 0.1, "origin_z": -3.0, "direction_x": 0.0, "direction_y": 0.0, "direction_z": 1.0, + "up_x": 0.0, "up_y": 1.0, "up_z": 0.0} + refused("M1: an axis exactly along the surface, neither out of it nor into it", "brokkr_kitbash.cut", {**UNDER, "cutter_name": "Along", "origin_z": 3.0, "direction_z": -1.0, "axis_x": 1.0}, + "'Along': the axis (1.0, 0.0, 0.0) points into the surface") + receipt, report = send("brokkr_kitbash.cut", **UNDER) + under = bpy.data.objects.get("Under") + check("M16: a ray that meets a one-sided face from behind gives a cutter whose z faces the ray, against the face's own normal", receipt["status"] == "accepted" and under is not None + and reading("framed", np.abs(np.array(under.matrix_basis)[:3, 2] - [0.0, 0.0, -1.0]).max()) < FRAMED, [receipt["message"], under and np.array(under.matrix_basis).tolist()]) + loose = place("Loose", "plate", location=[0.0, -18.0, 0.0]) + apart = bpy.data.collections.new("Apart") # a collection no scene holds: Loose is in a collection, and in no view layer + apart.objects.link(loose) + bpy.context.scene.collection.objects.unlink(loose) + veil = quad("Veil", (0.0, -21.0, 0.0)) # nothing depends on it: a disabled object another evaluated object needs (a parent, a cutter) is still evaluated + veil.hide_viewport = plate.hide_viewport = True + bpy.context.view_layer.update() + for name, why in (("Veil", "disabled in viewports"), ("Loose", "in a collection outside the view layer")): + NOT = f"Blender does not evaluate {name!r} in this view layer" + refused(f"unevaluable-target: cut on a target {why}", "brokkr_kitbash.cut", {**DOWN, "object_name": name, "cutter_name": "Unseen", "up_y": 1.0, "up_z": 0.0}, NOT) + refused(f"cut_many on a target {why}", "brokkr_kitbash.cut_many", + {"object_name": name, "cuts": json.dumps([{"name": "Unseen", "part": "box", "origin": [0.1, 0.1, 3.0], "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]}])}, NOT) + refused(f"boolean on a target {why}", "brokkr_kitbash.boolean", {"object_name": name, "cutter": "Sheet"}, NOT) + refused("apply on a part disabled in viewports", "brokkr_kitbash.apply", {"object_name": "Plate"}, "Blender does not evaluate 'Plate' in this view layer") + refused("apply on a part in a collection outside the view layer", "brokkr_kitbash.apply", {"object_name": "Loose"}, "Blender does not evaluate 'Loose' in this view layer") + veil.hide_viewport = plate.hide_viewport = False + bpy.context.view_layer.update() + + # --- receipt-fitted: rows that would not fit a receipt are left off and counted; the scene keeps the cutters --------------------- + section('receipt-fitted: rows that would not fit a receipt are left off and counted; the scene keeps the cutters') + addon = sys.modules["brokkr_kitbash"] + limit, fits = addon.REPORT_LIMIT, {} + SPOT = {"part": "cyl", "params": "r=0.03", "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]} + try: + addon.REPORT_LIMIT = 200 + fits["cut"] = send("brokkr_kitbash.cut", **{**DOWN, "cutter_name": "Fit1", "part": "cyl", "params": "r=0.03", "origin_x": -0.3, "up_y": 1.0, "up_z": 0.0}) + fits["cut_many"] = send("brokkr_kitbash.cut_many", object_name="Block", cuts=json.dumps([{**SPOT, "name": "Fit2", "origin": [-0.3, -0.3, 3.0]}, {**SPOT, "name": "Fit3", "origin": [0.3, -0.3, 3.0]}])) + fits["boolean"] = send("brokkr_kitbash.boolean", object_name="Block", cutter="Lump", operation="UNION") + finally: + addon.REPORT_LIMIT = limit + ROWS = [{"cutter": name, "operation": "DIFFERENCE"} for name in ("Pocket", "Fit1", "Fit2", "Fit3")] + [{"cutter": "Lump", "operation": "UNION"}] + for action, total, keeps in (("cut", 2, 0), ("cut_many", 4, 2), ("boolean", 5, 1)): # rows the scene had after each action, and how many of them 200 characters carry + receipt, report = fits[action] + check(f"receipt-fitted: {action} past what a receipt carries is accepted, its booleans cut short and the rest counted in booleansOmitted", receipt["status"] == "accepted" + and report is not None and report["booleans"] == ROWS[:keeps] and report.get("booleansOmitted") == total - keeps and (keeps == 0 or len(receipt["hostResult"]) <= 200), + [receipt["message"], receipt.get("hostResult")]) + check("the scene keeps every cutter a short receipt left off", [o.name for o in block.modifiers["Kit Difference"].collection.objects] == ["Pocket", "Fit1", "Fit2", "Fit3"] + and [o.name for o in block.modifiers["Kit Union"].collection.objects] == ["Lump"], stack(block)) + receipt, report = send("brokkr_kitbash.boolean", object_name="Block", cutter="Sheet", operation="INTERSECT") + check("a report that fits carries every row and no count", receipt["status"] == "accepted" and report["booleans"] == ROWS + [{"cutter": "Sheet", "operation": "INTERSECT"}] + and "booleansOmitted" not in report, report) + + # --- cut-orphan and closures-ends-first ----------------------------------------------------------------------------------------- + section('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) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file + check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:]) +finally: + R["ok"] = all(c["ok"] for c in R["checks"]) + R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} + Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") + for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) + print("READINGS", R["readings"], 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 index 74a159c..3b6c679 100644 --- a/surfaces/blender/tests/live/kitbash_shell.result.json +++ b/surfaces/blender/tests/live/kitbash_shell.result.json @@ -162,7 +162,7 @@ "detail": null }, { - "name": "refused, scene unchanged: cut_many whose report would not fit a receipt places none", + "name": "refused, scene unchanged: M7: cut_many of 65 cutters, one over the limit", "ok": true, "detail": null }, @@ -182,7 +182,7 @@ "detail": null }, { - "name": "a slot's three floors each take a part: at the centre and a third of the width to each side, all on the slot's one floor plane", + "name": "slot-floors: a slot's three floors each take a part: at the centre and at the round ends, all on the slot's one floor plane", "ok": true, "detail": null }, @@ -211,6 +211,11 @@ "ok": true, "detail": null }, + { + "name": "M3: a cut whose ray meets what a union added lands on the surface as designed: the cast has the Kit Union off too", + "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, @@ -226,6 +231,11 @@ "ok": true, "detail": null }, + { + "name": "M6: apply keeps a collection a copied part's modifier still reads", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: a ray that misses", "ok": true, @@ -276,6 +286,81 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: M1: an axis exactly along the surface, neither out of it nor into it", + "ok": true, + "detail": null + }, + { + "name": "M16: a ray that meets a one-sided face from behind gives a cutter whose z faces the ray, against the face's own normal", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: unevaluable-target: cut on a target disabled in viewports", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many on a target disabled in viewports", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean on a target disabled in viewports", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: unevaluable-target: cut on a target in a collection outside the view layer", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many on a target in a collection outside the view layer", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean on a target in a collection outside the view layer", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: apply on a part disabled in viewports", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: apply on a part in a collection outside the view layer", + "ok": true, + "detail": null + }, + { + "name": "receipt-fitted: cut past what a receipt carries is accepted, its booleans cut short and the rest counted in booleansOmitted", + "ok": true, + "detail": null + }, + { + "name": "receipt-fitted: cut_many past what a receipt carries is accepted, its booleans cut short and the rest counted in booleansOmitted", + "ok": true, + "detail": null + }, + { + "name": "receipt-fitted: boolean past what a receipt carries is accepted, its booleans cut short and the rest counted in booleansOmitted", + "ok": true, + "detail": null + }, + { + "name": "the scene keeps every cutter a short receipt left off", + "ok": true, + "detail": null + }, + { + "name": "a report that fits carries every row and no count", + "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, @@ -329,7 +414,7 @@ ], "hostErrors": [], "readings": { - "floored": 2.6e-07, + "floored": 3.3e-07, "framed": 5.1e-07, "recast": 0.0 }, diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index e29e1d3..2eda1cc 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -595,7 +595,7 @@ class CuttersKitTests(unittest.TestCase): self.assertAlmostEqual(float(b.V[:, 2].min()), -depth, places=12) self.assertAlmostEqual(float(b.V[:, 2].max()), lift, places=12) for socket in b.sockets: - side = {"floor": 0.0, "floor_l": -1.0, "floor_r": 1.0}[socket["name"]] * b.params.get("width", 0.0) / 3 + side = {"floor": 0.0, "floor_l": -1.0, "floor_r": 1.0}[socket["name"]] * (b.params.get("width", 0.0) - b.params.get("height", 0.0)) / 2 self.assertEqual(socket["matrix"][:, 3].tolist(), [side, 0.0, -depth, 1.0]) self.assertEqual(socket["matrix"][:3, :3].tolist(), np.eye(3).tolist()) self.assertGreater(socket["size"], 0.0) @@ -619,13 +619,21 @@ class CuttersKitTests(unittest.TestCase): self.assertTrue(seat < 1e-12 if count % 2 else abs(seat - 0.015) < 1e-12, f"{name} x{count}: {seat}") # even: 0.015 from each middle copy def test_a_slot_has_three_floors_on_its_bottom(self): - """A visor carries three eyes: floor_l and floor_r lie a third of the width to each side, on the slot's own - bottom, each the size of the slot's height. Mutant B4 (the two side floors swapped).""" + """slot-floors. A visor carries three eyes: floor_l and floor_r lie at the centres of the slot's round ends, on + its own bottom; the three never overlap (centres at least a size apart) and none passes the slot's ends, also + where height exceeds a third of the width. Mutants B4 (the two side floors swapped) and F1 (the side floors + back at a third of the width, each the size of the height: at 0.3 by 0.25 they overlap by 0.15 and pass the + ends by 0.075).""" part = self.kit["parts"]["slot"] - for given in ({"width": 0.66, "height": 0.12, "depth": 0.045}, {"width": 0.3, "height": 0.25}, {"width": 0.3, "height": 0.05, "count": 3, "pitch": 0.2}): + for given in ({"width": 0.66, "height": 0.12, "depth": 0.045}, {"width": 0.3, "height": 0.25}, {"width": 0.3, "height": 0.05, "count": 3, "pitch": 0.2}, + {"width": 0.06, "height": 0.05}, {"width": 0.3, "height": 0.1}): b = core.build(part, given) - self.assertEqual([(s["name"], round(float(s["matrix"][0, 3]), 12), s["size"]) for s in b.sockets], - [("floor", 0.0, given["height"]), ("floor_l", round(-given["width"] / 3, 12), given["height"]), ("floor_r", round(given["width"] / 3, 12), given["height"])]) + side, size = (given["width"] - given["height"]) / 2, min(given["height"], (given["width"] - given["height"]) / 2) + self.assertEqual([(s["name"], round(float(s["matrix"][0, 3]), 12), round(s["size"], 12)) for s in b.sockets], + [("floor", 0.0, round(size, 12)), ("floor_l", round(-side, 12), round(size, 12)), ("floor_r", round(side, 12), round(size, 12))]) + xs = [float(s["matrix"][0, 3]) for s in b.sockets] + self.assertGreaterEqual(min(xs[0] - xs[1], xs[2] - xs[0]), b.sockets[0]["size"] - 1e-12, given) + self.assertLessEqual(max(abs(x) for x in xs) + b.sockets[0]["size"] / 2, given["width"] / 2 + 1e-12, given) for socket in b.sockets: self.assertLess(socket_seat(b, dict(socket, matrix=socket["matrix"] @ core.FLIP)), 1e-12, socket["name"]) @@ -1275,14 +1283,18 @@ class OwnershipTests(unittest.TestCase): 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("), 4) + bodies = {body.split("(")[0]: body.split("\n\n\n")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:]} + self.assertEqual([name for name, body in bodies.items() if "evaluated_of(" in body], ["boolean", "apply"]) + self.assertEqual(source.count("evaluated_of("), 4) # its def, evaluable, boolean and apply + self.assertIn("evaluated_of(", source.split("def evaluable(")[1].split("\n\n\n")[0]) place = source.split("def place_cutters(")[1].split("\n\n\n")[0] # cut and cut_many place through it: one evaluation, with the Booleans off - self.assertEqual(place.count("evaluated_of("), 1) - self.assertLess(place.index("modifier.show_viewport = False"), place.index("evaluated_of(")) - self.assertLess(place.index("evaluated_of("), place.index("modifier.show_viewport = True")) - self.assertLess(place.index("report(booleans(target)"), place.index("bpy.data.meshes.new(")) # every refusal before any write + self.assertEqual((place.count("evaluable("), place.count("evaluated_of(")), (1, 0)) + self.assertLess(place.index("modifier.show_viewport = False"), place.index("evaluable(")) + self.assertLess(place.index("evaluable("), place.index("modifier.show_viewport = True")) + # unevaluable-target: every action that evaluates refuses an object Blender does not evaluate before its first write + for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["apply"], "bpy.data.meshes.new_from_object(")): + self.assertLess(body.index("evaluable("), body.index(first_write)) + self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply"]) for body in (place, *(source.split(f"class BROKKR_KITBASH_OT_{name}(")[1].split("class BROKKR_KITBASH_OT_")[0] for name in ("cut", "cut_many"))): self.assertNotIn("view_layer.update", body) # an update after a cutter joins would evaluate the Boolean self.assertEqual(body.count("place_cutters("), 0 if body is place else 1) From 9440a14b027105453201398f3bd1470ea5a05074 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 05:59:32 +0100 Subject: [PATCH 091/223] brokkr_kitbash core: PROFILES, one mitred sweep, crossings, resample and spans, engine-free sweep takes a closed outline along a polyline: frames x = y cross t on the bisector tangent, mitred joints, quads ring to ring, n-gon caps, wound outward; it refuses a short segment, a turn over 150 degrees, an up along the path and a fold, naming the path point. crossings finds where a chain meets a half-plane whatever its start or direction. resample spaces a chain by arc length. spans says which runs of a section keep their frame: an open run under the bridge closes, the rest stand clear by the clearance. Swept carries the fields write_mesh reads; joined puts shells side by side. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/core.py | 213 ++++++++++++++++++++++++ surfaces/blender/tests/test_kitbash.py | 165 ++++++++++++++++++ 2 files changed, 378 insertions(+) diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index f41c8a8..5951bc4 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -17,6 +17,11 @@ both kits declare the socket's type with the same match rule. surface_frame is t 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. +The structure under an armor cage is swept, not kit parts: PROFILES are the sections (I, C, T, L, box), sweep takes +an outline along a polyline with mitred joints (a rib, a longeron, a post are all one sweep), crossings finds where a +section line meets a half-plane, resample spaces a section's points and spans says which runs of a section keep +their frame where the plate over them is open. brokkr_kitbash.ribs is the bpy around them. + A pin's roll is its one degree of freedom, and it is solved in closed form: roll_terms gives how a point or an axis of the child moves along a world direction as the roll turns (a cosine, a sine and a constant), aim_roll the roll that points an axis of the child at a direction, reach_roll the roll that brings a point of the child to a plane. @@ -591,6 +596,214 @@ def build(part: dict, params: dict | None = None) -> Built: shell_count=len(shells), sockets=sockets, bevel=bevel, params=env) +# --- structure: sections swept along paths -------------------------------------------------------------------- + +PROFILES = { # (w, h, t) -> the outline, counter-clockwise in (x across, y along up): flange width, height, wall + "I": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (t / 2, -h / 2 + t), (t / 2, h / 2 - t), (w / 2, h / 2 - t), + (w / 2, h / 2), (-w / 2, h / 2), (-w / 2, h / 2 - t), (-t / 2, h / 2 - t), (-t / 2, -h / 2 + t), (-w / 2, -h / 2 + t)], + "C": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (-w / 2 + t, -h / 2 + t), (-w / 2 + t, h / 2 - t), (w / 2, h / 2 - t), + (w / 2, h / 2), (-w / 2, h / 2)], + "T": lambda w, h, t: [(-t / 2, -h / 2), (t / 2, -h / 2), (t / 2, h / 2 - t), (w / 2, h / 2 - t), (w / 2, h / 2), (-w / 2, h / 2), (-w / 2, h / 2 - t), (-t / 2, h / 2 - t)], + "L": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (-w / 2 + t, -h / 2 + t), (-w / 2 + t, h / 2), (-w / 2, h / 2)], + "box": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2), (-w / 2, h / 2)], +} +TURN_LIMIT = 150.0 # degrees a swept path may turn at one point: past it a mitre runs 3.9 times the section's width + + +def profile(kind: str, w: float, h: float, t: float) -> np.ndarray: + """PROFILES[kind] at a width, height and wall, as an (M, 2) array. Refuses a kind PROFILES does not have, a size + that is not above 0, and a wall that leaves no section: as wide as the flange, or as thick as the height its + flanges share (two on an I and a C, one on a T and an L). A box has no wall.""" + if kind not in PROFILES: + raise KitError(f"profile {kind!r} is not one of {', '.join(PROFILES)}") + limit = min(w, h / 2 if kind in ("I", "C") else h) + if not all(finite(v) and v > 0 for v in (w, h, t)) or (kind != "box" and not t < limit): + raise KitError(f"profile {kind!r} of width {w}, height {h}, wall {t}: every size must be above 0 and the wall under {limit:.6g}") + return np.array(PROFILES[kind](w, h, t), dtype=np.float64) + + +def circle(r: float, segments: int) -> np.ndarray: + """A regular polygon of `segments` corners on radius r, counter-clockwise from +x: a rod's or a hole's outline.""" + if not (finite(r) and r > 0) or not SEGMENTS[0] <= segments <= SEGMENTS[1]: + raise KitError(f"circle of radius {r} and {segments} segments: the radius must be above 0 and the segments {SEGMENTS[0]} to {SEGMENTS[1]}") + angle = 2.0 * math.pi * np.arange(segments) / segments + return np.stack([r * np.cos(angle), r * np.sin(angle)], axis=1) + + +class Swept(NamedTuple): + """Closed shells that are no kit part: the five fields of a Built that a mesh is written from. Every face flat.""" + V: np.ndarray + faces: np.ndarray + counts: np.ndarray + smooth: np.ndarray + sharp: np.ndarray + + +def joined(shells: list) -> Swept: + """Several Swept as one, in order: shells beside each other, sharing no vertex.""" + offsets = np.cumsum([0] + [len(s.V) for s in shells[:-1]]) + return Swept(V=np.vstack([s.V for s in shells] or [np.zeros((0, 3))]).astype(np.float64), + faces=np.concatenate([s.faces + o for s, o in zip(shells, offsets)] or [np.zeros(0)]).astype(np.int32), + counts=np.concatenate([s.counts for s in shells] or [np.zeros(0)]).astype(np.int32), + smooth=np.concatenate([s.smooth for s in shells] or [np.zeros(0)]).astype(bool), + sharp=np.concatenate([s.sharp + o for s, o in zip(shells, offsets)] or [NO_SHARP]).astype(np.int32)) + + +def sweep(path, outline, ups, closed: bool = False) -> Swept: + """A closed 2D outline (counter-clockwise in x across, y up) swept along a polyline: one closed shell, wound + outward. At each path point the outline stands in the plane that bisects the turn: t is the unit bisector + tangent, y the unit projection of that point's up off t, x = y cross t (surface_frame's handedness, with t as its + z). The joint is mitred: the outline's component in the plane of the turn is stretched by 1 / cos(half the + turn), so the section keeps its size on both sides of a corner. Quads join ring to ring; an open path is capped + by the outline as an n-gon at each end. `ups` is one vector or one per point. + + Refuses, naming the point's index: fewer than 2 points (3 when closed), a segment shorter than 1e-9, a turn over + TURN_LIMIT, an up along the tangent, and a fold: an outline point whose step from one ring to the next runs + against the path's own segment there (the path turns tighter than the outline is wide on the inside).""" + path, outline, ups = np.asarray(path, dtype=np.float64), np.asarray(outline, dtype=np.float64), np.asarray(ups, dtype=np.float64) + count, m = len(path), len(outline) + if path.ndim != 2 or path.shape[1] != 3 or count < (3 if closed else 2) or not np.isfinite(path).all(): + raise KitError(f"a swept path needs {'3 points when closed' if closed else '2 points'} of three finite numbers; it has {count}") + if outline.ndim != 2 or outline.shape[1] != 2 or m < 3 or not np.isfinite(outline).all(): + raise KitError("a swept outline is 3 or more points of two finite numbers") + ups = np.broadcast_to(ups, (count, 3)) if ups.shape == (3,) else ups + if ups.shape != (count, 3) or not np.isfinite(ups).all(): + raise KitError(f"a sweep takes one up or one for each of its {count} points") + steps = (np.roll(path, -1, axis=0) - path)[:count if closed else count - 1] + lengths = np.linalg.norm(steps, axis=1) + if (lengths < 1e-9).any(): + raise KitError(f"path point {int(np.argmax(lengths < 1e-9))}: the segment from it is shorter than 1e-9") + along = steps / lengths[:, None] + before = np.roll(along, 1, axis=0) if closed else np.vstack([along[:1], along]) # the segment into each point + after = along if closed else np.vstack([along, along[-1:]]) # and the one out of it + cosine = np.clip(np.einsum("ij,ij->i", before, after), -1.0, 1.0) + turned = np.degrees(np.arccos(cosine)) + if (turned > TURN_LIMIT).any(): + index = int(np.argmax(turned > TURN_LIMIT)) + raise KitError(f"path point {index}: the path turns {turned[index]:.1f} degrees there, over {TURN_LIMIT:g}") + tangent = before + after + tangent /= np.linalg.norm(tangent, axis=1)[:, None] + y = ups - tangent * np.einsum("ij,ij->i", ups, tangent)[:, None] + flat = np.linalg.norm(y, axis=1) + if not (flat > 1e-6 * np.linalg.norm(ups, axis=1)).all(): + index = int(np.argmin(flat > 1e-6 * np.linalg.norm(ups, axis=1))) + raise KitError(f"path point {index}: up {ups[index].tolist()} runs along the path there (or is zero): give an up that crosses it") + y /= flat[:, None] + x = np.cross(y, tangent) + offsets = outline[None, :, 0, None] * x[:, None, :] + outline[None, :, 1, None] * y[:, None, :] # (count, m, 3) + bend = after - before # in the turn's plane, across the bisector tangent + size = np.linalg.norm(bend, axis=1) + bend = np.divide(bend, size[:, None], out=np.zeros_like(bend), where=size[:, None] > 1e-12) + stretch = 1.0 / np.sqrt((1.0 + cosine) / 2.0) - 1.0 # 1 / cos(half the turn) - 1 + offsets = offsets + (stretch[:, None] * np.einsum("imk,ik->im", offsets, bend))[:, :, None] * bend[:, None, :] + V = path[:, None, :] + offsets + forward = np.einsum("imk,ik->im", (np.roll(V, -1, axis=0) - V)[:len(steps)], steps) + if (forward <= 0).any(): + index = int(np.argmax((forward <= 0).any(axis=1))) + raise KitError(f"path point {index}: the section folds there: the path turns tighter than the outline reaches on the inside of the turn") + ring = np.arange(m) + quads = [np.stack([i * m + ring, i * m + (ring + 1) % m, j * m + (ring + 1) % m, j * m + ring], axis=1) for i, j in + ((i, (i + 1) % count) for i in range(len(steps)))] + faces, counts = [np.concatenate(quads).ravel()], [np.full(len(steps) * m, 4)] + if not closed: # the first cap looks back along the path, the last along it + faces += [ring[::-1], (count - 1) * m + ring] + counts += [np.array([m, m])] + counts = np.concatenate(counts).astype(np.int32) + return Swept(V=V.reshape(-1, 3), faces=np.concatenate(faces).astype(np.int32), counts=counts, smooth=np.zeros(len(counts), dtype=bool), sharp=NO_SHARP.astype(np.int32)) + + +def crossings(points, closed: bool, origin, axis, toward) -> list: + """Where a polyline crosses a half-plane: the half of the plane through `origin` that holds `axis` and `toward`, + on toward's side of the line (origin, axis). [(segment index, point)], ordered along the axis: the points are the + same wherever the chain starts and whichever way it runs. A vertex on the plane counts for one of its two + segments. Refuses an axis of no length and a toward along it.""" + points, origin, axis, toward = (np.asarray(v, dtype=np.float64) for v in (points, origin, axis, toward)) + if not np.linalg.norm(axis) > 0: + raise KitError(f"axis {axis.tolist()} has no direction") + axis = axis / np.linalg.norm(axis) + side = toward - axis * (toward @ axis) + if not np.linalg.norm(side) > 1e-6 * np.linalg.norm(toward) or not np.linalg.norm(side) > 0: + raise KitError(f"toward {toward.tolist()} runs along the axis {np.round(axis, 6).tolist()} (or is zero): give a toward that crosses it") + side = side / np.linalg.norm(side) + normal = np.cross(axis, side) + height = (points - origin) @ normal + found = [] + for i in range(len(points) if closed else len(points) - 1): + j = (i + 1) % len(points) + if (height[i] < 0) != (height[j] < 0): + point = points[i] + (points[j] - points[i]) * (height[i] / (height[i] - height[j])) + if (point - origin) @ side > 0: + found.append((i, point)) + return sorted(found, key=lambda hit: (float((hit[1] - origin) @ axis), float((hit[1] - origin) @ side))) + + +def resample(points, closed: bool, step: float) -> np.ndarray: + """Points along a polyline, evenly spaced by arc length and no more than `step` apart: an open one keeps both its + ends, a closed one starts at its first point and has at least 3.""" + points = np.asarray(points, dtype=np.float64) + if not (finite(step) and step > 0) or len(points) < 2: + raise KitError(f"resample needs 2 or more points and a step above 0; got {len(points)} and {step}") + loop = np.vstack([points, points[:1]]) if closed else points + lengths = np.linalg.norm(np.diff(loop, axis=0), axis=1) + reach = np.concatenate([[0.0], np.cumsum(lengths)]) + if not reach[-1] > 0: + raise KitError("resample: the polyline has no length") + pieces = max(3 if closed else 1, int(math.ceil(reach[-1] / step - 1e-9))) + at = reach[-1] * np.arange(pieces if closed else pieces + 1) / pieces + return np.stack([np.interp(at, reach, loop[:, k]) for k in range(3)], axis=1) + + +def spans(flags, lengths, closed: bool, bridge: float, clearance: float) -> list: + """The runs of a chain that keep their frame, as arrays of point indices in chain order. flags[i] says point i is + open (no plate over it); lengths[i] is the segment from point i to the next (N of them when closed, N - 1 when + not). An open run is as long as the chain between the kept points either side of it: one shorter than `bridge` + is closed (a panel break: the frame runs behind it); beside any other, the kept points nearer than `clearance` + are dropped. A run of fewer than 2 points is none. A closed chain's run may cross its start; with nothing open + its one run is every point, and only then is the run itself closed.""" + flags, lengths = np.array(flags, dtype=bool), np.asarray(lengths, dtype=np.float64) + count = len(flags) + if len(lengths) != (count if closed else count - 1): + raise KitError(f"spans: {count} points {'closed' if closed else 'open'} have {count if closed else count - 1} segments, not {len(lengths)}") + + def runs(wanted): + """Maximal runs of flags == wanted as (first, length in points), a closed chain's run across its start as one.""" + found, i = [], 0 + while i < count: + if flags[i] == wanted: + j = i + while j + 1 < count and flags[j + 1] == wanted: + j += 1 + found.append([i, j - i + 1]) + i = j + 1 + else: + i += 1 + if closed and len(found) > 1 and found[0][0] == 0 and found[-1][0] + found[-1][1] == count: + found[0] = [found[-1][0], found[-1][1] + found[0][1]] + found.pop() + return found + + def arc(first, segments): + return float(sum(lengths[(first + k) % len(lengths)] for k in range(segments))) + + if flags.all(): + return [] + for first, size in runs(True): + inside = closed or (first > 0 and first + size < count) # an open chain's own end is not a break to bridge + if inside and arc((first - 1) % count, size + 1) < bridge: + flags[[(first + k) % count for k in range(size)]] = False + if not flags.any(): + return [np.arange(count)] + kept = [] + for first, size in runs(False): + indices = [(first + k) % count for k in range(size)] + cut_before, cut_after = closed or first > 0, closed or first + size < count + along = np.concatenate([[0.0], np.cumsum([lengths[i % len(lengths)] for i in indices[:-1]])]) if size > 1 else np.zeros(1) + keep = [k for k in range(size) if (not cut_before or along[k] >= clearance) and (not cut_after or along[-1] - along[k] >= clearance)] + if len(keep) >= 2: + kept.append(np.array([indices[k] for k in keep])) + return kept + + # --- reports ------------------------------------------------------------------------------------------------- def rows(matrix) -> list[list[float]]: diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 2eda1cc..7df3386 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1164,6 +1164,171 @@ class PoseTests(unittest.TestCase): core.reach_roll(world, sp, sc, [rng.uniform(-1, 1) for _ in range(3)], (world @ sp["matrix"])[:3, 2], 0.0, 0.0) +@unittest.skipIf(np is None, "numpy is not installed") +class StructureTests(unittest.TestCase): + """core's sweep, crossings, resample and spans: what brokkr_kitbash.ribs builds a frame from. Every reading is + exact arithmetic, so each assertion is the built value and names the mutant it kills.""" + SQUARE = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0)] + BENT = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.7, 0.0), (0.2, 1.4, 0.0)] + + @staticmethod + def area(outline) -> float: + x, y = np.asarray(outline, dtype=np.float64).T + return float(0.5 * np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y)) + + def test_the_profiles_are_counter_clockwise_sections(self): + w, h, t = 0.06, 0.1, 0.012 + areas = {"I": 2 * w * t + (h - 2 * t) * t, "C": 2 * w * t + (h - 2 * t) * t, "T": w * t + (h - t) * t, "L": w * t + (h - t) * t, "box": w * h} + self.assertEqual(sorted(core.PROFILES), sorted(areas)) + for kind, area in areas.items(): + outline = core.profile(kind, w, h, t) + self.assertAlmostEqual(self.area(outline), area, places=15, msg=kind) + self.assertAlmostEqual(float(outline[:, 0].max() - outline[:, 0].min()), w, places=15) + self.assertAlmostEqual(float(outline[:, 1].max() - outline[:, 1].min()), h, places=15) + self.assertAlmostEqual(self.area(core.circle(0.5, 16)), 0.5 * 16 * 0.25 * math.sin(2 * math.pi / 16), places=15) + self.assertEqual(core.circle(0.5, 16)[0].tolist(), [0.5, 0.0]) + for bad in (("Z", w, h, t), ("I", w, h, h / 2), ("T", w, h, w), ("L", 0.0, h, t), ("C", w, h, float("nan")), ("box", w, h, 0.0)): + with self.assertRaisesRegex(core.KitError, "profile"): + core.profile(*bad) + for bad in ((0.0, 16), (0.5, 2), (0.5, 129)): + with self.assertRaisesRegex(core.KitError, "circle of radius"): + core.circle(*bad) + + def test_a_sweep_is_closed_wound_outward_and_mitred(self): + """sweep-closed-mitred. A mitred section whose centroid lies on the path in the plane of each turn sweeps its + area times the path's length exactly. Mutants K1 (no mitre: the square loop of a 0.1 by 0.2 box loses + 0.0117 of 0.08, and its corner stands 0.0354 from each wall, not 0.05) and K3 (caps wound inward: an open + sweep is no longer oriented).""" + box, tee = core.profile("box", 0.1, 0.2, 0.01), core.profile("T", 0.1, 0.12, 0.02) + for outline in (box, tee): + loop = core.sweep(self.SQUARE, outline, (0.0, 0.0, 1.0), closed=True) + self.assertTrue(closed_and_oriented(loop)) + self.assertAlmostEqual(signed_volume(loop), self.area(outline) * 4.0, places=12) + self.assertEqual((len(loop.V), len(loop.counts), int(loop.counts.sum()), bool(loop.smooth.any()), len(loop.sharp)), (4 * len(outline), 4 * len(outline), 16 * len(outline), False, 0)) + bent = core.sweep(self.BENT, outline, (0.0, 0.0, 1.0)) + self.assertTrue(closed_and_oriented(bent)) + self.assertAlmostEqual(signed_volume(bent), self.area(outline) * (1.0 + 0.7 + math.hypot(0.8, 0.7)), places=12) + self.assertEqual(sorted(bent.counts.tolist())[-2:], [len(outline)] * 2) # two n-gon caps + loop = core.sweep(self.SQUARE, box, (0.0, 0.0, 1.0), closed=True) + ring = loop.V[4:8] # at the corner (1, 0, 0), between the walls y = 0 and x = 1 + self.assertAlmostEqual(float(np.abs(ring[:, 1]).max()), 0.05, places=12) + self.assertAlmostEqual(float(np.abs(ring[:, 0] - 1.0).max()), 0.05, places=12) + self.assertAlmostEqual(float(np.abs(ring[:, 0] - 1.0).min()), 0.05, places=12) + self.assertEqual(sorted(round(float(z), 12) for z in ring[:, 2]), [-0.1, -0.1, 0.1, 0.1]) + again = core.sweep(self.SQUARE, box, (0.0, 0.0, 1.0), closed=True) + self.assertTrue(all(np.array_equal(a, b) for a, b in zip(loop, again))) + + def test_a_sweep_stands_as_a_surface_frame_does(self): + """x = y cross t, as core.surface_frame's x = y cross z: a rod along +z with up +y carries its outline as that frame does.""" + rod = core.sweep([(0.0, 0.0, 0.0), (0.0, 0.0, 2.0)], [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)], (0.0, 1.0, 0.0)) + frame = core.surface_frame((0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 1.0, 0.0)) + self.assertEqual(rod.V[:3].tolist(), [[0.0, 0.0, 0.0], frame[:3, 0].tolist(), frame[:3, 1].tolist()]) + self.assertEqual(rod.V[3:, 2].tolist(), [2.0, 2.0, 2.0]) + self.assertAlmostEqual(signed_volume(rod), 1.0, places=12) + per_point = core.sweep([(0.0, 0.0, 0.0), (0.0, 0.0, 2.0)], [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)], [(0.0, 1.0, 0.0), (1.0, 0.0, 0.0)]) + self.assertEqual(np.round(per_point.V[3:], 12).tolist(), [[0.0, 0.0, 2.0], [0.0, -1.0, 2.0], [1.0, 0.0, 2.0]]) # the far ring turned with its own up + + def test_sweep_refuses_what_makes_no_section(self): + """sweep-refusals, each naming the path point. Mutant K2 (no fold refusal: the tight arc is swept into a + shell that crosses itself).""" + box = core.profile("box", 0.1, 0.1, 0.01) + with self.assertRaisesRegex(core.KitError, "needs 2 points of three finite numbers; it has 1"): + core.sweep([(0.0, 0.0, 0.0)], box, (0.0, 0.0, 1.0)) + with self.assertRaisesRegex(core.KitError, "needs 3 points when closed"): + core.sweep(self.SQUARE[:2], box, (0.0, 0.0, 1.0), closed=True) + with self.assertRaisesRegex(core.KitError, "path point 1: the segment from it is shorter than 1e-9"): + core.sweep([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.0, 0.0), (2.0, 0.0, 0.0)], box, (0.0, 0.0, 1.0)) + sharp = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0 - math.cos(math.radians(10)), math.sin(math.radians(10)), 0.0)] + with self.assertRaisesRegex(core.KitError, r"path point 1: the path turns 170\.0 degrees there, over 150"): + core.sweep(sharp, box, (0.0, 0.0, 1.0)) + with self.assertRaisesRegex(core.KitError, r"path point 0: up \[1\.0, 0\.0, 0\.0\] runs along the path there"): + core.sweep(self.BENT, box, (1.0, 0.0, 0.0)) + with self.assertRaisesRegex(core.KitError, r"path point 2: up \[0\.0, 0\.0, 0\.0\] runs along the path there"): + core.sweep(self.BENT, box, [(0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 0.0), (0.0, 0.0, 1.0)]) + with self.assertRaisesRegex(core.KitError, "one up or one for each of its 4 points"): + core.sweep(self.BENT, box, [(0.0, 0.0, 1.0)] * 3) + arc = [(0.05 * math.cos(a), 0.05 * math.sin(a), 0.0) for a in np.linspace(0.0, math.pi, 13)] # radius 0.05, turning left about +z + inside = [(0.1, -0.05), (0.3, -0.05), (0.3, 0.05), (0.1, 0.05)] # x = y cross t points into this turn: 0.1 to 0.3 inside a radius of 0.05 + with self.assertRaisesRegex(core.KitError, r"path point \d+: the section folds there"): + core.sweep(arc, inside, (0.0, 0.0, 1.0)) + outside = [(-x, y) for x, y in inside][::-1] + self.assertTrue(closed_and_oriented(core.sweep(arc, outside, (0.0, 0.0, 1.0)))) + self.assertTrue(closed_and_oriented(core.sweep(arc, [(x * 0.1, y) for x, y in inside], (0.0, 0.0, 1.0)))) # 0.01 to 0.03 inside a radius of 0.05 + + def test_crossings_do_not_depend_on_where_a_chain_starts(self): + """crossings-start-free. The same closed chain rotated to every start and reversed crosses a half-plane at + the same point; the opposite half-plane finds the opposite point; a chain off the plane finds none. Mutant K9 + (a station at a fraction of the section's length: it moves with the start).""" + angle = 2.0 * math.pi * (np.arange(40) + 0.3) / 40 + chain = np.stack([0.8 * np.cos(angle), 0.5 * np.sin(angle), np.full(40, 0.7)], axis=1) + origin, axis = (0.1, 0.05, 0.0), (0.0, 0.0, 1.0) + (segment, point), = core.crossings(chain, True, origin, axis, (1.0, 0.3, 0.0)) + self.assertTrue(point[0] > 0.1 and abs((point[1] - 0.05) - 0.3 * (point[0] - 0.1)) < 1e-12 and point[2] == 0.7) + self.assertTrue(np.allclose(point, chain[segment] + (chain[(segment + 1) % 40] - chain[segment]) * 0.5, atol=0.1)) + for start in range(40): + for turned in (np.roll(chain, -start, axis=0), np.roll(chain, -start, axis=0)[::-1]): + (_, again), = core.crossings(turned, True, origin, axis, (1.0, 0.3, 0.0)) + self.assertLess(float(np.abs(again - point).max()), 1e-12) + (_, other), = core.crossings(chain, True, origin, axis, (-1.0, -0.3, 0.0)) + self.assertLess(other[0], 0.1) + self.assertEqual(core.crossings(chain + [5.0, 0.0, 0.0], True, origin, axis, (0.0, 1.0, 0.0)), []) + self.assertEqual(len(core.crossings(chain[:20], False, origin, axis, (-1.0, -0.3, 0.0))), 0) # the open half that holds the other point only + self.assertEqual(len(core.crossings(chain[:20], False, origin, axis, (1.0, 0.3, 0.0))), 1) + on_vertex = [(-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (1.0, 0.0, 0.0)] # its middle vertex lies on the plane x = 0: one crossing, not two + self.assertEqual([(i, p.tolist()) for i, p in core.crossings(on_vertex, False, (0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 1.0, 0.0))], [(1, [0.0, 1.0, 0.0])]) + two = core.crossings([(-1.0, 1.0, 2.0), (1.0, 1.0, 2.0), (1.0, 1.0, 1.0), (-1.0, 1.0, 1.0)], False, (0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 1.0, 0.0)) + self.assertEqual([(i, p.tolist()) for i, p in two], [(2, [0.0, 1.0, 1.0]), (0, [0.0, 1.0, 2.0])]) # ordered along the axis + with self.assertRaisesRegex(core.KitError, "has no direction"): + core.crossings(chain, True, origin, (0.0, 0.0, 0.0), (1.0, 0.0, 0.0)) + with self.assertRaisesRegex(core.KitError, "runs along the axis"): + core.crossings(chain, True, origin, axis, (0.0, 0.0, 2.0)) + + def test_resample_spaces_points_by_arc_length(self): + line = core.resample([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0)], False, 0.3) + self.assertEqual((len(line), line[0].tolist(), line[-1].tolist()), (8, [0.0, 0.0, 0.0], [1.0, 1.0, 0.0])) + self.assertTrue(np.allclose(np.linalg.norm(np.diff(line, axis=0), axis=1)[[0, 1, 2, 4, 5, 6]], 2.0 / 7, atol=1e-12)) + loop = core.resample(self.SQUARE, True, 0.25) + self.assertEqual((len(loop), loop[0].tolist(), loop[4].tolist(), loop[15].tolist()), (16, [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.25, 0.0])) + self.assertEqual(len(core.resample(self.SQUARE, True, 100.0)), 3) + self.assertEqual(len(core.resample(self.SQUARE[:2], False, 100.0)), 2) + for bad in ((self.SQUARE[:1], False, 0.1), (self.SQUARE, True, 0.0), ([(0.0, 0.0, 0.0)] * 2, False, 0.1)): + with self.assertRaisesRegex(core.KitError, "resample"): + core.resample(*bad) + + def test_spans_bridge_a_break_and_stand_clear_of_a_port(self): + """spans. Twenty points 0.25 apart, a bridge of 1.25 and a clearance of 0.5. Mutants K5 (bridge ignored: the two-point break splits the run) and K6 + (clearance ignored: the run reaches the port's edge points).""" + def flags(*opened): + return [i in opened for i in range(20)] + closed, unclosed = [0.25] * 20, [0.25] * 19 + as_lists = lambda found: [run.tolist() for run in found] # noqa: E731 + self.assertEqual(as_lists(core.spans(flags(), closed, True, 1.25, 0.5)), [list(range(20))]) + self.assertEqual(as_lists(core.spans(flags(), unclosed, False, 1.25, 0.5)), [list(range(20))]) + self.assertEqual(core.spans([True] * 20, closed, True, 1.25, 0.5), []) + # a break of two open points is 0.75 between the kept points either side: under the bridge it closes, and the run is whole + self.assertEqual(as_lists(core.spans(flags(7, 8), closed, True, 1.25, 0.5)), [list(range(20))]) + self.assertEqual(as_lists(core.spans(flags(7, 8), closed, True, 0.75, 0.0)), [list(range(9, 20)) + list(range(7))]) # as long as the bridge: not closed; the run wraps the start + # a port of six open points (1.75) stays open, and the kept points within 0.5 of it go: two each side + self.assertEqual(as_lists(core.spans(flags(*range(5, 11)), closed, True, 1.25, 0.5)), [list(range(13, 20)) + list(range(3))]) + self.assertEqual(as_lists(core.spans(flags(*range(5, 11)), unclosed, False, 1.25, 0.5)), [list(range(0, 3)), list(range(13, 20))]) # an open chain's own ends stand + self.assertEqual(as_lists(core.spans(flags(*range(5, 11)), unclosed, False, 1.25, 0.0)), [list(range(0, 5)), list(range(11, 20))]) + # a port across a closed chain's start is one run; an open chain's first points being open is no break to bridge + self.assertEqual(as_lists(core.spans(flags(18, 19, 0, 1, 2, 3), closed, True, 1.25, 0.5)), [list(range(6, 16))]) + self.assertEqual(as_lists(core.spans(flags(0, 1), unclosed, False, 1.25, 0.5)), [list(range(4, 20))]) + self.assertEqual(as_lists(core.spans(flags(7, 8, *range(12, 18)), closed, True, 1.25, 0.5)), [list(range(0, 10))]) + self.assertEqual(core.spans(flags(*range(2, 18)), closed, True, 1.25, 0.5), []) # four kept points, each within 0.5 of the port + with self.assertRaisesRegex(core.KitError, "20 points closed have 20 segments, not 19"): + core.spans(flags(), unclosed, True, 1.25, 0.5) + + def test_joined_shells_stand_beside_each_other(self): + a, b = core.sweep(self.BENT, core.profile("box", 0.1, 0.1, 0.01), (0.0, 0.0, 1.0)), core.sweep(self.SQUARE, core.profile("T", 0.1, 0.12, 0.02), (0.0, 0.0, 1.0), closed=True) + both = core.joined([a, b]) + self.assertTrue(closed_and_oriented(both)) + self.assertAlmostEqual(signed_volume(both), signed_volume(a) + signed_volume(b), places=12) + self.assertEqual((len(both.V), len(both.counts), both.faces[len(a.faces):].min()), (len(a.V) + len(b.V), len(a.counts) + len(b.counts), len(a.V))) + self.assertEqual((len(core.joined([]).V), len(core.joined([]).counts)), (0, 0)) + + ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply"] From 4265443faddd30d29767054fd56330e42f584d78 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 06:38:45 +0100 Subject: [PATCH 092/223] brokkr_kitbash.ribs: ribs, lightening holes, posts and longerons derived from an armor cage as it is cut ribs reads the cage twice: with its Solidify, Bevel and Booleans off (the surface as designed; each plane cuts it into sections) and whole (the plate as cut: a ray at each section point says whether the plate is there). A rib is core.sweep of a rectangle along a section, set the standoff behind the plate's inner face; it stops clear of a port, runs behind a panel break and under a recess. Inward comes from the cage's normals, and a section whose normals change sides is refused. Posts and longerons are the same sweep; a longeron's stations are where its half-plane crosses each plane's rib, found by core.crossings. Holes are one Manifold Boolean a plane on that plane's webs alone, checked (closed, volume gone the holes' own) and refused otherwise; it is the one Manifold Boolean in the package. Every refusal comes before the ribs object is written; kit_ribs records the request. core: resample keeps a section's corners and fills between them (points spaced by arc length cut each corner in two and an inward offset folds between them); cornered says which points a frame is swept through. tests/live/kitbash_ribs.py pins it; bounds by the margin rule beside each constant. bl_info blender 5.3. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 287 ++++++++++++- .../brokkr_kitbash/brokkr_actions.json | 150 +++++++ surfaces/blender/brokkr_kitbash/core.py | 42 +- surfaces/blender/tests/live/kitbash.py | 2 +- .../blender/tests/live/kitbash.result.json | 3 +- .../blender/tests/live/kitbash_assembly.py | 2 +- surfaces/blender/tests/live/kitbash_ribs.py | 395 ++++++++++++++++++ .../tests/live/kitbash_ribs.result.json | 174 ++++++++ surfaces/blender/tests/test_kitbash.py | 63 ++- 9 files changed, 1093 insertions(+), 25 deletions(-) create mode 100644 surfaces/blender/tests/live/kitbash_ribs.py create mode 100644 surfaces/blender/tests/live/kitbash_ribs.result.json diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 05b6129..c566a12 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -36,12 +36,19 @@ one Boolean evaluation; cut_many places many cutters for one. Every action that cut_many, apply) first refuses one Blender does not evaluate (evaluable). A report's list that would not fit a receipt is trimmed by fitted, the rows left off counted beside it: the scene keeps what they would have said. +ribs derives the frame under an armor cage from the cage: ribs behind the plate along plane sections, stopped where +the plate is open, with lightening holes, posts and longerons, all core.sweep. What it reads is the cage evaluated +whole (where the plate is) and with its Solidify, Bevel and Booleans off (the surface as designed); it never reads +a cutter. The ribs object is a bake of the cage at that call, and kit_ribs on it is the request, kept as a record: +nothing reads it to decide geometry, and ribs is its one writer. The one Manifold Boolean in the package is the hole +cut inside ribs, on webs it built as closed shells that do not cross; a target's live Booleans stay Exact. + 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 solves a loop: a closure never places a part, and a report says how far its two sockets stand apart. """ -bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), +bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (5, 3, 0), "category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."} import json @@ -70,6 +77,8 @@ 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 +RIBS_LIMIT = 64 # planes in one ribs +LONGERONS_LIMIT = 16 # longerons in one ribs def kit_work(work): @@ -880,6 +889,280 @@ class BROKKR_KITBASH_OT_apply(PolishOperator): return {**part_report(obj, part, built), **measured(baked), "cutters": cutters} +RIBS = "kit_ribs" # on a ribs object: the request that derived it, as JSON; nothing reads it to decide geometry +SAMPLES_LIMIT = 20000 # section points in one ribs: every chain's length over step, summed +SHELL_MODIFIERS = ("SOLIDIFY", "BEVEL", "BOOLEAN") # what makes a designed surface a cut plate: off, the cage shows the surface +LIFT = 0.01 # metres outside the plate's outer face that the ray asking "is the plate here" starts +NUDGE = 1e-4 # metres along the section that ray is moved off its point: a section's corners lie on the cage's edges, and a ray along an edge can slip between two faces +HOLE_SEGMENTS, POST_SEGMENTS, PAD_SEGMENTS = 16, 8, 12 +# What a plane's lightening holes removed from its webs, over the holes' faceted area times the rib's thickness, less 1. +# Bound by lodur:ruling:deterministic-bound-margin: shipped worst 2.9e-06 (tests/live/kitbash_ribs.py: thirteen planes +# on a pod, a deck and an egg-crate, float32 meshes); least claimed bad cut 0.0066 (holes of radius 0.018 pitched 0.02, +# which overlap, on the egg-crate); the geometric mean, separation 47 each side. +HOLED = 1.4e-4 + + +def vectors(text: str, what: str, keys, least: int, limit: int) -> list: + """A JSON array of objects whose every key is three finite numbers, as arrays; anything else is refused.""" + try: + rows = json.loads(text) + except ValueError as error: + raise Refused(f"{what} is not JSON ({error}); nothing changed.") from None + if not isinstance(rows, list) or not least <= len(rows) <= limit: + raise Refused(f"{what} must be a JSON array of {least} to {limit} objects; nothing changed.") + for index, row in enumerate(rows): + if not isinstance(row, dict) or set(row) != set(keys) or not all(isinstance(row[k], list) and len(row[k]) == 3 and all(core.finite(v) for v in row[k]) for k in keys): + raise Refused(f"{what}[{index}] must be an object of {' and '.join(keys)}, each three numbers; nothing changed.") + return [{k: np.array(row[k], dtype=np.float64) for k in keys} for row in rows] + + +def chains_of(edges) -> list: + """The edges a plane cut, ordered into polylines: [(points (N, 3), closed)], open ones first, each from its + lowest vertex. None when a vertex joins three or more cut edges: no polyline passes it.""" + links = {} + for edge in edges: + a, b = edge.verts + links.setdefault(a, []).append(b) + links.setdefault(b, []).append(a) + if any(len(found) > 2 for found in links.values()): + return None + seen, chains = set(), [] + for start in sorted((v for v in links if len(links[v]) == 1), key=lambda v: v.index) + sorted(links, key=lambda v: v.index): + if start in seen: + continue + chain, here = [start], start + seen.add(start) + while True: + ahead = [v for v in links[here] if v not in seen] + if not ahead: + break + here = ahead[0] + chain.append(here) + seen.add(here) + chains.append((np.array([v.co for v in chain], dtype=np.float64), len(chain) > 2 and chain[0] in links[chain[-1]])) + return chains + + +def along(points, closed: bool, pitch: float): + """Stations on a polyline every `pitch` of its length, half a pitch from an open one's ends (none on one shorter + than a pitch), evenly round a closed one: [(point, segment index, fraction along the segment)].""" + loop = np.vstack([points, points[:1]]) if closed else points + reach = np.concatenate([[0.0], np.cumsum(np.linalg.norm(np.diff(loop, axis=0), axis=1))]) + count = int(reach[-1] / pitch + 1e-9) + found = [] + for at in (reach[-1] * np.arange(count) / max(count, 1) if closed else pitch / 2 + pitch * np.arange(count)): + segment = min(int(np.searchsorted(reach, at, side="right")) - 1, len(loop) - 2) + fraction = (at - reach[segment]) / (reach[segment + 1] - reach[segment]) + found.append((loop[segment] + (loop[segment + 1] - loop[segment]) * fraction, segment, fraction)) + return found + + +def shells_of(mesh) -> core.Swept: + """A mesh datablock's vertices and faces as core.Swept, every face flat.""" + V, faces, counts = np.zeros(3 * len(mesh.vertices)), np.zeros(len(mesh.loops), dtype=np.int32), np.zeros(len(mesh.polygons), dtype=np.int32) + mesh.vertices.foreach_get("co", V) + mesh.loops.foreach_get("vertex_index", faces) + mesh.polygons.foreach_get("loop_total", counts) + return core.Swept(V=V.reshape(-1, 3), faces=faces, counts=counts, smooth=np.zeros(len(counts), dtype=bool), sharp=core.NO_SHARP.astype(np.int32)) + + +class BROKKR_KITBASH_OT_ribs(PolishOperator): + """Derive the frame under an armor cage from the cage itself: a rib behind the plate along each plane's section, + stopped where the plate is open, lightening holes through the ribs, posts that stand the plate off them, and + longerons through the ribs; one mesh object, a child of the cage, baked at this call""" + bl_idname = "brokkr_kitbash.ribs" + bl_label = "Ribs From A Shell" + object_name: bpy.props.StringProperty(name="Object", description="The cage: a mesh whose surface is the plate's designed face, usually subdivided and with one Solidify") + ribs_name: bpy.props.StringProperty(name="Ribs", description="The new ribs object's name") + planes: bpy.props.StringProperty(name="Planes", description="A JSON array of 1 to 64 planes, each {origin, normal} in the cage's own frame: a rib runs where each cuts the surface") + standoff: bpy.props.FloatProperty(name="Standoff", default=0.09, min=0.0, max=2.0, description="Metres between the plate's inner face and the ribs") + depth: bpy.props.FloatProperty(name="Depth", default=0.09, min=0.005, max=2.0, description="How far a rib reaches inward from there") + thickness: bpy.props.FloatProperty(name="Thickness", default=0.014, min=0.0005, max=1.0, description="A rib's thickness across its plane") + step: bpy.props.FloatProperty(name="Step", default=0.01, min=0.001, max=1.0, description="Spacing of the points a section is followed by") + holes: bpy.props.FloatProperty(name="Holes", default=0.0, min=0.0, max=10.0, description="Pitch of lightening holes along each rib, radius 0.3 of depth; 0: none") + posts: bpy.props.FloatProperty(name="Posts", default=0.0, min=0.0, max=10.0, description="Pitch of the posts that stand the plate off each rib; 0: none") + post_r: bpy.props.FloatProperty(name="Post Radius", default=0.011, min=0.0005, max=0.5) + bridge: bpy.props.FloatProperty(name="Bridge", default=0.05, min=0.0, max=2.0, description="An opening shorter than this along a section is a panel break: the rib runs behind it") + clearance: bpy.props.FloatProperty(name="Clearance", default=0.02, min=0.0, max=2.0, description="How far a rib stops short of any other opening") + longerons: bpy.props.StringProperty(name="Longerons", default="[]", description="A JSON array of 0 to 16 longerons, each {origin, axis, toward} in the cage's own frame: " + "the half-plane from the line through origin along axis, on toward's side; the longeron runs through each plane's rib where it crosses") + longeron: bpy.props.EnumProperty(name="Longeron", default="T", items=[(name, name, "") for name in core.PROFILES]) + longeron_w: bpy.props.FloatProperty(name="Longeron Width", default=0.05, min=0.005, max=2.0) + longeron_h: bpy.props.FloatProperty(name="Longeron Height", default=0.05, min=0.005, max=2.0) + longeron_t: bpy.props.FloatProperty(name="Longeron Wall", default=0.008, min=0.0005, max=1.0) + + # the action table states each bound (thickness, step and the walls from 0.001 or 0.002): a float property rounds 0.001 up, so these stand just under + @kit_work + def work(self, context): + cage = mesh_object(self.object_name) + rigid(cage) + depsgraph, _ = evaluable(context, cage) + if not 1 <= len(self.ribs_name) <= 63 or self.ribs_name in bpy.data.objects: + raise Refused(f"ribs_name {self.ribs_name!r} must be 1 to 63 characters and no object's name; nothing changed.") + planes = vectors(self.planes, "planes", ("origin", "normal"), 1, RIBS_LIMIT) + longerons = vectors(self.longerons, "longerons", ("origin", "axis", "toward"), 0, LONGERONS_LIMIT) + for index, plane in enumerate(planes): + if not np.linalg.norm(plane["normal"]) > 0: + raise Refused(f"planes[{index}].normal has no direction; nothing changed.") + plane["normal"] = plane["normal"] / np.linalg.norm(plane["normal"]) + if longerons and len(planes) < 2: + raise Refused("A longeron runs through the ribs of two or more planes; this call has one; nothing changed.") + beam = core.profile(self.longeron, self.longeron_w, self.longeron_h, self.longeron_t) if longerons else None + walls = [m for m in cage.modifiers if m.type == "SOLIDIFY" and m.show_viewport] + if len(walls) > 1: + raise Refused(f"{cage.name!r} has {len(walls)} Solidify modifiers ({', '.join(m.name for m in walls)}): its plate has one thickness, read from one; nothing changed.") + plate, offset = (abs(walls[0].thickness), walls[0].offset) if walls else (0.0, 0.0) + outer, inner = plate * (1.0 + offset) / 2.0, plate * (1.0 - offset) / 2.0 # the plate's two faces, out of and into the designed surface + near, mid = inner + self.standoff, inner + self.standoff + self.depth / 2.0 + web = np.array([(-self.thickness / 2, near), (self.thickness / 2, near), (self.thickness / 2, near + self.depth), (-self.thickness / 2, near + self.depth)]) + whole = BVHTree.FromObject(cage, depsgraph) # the plate as it is cut: where a ray into it finds nothing, it is open + shown = [m for m in cage.modifiers if m.type in SHELL_MODIFIERS and m.show_viewport] + surface, made, drilled, sections, webs, rods, beams, samples, holes = None, [], [], [], [], [], [], 0, 0 + try: + for modifier in shown: + modifier.show_viewport = False + _, designed = evaluated_of(context, cage) + surface = bmesh.new() + surface.from_mesh(designed.to_mesh()) + designed.to_mesh_clear() + nearest = BVHTree.FromBMesh(surface) + for index, plane in enumerate(planes): + where, normal = f"planes[{index}]", plane["normal"] + cut = surface.copy() + edges = [g for g in bmesh.ops.bisect_plane(cut, geom=cut.verts[:] + cut.edges[:] + cut.faces[:], plane_co=Vector(plane["origin"]), plane_no=Vector(normal), + dist=1e-6)["geom_cut"] if isinstance(g, bmesh.types.BMEdge)] + cut.verts.index_update() + chains = chains_of(edges) + cut.free() + if chains is None: + raise Refused(f"{where} cuts {cage.name!r} where three or more of its faces share an edge: no section passes there; nothing changed.") + if not chains: + raise Refused(f"{where} misses {cage.name!r}; nothing changed.") + row = {"plane": index, "chains": len(chains), "pieces": 0, "length": 0.0, "open": 0.0, "ribs": [], "lines": []} + for points, closed in chains: + samples += int(np.linalg.norm(np.diff(points, axis=0), axis=1).sum() / self.step) + 1 + if samples > SAMPLES_LIMIT: + raise Refused(f"The sections are over {SAMPLES_LIMIT} points at step {self.step:.6g}: raise step, or give fewer planes; nothing changed.") + P = core.resample(points, closed, self.step) + out = np.array([nearest.find_nearest(Vector(p))[1] for p in P], dtype=np.float64) + flat = out - normal * (out @ normal)[:, None] + if not (np.linalg.norm(flat, axis=1) > 1e-3).all(): + raise Refused(f"{where} lies along {cage.name!r}'s surface where it meets it: a rib needs a plane that crosses the plate; nothing changed.") + inward = -flat / np.linalg.norm(flat, axis=1)[:, None] + ahead = np.roll(P, -1, axis=0) - np.roll(P, 1, axis=0) if closed else np.gradient(P, axis=0) + turn = np.cross(ahead, inward) @ normal # which side of the section its normals stand on: one sign all the way along + if (turn > 0).any() and (turn < 0).any(): + raise Refused(f"{where}: the normals of {cage.name!r} change sides along the section (some of its faces are flipped): " + "recalculate its normals so they all face out of the plate; nothing changed.") + if turn[0] < 0: # every section runs the same way about its plane's normal, wherever its chain started + P, out, inward = P[::-1], out[::-1], inward[::-1] + aside = np.roll(P, -1, axis=0) - P if closed else np.vstack([np.diff(P, axis=0), P[-2:-1] - P[-1:]]) # toward the next point; an open chain's last, toward the one before + aside = aside / np.linalg.norm(aside, axis=1)[:, None] * NUDGE + reach = LIFT + 1.25 * plate + 1e-4 + opened = [whole.ray_cast(Vector(p + n * (outer + LIFT)), Vector(-n), reach)[0] is None for p, n in zip(P + aside, out)] + lengths = np.linalg.norm(np.diff(np.vstack([P, P[:1]]) if closed else P, axis=0), axis=1) + row["lines"].append((P + inward * mid, closed)) + for piece in core.spans(opened, lengths, closed, self.bridge, self.clearance): + ring = closed and len(piece) == len(P) + piece = piece[core.cornered(P[piece], ring, near + self.depth)] # swept corner to corner + if len(piece) < 2: + continue + try: + rib = core.sweep(P[piece], web, inward[piece], closed=ring) + except core.KitError as error: + raise Refused(f"{where}: {error}: lower standoff or depth; nothing changed.") from None + centre = rib.V.reshape(len(piece), 4, 3).mean(axis=1) # the rib's mid-depth line, as swept + row["ribs"].append((centre, ring, P[piece], inward[piece])) + row["pieces"] += 1 + row["length"] += float(np.linalg.norm(np.diff(np.vstack([P[piece], P[piece][:1]]) if ring else P[piece], axis=0), axis=1).sum()) + webs.append((index, rib)) + row["open"] += float(lengths.sum()) + row["open"] = round(max(row["open"] - row["length"], 0.0), 6) + sections.append(row) + if not webs: + raise Refused(f"No rib: the plate of {cage.name!r} is open along every section; nothing changed.") + for row in sections: # posts stand on the kept runs only + for centre, ring, P, inward in row["ribs"] if self.posts > 0 else (): + for point, segment, fraction in along(P, ring, self.posts): + n = inward[segment] + (inward[(segment + 1) % len(P)] - inward[segment]) * fraction + n, up = n / np.linalg.norm(n), planes[row["plane"]]["normal"] + rods.append(core.sweep([point + n * (inner - outer) / 2.0, point + n * (near + 0.3 * self.depth)], core.circle(self.post_r, POST_SEGMENTS), up)) + rods.append(core.sweep([point + n * inner, point + n * (inner + self.post_r)], core.circle(2.4 * self.post_r, PAD_SEGMENTS), up)) + for index, longeron in enumerate(longerons): + where, stations, ups = f"longerons[{index}]", [], [] + for row in sections: + try: + hits = [(hit, rib) for rib in row["ribs"] for hit in core.crossings(rib[0], rib[1], longeron["origin"], longeron["axis"], longeron["toward"])] + through = any(core.crossings(line, closed, longeron["origin"], longeron["axis"], longeron["toward"]) for line, closed in row["lines"]) + except core.KitError as error: + raise Refused(f"{where}: {error}; nothing changed.") from None + if len(hits) != 1: + raise Refused(f"{where} " + (f"meets the ribs of planes[{row['plane']}] {len(hits)} times: its half-plane must cross them once" if hits else + f"crosses planes[{row['plane']}] where the plate is open and there is no rib" if through else + f"does not meet the ribs of planes[{row['plane']}]") + "; nothing changed.") + ((segment, point), (centre, ring, P, inward)), = hits + n = inward[segment] + (inward[(segment + 1) % len(P)] - inward[segment]) * float(np.linalg.norm(point - centre[segment]) / np.linalg.norm(centre[(segment + 1) % len(P)] - centre[segment])) + stations.append(point) + ups.append(-n / np.linalg.norm(n)) # up toward the plate + path = [stations[0] + (stations[0] - stations[1]) * 0.12] + stations + [stations[-1] + (stations[-1] - stations[-2]) * 0.12] + try: + beams.append((index, stations, core.sweep(path, beam, ups[:1] + ups + ups[-1:]))) + except core.KitError as error: + raise Refused(f"{where}: {error}; nothing changed.") from None + for index in sorted({index for index, _ in webs}) if self.holes > 0 else (): # one Boolean a plane: a plane's webs never cross each other, two planes' do + normal = planes[index]["normal"] + drills = [core.sweep([point - normal * 2.0 * self.thickness, point + normal * 2.0 * self.thickness], core.circle(0.3 * self.depth, HOLE_SEGMENTS), inward[segment]) + for centre, ring, _, inward in sections[index]["ribs"] for point, segment, _ in along(centre, ring, self.holes)] + if not drills: + continue + pair = [] + for name, shells in ((f"{self.ribs_name}.webs.{index}", [rib for at, rib in webs if at == index]), (f"{self.ribs_name}.holes.{index}", drills)): + pair.append(bpy.data.objects.new(name, bpy.data.meshes.new(name))) + made.append(pair[-1]) + write_mesh(pair[-1].data, core.joined(shells)) + context.scene.collection.objects.link(pair[0]) + modifier = pair[0].modifiers.new("Holes", "BOOLEAN") # closed shells that do not cross: what Manifold takes, a hundred times sooner than Exact + modifier.object, modifier.operation = pair[1], "DIFFERENCE" + modifier.solver = "MANIFOLD" + drilled.append((index, len(drills), measured(pair[0].data)["volume"], pair[0])) + for index, count, before, target in drilled: + _, holed = evaluated_of(context, target) + cut_mesh = holed.to_mesh() + after, cut_webs = measured(cut_mesh), shells_of(cut_mesh) + holed.to_mesh_clear() + wanted = count * 0.5 * HOLE_SEGMENTS * (0.3 * self.depth) ** 2 * math.sin(2.0 * math.pi / HOLE_SEGMENTS) * self.thickness + if after["nonManifoldEdges"] or not abs((before - after["volume"]) / wanted - 1.0) < HOLED: + raise Refused(f"planes[{index}]: the lightening holes did not cut cleanly (they removed {before - after['volume']:.6g} m3 where {count} holes are {wanted:.6g}, and left " + f"{after['nonManifoldEdges']} open edges): they overlap or leave the rib; raise holes, or lower depth; nothing changed.") + webs = [(at, rib) for at, rib in webs if at != index] + [(index, cut_webs)] + holes += count + finally: + for modifier in shown: + modifier.show_viewport = True + for obj in made: # the webs and drills of the hole cut: gone whether it held or not + mesh = obj.data + bpy.data.objects.remove(obj) + bpy.data.meshes.remove(mesh) + if surface is not None: + surface.free() + mesh = bpy.data.meshes.new(self.ribs_name) + write_mesh(mesh, core.joined([rib for _, rib in sorted(webs, key=lambda found: found[0])] + rods + [beam for _, _, beam in beams])) + ribs = bpy.data.objects.new(self.ribs_name, mesh) + context.scene.collection.objects.link(ribs) + ribs.parent = cage + ribs.matrix_world = cage.matrix_world.copy() # read by a report; no depsgraph update here + seat(ribs, np.eye(4)) + ribs[RIBS] = json.dumps({"object_name": cage.name, "planes": json.loads(self.planes), "standoff": self.standoff, "depth": self.depth, "thickness": self.thickness, + "step": self.step, "holes": self.holes, "posts": self.posts, "post_r": self.post_r, "bridge": self.bridge, "clearance": self.clearance, + "longerons": json.loads(self.longerons), "longeron": self.longeron, "longeron_w": self.longeron_w, "longeron_h": self.longeron_h, + "longeron_t": self.longeron_t}) + report = {"object": ribs.name, "ribs": sum(row["pieces"] for row in sections), "thickness": round(plate, 6), + "sections": [{"plane": row["plane"], "chains": row["chains"], "pieces": row["pieces"], "length": round(row["length"], 6), "open": row["open"]} for row in sections], + "posts": len(rods) // 2, "holes": holes, **measured(mesh)} + report["longerons"] = fitted(report, "longerons", [{"index": index, "stations": [[round(float(v), 6) for v in station] for station in stations]} for index, stations, _ in beams]) + return report + + class BROKKR_KITBASH_OT_describe(PolishOperator): """List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame at default params""" @@ -911,7 +1194,7 @@ class BROKKR_KITBASH_OT_report(PolishOperator): classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report, BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach, - BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply) + BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply, BROKKR_KITBASH_OT_ribs) def register(): diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 1fe79d4..8768e4b 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -566,6 +566,156 @@ "maxLength": 63 } ] + }, + { + "name": "brokkr_kitbash.ribs", + "doc": "Derive the frame under an armor cage from the cage itself, so it fits the armor by construction: a rib along each plane's section of the cage's surface, set the standoff behind the plate's inner face and reaching depth inward; lightening holes through the ribs; posts that stand the plate off them; longerons through the ribs. The plate's thickness is read from the cage's one Solidify. A rib stops where the plate is open (a port cut through it), runs behind an opening shorter than bridge (a panel break) and under a recess: openings are read from the cage as it is cut, so cut first. Inward is the side the cage's normals face away from. Makes one mesh object, a child of the cage, baked at this call: after the cage or its cuts change, delete it and run ribs again (its kit_ribs property keeps the request). Every plane and longeron is checked before anything is written. Reports ribs, thickness, sections [{plane, chains, pieces, length, open}], posts, holes, longerons [{index, stations}], faces, volume and nonManifoldEdges.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the cage: a mesh whose surface is the plate's designed face, not scaled, its normals facing out of the plate" + }, + { + "name": "ribs_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the new ribs object's name" + }, + { + "name": "planes", + "type": "string", + "required": true, + "minLength": 2, + "maxLength": 8000, + "doc": "a JSON array of 1 to 64 planes, each {\"origin\": [x, y, z], \"normal\": [x, y, z]} in the cage's own frame; a rib runs where each cuts the surface" + }, + { + "name": "standoff", + "type": "number", + "minimum": 0, + "maximum": 2, + "default": 0.09, + "doc": "metres between the plate's inner face and the ribs" + }, + { + "name": "depth", + "type": "number", + "minimum": 0.005, + "maximum": 2, + "default": 0.09, + "doc": "how far a rib reaches inward from there" + }, + { + "name": "thickness", + "type": "number", + "minimum": 0.001, + "maximum": 1, + "default": 0.014, + "doc": "a rib's thickness across its plane" + }, + { + "name": "step", + "type": "number", + "minimum": 0.002, + "maximum": 1, + "default": 0.01, + "doc": "spacing of the points at which a section asks whether the plate is there" + }, + { + "name": "holes", + "type": "number", + "minimum": 0, + "maximum": 10, + "default": 0, + "doc": "pitch of the lightening holes along each rib (radius 0.3 of depth); 0: none" + }, + { + "name": "posts", + "type": "number", + "minimum": 0, + "maximum": 10, + "default": 0, + "doc": "pitch of the posts that stand the plate off each rib; 0: none" + }, + { + "name": "post_r", + "type": "number", + "minimum": 0.001, + "maximum": 0.5, + "default": 0.011, + "doc": "a post's radius; its pad on the plate is 2.4 times as wide" + }, + { + "name": "bridge", + "type": "number", + "minimum": 0, + "maximum": 2, + "default": 0.05, + "doc": "an opening shorter than this along a section is a panel break: the rib runs behind it" + }, + { + "name": "clearance", + "type": "number", + "minimum": 0, + "maximum": 2, + "default": 0.02, + "doc": "how far a rib stops short of any other opening" + }, + { + "name": "longerons", + "type": "string", + "default": "[]", + "minLength": 2, + "maxLength": 4000, + "doc": "a JSON array of 0 to 16 longerons, each {\"origin\": [x, y, z], \"axis\": [x, y, z], \"toward\": [x, y, z]} in the cage's own frame: the half-plane from the line through origin along axis, on toward's side. The longeron runs through the rib of every plane, in the planes' order, where the half-plane crosses the rib's mid-depth line: exactly once a plane, and not in an opening" + }, + { + "name": "longeron", + "type": "string", + "enum": [ + "I", + "C", + "T", + "L", + "box" + ], + "default": "T", + "doc": "the longerons' section; its up faces the plate" + }, + { + "name": "longeron_w", + "type": "number", + "minimum": 0.005, + "maximum": 2, + "default": 0.05, + "doc": "the section's width" + }, + { + "name": "longeron_h", + "type": "number", + "minimum": 0.005, + "maximum": 2, + "default": 0.05, + "doc": "the section's height" + }, + { + "name": "longeron_t", + "type": "number", + "minimum": 0.001, + "maximum": 1, + "default": 0.008, + "doc": "the section's wall" + } + ] } ] } diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 5951bc4..2cf3972 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -19,8 +19,8 @@ whatever the roll: what closes a loop the tree of connections cannot state. The structure under an armor cage is swept, not kit parts: PROFILES are the sections (I, C, T, L, box), sweep takes an outline along a polyline with mitred joints (a rib, a longeron, a post are all one sweep), crossings finds where a -section line meets a half-plane, resample spaces a section's points and spans says which runs of a section keep -their frame where the plate over them is open. brokkr_kitbash.ribs is the bpy around them. +section line meets a half-plane, resample fills a section's points in, spans says which runs of a section keep +their frame where the plate over them is open, and cornered which of a run's points the frame is swept through. brokkr_kitbash.ribs is the bpy around them. A pin's roll is its one degree of freedom, and it is solved in closed form: roll_terms gives how a point or an axis of the child moves along a world direction as the roll turns (a cosine, a sine and a constant), aim_roll the roll @@ -738,19 +738,43 @@ def crossings(points, closed: bool, origin, axis, toward) -> list: def resample(points, closed: bool, step: float) -> np.ndarray: - """Points along a polyline, evenly spaced by arc length and no more than `step` apart: an open one keeps both its - ends, a closed one starts at its first point and has at least 3.""" + """A polyline's own points with more between them, evenly along each segment, so that none stands over `step` + from the next. A corner stays a corner: points spaced along the arc instead would cut each corner into two, a + step apart, and a section offset inward folds between them. A segment shorter than 1e-7 is dropped with its + first point. An open polyline keeps both ends; a closed one starts at its first point.""" points = np.asarray(points, dtype=np.float64) if not (finite(step) and step > 0) or len(points) < 2: raise KitError(f"resample needs 2 or more points and a step above 0; got {len(points)} and {step}") loop = np.vstack([points, points[:1]]) if closed else points lengths = np.linalg.norm(np.diff(loop, axis=0), axis=1) - reach = np.concatenate([[0.0], np.cumsum(lengths)]) - if not reach[-1] > 0: + if not lengths.sum() > 0: raise KitError("resample: the polyline has no length") - pieces = max(3 if closed else 1, int(math.ceil(reach[-1] / step - 1e-9))) - at = reach[-1] * np.arange(pieces if closed else pieces + 1) / pieces - return np.stack([np.interp(at, reach, loop[:, k]) for k in range(3)], axis=1) + made = [loop[i] + (loop[i + 1] - loop[i]) * (k / pieces) for i, length in enumerate(lengths) if length >= 1e-7 + for pieces in (max(1, int(math.ceil(length / step - 1e-9))),) for k in range(pieces)] + return np.array(made if closed else made + [loop[-1]]) + + +def cornered(points, closed: bool, reach: float) -> np.ndarray: + """Indices of the points a section's frame is swept through: those where the polyline turns, and an open one's + two ends. Points along a straight run add nothing to a sweep and would each stand a ring square to the run, + which a mitre at the next corner then folds over. For the same reason an open polyline's end is left out when + the corner beside it stands nearer than its mitre sets back, `reach` (how far the frame reaches to the inside) + times the tangent of half the turn there: the frame then ends at that corner. Fewer than 2 points left is none; a + closed polyline with no corner keeps every point.""" + points = np.asarray(points, dtype=np.float64) + count = len(points) + steps = (np.roll(points, -1, axis=0) - points)[:count if closed else count - 1] + steps = steps / np.linalg.norm(steps, axis=1)[:, None] + cosine = np.clip(np.einsum("ij,ij->i", np.roll(steps, 1, axis=0) if closed else steps[:-1], steps if closed else steps[1:]), -1.0, 1.0) + straight = cosine > 1.0 - 1e-12 + if closed: + return np.flatnonzero(~straight) if (~straight).sum() >= 3 else np.arange(count) + inner = (np.flatnonzero(~straight) + 1).tolist() + back = lambda corner: reach * math.sqrt((1.0 - cosine[corner - 1]) / max(1.0 + cosine[corner - 1], 1e-12)) + 1e-9 # noqa: E731 how far that corner's mitre sets the inside back + first = [] if inner and np.linalg.norm(points[inner[0]] - points[0]) <= back(inner[0]) else [0] + last = [] if inner and np.linalg.norm(points[inner[-1]] - points[-1]) <= back(inner[-1]) else [count - 1] + kept = first + inner + last + return np.array(kept if len(kept) >= 2 else [], dtype=np.int64) def spans(flags, lengths, closed: bool, bridge: float, clearance: float) -> list: diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 3b100a4..9c48891 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -75,7 +75,7 @@ def extent(obj, axis=2): check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == [f"brokkr_kitbash.{name}" for name in ( - "place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply")], [R["hostErrors"], R["hostRows"]]) + "place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply", "ribs")], [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 e95d92c..7d2950a 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -419,7 +419,8 @@ "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", - "brokkr_kitbash.apply" + "brokkr_kitbash.apply", + "brokkr_kitbash.ribs" ], "placed": { "nozzle": { diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index c14b342..3802282 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -177,7 +177,7 @@ def evaluated(obj): rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == [f"brokkr_kitbash.{n}" for n in ( - "place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply")], [R["hostErrors"], rows]) + "place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply", "ribs")], [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_ribs.py b/surfaces/blender/tests/live/kitbash_ribs.py new file mode 100644 index 0000000..57a6e5e --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_ribs.py @@ -0,0 +1,395 @@ +"""Live proof, in a background Blender, of brokkr_kitbash.ribs through run_intent: ribs that stand a standoff behind a +cage's plate and in their planes, that stop at a port, run behind a panel break and under a recess, that take their side +from the cage's normals, longerons through the ribs of a cage a plane cuts twice, lightening holes through crossing +ribs, and the refusals. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_ribs.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. The checks run inside +one try: an uncaught error is a failed check that names its section, and the result file is always written. +""" +import importlib.util +import json +import math +import os +import sys +import tempfile +import traceback +import types +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix, Vector +from mathutils.bvhtree import BVHTree + +SURFACE = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(SURFACE / "tools")) +import private_dirs # noqa: E402 + +_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) +if _refused: + raise SystemExit(_refused) +OUT = sys.argv[sys.argv.index("--") + 1] +if not Path(OUT).is_absolute(): + raise SystemExit(f"{OUT!r} is not an absolute path") +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules["brokkr_bridge"] = package +from brokkr_bridge import blender_target as bt # noqa: E402 + +import addon_utils # noqa: E402 + +spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_reference", SURFACE / "brokkr_kitbash" / "core.py") +core = importlib.util.module_from_spec(spec) # core as the unit tests load it +spec.loader.exec_module(core) + +sys.path.append(str(SURFACE)) +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_kitbash"): + addon_utils.enable(module, default_set=True) +target = bt.BrokkrBlenderTarget(bpy) +WORK = Path(tempfile.mkdtemp(prefix="brokkr-kitbash-ribs-")) +target.configure_action_dirs("", str(WORK)) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}} +COUNT, SECTION = [0], ["setup"] +STANDOFF, DEPTH, THICKNESS = 0.04, 0.06, 0.014 +SIZES = {"standoff": STANDOFF, "depth": DEPTH, "thickness": THICKNESS} +# Metres between where a rib vertex stands behind the plate's inner face, along its plane, and the standoff (its outer +# edge) or the standoff and depth (its inner edge). Shipped worst 0.0093 (the pod: the plate is 0.06 thick along its +# own normal, which leans up to 30 degrees out of a rib's plane, and the rib is set 0.06 back along the plane); +# least claimed mutant 0.065 (K12, the standoff taken from the outer face: the rib's outer edge is then inside the plate); +# separation 3.5 each side. +FIT = 0.018 +# Metres a rib vertex stands off its plane beyond half the rib's thickness. Shipped worst 1.4e-07 (float32 meshes); +# least claimed mutant 0.007 (KP, a rib twice as thick across its plane); separation 220 each side. +PLANAR = 3.1e-5 +# Metres from the port's opening to the nearest vertex of a rib, post or hole, along the section: the least is the +# worst. Shipped 0.031 (the last sample under the plate, the clearance of 0.02 and up to a step); least claimed mutant +# 0.0011 (K6, the clearance ignored); separation 5.3 each side. K4 and K10 put vertices inside the opening: -0.12. +CLEARED = 0.0058 +# Metres a longeron's station stands from its half-plane, its plane's height or the rib's mid-depth line. Shipped worst +# 5.2e-07; least claimed mutant 0.0021 (K1, a sweep with no mitre: the rib's mid-depth line stands in from where the +# facets' offsets meet); separation 64 each side. K9 (the station at the chain's first point) reads 1.2. +STATIONED = 3.3e-5 +# What lightening holes removed from five crossing ribs, over the holes' faceted area times the thickness, less 1. +# Shipped 2.7e-08; least claimed mutant 22 (K11, each plane's Manifold Boolean taken over all five ribs' webs, which +# cross, with the action's own check of the cut off); separation 28000 each side. +HOLED = 7.7e-4 + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) + + +def reading(name, value, least=False): + """The worst of a metric: the largest, or with `least` the smallest.""" + R["readings"][name] = (min if least else max)(R["readings"].get(name, float(value)), float(value)) + return float(value) + + +def section(name): + SECTION[0] = name + + +def send(action, **fields): + COUNT[0] += 1 + receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "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 scene_state(): + return {o.name: (o.parent and o.parent.name, np.round(np.array(o.matrix_basis), 6).tolist(), {k: repr(o[k]) for k in sorted(o.keys()) if k.startswith("kit_")}, + [(m.name, m.type, m.show_viewport) for m in o.modifiers], o.data.name if o.type == "MESH" else None, len(o.data.polygons) if o.type == "MESH" else None) + for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes), sorted(c.name for c in bpy.data.collections) + + +def refused(label, fields, expected): + state = scene_state() + receipt, _ = send("brokkr_kitbash.ribs", **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 mesh_object(name, vertices, faces, world=None, wall=None, levels=0): + """A mesh object from points and faces, normals as the faces are wound, optionally subdivided and given a wall inward.""" + made = bpy.data.objects.new(name, bpy.data.meshes.new(name)) + made.data.from_pydata(vertices, [], faces) + bpy.context.scene.collection.objects.link(made) + if levels: + made.modifiers.new("Subsurf", "SUBSURF").levels = levels + if wall: + solid = made.modifiers.new("Solidify", "SOLIDIFY") + solid.thickness, solid.offset, solid.use_even_offset = wall, -1.0, True + if world is not None: + made.matrix_world = world + bpy.context.view_layer.update() + return made + + +def tree(obj, off=()): + """This script's own BVH of an object evaluated with the modifiers of the named types off, in its own frame.""" + hidden = [m for m in obj.modifiers if m.type in off and m.show_viewport] + for m in hidden: + m.show_viewport = False + try: + return BVHTree.FromObject(obj, bpy.context.evaluated_depsgraph_get()) + finally: + for m in hidden: + m.show_viewport = True + + +def points(obj): + V = np.zeros(3 * len(obj.data.vertices)) + obj.data.vertices.foreach_get("co", V) + return V.reshape(-1, 3) + + +def measure(mesh): + bm = bmesh.new() + bm.from_mesh(mesh) + row = {"faces": len(bm.faces), "volume": bm.calc_volume(signed=True), "nonManifoldEdges": sum(1 for e in bm.edges if not e.is_manifold), + "shells": len({min(v.index for v in island) for island in islands(bm)})} + bm.free() + return row + + +def islands(bm): + seen, found = set(), [] + for start in bm.verts: + if start in seen: + continue + island, stack = [], [start] + seen.add(start) + while stack: + v = stack.pop() + island.append(v) + for e in v.link_edges: + other = e.other_vert(v) + if other not in seen: + seen.add(other) + stack.append(other) + found.append(island) + return found + + +def child_of(ribs, cage): + return ribs is not None and ribs.parent == cage and np.array_equal(np.array(ribs.matrix_parent_inverse), np.eye(4)) and np.array_equal(np.array(ribs.matrix_basis), np.eye(4)) \ + and np.abs(np.array(ribs.matrix_world) - np.array(cage.matrix_world)).max() < 1e-6 and len(ribs.modifiers) == 0 and len(ribs.data.materials) == 0 + + +def flat(z_planes): + return json.dumps([{"origin": [0.0, 0.0, z], "normal": [0.0, 0.0, 1.0]} for z in z_planes]) + + +try: + # --- a pod: a closed loft of 6 rings of 8, subdivided, with a wall, a port, a panel break and a recess -------------------- + section("a pod") + + def ring(w, d, z, n=8, p=3.0): + return [(0.5 * w * math.copysign(abs(math.cos(a)) ** (2 / p), math.cos(a)), 0.5 * d * math.copysign(abs(math.sin(a)) ** (2 / p), math.sin(a)), z) + for a in (2 * math.pi * (k + 0.5) / n for k in range(n))] + + rings = [ring(w, d, z) for z, w, d in ((0, .6, .5), (.3, 1.0, .8), (.7, 1.2, .95), (1.1, 1.1, .9), (1.4, .8, .6), (1.6, .4, .3))] + pod = mesh_object("Pod", [p for r in rings for p in r], [(i * 8 + j, i * 8 + (j + 1) % 8, (i + 1) * 8 + (j + 1) % 8, (i + 1) * 8 + j) for i in range(5) for j in range(8)], + Matrix.Translation((4.0, -1.0, 2.0)) @ Matrix.Rotation(0.6, 4, "Z") @ Matrix.Rotation(-0.3, 4, "X"), wall=0.06, levels=3) + CUTS = [{"name": "Port", "part": "box", "params": "width=0.25; height=0.2; depth=0.2", "origin": [2, 0, 0.7], "direction": [-1, 0, 0]}, + {"name": "Seam", "part": "slab", "params": "gap=0.02; length=0.6; depth=0.2", "origin": [-2, 0, 0.7], "direction": [1, 0, 0]}, + {"name": "Recess", "part": "box", "params": "width=0.2; height=0.15; depth=0.03", "origin": [0, 2, 0.7], "direction": [0, -1, 0]}] + receipt, _ = send("brokkr_kitbash.cut_many", object_name="Pod", cuts=json.dumps(CUTS)) + check("the pod is cut by a port, a panel break and a recess", receipt["status"] == "accepted", receipt["message"]) + HEIGHTS = (0.3, 0.5, 0.7, 0.9, 1.15) + designed = tree(pod, ("SOLIDIFY", "BEVEL", "BOOLEAN")) # the surface as designed + cuts = [m for m in pod.modifiers if m.type == "BOOLEAN"] + for m in cuts: + m.show_viewport = False + wall = pod.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh() # the wall before it is cut; its inner face is the faces that stand off the designed surface + inner = BVHTree.FromPolygons([v.co.copy() for v in wall.vertices], [tuple(p.vertices) for p in wall.polygons if designed.find_nearest(p.center)[3] > 0.045]) + for m in cuts: + m.show_viewport = True + bpy.context.view_layer.update() + + # --- ribs-fit-the-plate ---------------------------------------------------------------------------------------------------- + section("ribs-fit-the-plate") + request = {"object_name": "Pod", "ribs_name": "Fit", "planes": flat(HEIGHTS), **SIZES} + receipt, report = send("brokkr_kitbash.ribs", **request) + fit = bpy.data.objects.get("Fit") + stored = json.loads(fit["kit_ribs"]) if fit is not None and "kit_ribs" in fit else {} + check("ribs makes one mesh object under the cage: a child under identity matrices, no modifier, no material, and kit_ribs the request", receipt["status"] == "accepted" + and child_of(fit, pod) and stored.get("planes") == json.loads(request["planes"]) and stored.get("object_name") == "Pod" + and all(abs(stored[k] - v) < 1e-7 for k, v in SIZES.items()) and sorted(stored) == sorted( + ["object_name", "planes", "standoff", "depth", "thickness", "step", "holes", "posts", "post_r", "bridge", "clearance", "longerons", "longeron", "longeron_w", "longeron_h", "longeron_t"]), + [receipt["message"], stored]) + shape = measure(fit.data) + check("ribs reports the frame: one rib a plane, the plate's thickness read from the Solidify, the port's plane open along it, closed shells", + report and sorted(report) == ["faces", "holes", "longerons", "nonManifoldEdges", "object", "posts", "ribs", "sections", "thickness", "volume"] + and (report["object"], report["ribs"], report["thickness"], report["posts"], report["holes"], report["longerons"], report["nonManifoldEdges"]) == ("Fit", 5, 0.06, 0, 0, [], 0) + and [(s["plane"], s["chains"], s["pieces"]) for s in report["sections"]] == [(k, 1, 1) for k in range(5)] + and [s["open"] > 0.25 for s in report["sections"]] == [False, False, True, False, False] and all(s["open"] == 0.0 for k, s in enumerate(report["sections"]) if k != 2) + and (shape["faces"], shape["nonManifoldEdges"], shape["shells"]) == (report["faces"], 0, 5) and abs(shape["volume"] - report["volume"]) < 1e-8 + and 0.5 < report["volume"] / (sum(s["length"] for s in report["sections"]) * DEPTH * THICKNESS) < 1.0, report) # a rib inside a curve is shorter than the section it follows + behind = True + for v in points(fit): + plane = min(HEIGHTS, key=lambda z: abs(v[2] - z)) + reading("planar", abs(abs(v[2] - plane) - THICKNESS / 2)) + on, normal, _, _ = designed.find_nearest(Vector((v[0], v[1], plane))) + out = Vector((normal.x, normal.y, 0.0)).normalized() + hit, _, _, distance = inner.ray_cast(Vector((v[0], v[1], plane)), out) # the inner face, outward of the vertex along its plane + if hit is None: # or the vertex is in the plate, and the inner face is behind it + hit, _, _, distance = inner.ray_cast(Vector((v[0], v[1], plane)), -out) + behind, distance = False, -distance if hit is not None else 1.0 + behind = behind and (Vector((v[0], v[1], plane)) - on).dot(normal) < 0 + reading("fit", min(abs(distance - STANDOFF), abs(distance - STANDOFF - DEPTH))) + check("ribs-fit-the-plate: every rib vertex stands the standoff, or the standoff and the depth, behind the plate's inner face along its plane, in its plane, on the side the normals face away from", + behind and R["readings"]["fit"] < FIT and R["readings"]["planar"] < PLANAR, R["readings"]) + + # --- ribs-stop-at-ports: a flat deck with a port, a panel break and a recess along one section ---------------------------------- + section("ribs-stop-at-ports") + deck = mesh_object("Deck", [(-0.8, -0.5, 0.0), (0.8, -0.5, 0.0), (0.8, 0.5, 0.0), (-0.8, 0.5, 0.0)], [(0, 1, 2, 3)], Matrix.Translation((0.0, 5.0, 0.0)) @ Matrix.Rotation(0.4, 4, "Y"), wall=0.05) + DOWN = {"direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]} + DECK_CUTS = [{**DOWN, "name": "DeckPort", "part": "box", "params": "width=0.25; height=0.2; depth=0.2", "origin": [-0.3, 0.0, 2.0]}, + {**DOWN, "name": "DeckSeam", "part": "slab", "params": "gap=0.02; length=0.6; depth=0.2", "origin": [0.3, 0.0, 2.0]}, + {**DOWN, "name": "DeckRecess", "part": "box", "params": "width=0.15; height=0.15; depth=0.02", "origin": [0.6, 0.0, 2.0]}] + send("brokkr_kitbash.cut_many", object_name="Deck", cuts=json.dumps(DECK_CUTS)) + ALONG = json.dumps([{"origin": [0.0, 0.0, 0.0], "normal": [0.0, 1.0, 0.0]}, {"origin": [0.0, 0.25, 0.0], "normal": [0.0, 1.0, 0.0]}]) # through all three cuts; through the break alone + receipt, report = send("brokkr_kitbash.ribs", object_name="Deck", ribs_name="DeckRibs", planes=ALONG, **SIZES, posts=0.2, holes=0.1) + ribs = bpy.data.objects.get("DeckRibs") + V = points(ribs) if ribs is not None else np.zeros((1, 3)) + first = V[np.abs(V[:, 1]) < 0.1] # the section through the port: everything the frame put there, ribs, posts and holes + for x in first[:, 0]: + reading("cleared", abs(x + 0.3) - 0.125, least=True) + lengths = [s["length"] for s in report["sections"]] if report else [] + check("ribs-stop-at-ports: no rib, post or hole stands within the clearance of the port; behind the panel break the rib is one piece; under the recess it runs on", + receipt["status"] == "accepted" and child_of(ribs, deck) and [(s["chains"], s["pieces"]) for s in report["sections"]] == [(1, 2), (1, 1)] + and CLEARED < R["readings"]["cleared"] < 0.02 + 2 * 0.01 and 0.25 + 2 * 0.02 < 1.6 - lengths[0] < 0.25 + 4 * 0.02 and abs(lengths[1] - 1.6) < 1e-6 + and report["sections"][1]["open"] == 0.0 and abs(report["sections"][0]["open"] - (1.6 - lengths[0])) < 1e-5 and first[:, 0].max() > 0.79 and first[:, 0].min() < -0.79 + and (report["posts"], report["holes"], report["nonManifoldEdges"]) == (1 + 4 + 8, 3 + 9 + 16, 0) # runs of 0.34, 0.94 and 1.6: a post every 0.2 and a hole every 0.1, half a pitch from each end + and abs(float(V[:, 2].max()) + 0.025) < 1e-6 and abs(float(V[:, 2].min()) + 0.05 + STANDOFF + DEPTH) < 1e-6, [receipt["message"], report, R["readings"]]) # a post starts mid-plate; the ribs end 0.15 down + seam_free = send("brokkr_kitbash.ribs", object_name="Deck", ribs_name="DeckSplit", planes=ALONG, **SIZES, bridge=0.0)[1] + check("with no bridge the panel break splits both ribs", seam_free and [s["pieces"] for s in seam_free["sections"]] == [3, 2], seam_free) + + # --- ribs-from-normals: a dish whose normals face its hollow side ------------------------------------------------------------ + section("ribs-from-normals") + ARC = [math.radians(a) for a in range(-40, 41, 10)] + dish_points = [(math.sin(a), y, 1.0 - math.cos(a)) for y in (-0.3, 0.3) for a in ARC] # a trough of radius 1 about the line x = 0, z = 1; its hollow side is up + dish = mesh_object("Dish", dish_points, [(k, k + 1, k + 10, k + 9) for k in range(8)]) + up_facing = all(p.normal.z > 0 for p in dish.data.polygons) + receipt, report = send("brokkr_kitbash.ribs", object_name="Dish", ribs_name="DishRibs", planes=json.dumps([{"origin": [0.0, 0.0, 0.0], "normal": [0.0, 1.0, 0.0]}]), **SIZES) + ribs = bpy.data.objects.get("DishRibs") + from_axis = np.hypot(points(ribs)[:, 0], points(ribs)[:, 2] - 1.0) if ribs is not None else np.zeros(1) + check("ribs-from-normals: a dish whose normals face its hollow side gets its rib on the other, the round side, though its section's middle lies in the hollow; a cage with no Solidify has a plate of no thickness", + receipt["status"] == "accepted" and up_facing and report["thickness"] == 0.0 and report["ribs"] == 1 and report["sections"][0]["open"] == 0.0 + and abs(float(from_axis.min()) - (1.0 + STANDOFF)) < 1e-3 and float(from_axis.max()) > 1.0 + STANDOFF + DEPTH - 1e-6, [receipt["message"], report, from_axis.min(), from_axis.max()]) + for polygon in list(dish.data.polygons)[:4]: + polygon.flip() + dish.data.update() + bpy.context.view_layer.update() + refused("a cage with a flipped region, naming the plane", {"object_name": "Dish", "ribs_name": "Flipped", "planes": json.dumps([{"origin": [0.0, 0.0, 0.0], "normal": [0.0, 1.0, 0.0]}]), **SIZES}, + "planes[0]: the normals of 'Dish' change sides along the section") + + # --- longerons-through-ribs: two legs in one cage, so every plane cuts two chains -------------------------------------------- + section("longerons-through-ribs") + leg_points = [(side * 0.6 + 0.3 * math.cos(2 * math.pi * k / 16), 0.3 * math.sin(2 * math.pi * k / 16), z) for side in (-1, 1) for z in (0.0, 1.0) for k in range(16)] + legs = mesh_object("Legs", leg_points, [(s * 32 + k, s * 32 + (k + 1) % 16, s * 32 + 16 + (k + 1) % 16, s * 32 + 16 + k) for s in (0, 1) for k in range(16)], wall=0.04) + TOWARD = [math.cos(math.pi / 16), math.sin(math.pi / 16), 0.0] # through the middle of a facet + BEAMS = [{"origin": [0.6, 0.0, 0.0], "axis": [0.0, 0.0, 1.0], "toward": TOWARD}, {"origin": [-0.6, 0.0, 0.0], "axis": [0.0, 0.0, 1.0], "toward": [-TOWARD[0], TOWARD[1], 0.0]}] + LEVELS = (0.2, 0.5, 0.8) + receipt, report = send("brokkr_kitbash.ribs", object_name="Legs", ribs_name="LegRibs", planes=flat(LEVELS), **SIZES, longerons=json.dumps(BEAMS), longeron="T", longeron_w=0.05, longeron_h=0.05, longeron_t=0.008) + ribs = bpy.data.objects.get("LegRibs") + middle = 0.3 * math.cos(math.pi / 16) - (0.04 + STANDOFF + DEPTH / 2) # the rib's mid-depth line where the half-plane crosses it, from the leg's axis + for row in (report or {}).get("longerons", []): + beam = BEAMS[row["index"]] + for station, level in zip(row["stations"], LEVELS): + from_line = np.array(station) - beam["origin"] + across = np.cross([0.0, 0.0, 1.0], beam["toward"]) + reading("stationed", max(abs(from_line @ across), abs(station[2] - level), abs(math.hypot(from_line[0], from_line[1]) - middle), 0.0 if from_line @ np.array(beam["toward"]) > 0 else 1.0)) + shape = measure(ribs.data) if ribs is not None else {} + check("longerons-through-ribs: a cage every plane cuts into two chains gets a longeron through each leg's ribs: every station on its half-plane, at its plane's height, on the rib's mid-depth line", + receipt["status"] == "accepted" and [s["chains"] for s in report["sections"]] == [2, 2, 2] and report["ribs"] == 6 and [(r["index"], len(r["stations"])) for r in report["longerons"]] == [(0, 3), (1, 3)] + and R["readings"].get("stationed", 1.0) < STATIONED and (shape["shells"], shape["nonManifoldEdges"]) == (8, 0) + and abs(float(points(ribs)[:, 2].max()) - (0.8 + 0.3 * 0.12)) < 1e-6 and abs(float(points(ribs)[:, 2].min()) - (0.2 - 0.3 * 0.12)) < 1e-6, [receipt["message"], report, R["readings"]]) + LEG = {"object_name": "Legs", "ribs_name": "Bad", "planes": flat(LEVELS), **SIZES} + refused("a longeron whose half-plane meets no rib", {**LEG, "longerons": json.dumps([{"origin": [0.0, 0.0, 0.0], "axis": [0.0, 0.0, 1.0], "toward": [0.0, 1.0, 0.0]}])}, + "longerons[0] does not meet the ribs of planes[0]") + refused("a longeron whose half-plane meets two ribs", {**LEG, "longerons": json.dumps([{"origin": [0.0, 0.0, 0.0], "axis": [0.0, 0.0, 1.0], "toward": [1.0, 0.0, 0.0]}])}, + "longerons[0] meets the ribs of planes[0] 2 times") + refused("a longeron with one plane", {**LEG, "planes": flat([0.5]), "longerons": json.dumps(BEAMS[:1])}, "A longeron runs through the ribs of two or more planes") + refused("a longeron whose wall leaves no section", {**LEG, "longerons": json.dumps(BEAMS[:1]), "longeron": "I", "longeron_t": 0.03}, "profile 'I' of width") + refused("a longeron through the pod's port", {"object_name": "Pod", "ribs_name": "Bad", "planes": flat(HEIGHTS), **SIZES, + "longerons": json.dumps([{"origin": [0.0, 0.0, 0.0], "axis": [0.0, 0.0, 1.0], "toward": [1.0, 0.0, 0.0]}])}, + "longerons[0] crosses planes[2] where the plate is open and there is no rib") + receipt, report = send("brokkr_kitbash.ribs", object_name="Pod", ribs_name="Frame", planes=flat(HEIGHTS), **SIZES, posts=0.27, holes=0.11, + longerons=json.dumps([{"origin": [0.0, 0.0, 0.0], "axis": [0.0, 0.0, 1.0], "toward": [math.cos(a), math.sin(a), 0.0]} for a in (0.8, 2.4, 3.9, 5.5)])) + check("the pod takes ribs, holes, posts and four longerons clear of its port in one call", receipt["status"] == "accepted" and child_of(bpy.data.objects.get("Frame"), pod) + and (report["ribs"], len(report["longerons"]), report["nonManifoldEdges"]) == (5, 4, 0) and report["posts"] > 40 and report["holes"] > 80 + and all(len(r["stations"]) == 5 for r in report["longerons"]), [receipt["message"], report]) + + # --- holes-manifold: an egg-crate of five ribs that cross --------------------------------------------------------------------- + section("holes-manifold") + crate = mesh_object("Crate", [(-0.5, -0.5, 0.0), (0.5, -0.5, 0.0), (0.5, 0.5, 0.0), (-0.5, 0.5, 0.0)], [(0, 1, 2, 3)], Matrix.Translation((0.0, -5.0, 0.0)), wall=0.05) + GRID = json.dumps([{"origin": [x, 0.0, 0.0], "normal": [1.0, 0.0, 0.0]} for x in (-0.3, 0.0, 0.3)] + [{"origin": [0.0, y, 0.0], "normal": [0.0, 1.0, 0.0]} for y in (-0.3, 0.3)]) + _, solid = send("brokkr_kitbash.ribs", object_name="Crate", ribs_name="CrateSolid", planes=GRID, **SIZES) + receipt, report = send("brokkr_kitbash.ribs", object_name="Crate", ribs_name="CrateHoled", planes=GRID, **SIZES, holes=0.09) + holed = bpy.data.objects.get("CrateHoled") + one = 0.5 * 16 * (0.3 * DEPTH) ** 2 * math.sin(2 * math.pi / 16) * THICKNESS + removed = (measure(bpy.data.objects["CrateSolid"].data)["volume"] - measure(holed.data)["volume"]) if holed is not None and solid else 0.0 + shape = measure(holed.data) if holed is not None else {} + reading("holed", abs(removed / (55 * one) - 1.0)) + check("holes-manifold: five ribs that cross each get their eleven holes, cut a plane at a time: closed shells, and the volume gone is the holes' own", + receipt["status"] == "accepted" and (report["ribs"], report["holes"], report["nonManifoldEdges"]) == (5, 55, 0) and (shape["shells"], shape["nonManifoldEdges"]) == (5, 0) + and R["readings"]["holed"] < HOLED and abs(solid["volume"] - 5 * DEPTH * THICKNESS) < 1e-7 + and sorted(o.name for o in bpy.data.objects if o.name.startswith("Crate")) == ["Crate", "CrateHoled", "CrateSolid"], [receipt["message"], report, removed, 55 * one]) + refused("holes that overlap", {"object_name": "Crate", "ribs_name": "Bad", "planes": GRID, **SIZES, "holes": 0.02}, "planes[0]: the lightening holes did not cut cleanly") + + # --- ribs-refusals -------------------------------------------------------------------------------------------------------------- + section("ribs-refusals") + POD = {"object_name": "Pod", "ribs_name": "New", "planes": flat(HEIGHTS), **SIZES} + refused("a name an object has", {**POD, "ribs_name": "Fit"}, "ribs_name 'Fit' must be 1 to 63 characters and no object's name") + refused("a plane that misses the cage", {**POD, "planes": flat([0.5, 9.0])}, "planes[1] misses 'Pod'") + refused("65 planes", {**POD, "planes": flat([0.3 + 0.01 * k for k in range(65)])}, "planes must be a JSON array of 1 to 64 objects") + refused("no plane", {**POD, "planes": "[]"}, "planes must be a JSON array of 1 to 64 objects") + refused("planes that are not JSON", {**POD, "planes": "[{"}, "planes is not JSON") + refused("a plane with no normal", {**POD, "planes": json.dumps([{"origin": [0.0, 0.0, 0.5]}])}, "planes[0] must be an object of origin and normal, each three numbers") + refused("a plane whose normal has no length", {**POD, "planes": json.dumps([{"origin": [0.0, 0.0, 0.5], "normal": [0.0, 0.0, 0.0]}])}, "planes[0].normal has no direction") + refused("17 longerons", {**POD, "longerons": json.dumps([BEAMS[0]] * 17)}, "longerons must be a JSON array of 0 to 16 objects") + refused("a fold: ribs deeper than the pod's top turns", {**POD, "planes": flat([0.5, 1.5]), "standoff": 0.15, "depth": 0.3}, "the section folds there: the path turns tighter than the outline reaches") + refused("a cage that is not a mesh", {**POD, "object_name": "Nothing"}, "No mesh object named 'Nothing'") + refused("a section too long for its step", {**POD, "planes": flat([0.3 + 0.01 * k for k in range(64)]), "step": 0.002}, "The sections are over 20000 points at step 0.002") + pod.scale = (1.0, 1.0, 1.01) + bpy.context.view_layer.update() + refused("a scaled cage", POD, "'Pod' is scaled, mirrored or sheared in the world") + pod.scale = (1.0, 1.0, 1.0) + crate.hide_viewport = True # nothing depends on the crate's cage but its ribs, and children do not hold a parent out of the depsgraph... they do: so they go first + for name in ("CrateSolid", "CrateHoled"): + bpy.data.objects[name].parent = None + bpy.context.view_layer.update() + refused("a cage Blender does not evaluate", {"object_name": "Crate", "ribs_name": "New", "planes": GRID, **SIZES}, "Blender does not evaluate 'Crate' in this view layer") + crate.hide_viewport = False + extra = crate.modifiers.new("Second", "SOLIDIFY") + bpy.context.view_layer.update() + refused("a cage with two Solidifies", {"object_name": "Crate", "ribs_name": "New", "planes": GRID, **SIZES}, "'Crate' has 2 Solidify modifiers (Solidify, Second)") + crate.modifiers.remove(extra) + check("every refusal left the cages' modifiers shown", all(m.show_viewport for o in (pod, deck, legs, crate, dish) for m in o.modifiers), None) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file + check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:]) +finally: + R["ok"] = all(c["ok"] for c in R["checks"]) + R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} + Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") + for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) + print("READINGS", R["readings"], flush=True) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_ribs.result.json b/surfaces/blender/tests/live/kitbash_ribs.result.json new file mode 100644 index 0000000..ad6e146 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_ribs.result.json @@ -0,0 +1,174 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "the pod is cut by a port, a panel break and a recess", + "ok": true, + "detail": null + }, + { + "name": "ribs makes one mesh object under the cage: a child under identity matrices, no modifier, no material, and kit_ribs the request", + "ok": true, + "detail": null + }, + { + "name": "ribs reports the frame: one rib a plane, the plate's thickness read from the Solidify, the port's plane open along it, closed shells", + "ok": true, + "detail": null + }, + { + "name": "ribs-fit-the-plate: every rib vertex stands the standoff, or the standoff and the depth, behind the plate's inner face along its plane, in its plane, on the side the normals face away from", + "ok": true, + "detail": null + }, + { + "name": "ribs-stop-at-ports: no rib, post or hole stands within the clearance of the port; behind the panel break the rib is one piece; under the recess it runs on", + "ok": true, + "detail": null + }, + { + "name": "with no bridge the panel break splits both ribs", + "ok": true, + "detail": null + }, + { + "name": "ribs-from-normals: a dish whose normals face its hollow side gets its rib on the other, the round side, though its section's middle lies in the hollow; a cage with no Solidify has a plate of no thickness", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a cage with a flipped region, naming the plane", + "ok": true, + "detail": null + }, + { + "name": "longerons-through-ribs: a cage every plane cuts into two chains gets a longeron through each leg's ribs: every station on its half-plane, at its plane's height, on the rib's mid-depth line", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a longeron whose half-plane meets no rib", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a longeron whose half-plane meets two ribs", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a longeron with one plane", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a longeron whose wall leaves no section", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a longeron through the pod's port", + "ok": true, + "detail": null + }, + { + "name": "the pod takes ribs, holes, posts and four longerons clear of its port in one call", + "ok": true, + "detail": null + }, + { + "name": "holes-manifold: five ribs that cross each get their eleven holes, cut a plane at a time: closed shells, and the volume gone is the holes' own", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: holes that overlap", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a name an object has", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a plane that misses the cage", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: 65 planes", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: no plane", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: planes that are not JSON", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a plane with no normal", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a plane whose normal has no length", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: 17 longerons", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a fold: ribs deeper than the pod's top turns", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a cage that is not a mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a section too long for its step", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a scaled cage", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a cage Blender does not evaluate", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a cage with two Solidifies", + "ok": true, + "detail": null + }, + { + "name": "every refusal left the cages' modifiers shown", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "readings": { + "cleared": 0.031, + "fit": 0.0052, + "holed": 2.7e-08, + "planar": 1.4e-07, + "stationed": 5.2e-07 + }, + "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 7df3386..675748f 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1283,18 +1283,38 @@ class StructureTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, "runs along the axis"): core.crossings(chain, True, origin, axis, (0.0, 0.0, 2.0)) - def test_resample_spaces_points_by_arc_length(self): - line = core.resample([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0)], False, 0.3) - self.assertEqual((len(line), line[0].tolist(), line[-1].tolist()), (8, [0.0, 0.0, 0.0], [1.0, 1.0, 0.0])) - self.assertTrue(np.allclose(np.linalg.norm(np.diff(line, axis=0), axis=1)[[0, 1, 2, 4, 5, 6]], 2.0 / 7, atol=1e-12)) + def test_resample_keeps_every_corner_and_fills_between(self): + """A corner stays a point of the chain, and no two points stand over the step apart.""" + line = core.resample([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.5, 0.0)], False, 0.3) + self.assertEqual((len(line), line[0].tolist(), line[4].tolist(), line[-1].tolist()), (7, [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.5, 0.0])) + self.assertTrue(np.allclose(np.linalg.norm(np.diff(line, axis=0), axis=1), [0.25] * 6, atol=1e-12)) loop = core.resample(self.SQUARE, True, 0.25) self.assertEqual((len(loop), loop[0].tolist(), loop[4].tolist(), loop[15].tolist()), (16, [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.25, 0.0])) - self.assertEqual(len(core.resample(self.SQUARE, True, 100.0)), 3) + self.assertEqual(core.resample(self.SQUARE, True, 100.0).tolist(), [list(p) for p in self.SQUARE]) self.assertEqual(len(core.resample(self.SQUARE[:2], False, 100.0)), 2) + doubled = core.resample([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.0, 1e-9), (1.0, 1.0, 0.0)], False, 100.0) + self.assertEqual(len(doubled), 3) # the doubled point is one for bad in ((self.SQUARE[:1], False, 0.1), (self.SQUARE, True, 0.0), ([(0.0, 0.0, 0.0)] * 2, False, 0.1)): with self.assertRaisesRegex(core.KitError, "resample"): core.resample(*bad) + def test_a_frame_is_swept_corner_to_corner(self): + """cornered keeps the points where a section turns and an open one's ends: an end is left out when the corner + beside it is nearer than that corner's mitre sets the frame's inside back.""" + el = [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.25, 0.0), (1.0, 0.5, 0.0)] # a right angle at index 2: its mitre sets back the reach itself + self.assertEqual(core.cornered(el, False, 0.25).tolist(), [0, 2, 4]) + self.assertEqual(core.cornered(el, False, 0.5).tolist(), [0, 2]) # the far end stands 0.5 from the corner: not beyond a set-back of 0.5 + self.assertEqual(core.cornered(el, False, 1.0).tolist(), []) # nor does the near one, and one point is no frame + self.assertEqual(core.cornered(el[:3], False, 9.0).tolist(), [0, 2]) # no corner: both ends, whatever the reach + shallow = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0 + math.cos(0.2), math.sin(0.2), 0.0)] # a turn of 0.2 rad sets back reach * tan(0.1) + self.assertEqual(core.cornered(shallow, False, 9.9).tolist(), [0, 1, 2]) + self.assertEqual(core.cornered(shallow, False, 10.0).tolist(), []) # both ends within 10 * tan(0.1) = 1.003: one point is left, and is no frame + square = core.resample(self.SQUARE, True, 0.25) + self.assertEqual(core.cornered(square, True, 0.1).tolist(), [0, 4, 8, 12]) + round_ = [(math.cos(a), math.sin(a), 0.0) for a in np.linspace(0.0, 2.0 * math.pi, 12, endpoint=False)] + self.assertEqual(core.cornered(round_, True, 0.1).tolist(), list(range(12))) + self.assertEqual(core.cornered(core.resample(self.SQUARE[:2] + [(0.5, 1e-13, 0.0)], True, 0.25), True, 0.1).tolist()[:1], [0]) + def test_spans_bridge_a_break_and_stand_clear_of_a_port(self): """spans. Twenty points 0.25 apart, a bridge of 1.25 and a clearance of 0.5. Mutants K5 (bridge ignored: the two-point break splits the run) and K6 (clearance ignored: the run reaches the port's edge points).""" @@ -1331,7 +1351,7 @@ class StructureTests(unittest.TestCase): ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", - "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply"] + "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs"] class HostFileTests(unittest.TestCase): @@ -1435,7 +1455,14 @@ class OwnershipTests(unittest.TestCase): 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(): + if pattern is self.PACKAGE[2] and name == "__init__.py": + continue self.assertIsNone(re.search(pattern, text), f"{pattern} in {name}") + # one Manifold Boolean in the package: the rib hole cut inside ribs, on shells ribs built closed and apart; a target's live Booleans stay Exact with self-intersection + source = self.sources()["__init__.py"] + self.assertEqual(re.findall(self.PACKAGE[2], source), ['solver = "MANIFOLD']) + self.assertIn('modifier.solver = "MANIFOLD"', source.split("class BROKKR_KITBASH_OT_ribs(")[1].split("class BROKKR_KITBASH_OT_")[0]) + self.assertIn('"COLLECTION", "EXACT", True', source.split("def operation_collection(")[1].split("\n\n\n")[0]) self.assertIsNone(re.search(self.CORE, self.sources()["core.py"], re.M)) schemas = [p for p in (SURFACE.parents[1] / "schemas").rglob("*") if p.is_file()] self.assertTrue(schemas) @@ -1449,21 +1476,35 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(source.count("evaluated_get("), 1) self.assertIn("evaluated_get(", source.split("def evaluated_of(")[1].split("\n\n\n")[0]) bodies = {body.split("(")[0]: body.split("\n\n\n")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:]} - self.assertEqual([name for name, body in bodies.items() if "evaluated_of(" in body], ["boolean", "apply"]) - self.assertEqual(source.count("evaluated_of("), 4) # its def, evaluable, boolean and apply + self.assertEqual([name for name, body in bodies.items() if "evaluated_of(" in body], ["boolean", "apply", "ribs"]) + self.assertEqual(source.count("evaluated_of("), 6) # its def, evaluable, boolean, apply, and ribs for the designed surface and for its holes self.assertIn("evaluated_of(", source.split("def evaluable(")[1].split("\n\n\n")[0]) place = source.split("def place_cutters(")[1].split("\n\n\n")[0] # cut and cut_many place through it: one evaluation, with the Booleans off self.assertEqual((place.count("evaluable("), place.count("evaluated_of(")), (1, 0)) self.assertLess(place.index("modifier.show_viewport = False"), place.index("evaluable(")) self.assertLess(place.index("evaluable("), place.index("modifier.show_viewport = True")) # unevaluable-target: every action that evaluates refuses an object Blender does not evaluate before its first write - for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["apply"], "bpy.data.meshes.new_from_object(")): + for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["apply"], "bpy.data.meshes.new_from_object("), + (bodies["ribs"], "show_viewport = False")): self.assertLess(body.index("evaluable("), body.index(first_write)) - self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply"]) + self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs"]) + ribs = bodies["ribs"] # every refusal before the ribs object is written, and the cage's modifiers shown again whatever happened + self.assertLess(ribs.rindex("raise Refused("), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)")) + self.assertLess(ribs.index("finally:"), ribs.index("modifier.show_viewport = True")) + self.assertLess(ribs.index("modifier.show_viewport = True"), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)")) for body in (place, *(source.split(f"class BROKKR_KITBASH_OT_{name}(")[1].split("class BROKKR_KITBASH_OT_")[0] for name in ("cut", "cut_many"))): self.assertNotIn("view_layer.update", body) # an update after a cutter joins would evaluate the Boolean self.assertEqual(body.count("place_cutters("), 0 if body is place else 1) - self.assertEqual(source.count("to_mesh("), 1) + self.assertEqual(source.count("to_mesh("), 3) # boolean's report, and in ribs the designed surface and the holed webs + + def test_only_ribs_writes_kit_ribs(self): + """kit_ribs is the request a ribs object was derived from: ribs assigns it once and nothing reads it back to + decide geometry.""" + source = self.sources()["__init__.py"] + writes = re.findall(r'[^\n]*\[(?:RIBS|"kit_ribs")\]\s*=(?!=)[^\n]*', source) + self.assertEqual(len(writes), 1) + self.assertIn(writes[0], source.split("class BROKKR_KITBASH_OT_ribs(")[1].split("class BROKKR_KITBASH_OT_")[0]) + self.assertEqual(len(re.findall(r'\[RIBS\]|\bRIBS\b(?! =)|"kit_ribs"', source)), 2) # the constant's own line, and that write def test_only_write_connection_writes_the_roll(self): """one-writer. kit_roll is the one statement of a connection's roll, and write_connection its one writer: attach From 3b0096106e7b1102b1a03bf70a02e6608a53bd39 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 06:38:45 +0100 Subject: [PATCH 093/223] docs/kitbash.md: Ribs from a shell, and the ribs row What ribs makes, how it reads the cage, what it refuses, that the ribs object is a bake, and its cost on the pod: 1.60 s with holes, posts and longerons and 1.44 s alone, each holding one whole evaluation of the cage (1.35 s), medians of 3. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 51 ++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 888fd4c..54b2817 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -370,6 +370,56 @@ view layer: an object disabled in viewports that nothing evaluated depends on, o layer shows. A disabled object that an evaluated object needs (a parent of one, a cutter of one) is evaluated all the same, and is cut. +## Ribs from a shell + +`ribs` derives the frame under an armor cage from the cage, so the frame fits the armor by construction. It +takes planes in the cage's own frame and makes, as one mesh object under the cage: + +- a rib along each plane's section of the cage's surface: `thickness` across the plane, set `standoff` behind + the plate's inner face and reaching `depth` further in; +- lightening holes through each rib every `holes` of its length (radius 0.3 of `depth`; 0 for none); +- posts every `posts` that stand the plate off the rib: a rod from the middle of the plate into the rib, and a pad + on the plate's inner face (0 for none); +- longerons through the ribs: each `{origin, axis, toward}` is the half-plane from the line through `origin` + along `axis`, on `toward`'s side. Where it crosses a plane's rib, at the rib's mid-depth, is a station; the + longeron runs through the stations in the planes' order and 0.12 of the end gaps past the end ribs, a section + `longeron` (`I`, `C`, `T`, `L` or `box`; `longeron_w`, `longeron_h`, `longeron_t`) with its up toward the plate. + +Ribs, posts and longerons are one sweep of an outline along a path with mitred corners (`core.sweep`). + +The cage is read twice. Evaluated with its Solidify, Bevel and Boolean modifiers off it is the surface as +designed: each plane cuts that surface into sections, and a section may be several chains (two legs in one cage). +Evaluated whole it is the plate as it is cut: at points `step` apart along a section, a ray from just outside the +plate's outer face asks whether the plate is there. Where it is not, the plate is open. An opening shorter than +`bridge` along the section is a panel break, and the rib runs behind it; at any other the rib stops `clearance` +short, and no post or hole stands there. A recess that does not go through is plate. `ribs` reads no cutter: cut +the cage first, in any way, and the ribs follow what the plate became. + +The plate's thickness and which way it grows are read from the cage's one Solidify (a cage with none has a plate +of no thickness; one with two is refused). Inward is the side the cage's normals face away from, not a guess from +the section's shape: a cage whose normals change sides along a section is refused, and one whose normals all +face inward gets its frame outside. A rib is swept through the section's own corners, so its faces lie the +standoff from the cage's facets, and an end that would fold over the corner beside it ends at that corner. + +Everything is checked before the ribs object is written, and a refusal names the plane or longeron: a plane that +misses the cage or lies along its surface; a section that turns tighter than the rib reaches in, so that the rib +would fold (lower `standoff` or `depth`); a longeron that meets a plane's ribs twice, not at all, or in an opening; +holes that overlap or leave the rib; a cage that is scaled or that Blender does not evaluate; more than 64 planes or +16 longerons. + +The ribs object is a bake of the cage at the call: a child of the cage under identity matrices, with no modifier +and no material. Its `kit_ribs` property is the request as JSON. After the cage or its cuts change, delete the +object and run `ribs` again. The holes are cut with one Manifold Boolean a plane, on that plane's ribs alone +(ribs of one plane never cross; ribs of two planes do), and each cut is checked: closed, and the volume gone is +the holes' own. Manifold is used here and nowhere else because these shells are built closed and apart; a target's +live Booleans stay Exact. + +On a pod (2560 faces subdivided, a wall of 0.06, a port, a panel break and a recess; one whole evaluation +1.35 s), five ribs with 93 holes, 51 posts and four longerons took 1.60 s and the five ribs alone +1.44 s, medians of 3 interleaved with that evaluation (Blender 5.3 on Starfire). Each figure holds one whole +evaluation of the cage, which Blender makes after any action that touched it (`ribs` shows the cage's modifiers +again when it is done); the rest, 0.25 s and 0.09 s, is the action's own work. + ## Expressions Every numeric field of a shape or socket, and `bevel`, is a number or a string over the part's params: @@ -402,6 +452,7 @@ vertices overflow. | `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | +| `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored value (`set_params`). A value outside its bounds is refused with the bounds in the message. From e9f53fc3a93dcb1417fd74525bc4122ed06c759b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 08:47:12 +0100 Subject: [PATCH 094/223] brokkr_kitbash.ribs: the standoff along the plate's normal, ribs that follow a crease, and the s1 Lows Fix batch h2 of cut-kit-ribs, against verdict aetheria-release:verdict:cut-kit-ribs.s1 and follow_up ribs-fold-at-crease. core.band replaces core.cornered and the rib's sweep: the rib is the band beside its section, each edge the section offset with mitred corners and clipped as a polygon offset is (core.away, the distance to a polyline less each segment's own distance). Inside a turn tighter than the rib reaches the edges cut the corner instead of folding, so a creased shell is ribbed and not refused; a section that leaves no room at all is refused by reason. Holes stand on the band's clipped centre line; a post that would end outside the rib inside such a turn is left out. The band does not depend on the section's direction, so the chain reversal (mutant N3, dead) is gone. standoff-oblique-sections: a segment's distance is the plate's thickness and the standoff over the cosine of the plate's lean out of the plane, plus half the rib's thickness times its tangent. Pinned on cones leaning 0, 30, 45 and 60 degrees and a hipped box (45 against 20): the rib comes the standoff from the plate, 5.3e-08 off, and is the analytic ring. negative-solidify-thickness: the sign is folded into the offset. planes-string-cap-below-64: planes 16000 characters, longerons 8000; 64 planes at full precision are taken. plate-window-unpinned: a recess 0.8 of the plate deep (N5) and a port in a cage whose far wall stands 3.5 plates behind (N13). figures-do-not-match: FIT is re-measured along the normal (0.0011, bound 0.002), Manifold is 26 times Exact, not a hundred. Sixteen mutants die on this tree (O1 O2 O3 S1 N5 N13 P1 C1 V1 M1 T1 D1 G1 A1 live or unit, L1 W1 unit). 496 unit tests; kitbash_ribs 41 checks. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 64 +++---- .../brokkr_kitbash/brokkr_actions.json | 8 +- surfaces/blender/brokkr_kitbash/core.py | 163 +++++++++++++++--- surfaces/blender/tests/live/kitbash_ribs.py | 145 ++++++++++++++-- .../tests/live/kitbash_ribs.result.json | 56 +++++- surfaces/blender/tests/test_kitbash.py | 116 +++++++++++-- 6 files changed, 453 insertions(+), 99 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index c566a12..26465a7 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -37,7 +37,7 @@ cut_many, apply) first refuses one Blender does not evaluate (evaluable). A repo receipt is trimmed by fitted, the rows left off counted beside it: the scene keeps what they would have said. ribs derives the frame under an armor cage from the cage: ribs behind the plate along plane sections, stopped where -the plate is open, with lightening holes, posts and longerons, all core.sweep. What it reads is the cage evaluated +the plate is open (core.band), with lightening holes, posts and longerons (core.sweep). What it reads is the cage evaluated whole (where the plate is) and with its Solidify, Bevel and Booleans off (the surface as designed); it never reads a cutter. The ribs object is a bake of the cage at that call, and kit_ribs on it is the request, kept as a record: nothing reads it to decide geometry, and ribs is its one writer. The one Manifold Boolean in the package is the hole @@ -975,7 +975,7 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): object_name: bpy.props.StringProperty(name="Object", description="The cage: a mesh whose surface is the plate's designed face, usually subdivided and with one Solidify") ribs_name: bpy.props.StringProperty(name="Ribs", description="The new ribs object's name") planes: bpy.props.StringProperty(name="Planes", description="A JSON array of 1 to 64 planes, each {origin, normal} in the cage's own frame: a rib runs where each cuts the surface") - standoff: bpy.props.FloatProperty(name="Standoff", default=0.09, min=0.0, max=2.0, description="Metres between the plate's inner face and the ribs") + standoff: bpy.props.FloatProperty(name="Standoff", default=0.09, min=0.0, max=2.0, description="Metres between the plate's inner face and the ribs, along the plate's normal") depth: bpy.props.FloatProperty(name="Depth", default=0.09, min=0.005, max=2.0, description="How far a rib reaches inward from there") thickness: bpy.props.FloatProperty(name="Thickness", default=0.014, min=0.0005, max=1.0, description="A rib's thickness across its plane") step: bpy.props.FloatProperty(name="Step", default=0.01, min=0.001, max=1.0, description="Spacing of the points a section is followed by") @@ -1011,15 +1011,14 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): walls = [m for m in cage.modifiers if m.type == "SOLIDIFY" and m.show_viewport] if len(walls) > 1: raise Refused(f"{cage.name!r} has {len(walls)} Solidify modifiers ({', '.join(m.name for m in walls)}): its plate has one thickness, read from one; nothing changed.") - plate, offset = (abs(walls[0].thickness), walls[0].offset) if walls else (0.0, 0.0) + # a Solidify of negative thickness grows the other way: the same plate as its size with the offset turned over + plate, offset = (abs(walls[0].thickness), math.copysign(1.0, walls[0].thickness) * walls[0].offset) if walls else (0.0, 0.0) outer, inner = plate * (1.0 + offset) / 2.0, plate * (1.0 - offset) / 2.0 # the plate's two faces, out of and into the designed surface - near, mid = inner + self.standoff, inner + self.standoff + self.depth / 2.0 - web = np.array([(-self.thickness / 2, near), (self.thickness / 2, near), (self.thickness / 2, near + self.depth), (-self.thickness / 2, near + self.depth)]) whole = BVHTree.FromObject(cage, depsgraph) # the plate as it is cut: where a ray into it finds nothing, it is open shown = [m for m in cage.modifiers if m.type in SHELL_MODIFIERS and m.show_viewport] surface, made, drilled, sections, webs, rods, beams, samples, holes = None, [], [], [], [], [], [], 0, 0 try: - for modifier in shown: + for modifier in shown: # this tags the cage, and Blender evaluates it whole again after the call: one evaluation a call, and no cheaper way to the designed surface (docs/kitbash.md, Ribs from a shell) modifier.show_viewport = False _, designed = evaluated_of(context, cage) surface = bmesh.new() @@ -1044,55 +1043,59 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): if samples > SAMPLES_LIMIT: raise Refused(f"The sections are over {SAMPLES_LIMIT} points at step {self.step:.6g}: raise step, or give fewer planes; nothing changed.") P = core.resample(points, closed, self.step) - out = np.array([nearest.find_nearest(Vector(p))[1] for p in P], dtype=np.float64) + between = ((P + np.roll(P, -1, axis=0)) / 2.0)[:len(P) if closed else len(P) - 1] # the middle of each segment: a point of one facet, where a corner is a point of two + out, facing = (np.array([nearest.find_nearest(Vector(p))[1] for p in at], dtype=np.float64) for at in (P, between)) flat = out - normal * (out @ normal)[:, None] - if not (np.linalg.norm(flat, axis=1) > 1e-3).all(): + upright = np.sqrt(1.0 - np.minimum((facing @ normal) ** 2, 1.0)) # the cosine of how far the plate's normal leans out of the plane, a segment + if not (np.linalg.norm(flat, axis=1) > 1e-3).all() or not (upright > 1e-3).all(): raise Refused(f"{where} lies along {cage.name!r}'s surface where it meets it: a rib needs a plane that crosses the plate; nothing changed.") inward = -flat / np.linalg.norm(flat, axis=1)[:, None] + # The plate is `inner` thick and the rib stands `standoff` off it along the plate's own normal: along the plane, where + # the rib lies, both are longer by 1 / upright, and the rib's edge on the side the plate leans over is half a + # thickness nearer still. One distance for each segment of the section. + slope, back = 1.0 / upright, ((inner + self.standoff) + self.thickness / 2.0 * np.abs(facing @ normal)) / upright ahead = np.roll(P, -1, axis=0) - np.roll(P, 1, axis=0) if closed else np.gradient(P, axis=0) turn = np.cross(ahead, inward) @ normal # which side of the section its normals stand on: one sign all the way along if (turn > 0).any() and (turn < 0).any(): raise Refused(f"{where}: the normals of {cage.name!r} change sides along the section (some of its faces are flipped): " "recalculate its normals so they all face out of the plate; nothing changed.") - if turn[0] < 0: # every section runs the same way about its plane's normal, wherever its chain started - P, out, inward = P[::-1], out[::-1], inward[::-1] aside = np.roll(P, -1, axis=0) - P if closed else np.vstack([np.diff(P, axis=0), P[-2:-1] - P[-1:]]) # toward the next point; an open chain's last, toward the one before aside = aside / np.linalg.norm(aside, axis=1)[:, None] * NUDGE reach = LIFT + 1.25 * plate + 1e-4 opened = [whole.ray_cast(Vector(p + n * (outer + LIFT)), Vector(-n), reach)[0] is None for p, n in zip(P + aside, out)] lengths = np.linalg.norm(np.diff(np.vstack([P, P[:1]]) if closed else P, axis=0), axis=1) - row["lines"].append((P + inward * mid, closed)) + row["lines"].append((P + inward * (np.resize(back, len(P)) + self.depth / 2.0)[:, None], closed)) # about where a rib would run: only asked whether a longeron crosses it for piece in core.spans(opened, lengths, closed, self.bridge, self.clearance): ring = closed and len(piece) == len(P) - piece = piece[core.cornered(P[piece], ring, near + self.depth)] # swept corner to corner - if len(piece) < 2: - continue try: - rib = core.sweep(P[piece], web, inward[piece], closed=ring) + rib = core.band(P[piece], ring, normal, inward[piece], back[piece if ring else piece[:-1]], self.depth, self.thickness) except core.KitError as error: raise Refused(f"{where}: {error}: lower standoff or depth; nothing changed.") from None - centre = rib.V.reshape(len(piece), 4, 3).mean(axis=1) # the rib's mid-depth line, as swept - row["ribs"].append((centre, ring, P[piece], inward[piece])) + row["ribs"].append({"band": rib, "ring": ring, "P": P[piece], "inward": inward[piece], "back": back[piece if ring else piece[:-1]], "slope": slope[piece if ring else piece[:-1]]}) row["pieces"] += 1 row["length"] += float(np.linalg.norm(np.diff(np.vstack([P[piece], P[piece][:1]]) if ring else P[piece], axis=0), axis=1).sum()) - webs.append((index, rib)) + webs.append((index, rib.shell)) row["open"] += float(lengths.sum()) row["open"] = round(max(row["open"] - row["length"], 0.0), 6) sections.append(row) if not webs: raise Refused(f"No rib: the plate of {cage.name!r} is open along every section; nothing changed.") for row in sections: # posts stand on the kept runs only - for centre, ring, P, inward in row["ribs"] if self.posts > 0 else (): - for point, segment, fraction in along(P, ring, self.posts): - n = inward[segment] + (inward[(segment + 1) % len(P)] - inward[segment]) * fraction - n, up = n / np.linalg.norm(n), planes[row["plane"]]["normal"] - rods.append(core.sweep([point + n * (inner - outer) / 2.0, point + n * (near + 0.3 * self.depth)], core.circle(self.post_r, POST_SEGMENTS), up)) - rods.append(core.sweep([point + n * inner, point + n * (inner + self.post_r)], core.circle(2.4 * self.post_r, PAD_SEGMENTS), up)) + for rib in row["ribs"] if self.posts > 0 else (): + P, up = rib["P"], planes[row["plane"]]["normal"] + for point, segment, fraction in along(P, rib["ring"], self.posts): + n, back, slope = rib["inward"][segment] + (rib["inward"][(segment + 1) % len(P)] - rib["inward"][segment]) * fraction, rib["back"][segment], rib["slope"][segment] + n = n / np.linalg.norm(n) + foot = point + n * (back + 0.3 * self.depth) + if core.away(foot, P, rib["ring"])[0] < back: # inside a turn the rib was clipped at: a post there would end outside it + continue + rods.append(core.sweep([point + n * slope * (inner - outer) / 2.0, foot], core.circle(self.post_r, POST_SEGMENTS), up)) + rods.append(core.sweep([point + n * slope * inner, point + n * (slope * inner + self.post_r)], core.circle(2.4 * self.post_r, PAD_SEGMENTS), up)) for index, longeron in enumerate(longerons): where, stations, ups = f"longerons[{index}]", [], [] for row in sections: try: - hits = [(hit, rib) for rib in row["ribs"] for hit in core.crossings(rib[0], rib[1], longeron["origin"], longeron["axis"], longeron["toward"])] + hits = [(hit, rib) for rib in row["ribs"] for hit in core.crossings(rib["band"].centre, rib["ring"], longeron["origin"], longeron["axis"], longeron["toward"])] through = any(core.crossings(line, closed, longeron["origin"], longeron["axis"], longeron["toward"]) for line, closed in row["lines"]) except core.KitError as error: raise Refused(f"{where}: {error}; nothing changed.") from None @@ -1100,8 +1103,9 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): raise Refused(f"{where} " + (f"meets the ribs of planes[{row['plane']}] {len(hits)} times: its half-plane must cross them once" if hits else f"crosses planes[{row['plane']}] where the plate is open and there is no rib" if through else f"does not meet the ribs of planes[{row['plane']}]") + "; nothing changed.") - ((segment, point), (centre, ring, P, inward)), = hits - n = inward[segment] + (inward[(segment + 1) % len(P)] - inward[segment]) * float(np.linalg.norm(point - centre[segment]) / np.linalg.norm(centre[(segment + 1) % len(P)] - centre[segment])) + ((segment, point), rib), = hits + centre, inward = rib["band"].centre, rib["inward"][rib["band"].at] + n = inward[segment] + (inward[(segment + 1) % len(centre)] - inward[segment]) * float(np.linalg.norm(point - centre[segment]) / np.linalg.norm(centre[(segment + 1) % len(centre)] - centre[segment])) stations.append(point) ups.append(-n / np.linalg.norm(n)) # up toward the plate path = [stations[0] + (stations[0] - stations[1]) * 0.12] + stations + [stations[-1] + (stations[-1] - stations[-2]) * 0.12] @@ -1111,8 +1115,8 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): raise Refused(f"{where}: {error}; nothing changed.") from None for index in sorted({index for index, _ in webs}) if self.holes > 0 else (): # one Boolean a plane: a plane's webs never cross each other, two planes' do normal = planes[index]["normal"] - drills = [core.sweep([point - normal * 2.0 * self.thickness, point + normal * 2.0 * self.thickness], core.circle(0.3 * self.depth, HOLE_SEGMENTS), inward[segment]) - for centre, ring, _, inward in sections[index]["ribs"] for point, segment, _ in along(centre, ring, self.holes)] + drills = [core.sweep([point - normal * 2.0 * self.thickness, point + normal * 2.0 * self.thickness], core.circle(0.3 * self.depth, HOLE_SEGMENTS), rib["inward"][0]) + for rib in sections[index]["ribs"] for point, _, _ in along(rib["band"].centre, rib["ring"], self.holes)] # the centre line stands 0.5 of depth off both edges wherever it runs if not drills: continue pair = [] @@ -1121,7 +1125,7 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): made.append(pair[-1]) write_mesh(pair[-1].data, core.joined(shells)) context.scene.collection.objects.link(pair[0]) - modifier = pair[0].modifiers.new("Holes", "BOOLEAN") # closed shells that do not cross: what Manifold takes, a hundred times sooner than Exact + modifier = pair[0].modifiers.new("Holes", "BOOLEAN") # closed shells that do not cross: what Manifold takes, 26 times sooner than Exact (0.017 s against 0.44 s for the pod's 93 holes) modifier.object, modifier.operation = pair[1], "DIFFERENCE" modifier.solver = "MANIFOLD" drilled.append((index, len(drills), measured(pair[0].data)["volume"], pair[0])) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 8768e4b..d2906e9 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -569,7 +569,7 @@ }, { "name": "brokkr_kitbash.ribs", - "doc": "Derive the frame under an armor cage from the cage itself, so it fits the armor by construction: a rib along each plane's section of the cage's surface, set the standoff behind the plate's inner face and reaching depth inward; lightening holes through the ribs; posts that stand the plate off them; longerons through the ribs. The plate's thickness is read from the cage's one Solidify. A rib stops where the plate is open (a port cut through it), runs behind an opening shorter than bridge (a panel break) and under a recess: openings are read from the cage as it is cut, so cut first. Inward is the side the cage's normals face away from. Makes one mesh object, a child of the cage, baked at this call: after the cage or its cuts change, delete it and run ribs again (its kit_ribs property keeps the request). Every plane and longeron is checked before anything is written. Reports ribs, thickness, sections [{plane, chains, pieces, length, open}], posts, holes, longerons [{index, stations}], faces, volume and nonManifoldEdges.", + "doc": "Derive the frame under an armor cage from the cage itself, so it fits the armor by construction: a rib along each plane's section of the cage's surface, set the standoff behind the plate's inner face (along the plate's normal, however it leans out of the plane) and reaching depth inward, clipped inside a crease tighter than that; lightening holes through the ribs; posts that stand the plate off them; longerons through the ribs. The plate's thickness is read from the cage's one Solidify. A rib stops where the plate is open (a port cut through it), runs behind an opening shorter than bridge (a panel break) and under a recess: openings are read from the cage as it is cut, so cut first. Inward is the side the cage's normals face away from. Makes one mesh object, a child of the cage, baked at this call: after the cage or its cuts change, delete it and run ribs again (its kit_ribs property keeps the request). Every plane and longeron is checked before anything is written. Reports ribs, thickness, sections [{plane, chains, pieces, length, open}], posts, holes, longerons [{index, stations}], faces, volume and nonManifoldEdges.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -595,7 +595,7 @@ "type": "string", "required": true, "minLength": 2, - "maxLength": 8000, + "maxLength": 16000, "doc": "a JSON array of 1 to 64 planes, each {\"origin\": [x, y, z], \"normal\": [x, y, z]} in the cage's own frame; a rib runs where each cuts the surface" }, { @@ -604,7 +604,7 @@ "minimum": 0, "maximum": 2, "default": 0.09, - "doc": "metres between the plate's inner face and the ribs" + "doc": "metres between the plate's inner face and the ribs, along the plate's own normal" }, { "name": "depth", @@ -675,7 +675,7 @@ "type": "string", "default": "[]", "minLength": 2, - "maxLength": 4000, + "maxLength": 8000, "doc": "a JSON array of 0 to 16 longerons, each {\"origin\": [x, y, z], \"axis\": [x, y, z], \"toward\": [x, y, z]} in the cage's own frame: the half-plane from the line through origin along axis, on toward's side. The longeron runs through the rib of every plane, in the planes' order, where the half-plane crosses the rib's mid-depth line: exactly once a plane, and not in an opening" }, { diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 2cf3972..cce0f57 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -17,10 +17,12 @@ both kits declare the socket's type with the same match rule. surface_frame is t 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. -The structure under an armor cage is swept, not kit parts: PROFILES are the sections (I, C, T, L, box), sweep takes -an outline along a polyline with mitred joints (a rib, a longeron, a post are all one sweep), crossings finds where a -section line meets a half-plane, resample fills a section's points in, spans says which runs of a section keep -their frame where the plate over them is open, and cornered which of a run's points the frame is swept through. brokkr_kitbash.ribs is the bpy around them. +The structure under an armor cage is built, not kit parts: PROFILES are the sections (I, C, T, L, box), sweep takes +an outline along a polyline with mitred joints (a longeron, a post), band is the rib beside a section in its plane, +offset and clipped so that it follows a crease instead of folding in it (away, the distance to a polyline, is what +clips it), crossings finds where a section line meets a half-plane, resample fills a section's points in, and spans +says which runs of a section keep their frame where the plate over them is open. brokkr_kitbash.ribs is the bpy +around them. A pin's roll is its one degree of freedom, and it is solved in closed form: roll_terms gives how a point or an axis of the child moves along a world direction as the roll turns (a cosine, a sine and a constant), aim_roll the roll @@ -740,7 +742,7 @@ def crossings(points, closed: bool, origin, axis, toward) -> list: def resample(points, closed: bool, step: float) -> np.ndarray: """A polyline's own points with more between them, evenly along each segment, so that none stands over `step` from the next. A corner stays a corner: points spaced along the arc instead would cut each corner into two, a - step apart, and a section offset inward folds between them. A segment shorter than 1e-7 is dropped with its + step apart, and a band beside the section would be clipped at both. A segment shorter than 1e-7 is dropped with its first point. An open polyline keeps both ends; a closed one starts at its first point.""" points = np.asarray(points, dtype=np.float64) if not (finite(step) and step > 0) or len(points) < 2: @@ -754,27 +756,136 @@ def resample(points, closed: bool, step: float) -> np.ndarray: return np.array(made if closed else made + [loop[-1]]) -def cornered(points, closed: bool, reach: float) -> np.ndarray: - """Indices of the points a section's frame is swept through: those where the polyline turns, and an open one's - two ends. Points along a straight run add nothing to a sweep and would each stand a ring square to the run, - which a mitre at the next corner then folds over. For the same reason an open polyline's end is left out when - the corner beside it stands nearer than its mitre sets back, `reach` (how far the frame reaches to the inside) - times the tangent of half the turn there: the frame then ends at that corner. Fewer than 2 points left is none; a - closed polyline with no corner keeps every point.""" - points = np.asarray(points, dtype=np.float64) - count = len(points) - steps = (np.roll(points, -1, axis=0) - points)[:count if closed else count - 1] - steps = steps / np.linalg.norm(steps, axis=1)[:, None] - cosine = np.clip(np.einsum("ij,ij->i", np.roll(steps, 1, axis=0) if closed else steps[:-1], steps if closed else steps[1:]), -1.0, 1.0) - straight = cosine > 1.0 - 1e-12 - if closed: - return np.flatnonzero(~straight) if (~straight).sum() >= 3 else np.arange(count) - inner = (np.flatnonzero(~straight) + 1).tolist() - back = lambda corner: reach * math.sqrt((1.0 - cosine[corner - 1]) / max(1.0 + cosine[corner - 1], 1e-12)) + 1e-9 # noqa: E731 how far that corner's mitre sets the inside back - first = [] if inner and np.linalg.norm(points[inner[0]] - points[0]) <= back(inner[0]) else [0] - last = [] if inner and np.linalg.norm(points[inner[-1]] - points[-1]) <= back(inner[-1]) else [count - 1] - kept = first + inner + last - return np.array(kept if len(kept) >= 2 else [], dtype=np.int64) +AWAY_SPAN = 64 # points, and segments, that away takes at a time: a block of points skips the blocks of segments too far off to matter + + +def away(points, chain, closed: bool, less=0.0, limit: float = math.inf) -> np.ndarray: + """How far each point stands from a polyline: its least distance to any segment. With `less`, one length for + each segment, the least over the segments of the distance less that segment's length: 0 or more where the point + stands at least each segment's own length off it. A value over `limit` is not looked for and comes back as + `limit`: with one, a long polyline costs each point the segments near it and not all of them (the three edges + of a band on 20000 points: about 60 s without; the whole band 0.7 s with a limit of 0).""" + points, chain = np.asarray(points, dtype=np.float64).reshape(-1, 3), np.asarray(chain, dtype=np.float64) + a, b = (chain, np.roll(chain, -1, axis=0)) if closed else (chain[:-1], chain[1:]) + ab = b - a + square, less = np.maximum(np.einsum("ij,ij->i", ab, ab), 1e-300), np.broadcast_to(np.asarray(less, dtype=np.float64), (len(a),)) + starts = np.arange(0, len(a), AWAY_SPAN) + low, high = (np.array([side(np.vstack([a[j:j + AWAY_SPAN], b[j:j + AWAY_SPAN]]), axis=0) for j in starts]) for side in (np.min, np.max)) # each block of segments' box + most = np.maximum.reduceat(less, starts) + least = np.full(len(points), float(limit)) + for first in range(0, len(points), AWAY_SPAN): + block = points[first:first + AWAY_SPAN] + apart = np.linalg.norm(np.maximum(0.0, np.maximum(low - block.max(axis=0), block.min(axis=0) - high)), axis=1) - most # no segment of a block reads under this + near = np.concatenate([np.arange(j, min(j + AWAY_SPAN, len(a))) for j in starts[apart <= limit]] or [np.zeros(0, dtype=np.int64)]) + if len(near): + offset = block[:, None, :] - a[near][None] + offset = offset - np.clip(np.einsum("ksj,sj->ks", offset, ab[near]) / square[near], 0.0, 1.0)[:, :, None] * ab[near][None] + least[first:first + AWAY_SPAN] = np.minimum(least[first:first + AWAY_SPAN], (np.sqrt(np.einsum("ksj,ksj->ks", offset, offset)) - less[near][None]).min(axis=1)) + return least + + +class Band(NamedTuple): + """A band beside a polyline, as one closed shell, and the lines a frame is hung on it by.""" + shell: Swept + outer: np.ndarray # the band's edge next to the polyline + inner: np.ndarray # its far edge + centre: np.ndarray # the line midway between them: the polyline offset by back + depth / 2, clipped as the edges are + at: np.ndarray # for each point of centre, the index of the polyline's point it is offset from + + +def band(points, closed: bool, normal, inward, back, depth: float, thickness: float) -> Band: + """The band beside a polyline that lies in a plane: everything in that plane, on the side `inward` points to, + that stands from back to back + depth off the polyline, `thickness` across the plane; one closed shell, wound + outward. `normal` is the plane's unit normal; `inward` (one in-plane vector for each point) only says which + side; `back` is one distance, or one for each segment. + + Each edge is the polyline offset and then clipped, as a polygon offset is. A point's offset stands where its two + segments' offset lines meet, a mitre; where their distances differ and the lines meet beside one segment but + past the end of the other (two segments that are nearly one line), it stands the greater distance off both. An + offset point that stands nearer any segment than that segment's own distance is left out, and its neighbours + close the edge there. So inside a turn tighter than the band reaches the far edge cuts the corner, and the band + narrows instead of folding; between two kept points the cut is a chord, which leaves the true corner out by + less than the points' spacing. Points along a straight run with nothing clipped beside them are left out too: + they add no shape. + + Refuses, naming the point: fewer than 2 points (3 when closed), a segment shorter than 1e-9, a turn over + TURN_LIMIT; and a polyline that leaves an edge fewer than 2 points (3 when closed): it closes in on itself + nearer than the band reaches, everywhere.""" + P, normal, inward, back = (np.asarray(v, dtype=np.float64) for v in (points, normal, inward, back)) + count, least = len(P), 3 if closed else 2 + if P.ndim != 2 or P.shape[1] != 3 or count < least or inward.shape != P.shape or back.shape not in ((), (count if closed else count - 1,)) or not ( + np.isfinite(P).all() and np.isfinite(back).all() and (back >= 0).all() and depth > 0 and thickness > 0): + raise KitError(f"a band needs {least} points of three finite numbers, an inward for each, one distance of 0 or more or one for each segment, and a depth and thickness above 0; it has {count} points") + back = np.broadcast_to(back, (count if closed else count - 1,)) + steps = (np.roll(P, -1, axis=0) - P)[:count if closed else count - 1] + lengths = np.linalg.norm(steps, axis=1) + if (lengths < 1e-9).any(): + raise KitError(f"path point {int(np.argmax(lengths < 1e-9))}: the segment from it is shorter than 1e-9") + along = steps / lengths[:, None] + aside = np.cross(normal, along) # each segment's in-plane normal + into = lambda of: (np.roll(of, 1, axis=0), of) if closed else (np.concatenate([of[:1], of]), np.concatenate([of, of[-1:]])) # noqa: E731 a point's segment before and after + (before, after), (arriving, leaving) = into(aside), into(along) + cosine = np.clip(np.einsum("ij,ij->i", before, after), -1.0, 1.0) + if (cosine < math.cos(math.radians(TURN_LIMIT))).any(): + index = int(np.argmax(cosine < math.cos(math.radians(TURN_LIMIT)))) + raise KitError(f"path point {index}: the path turns {math.degrees(math.acos(cosine[index])):.1f} degrees there, over {TURN_LIMIT:g}") + side = 1.0 if np.einsum("ij,ij->", before + after, inward) > 0 else -1.0 + square = np.maximum(1.0 - cosine ** 2, 1e-18) + edges, valid, uneven = [], [], np.zeros(count, dtype=bool) + for further in (0.0, depth, depth / 2.0): + first, second = into(back + further) + even = (np.maximum(first, second) / (1.0 + cosine))[:, None] * (before + after) # the greater distance off both segments + met = ((first - cosine * second) / square)[:, None] * before + ((second - cosine * first) / square)[:, None] * after # first off one, second off the other + mitred = (first != second) & (np.einsum("ij,ij->i", met, arriving) * np.einsum("ij,ij->i", met, leaving) <= 0.0) # beside both segments, or past the ends of both + edges.append(P + side * np.where(mitred[:, None], met, even)) + valid.append(away(edges[-1], P, closed, back + further, limit=0.0) >= -1e-6 * np.maximum(first, second) - 1e-9) + uneven |= first != second + turns = (cosine < 1.0 - 1e-12) | uneven + if not closed: + turns[[0, -1]] = True + state = valid[0] * 4 + valid[1] * 2 + valid[2] + changes = (state != np.roll(state, 1)) | (state != np.roll(state, -1)) + if not closed: + changes[0], changes[-1] = state[0] != state[1], state[-1] != state[-2] + kept = np.flatnonzero((turns | changes) & (valid[0] | valid[1])) + reached = np.concatenate([[0.0], np.cumsum(lengths)]) + lines, maps = [], [] + for edge, ok in zip(edges, valid): # a clipped point takes the nearest kept one along the polyline + own = kept[ok[kept]] + if len(own) < least: + raise KitError(f"path point {int(np.argmin(valid[1]))}: the section leaves a rib no room: it turns or closes in tighter than the rib reaches") + apart = np.linalg.norm(np.diff(edge[own], axis=0), axis=1) > 1e-9 # a point clipped exactly onto its neighbour is that neighbour + own = own[np.concatenate([[True], apart])] + if closed and np.linalg.norm(edge[own[0]] - edge[own[-1]]) <= 1e-9: + own = own[:-1] + after = np.searchsorted(reached[own], reached[kept]) # the kept point of this edge at or after each kept point, and the one before + pair = np.stack([after - 1, after]) % len(own) if closed else np.clip(np.stack([after - 1, after]), 0, len(own) - 1) + gap = np.abs(reached[own][pair] - reached[kept][None, :]) + lines.append((edge[own], own)) + maps.append(pair[np.argmin(np.minimum(gap, reached[-1] - gap) if closed else gap, axis=0), np.arange(len(kept))]) + ((outer, _), (inner, _), (centre, at)), (to_outer, to_inner, _) = lines, maps + half = normal * thickness / 2.0 + A, B = len(outer), len(inner) # vertices: outer low, outer high, inner low, inner high + faces = [] + for i, j in [(k, k + 1) for k in range(len(kept) - 1)] + ([(len(kept) - 1, 0)] if closed else []): + a0, a1, b0, b1 = to_outer[i], to_outer[j], 2 * A + to_inner[i], 2 * A + to_inner[j] + if a0 != a1: + faces.append((a0, a1, A + a1, A + a0)) + if b0 != b1: + faces.append((b0, B + b0, B + b1, b1)) + cap = ([a0] if a0 == a1 else [a0, a1]) + ([b1] if b0 == b1 else [b1, b0]) + if len(cap) > 2: + faces.append(tuple(A + v if v < 2 * A else B + v for v in cap)) + faces.append(tuple(cap[::-1])) + if not closed: + faces.append((to_outer[0], A + to_outer[0], 2 * A + B + to_inner[0], 2 * A + to_inner[0])) + faces.append((to_outer[-1], 2 * A + to_inner[-1], 2 * A + B + to_inner[-1], A + to_outer[-1])) + if side < 0: + faces = [face[::-1] for face in faces] + counts = np.array([len(face) for face in faces], dtype=np.int32) + shell = Swept(V=np.vstack([outer - half, outer + half, inner - half, inner + half]), faces=np.concatenate(faces).astype(np.int32), counts=counts, + smooth=np.zeros(len(counts), dtype=bool), sharp=NO_SHARP.astype(np.int32)) + return Band(shell=shell, outer=outer, inner=inner, centre=centre, at=at) def spans(flags, lengths, closed: bool, bridge: float, clearance: float) -> list: diff --git a/surfaces/blender/tests/live/kitbash_ribs.py b/surfaces/blender/tests/live/kitbash_ribs.py index 57a6e5e..3446c07 100644 --- a/surfaces/blender/tests/live/kitbash_ribs.py +++ b/surfaces/blender/tests/live/kitbash_ribs.py @@ -1,6 +1,6 @@ """Live proof, in a background Blender, of brokkr_kitbash.ribs through run_intent: ribs that stand a standoff behind a -cage's plate and in their planes, that stop at a port, run behind a panel break and under a recess, that take their side -from the cage's normals, longerons through the ribs of a cage a plane cuts twice, lightening holes through crossing +cage's plate along the plate's own normal, however it leans, and in their planes, that follow a crease tighter than they +reach, that stop at a port, run behind a panel break and under a recess, that take their side from the cage's normals, longerons through the ribs of a cage a plane cuts twice, lightening holes through crossing ribs, and the refusals. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_ribs.py -- @@ -61,12 +61,24 @@ R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_ COUNT, SECTION = [0], ["setup"] STANDOFF, DEPTH, THICKNESS = 0.04, 0.06, 0.014 SIZES = {"standoff": STANDOFF, "depth": DEPTH, "thickness": THICKNESS} -# Metres between where a rib vertex stands behind the plate's inner face, along its plane, and the standoff (its outer -# edge) or the standoff and depth (its inner edge). Shipped worst 0.0093 (the pod: the plate is 0.06 thick along its -# own normal, which leans up to 30 degrees out of a rib's plane, and the rib is set 0.06 back along the plane); -# least claimed mutant 0.065 (K12, the standoff taken from the outer face: the rib's outer edge is then inside the plate); -# separation 3.5 each side. -FIT = 0.018 +# Metres between the standoff and how near a rib's outer edge comes to the plate's inner face, at each point of the edge, +# on the pod: a doubly curved wall that leans up to 30 degrees out of a rib's plane. Shipped worst 0.0011 (a facet's rib +# is straight where the wall is curved); least claimed mutant 0.0036 (O2, the rib's half thickness, which a leaning plate +# comes nearer, left out); the geometric mean, separation 1.8 each side. O3 (only the plate's thickness laid off along +# its normal) reads 0.0067, O1 (both laid off along the plane, as before cut-kit-ribs.h2) 0.011, K12 (the standoff taken +# from the outer face) 0.06. +FIT = 0.002 +# The same on cages of flat facets, where it is exact: cones whose wall leans 0, 30, 45 and 60 degrees out of the plane, a +# cylinder whose Solidify is negative, a hipped box, and a crease. Shipped worst 5.3e-08 (float32 meshes); least claimed mutant 0.006 +# (O2 at 60 degrees); the geometric mean, separation 340 each side. O3 reads 0.026, O1 0.036, S1 (a negative +# thickness read as its size alone) 0.06. +STOOD = 1.8e-5 +# A cone's rib or a hipped box's, over the ring between the section's two offsets times the thickness, less 1. Shipped worst 2.1e-06; +# least claimed mutant 0.034 (O2); the geometric mean, separation 130 each side. +RING = 2.7e-4 +# A rib inside a crease, over the true clipped offset's area times the thickness, less 1: tests/test_kitbash.py CREASED, +# the same polyline. Shipped 0.0013; least claimed mutant 0.079 (C1, nothing clipped); separation 7.9 each side. +CREASED = 0.0099 # Metres a rib vertex stands off its plane beyond half the rib's thickness. Shipped worst 1.4e-07 (float32 meshes); # least claimed mutant 0.007 (KP, a rib twice as thick across its plane); separation 220 each side. PLANAR = 3.1e-5 @@ -186,6 +198,15 @@ def islands(bm): return found +def nearest_by_column(surface, V): + """The least distance from a BVH to the vertices that share an x and y (to 1e-5), for each such column.""" + found = {} + for v in V: + key = (round(float(v[0]), 5), round(float(v[1]), 5)) + found[key] = min(found.get(key, 1.0), surface.find_nearest(Vector(v))[3]) + return found + + def child_of(ribs, cage): return ribs is not None and ribs.parent == cage and np.array_equal(np.array(ribs.matrix_parent_inverse), np.eye(4)) and np.array_equal(np.array(ribs.matrix_basis), np.eye(4)) \ and np.abs(np.array(ribs.matrix_world) - np.array(cage.matrix_world)).max() < 1e-6 and len(ribs.modifiers) == 0 and len(ribs.data.materials) == 0 @@ -241,21 +262,103 @@ try: and [s["open"] > 0.25 for s in report["sections"]] == [False, False, True, False, False] and all(s["open"] == 0.0 for k, s in enumerate(report["sections"]) if k != 2) and (shape["faces"], shape["nonManifoldEdges"], shape["shells"]) == (report["faces"], 0, 5) and abs(shape["volume"] - report["volume"]) < 1e-8 and 0.5 < report["volume"] / (sum(s["length"] for s in report["sections"]) * DEPTH * THICKNESS) < 1.0, report) # a rib inside a curve is shorter than the section it follows - behind = True - for v in points(fit): + behind, V = True, points(fit) + for v in V: plane = min(HEIGHTS, key=lambda z: abs(v[2] - z)) reading("planar", abs(abs(v[2] - plane) - THICKNESS / 2)) on, normal, _, _ = designed.find_nearest(Vector((v[0], v[1], plane))) - out = Vector((normal.x, normal.y, 0.0)).normalized() - hit, _, _, distance = inner.ray_cast(Vector((v[0], v[1], plane)), out) # the inner face, outward of the vertex along its plane - if hit is None: # or the vertex is in the plate, and the inner face is behind it - hit, _, _, distance = inner.ray_cast(Vector((v[0], v[1], plane)), -out) - behind, distance = False, -distance if hit is not None else 1.0 behind = behind and (Vector((v[0], v[1], plane)) - on).dot(normal) < 0 - reading("fit", min(abs(distance - STANDOFF), abs(distance - STANDOFF - DEPTH))) - check("ribs-fit-the-plate: every rib vertex stands the standoff, or the standoff and the depth, behind the plate's inner face along its plane, in its plane, on the side the normals face away from", + for least in nearest_by_column(inner, V).values(): # a column: the vertices of one point of an edge, half a thickness either side of the plane + if least < STANDOFF + 0.4 * DEPTH: # the outer edge's; the inner edge's stand a depth further in + reading("fit", abs(least - STANDOFF)) + check("ribs-fit-the-plate: at every point of a rib's outer edge the nearer vertex stands the standoff behind the plate's inner face, along the plate's normal; every vertex in its plane, on the side the normals face away from", behind and R["readings"]["fit"] < FIT and R["readings"]["planar"] < PLANAR, R["readings"]) + # --- standoff-oblique-sections: cones, a negative Solidify, and a crease ---------------------------------------------------------- + section("ribs-on-leaning-plates") + SIDES = 24 + + def frustum(name, lean, at): + """A cone's wall from z = 0.3 to 0.7 that leans `lean` degrees from its axis, radius 0.6 at z = 0.5, normals outward, a wall of 0.06 inward.""" + rows = [[((0.6 + (z - 0.5) * math.tan(math.radians(lean))) * math.cos(a), (0.6 + (z - 0.5) * math.tan(math.radians(lean))) * math.sin(a), z) + for a in (2 * math.pi * (k + 0.5) / SIDES for k in range(SIDES))] for z in (0.3, 0.7)] + return mesh_object(name, rows[0] + rows[1], [(k, (k + 1) % SIDES, SIDES + (k + 1) % SIDES, SIDES + k) for k in range(SIDES)], Matrix.Translation(at), wall=0.06) + + def stood(cage, ribs, standoff=STANDOFF): + """How near the ribs come to the cage's plate as it is evaluated, less the standoff.""" + plate = tree(cage) + return reading("stood", abs(min(plate.find_nearest(Vector(v))[3] for v in points(ribs)) - standoff)) + + leaned = [] + for k, lean in enumerate((0, 30, 45, 60)): + cone = frustum(f"Cone{lean}", lean, (3.0 * k, 9.0, 0.0)) + receipt, report = send("brokkr_kitbash.ribs", object_name=cone.name, ribs_name=f"ConeRibs{lean}", planes=flat([0.5]), **SIZES) + ribs = bpy.data.objects.get(f"ConeRibs{lean}") + slope = math.tan(math.radians(lean)) * math.cos(math.pi / SIDES) # of a facet: the cone's own lean is its corners' + back = (0.06 + STANDOFF) * math.hypot(1.0, slope) + THICKNESS / 2 * slope # along the plane, to the rib's outer edge + outer = 0.6 * math.cos(math.pi / SIDES) - back # the inradius of the rib's outer edge, a regular polygon + ring = SIDES * math.tan(math.pi / SIDES) * (outer ** 2 - (outer - DEPTH) ** 2) * THICKNESS + readings = (stood(cone, ribs), reading("ring", abs(measure(ribs.data)["volume"] / ring - 1.0))) if ribs is not None else (1.0, 1.0) + leaned.append(receipt["status"] == "accepted" and child_of(ribs, cone) and (report["ribs"], report["thickness"], report["nonManifoldEdges"]) == (1, 0.06, 0) + and readings[0] < STOOD and readings[1] < RING) + check("standoff-oblique-sections: on cones whose wall leans 0, 30, 45 and 60 degrees out of the rib's plane the rib comes the standoff from the plate's inner face and no nearer, and is the ring between the section's offsets", + leaned == [True] * 4, [leaned, R["readings"]]) + # A hipped box: walls that lean 45 and 20 degrees meet at its four corners. No Solidify: Blender's even thickness is not even where a + # vertex's faces meet at unequal angles (a wall of 0.06 here is 0.057 and 0.066 thick), and this check is of the rib, against a plate that is exact. + hip = mesh_object("Hip", [(sx * (0.6 + (z - 0.5) * math.tan(math.radians(45))), sy * (0.5 + (z - 0.5) * math.tan(math.radians(20))), z) for z in (0.3, 0.7) for sx, sy in ((1, -1), (1, 1), (-1, 1), (-1, -1))], + [(k, (k + 1) % 4, 4 + (k + 1) % 4, 4 + k) for k in range(4)], Matrix.Translation((15.0, 9.0, 0.0))) + receipt, report = send("brokkr_kitbash.ribs", object_name="Hip", ribs_name="HipRibs", planes=flat([0.5]), **SIZES) + ribs = bpy.data.objects.get("HipRibs") + wide, deep = (0.6 - STANDOFF * math.hypot(1.0, math.tan(math.radians(lean))) - THICKNESS / 2 * math.tan(math.radians(lean)) for lean in (45, 20)) # the rib's outer edge, from the middle + ring = 4.0 * (wide * (deep - 0.1) - (wide - DEPTH) * (deep - 0.1 - DEPTH)) * THICKNESS + check("where walls that lean 45 and 20 degrees meet, the rib stands the standoff off each wall right into the corner: its edges are each wall's own, met in a mitre (mutant V1 runs one wall's edge into the other's standoff)", + receipt["status"] == "accepted" and (report["ribs"], report["thickness"], report["nonManifoldEdges"]) == (1, 0.0, 0) and stood(hip, ribs) < STOOD + and reading("ring", abs(measure(ribs.data)["volume"] / ring - 1.0)) < RING, [receipt["message"], report, R["readings"]]) + turned = frustum("Turned", 0, (12.0, 9.0, 0.0)) + turned.modifiers["Solidify"].thickness = -0.06 # the plate grows outward of the designed surface + bpy.context.view_layer.update() + grown = max(math.hypot(v.co.x, v.co.y) for v in turned.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.vertices) + receipt, report = send("brokkr_kitbash.ribs", object_name="Turned", ribs_name="TurnedRibs", planes=flat([0.5]), **SIZES) + check("negative-solidify-thickness: a wall of -0.06 grows outward, and the rib stands the standoff inside the designed surface, the plate's inner face", + receipt["status"] == "accepted" and grown > 0.65 and report["thickness"] == 0.06 and stood(turned, bpy.data.objects["TurnedRibs"]) < STOOD, [receipt["message"], report, grown, R["readings"]]) + turn, facet, run = math.radians(49.4), 0.062, 0.3 # tests/test_kitbash.py test_a_band_follows_a_crease_tighter_than_it_reaches: the same section, in x and z + profile = [(-facet / 2 - run * math.cos(turn), -run * math.sin(turn)), (-facet / 2, 0.0), (facet / 2, 0.0), (facet / 2 + run * math.cos(turn), -run * math.sin(turn))] + creased = mesh_object("Creased", [(x, y, z) for y in (-0.3, 0.3) for x, z in profile], [(k, k + 1, k + 5, k + 4) for k in range(3)], Matrix.Translation((0.0, 12.0, 0.0)), wall=0.06) + CREASE = {"object_name": "Creased", "planes": json.dumps([{"origin": [0.0, 0.0, 0.0], "normal": [0.0, 1.0, 0.0]}]), "standoff": 0.03, "depth": 0.08, "thickness": THICKNESS} + receipt, report = send("brokkr_kitbash.ribs", ribs_name="CreaseRibs", **CREASE) + ribs = bpy.data.objects.get("CreaseRibs") + near, far, apex = 0.06 + 0.03, 0.06 + 0.03 + 0.08, facet / 2 / math.cos(turn) + area = 2.0 * ((run + apex) * (far - near) - math.tan(turn) * (far ** 2 - near ** 2) / 2.0) + V = points(ribs) if ribs is not None else np.zeros((1, 3)) + off = core.away(V * (1.0, 0.0, 1.0), [(x, 0.0, z) for x, z in profile], False) + check("ribs-fold-at-crease: behind a crease of 49.4 degrees either side of a facet of 0.062 a rib of standoff 0.03 and depth 0.08 is made, clipped: one closed shell the area of the true offset, no vertex nearer the section than the rib starts or further than it reaches", + receipt["status"] == "accepted" and child_of(ribs, creased) and (report["ribs"], report["nonManifoldEdges"], report["sections"][0]["pieces"]) == (1, 0, 1) + and reading("creased", abs(measure(ribs.data)["volume"] / THICKNESS / area - 1.0)) < CREASED and stood(creased, ribs, 0.03) < STOOD + and float(off.min()) > near - 1e-6 and float(off.max()) < far + 1e-6, [receipt["message"], report, off.min(), off.max(), R["readings"]]) + receipt, report = send("brokkr_kitbash.ribs", ribs_name="CreaseFrame", **CREASE, holes=0.1, posts=0.05) + check("the creased rib takes holes along its clipped centre line, cut clean, and posts", receipt["status"] == "accepted" and (report["holes"], report["posts"], report["nonManifoldEdges"]) == (3, 11, 0), + [receipt["message"], report]) # the centre line is 0.3 + 0.048 - 0.13 tan 49.4 = 0.196 a run: 0.39 holds three holes 0.1 apart; the section, 0.662, thirteen post stations, one each side of the facet clipped + angle = mesh_object("Angle", [(x, y, z) for y in (-0.3, 0.3) for x, z in ((-0.4, 0.0), (0.0, 0.0), (0.0, -0.4))], [(0, 1, 4, 3), (1, 2, 5, 4)], Matrix.Translation((3.0, 12.0, 0.0)), wall=0.05) + receipt, report = send("brokkr_kitbash.ribs", object_name="Angle", ribs_name="AngleRibs", planes=CREASE["planes"], **SIZES, posts=0.05) + check("inside a right angle no post stands nearer the corner than the rib's outer edge is set back, 0.09: twelve of the sixteen stations (mutant P1 posts all sixteen, four through the other wall)", + receipt["status"] == "accepted" and (report["ribs"], report["posts"], report["nonManifoldEdges"]) == (1, 12, 0) and abs(report["sections"][0]["length"] - 0.8) < 1e-6, [receipt["message"], report]) + + # --- plate-window-unpinned: how deep the ray that asks "is the plate here" looks --------------------------------------------------- + section("the-plate-window") + sunk = mesh_object("Sunk", [(-0.5, -0.2, 0.0), (0.5, -0.2, 0.0), (0.5, 0.2, 0.0), (-0.5, 0.2, 0.0)], [(0, 1, 2, 3)], Matrix.Translation((0.0, 15.0, 0.0)), wall=0.05) + send("brokkr_kitbash.cut_many", object_name="Sunk", cuts=json.dumps([{"name": "Deep", "part": "box", "params": "width=0.15; height=0.15; depth=0.04", "origin": [0.0, 0.0, 2.0], + "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]}])) + receipt, report = send("brokkr_kitbash.ribs", object_name="Sunk", ribs_name="SunkRibs", planes=json.dumps([{"origin": [0.0, 0.0, 0.0], "normal": [0.0, 1.0, 0.0]}]), **SIZES) + check("a recess 0.8 of the plate deep is plate: the rib runs on under it (the ray looks 1.25 of the plate deep; mutant N5 looks 0.5)", + receipt["status"] == "accepted" and [(s["pieces"], s["open"]) for s in report["sections"]] == [(1, 0.0)] and abs(report["sections"][0]["length"] - 1.0) < 1e-6, [receipt["message"], report]) + tube = [(0.09 * math.cos(a), 0.09 * math.sin(a), z) for z in (0.0, 0.6) for a in (2 * math.pi * (k + 0.5) / 16 for k in range(16))] + narrow = mesh_object("Narrow", tube, [(k, (k + 1) % 16, 16 + (k + 1) % 16, 16 + k) for k in range(16)], Matrix.Translation((3.0, 15.0, 0.0)), wall=0.04) + send("brokkr_kitbash.cut_many", object_name="Narrow", cuts=json.dumps([{"name": "Slot", "part": "box", "params": "width=0.06; height=0.2; depth=0.07", "origin": [2.0, 0.0, 0.3], "direction": [-1.0, 0.0, 0.0]}])) + receipt, report = send("brokkr_kitbash.ribs", object_name="Narrow", ribs_name="NarrowRibs", planes=flat([0.3]), standoff=0.005, depth=0.015, thickness=THICKNESS) + check("a port in a narrow cage is open though the far wall stands 3.5 plates behind it: the rib stops either side (mutant N13 looks 5 plates deep and finds the far wall)", + receipt["status"] == "accepted" and [(s["chains"], s["pieces"]) for s in report["sections"]] == [(1, 1)] and 0.06 < report["sections"][0]["open"] < 0.06 + 4 * 0.02 + 2 * 0.01, + [receipt["message"], report]) + # --- ribs-stop-at-ports: a flat deck with a port, a panel break and a recess along one section ---------------------------------- section("ribs-stop-at-ports") deck = mesh_object("Deck", [(-0.8, -0.5, 0.0), (0.8, -0.5, 0.0), (0.8, 0.5, 0.0), (-0.8, 0.5, 0.0)], [(0, 1, 2, 3)], Matrix.Translation((0.0, 5.0, 0.0)) @ Matrix.Rotation(0.4, 4, "Y"), wall=0.05) @@ -365,7 +468,11 @@ try: refused("a plane with no normal", {**POD, "planes": json.dumps([{"origin": [0.0, 0.0, 0.5]}])}, "planes[0] must be an object of origin and normal, each three numbers") refused("a plane whose normal has no length", {**POD, "planes": json.dumps([{"origin": [0.0, 0.0, 0.5], "normal": [0.0, 0.0, 0.0]}])}, "planes[0].normal has no direction") refused("17 longerons", {**POD, "longerons": json.dumps([BEAMS[0]] * 17)}, "longerons must be a JSON array of 0 to 16 objects") - refused("a fold: ribs deeper than the pod's top turns", {**POD, "planes": flat([0.5, 1.5]), "standoff": 0.15, "depth": 0.3}, "the section folds there: the path turns tighter than the outline reaches") + refused("ribs deeper than the pod is wide", {**POD, "planes": flat([0.5, 1.5]), "standoff": 0.15, "depth": 0.3}, "the section leaves a rib no room: it turns or closes in tighter than the rib reaches: lower standoff or depth") + precise = json.dumps([{"origin": [0.012345678901234567, -0.012345678901234567, 0.3 + 0.012345678901234567 * k], "normal": [1.2345678901234567e-05, -1.2345678901234567e-05, 0.99999999987654321]} for k in range(64)]) + receipt, report = send("brokkr_kitbash.ribs", **{**POD, "ribs_name": "Sixtyfour", "planes": precise}) + check("planes-string-cap-below-64: 64 planes written at full precision, over 9000 characters, are taken", len(precise) > 9000 and receipt["status"] == "accepted" and len(report["sections"]) == 64, + [len(precise), receipt["message"]]) refused("a cage that is not a mesh", {**POD, "object_name": "Nothing"}, "No mesh object named 'Nothing'") refused("a section too long for its step", {**POD, "planes": flat([0.3 + 0.01 * k for k in range(64)]), "step": 0.002}, "The sections are over 20000 points at step 0.002") pod.scale = (1.0, 1.0, 1.01) @@ -382,7 +489,7 @@ try: bpy.context.view_layer.update() refused("a cage with two Solidifies", {"object_name": "Crate", "ribs_name": "New", "planes": GRID, **SIZES}, "'Crate' has 2 Solidify modifiers (Solidify, Second)") crate.modifiers.remove(extra) - check("every refusal left the cages' modifiers shown", all(m.show_viewport for o in (pod, deck, legs, crate, dish) for m in o.modifiers), None) + check("every refusal left the cages' modifiers shown", all(m.show_viewport for o in (pod, deck, legs, crate, dish, hip, creased, angle, sunk, narrow) for m in o.modifiers), None) except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:]) finally: diff --git a/surfaces/blender/tests/live/kitbash_ribs.result.json b/surfaces/blender/tests/live/kitbash_ribs.result.json index ad6e146..c9d7f01 100644 --- a/surfaces/blender/tests/live/kitbash_ribs.result.json +++ b/surfaces/blender/tests/live/kitbash_ribs.result.json @@ -17,7 +17,47 @@ "detail": null }, { - "name": "ribs-fit-the-plate: every rib vertex stands the standoff, or the standoff and the depth, behind the plate's inner face along its plane, in its plane, on the side the normals face away from", + "name": "ribs-fit-the-plate: at every point of a rib's outer edge the nearer vertex stands the standoff behind the plate's inner face, along the plate's normal; every vertex in its plane, on the side the normals face away from", + "ok": true, + "detail": null + }, + { + "name": "standoff-oblique-sections: on cones whose wall leans 0, 30, 45 and 60 degrees out of the rib's plane the rib comes the standoff from the plate's inner face and no nearer, and is the ring between the section's offsets", + "ok": true, + "detail": null + }, + { + "name": "where walls that lean 45 and 20 degrees meet, the rib stands the standoff off each wall right into the corner: its edges are each wall's own, met in a mitre (mutant V1 runs one wall's edge into the other's standoff)", + "ok": true, + "detail": null + }, + { + "name": "negative-solidify-thickness: a wall of -0.06 grows outward, and the rib stands the standoff inside the designed surface, the plate's inner face", + "ok": true, + "detail": null + }, + { + "name": "ribs-fold-at-crease: behind a crease of 49.4 degrees either side of a facet of 0.062 a rib of standoff 0.03 and depth 0.08 is made, clipped: one closed shell the area of the true offset, no vertex nearer the section than the rib starts or further than it reaches", + "ok": true, + "detail": null + }, + { + "name": "the creased rib takes holes along its clipped centre line, cut clean, and posts", + "ok": true, + "detail": null + }, + { + "name": "inside a right angle no post stands nearer the corner than the rib's outer edge is set back, 0.09: twelve of the sixteen stations (mutant P1 posts all sixteen, four through the other wall)", + "ok": true, + "detail": null + }, + { + "name": "a recess 0.8 of the plate deep is plate: the rib runs on under it (the ray looks 1.25 of the plate deep; mutant N5 looks 0.5)", + "ok": true, + "detail": null + }, + { + "name": "a port in a narrow cage is open though the far wall stands 3.5 plates behind it: the rib stops either side (mutant N13 looks 5 plates deep and finds the far wall)", "ok": true, "detail": null }, @@ -127,7 +167,12 @@ "detail": null }, { - "name": "refused, scene unchanged: a fold: ribs deeper than the pod's top turns", + "name": "refused, scene unchanged: ribs deeper than the pod is wide", + "ok": true, + "detail": null + }, + { + "name": "planes-string-cap-below-64: 64 planes written at full precision, over 9000 characters, are taken", "ok": true, "detail": null }, @@ -165,10 +210,13 @@ "hostErrors": [], "readings": { "cleared": 0.031, - "fit": 0.0052, + "creased": 0.0013, + "fit": 0.0011, "holed": 2.7e-08, "planar": 1.4e-07, - "stationed": 5.2e-07 + "ring": 2.1e-06, + "stationed": 5.2e-07, + "stood": 5.3e-08 }, "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 675748f..b1609eb 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1166,7 +1166,7 @@ class PoseTests(unittest.TestCase): @unittest.skipIf(np is None, "numpy is not installed") class StructureTests(unittest.TestCase): - """core's sweep, crossings, resample and spans: what brokkr_kitbash.ribs builds a frame from. Every reading is + """core's sweep, band, crossings, resample and spans: what brokkr_kitbash.ribs builds a frame from. Every reading is exact arithmetic, so each assertion is the built value and names the mutant it kills.""" SQUARE = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0)] BENT = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.7, 0.0), (0.2, 1.4, 0.0)] @@ -1298,22 +1298,92 @@ class StructureTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, "resample"): core.resample(*bad) - def test_a_frame_is_swept_corner_to_corner(self): - """cornered keeps the points where a section turns and an open one's ends: an end is left out when the corner - beside it is nearer than that corner's mitre sets the frame's inside back.""" - el = [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.25, 0.0), (1.0, 0.5, 0.0)] # a right angle at index 2: its mitre sets back the reach itself - self.assertEqual(core.cornered(el, False, 0.25).tolist(), [0, 2, 4]) - self.assertEqual(core.cornered(el, False, 0.5).tolist(), [0, 2]) # the far end stands 0.5 from the corner: not beyond a set-back of 0.5 - self.assertEqual(core.cornered(el, False, 1.0).tolist(), []) # nor does the near one, and one point is no frame - self.assertEqual(core.cornered(el[:3], False, 9.0).tolist(), [0, 2]) # no corner: both ends, whatever the reach - shallow = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0 + math.cos(0.2), math.sin(0.2), 0.0)] # a turn of 0.2 rad sets back reach * tan(0.1) - self.assertEqual(core.cornered(shallow, False, 9.9).tolist(), [0, 1, 2]) - self.assertEqual(core.cornered(shallow, False, 10.0).tolist(), []) # both ends within 10 * tan(0.1) = 1.003: one point is left, and is no frame + def test_away_is_the_least_distance_to_a_polyline(self): + el = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0)] + self.assertEqual(core.away([(0.5, 0.25, 0.0), (2.0, 0.0, 0.0), (-3.0, 4.0, 0.0), (0.5, 0.5, 0.0)], el, False).tolist(), [0.25, 1.0, 5.0, 0.5]) + self.assertAlmostEqual(float(core.away((0.5, 0.75, 0.0), el, True)[0]), 0.25 / math.sqrt(2.0), places=15) # closed, the segment back to the start is nearest + turns = np.linspace(0.0, 6.0 * math.pi, 400) # a spiral of 399 segments, seven blocks of them, and points all over it: a limit changes no value under it + spiral = np.stack([turns * np.cos(turns), turns * np.sin(turns), np.zeros(400)], axis=1) + spots = np.random.default_rng(7).uniform(-20.0, 20.0, (500, 3)) * (1.0, 1.0, 0.0) + lengths = np.linspace(0.0, 2.0, 399) + for closed, less in ((False, 0.0), (True, 0.0), (False, lengths), (True, np.linspace(0.0, 2.0, 400))): + every = core.away(spots, spiral, closed, less) + for limit in (0.0, 1.5): + self.assertEqual(core.away(spots, spiral, closed, less, limit).tolist(), np.minimum(every, limit).tolist()) # mutant A1 (a block's own segments only) reads the limit where another turn is nearer + self.assertTrue((every < 0.0).any() or less is 0.0) + self.assertTrue((every > 1.5).any()) + + def test_a_band_stands_beside_a_polyline_on_the_side_it_is_told(self): + """band on a straight run and on a square: the built values. A straight run is built at its two ends only; the + side comes from `inward`, whichever way the polyline runs; inside a square the far edge is clipped to the + smaller square (the points within a set-back of a corner are left out) and the volume is the ring's.""" + line, up = [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0)], (0.0, 0.0, 1.0) + for path in (line, line[::-1]): + for side in (1.0, -1.0): + made = core.band(path, False, up, [(0.0, side, 0.0)] * 3, 0.1, 0.2, 0.05) + self.assertTrue(closed_and_oriented(made.shell)) + self.assertAlmostEqual(signed_volume(made.shell), 1.0 * 0.2 * 0.05, places=15) + self.assertEqual((made.at.tolist(), len(made.shell.V), len(made.shell.counts)), ([0, 2], 8, 6)) + self.assertEqual(sorted(made.outer[:, 1].tolist() + made.centre[:, 1].tolist() + made.inner[:, 1].tolist()), sorted([0.1 * side, 0.2 * side, side * (0.1 + 0.2)] * 2)) + self.assertEqual(sorted(set(np.round(made.shell.V[:, 2], 12).tolist())), [-0.025, 0.025]) square = core.resample(self.SQUARE, True, 0.25) - self.assertEqual(core.cornered(square, True, 0.1).tolist(), [0, 4, 8, 12]) - round_ = [(math.cos(a), math.sin(a), 0.0) for a in np.linspace(0.0, 2.0 * math.pi, 12, endpoint=False)] - self.assertEqual(core.cornered(round_, True, 0.1).tolist(), list(range(12))) - self.assertEqual(core.cornered(core.resample(self.SQUARE[:2] + [(0.5, 1e-13, 0.0)], True, 0.25), True, 0.1).tolist()[:1], [0]) + middle = np.array([0.5, 0.5, 0.0]) + for path in (square, square[::-1]): + inside = core.band(path, True, up, middle - path, 0.1, 0.2, 0.05) + self.assertTrue(closed_and_oriented(inside.shell)) + self.assertAlmostEqual(signed_volume(inside.shell), (0.8 ** 2 - 0.4 ** 2) * 0.05, places=15) + self.assertEqual((len(inside.outer), len(inside.inner)), (16, 8)) # 0.25 from a corner the far edge, set back 0.3, is clipped; the near one, set back 0.1, is not + outside = core.band(path, True, up, path - middle, 0.1, 0.2, 0.05) + self.assertTrue(closed_and_oriented(outside.shell)) + self.assertAlmostEqual(signed_volume(outside.shell), (1.6 ** 2 - 1.2 ** 2) * 0.05, places=14) + self.assertEqual((len(outside.outer), len(outside.inner)), (4, 4)) + el = core.resample([(-1.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, -1.0, 0.0)], False, 0.05) # a distance for each segment: 0.1 along x, 0.3 along y, inside the right angle + two = core.band(el, False, up, [(-1.0, -1.0, 0.0)] * len(el), [0.1] * 20 + [0.3] * 20, 0.2, 0.05) + self.assertTrue(closed_and_oriented(two.shell)) + self.assertAlmostEqual(signed_volume(two.shell), (0.2 * (0.7 + 0.5) / 2.0 + 0.2 * (0.9 + 0.7) / 2.0) * 0.05, places=15) # each edge's corner stands each leg's own distance off it + self.assertIn([-0.3, -0.1, 0.0], two.outer.round(12).tolist()) + self.assertIn([-0.5, -0.3, 0.0], two.inner.round(12).tolist()) + for edge, length in ((two.outer, 0.7 + 0.9), (two.centre, 0.6 + 0.8), (two.inner, 0.5 + 0.7)): + # an edge runs once along each leg: mutant L1 (the corner the greater distance off both legs) runs 0.2 past the corner and back, mutant V1 + # (clipped at a point's own distance) runs the first leg's edge on to 0.1 from the second; mutant W1 (no weld) has the corner twice + self.assertAlmostEqual(float(np.linalg.norm(np.diff(edge, axis=0), axis=1).sum()), length, places=12) + self.assertGreater(float(np.linalg.norm(np.diff(edge, axis=0), axis=1).min()), 1e-9) + self.assertEqual(core.away([(-0.3, -0.1, 0.0), (-0.3, -0.3, 0.0)], [(-1.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, -1.0, 0.0)], False, [0.1, 0.3]).round(12).tolist(), [0.0, 0.0]) + with self.assertRaisesRegex(core.KitError, "path point 0: the section leaves a rib no room"): + core.band(square, True, up, middle - square, 0.1, 0.45, 0.05) # 0.55 in from a square 1 wide: nothing is that far from its sides + with self.assertRaisesRegex(core.KitError, "path point 1: the path turns 160.0 degrees there, over 150"): + core.band([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0 - math.cos(math.radians(20.0)), math.sin(math.radians(20.0)), 0.0)], False, up, [(0.0, 1.0, 0.0)] * 3, 0.1, 0.2, 0.05) + with self.assertRaisesRegex(core.KitError, "path point 0: the segment from it is shorter than 1e-9"): + core.band([line[0], line[0], line[2]], False, up, [(0.0, 1.0, 0.0)] * 3, 0.1, 0.2, 0.05) + for bad in ((line[:1], False), (line[:2], True)): + with self.assertRaisesRegex(core.KitError, "a band needs"): + core.band(bad[0], bad[1], up, [(0.0, 1.0, 0.0)] * len(bad[0]), 0.1, 0.2, 0.05) + + # What a band inside a crease holds, over the area of the true clipped offset, less 1. Bound by + # lodur:ruling:deterministic-bound-margin: shipped 0.0013 (each clipped corner is cut by a chord between points + # 0.01 apart); least claimed mutant 0.079 (C1, nothing clipped: both edges fold through the crease); separation 7.9. + CREASED = 0.0099 + + def test_a_band_follows_a_crease_tighter_than_it_reaches(self): + """ribs-fold-at-crease. Two runs of 0.3 that turn 49.4 degrees at each end of a facet of 0.062, as a creased + shell's section does, and a rib from 0.09 to 0.17 inside the turn: both of the facet's offsets are gone (each + end sets them back 0.041 and 0.078), so each edge is the two runs' offsets, met at one corner. No vertex + stands nearer the section than 0.09 or further than 0.17. Mutant C1 reads 0.079 and stands 0.07 off.""" + turn, facet, run, near, far = math.radians(49.4), 0.062, 0.3, 0.09, 0.17 + section = [(-facet / 2 - run * math.cos(turn), -run * math.sin(turn), 0.0), (-facet / 2, 0.0, 0.0), (facet / 2, 0.0, 0.0), (facet / 2 + run * math.cos(turn), -run * math.sin(turn), 0.0)] + dense = core.resample(section, False, 0.01) + made = core.band(dense, False, (0.0, 0.0, 1.0), [(0.0, -1.0, 0.0)] * len(dense), near, far - near, 0.014) + self.assertTrue(closed_and_oriented(made.shell)) + apex = facet / 2 / math.cos(turn) # from each end of the facet to where the two runs' lines meet + area = 2.0 * ((run + apex) * (far - near) - math.tan(turn) * (far ** 2 - near ** 2) / 2.0) + self.assertLess(abs(signed_volume(made.shell) / 0.014 / area - 1.0), self.CREASED) + off = core.away(made.shell.V * (1.0, 1.0, 0.0), section, False) + self.assertGreaterEqual(float(off.min()), near - 1e-15) + self.assertLessEqual(float(off.max()), far + 1e-15) + self.assertEqual((len(made.outer), len(made.centre), len(made.inner)), (12, 8, 4)) # the far edge: an end, the last point before the corner, the first after, an end; the centre line and the near edge also where the edges further in start and stop being clipped + middle = core.away(made.centre, section, False) + self.assertAlmostEqual(float(middle.min()), (near + far) / 2.0, places=15) # the centre line stands half a depth off both edges, so a hole of radius 0.3 of depth on it stays in the rib + self.assertAlmostEqual(float(middle.max()), (near + far) / 2.0, places=15) def test_spans_bridge_a_break_and_stand_clear_of_a_port(self): """spans. Twenty points 0.25 apart, a bridge of 1.25 and a clearance of 0.5. Mutants K5 (bridge ignored: the two-point break splits the run) and K6 @@ -1419,6 +1489,20 @@ class HostFileTests(unittest.TestCase): for row in self.document["actions"][4:]: self.assertTrue(all(field["type"] in ("string", "number") for field in row["fields"]), row["name"]) + def test_the_ribs_row_takes_64_planes_and_16_longerons_at_full_precision(self): + """planes-string-cap-below-64. A float's longest repr is 24 characters (-1.2345678901234567e-05): 64 planes of + them are 11.3 KB and 16 longerons 4.2 KB, each under its cap; the 65th and 17th are the action's to refuse.""" + host = [{**row, "host": "brokkr_kitbash"} for row in self.document["actions"]] + long = [-1.2345678901234567e-05] * 3 + planes, longerons = json.dumps([{"origin": long, "normal": long}] * 64), json.dumps([{"origin": long, "axis": long, "toward": long}] * 16) + self.assertEqual((len(planes), len(longerons)), (11264, 4176)) + intent = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver", "action": "brokkr_kitbash.ribs", "object_name": "Pod", + "ribs_name": "Ribs", "planes": planes, "longerons": longerons} + self.assertEqual(at.validate(intent, host)["planes"], planes) + for field, cap in (("planes", 16000), ("longerons", 8000)): + with self.assertRaisesRegex(Exception, f"{field} must have at most {cap} characters"): + at.validate({**intent, field: "[" + " " * cap}, host) + def test_the_pose_rows_take_scalars_inside_their_bounds(self): host = [{**row, "host": "brokkr_kitbash"} for row in self.document["actions"]] envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver", "object_name": "Strut"} From 585ece4e4d35f09a4f721f24c0ffeb1a395f1525 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 08:47:12 +0100 Subject: [PATCH 095/223] docs/kitbash.md: ribs as built in h2, and what a ribs call costs and why The standoff along the plate's normal, the band and its clipping at a crease, the plate window, a negative Solidify, and that Solidify's even thickness is not even where faces meet at unequal angles. reeval-per-call: one whole evaluation of the cage a call stays. Measured on the pod: hiding the shell modifiers tags the cage (1.36 s); a temporary copy without them links and evaluates in 0.001 s, but deleting any datablock makes Blender 5.3 evaluate the cage again (1.44 to 1.54 s), and the hole cut's temporaries must be deleted. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 47 +++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 13 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 54b2817..404579a 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -376,7 +376,10 @@ all the same, and is cut. takes planes in the cage's own frame and makes, as one mesh object under the cage: - a rib along each plane's section of the cage's surface: `thickness` across the plane, set `standoff` behind - the plate's inner face and reaching `depth` further in; + the plate's inner face and reaching `depth` further in. `standoff` is measured along the plate's own normal: + where the plate leans out of the rib's plane, the rib is set further back along the plane (the plate's + thickness and the standoff over the cosine of the lean, and what half the rib's thickness needs on the side the + plate leans over), so that no part of the rib comes nearer the inner face than `standoff`; - lightening holes through each rib every `holes` of its length (radius 0.3 of `depth`; 0 for none); - posts every `posts` that stand the plate off the rib: a rod from the middle of the plate into the rib, and a pad on the plate's inner face (0 for none); @@ -385,25 +388,35 @@ takes planes in the cage's own frame and makes, as one mesh object under the cag longeron runs through the stations in the planes' order and 0.12 of the end gaps past the end ribs, a section `longeron` (`I`, `C`, `T`, `L` or `box`; `longeron_w`, `longeron_h`, `longeron_t`) with its up toward the plate. -Ribs, posts and longerons are one sweep of an outline along a path with mitred corners (`core.sweep`). +A rib is a band beside its section (`core.band`): the section offset twice in its plane, with mitred corners, +and clipped as a polygon offset is. Inside a turn tighter than the rib reaches (the corner of a creased shell, a +facet shorter than its two corners set the rib back) the rib's edges cut the corner and the rib follows the +crease; the cut is a chord between points `step` apart, so it leaves out less than a `step` of the true corner. +Lightening holes stand on the band's centre line, clipped the same way, so a hole (0.3 of `depth`) keeps 0.2 of +`depth` of web on both sides; a post that would end outside the rib inside such a turn is left out. Posts and +longerons are a sweep of an outline along a path with mitred corners (`core.sweep`). The cage is read twice. Evaluated with its Solidify, Bevel and Boolean modifiers off it is the surface as designed: each plane cuts that surface into sections, and a section may be several chains (two legs in one cage). Evaluated whole it is the plate as it is cut: at points `step` apart along a section, a ray from just outside the -plate's outer face asks whether the plate is there. Where it is not, the plate is open. An opening shorter than +plate's outer face asks whether the plate is there, looking 1.25 of the plate's thickness deep: a recess +shallower than the plate is plate, and the far wall of a narrow cage is not. Where it is not, the plate is open. An opening shorter than `bridge` along the section is a panel break, and the rib runs behind it; at any other the rib stops `clearance` short, and no post or hole stands there. A recess that does not go through is plate. `ribs` reads no cutter: cut the cage first, in any way, and the ribs follow what the plate became. The plate's thickness and which way it grows are read from the cage's one Solidify (a cage with none has a plate -of no thickness; one with two is refused). Inward is the side the cage's normals face away from, not a guess from +of no thickness; one with two is refused; a negative thickness is the same plate grown to the other side of the +surface, and is read so). The plate is taken to be that thick along its normal everywhere. Solidify's even +thickness is not, where a vertex's faces meet at unequal angles: a wall of 0.06 on a box whose sides lean 45 and +20 degrees is 0.057 and 0.066 thick, and the standoff there is off by as much. Inward is the side the cage's normals face away from, not a guess from the section's shape: a cage whose normals change sides along a section is refused, and one whose normals all -face inward gets its frame outside. A rib is swept through the section's own corners, so its faces lie the -standoff from the cage's facets, and an end that would fold over the corner beside it ends at that corner. +face inward gets its frame outside. A rib is built at the section's own corners, so its faces lie along the +cage's facets, and it does not depend on which way round the section was followed. Everything is checked before the ribs object is written, and a refusal names the plane or longeron: a plane that -misses the cage or lies along its surface; a section that turns tighter than the rib reaches in, so that the rib -would fold (lower `standoff` or `depth`); a longeron that meets a plane's ribs twice, not at all, or in an opening; +misses the cage or lies along its surface; a section that leaves a rib no room, closing in on itself nearer than +the rib reaches everywhere (lower `standoff` or `depth`); a longeron that meets a plane's ribs twice, not at all, or in an opening; holes that overlap or leave the rib; a cage that is scaled or that Blender does not evaluate; more than 64 planes or 16 longerons. @@ -415,10 +428,18 @@ the holes' own. Manifold is used here and nowhere else because these shells are live Booleans stay Exact. On a pod (2560 faces subdivided, a wall of 0.06, a port, a panel break and a recess; one whole evaluation -1.35 s), five ribs with 93 holes, 51 posts and four longerons took 1.60 s and the five ribs alone -1.44 s, medians of 3 interleaved with that evaluation (Blender 5.3 on Starfire). Each figure holds one whole -evaluation of the cage, which Blender makes after any action that touched it (`ribs` shows the cage's modifiers -again when it is done); the rest, 0.25 s and 0.09 s, is the action's own work. +1.36 s), five ribs with 91 holes, 51 posts and four longerons took 1.70 s and the five ribs alone +1.51 s, medians of 3 interleaved with that evaluation (Blender 5.3 on Starfire). The hole cut is the Manifold +Boolean: 0.017 s a call for those holes against 0.44 s with Exact, 26 times. + +Each call costs one whole evaluation of the cage, which scales with the cage's Exact Booleans: the action's own +work is the rest, 0.34 s and 0.15 s here. No cheaper route was found in Blender 5.3. The designed surface is read by hiding the cage's +Solidify, Bevel and Boolean modifiers for the call, which tags the cage, and Blender evaluates it whole again +afterwards. Reading the surface from a temporary copy without those modifiers costs 0.001 s to link and +evaluate, but deleting the copy costs the same whole evaluation (1.44 to 1.54 s on the pod against 1.45 to +1.52 s forced): Blender 5.3 evaluates the cage again after any datablock is deleted, a bare unlinked object +included, and the hole cut's temporary objects must be deleted too. So a hull with twenty cutters pays their +evaluation once for every `ribs` call; iterate planes on the cage before it is cut, or with its Booleans off. ## Expressions @@ -452,7 +473,7 @@ vertices overflow. | `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | -| `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | +| `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored value (`set_params`). A value outside its bounds is refused with the bounds in the message. From c4717c92930f4076ab766a11cf0bc34afaa6e3d3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 10:29:17 +0100 Subject: [PATCH 096/223] brokkr_kitbash.ribs: the rib's edge cut from the inner face offset inward, the plate's faces read from its Solidify, posts kept under the outer face The standoff held only where the plate's lean was constant across the rib's reach: laid off along the plane from each segment's own lean, it fell short under a tilted plane (0.007 of 0.04 on a 24-sided prism) and on a doubly curved wall (0.020 on a sphere), and at radius 0.6 with a standoff of 0.01 the rib stood through the inner face (finding cut-kit-ribs.s2.standoff-curved-and-tilted). - core.inset: the step that takes each vertex of a mesh behind every face it is a corner of, the mitre of its faces moved in. ribs offsets the plate's inner face by the standoff with it. - A rib's outer edge is where its plane cuts that offset surface: points along the section look square in for it, corners go where the offset faces meet, and points that measure nearer the plate than the standoff (the offset surface folded) are left out. core.band then lays off only the rib's half thickness and its depth. - The finished edge is measured against the inner face and moved in until no vertex is nearer than the standoff; a rib that cannot be stood off is refused. - The plate's two faces are read from the Solidify as Blender evaluates it, so a Solidify that is not even (Blender's default) gives the plate it makes, 0.0424 beside a right angle for 0.06 (finding solidify-default-unbounded). A Solidify whose faces cannot be read is refused. - A post starts inside the plate, deeper where it leans, and its pad lies flat on the inner face. - tests/live/kitbash_ribs.py: a tilted plane through a prism, spheres of radius 1 and 0.6 at 60 degrees, a box with the default Solidify, posts under the outer face, a shallow rib in a crease; bounds by lodur:ruling:deterministic-bound-margin, RING now set from L1 (finding ring-bound-misses-l1). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 153 +++++++++++++++--- .../brokkr_kitbash/brokkr_actions.json | 2 +- surfaces/blender/brokkr_kitbash/core.py | 36 ++++- surfaces/blender/tests/live/kitbash_ribs.py | 121 +++++++++++--- .../tests/live/kitbash_ribs.result.json | 47 +++++- surfaces/blender/tests/test_kitbash.py | 24 ++- 6 files changed, 338 insertions(+), 45 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 26465a7..22b2c3d 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -895,6 +895,10 @@ SHELL_MODIFIERS = ("SOLIDIFY", "BEVEL", "BOOLEAN") # what makes a designed surf LIFT = 0.01 # metres outside the plate's outer face that the ray asking "is the plate here" starts NUDGE = 1e-4 # metres along the section that ray is moved off its point: a section's corners lie on the cage's edges, and a ray along an edge can slip between two faces HOLE_SEGMENTS, POST_SEGMENTS, PAD_SEGMENTS = 16, 8, 12 +STANDOFF_CLIP = 1e-6 # of the standoff: a point of the offset surface that stands this much nearer the plate than the standoff is where the surface folded, and is left out +STANDOFF_HELD = 1e-7 # metres inside the standoff that a rib's edge may measure and hold it: what a float32 tree's distances are good to +STANDOFF_ROUNDS = 8 # times a rib's edge is measured against the plate and moved in by what it is short +POST_SUNK = 0.5 # of the plate's thickness: how far under the outer face a post starts # What a plane's lightening holes removed from its webs, over the holes' faceted area times the rib's thickness, less 1. # Bound by lodur:ruling:deterministic-bound-margin: shipped worst 2.9e-06 (tests/live/kitbash_ribs.py: thirteen planes # on a pod, a deck and an egg-crate, float32 meshes); least claimed bad cut 0.0066 (holes of radius 0.018 pitched 0.02, @@ -948,7 +952,7 @@ def along(points, closed: bool, pitch: float): than a pitch), evenly round a closed one: [(point, segment index, fraction along the segment)].""" loop = np.vstack([points, points[:1]]) if closed else points reach = np.concatenate([[0.0], np.cumsum(np.linalg.norm(np.diff(loop, axis=0), axis=1))]) - count = int(reach[-1] / pitch + 1e-9) + count = int(reach[-1] / pitch + 1e-6) # a length that is a whole number of pitches but for a float32's rounding holds them all found = [] for at in (reach[-1] * np.arange(count) / max(count, 1) if closed else pitch / 2 + pitch * np.arange(count)): segment = min(int(np.searchsorted(reach, at, side="right")) - 1, len(loop) - 2) @@ -1025,6 +1029,34 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): surface.from_mesh(designed.to_mesh()) designed.to_mesh_clear() nearest = BVHTree.FromBMesh(surface) + at = np.array([v.co for v in surface.verts], dtype=np.float64).reshape(-1, 3) + polygons = [tuple(v.index for v in face.verts) for face in surface.faces] + inner_at = outer_at = at + if walls: # the plate's two faces as its Solidify makes them, whatever its thickness mode: a simple Solidify writes the surface's vertices twice, in the surface's order + walls[0].show_viewport = True + _, walled = evaluated_of(context, cage) + wall = walled.to_mesh() + both = np.zeros(3 * len(wall.vertices)) + wall.vertices.foreach_get("co", both) + walled.to_mesh_clear() + walls[0].show_viewport = False + if len(both) != 6 * len(at): + raise Refused(f"{cage.name!r}'s Solidify {walls[0].name!r} does not make the plate's two faces from the surface's own vertices ({len(both) // 3} vertices from {len(at)}): " + "ribs reads the plate from a simple Solidify with nothing after it but Bevel and Booleans; nothing changed.") + both = both.reshape(2, -1, 3).astype(np.float64) + out_of = [float(np.einsum("ij,ij->", face - at, np.array([v.normal for v in surface.verts]))) for face in both] # the inner face is the one further against the normals + inner_at, outer_at = (both[0], both[1]) if out_of[0] < out_of[1] else (both[1], both[0]) + skin = BVHTree.FromPolygons(inner_at.tolist(), polygons) # the plate's inner face: what the standoff is measured from + hide = BVHTree.FromPolygons(outer_at.tolist(), polygons) if self.posts > 0 else None # its outer face: what no post may stand through + # The inner face offset inward by the standoff, along its own faces' normals: a rib's outer edge is cut from this, so it + # stands the standoff off the plate at any tilt of its plane and any curvature of the wall. + offset = BVHTree.FromPolygons((inner_at + self.standoff * core.inset(inner_at, polygons)).tolist(), polygons) + clip = STANDOFF_CLIP * self.standoff + 1e-7 # and what a float32 tree's distances are good to + + def short(points) -> float: + """How far the nearest of some points comes inside the standoff: over 0, too near the plate.""" + return self.standoff - min(skin.find_nearest(Vector(point))[3] for point in points) + for index, plane in enumerate(planes): where, normal = f"planes[{index}]", plane["normal"] cut = surface.copy() @@ -1044,16 +1076,14 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): raise Refused(f"The sections are over {SAMPLES_LIMIT} points at step {self.step:.6g}: raise step, or give fewer planes; nothing changed.") P = core.resample(points, closed, self.step) between = ((P + np.roll(P, -1, axis=0)) / 2.0)[:len(P) if closed else len(P) - 1] # the middle of each segment: a point of one facet, where a corner is a point of two - out, facing = (np.array([nearest.find_nearest(Vector(p))[1] for p in at], dtype=np.float64) for at in (P, between)) + out, facing = (np.array([nearest.find_nearest(Vector(p))[1] for p in at_points], dtype=np.float64) for at_points in (P, between)) flat = out - normal * (out @ normal)[:, None] upright = np.sqrt(1.0 - np.minimum((facing @ normal) ** 2, 1.0)) # the cosine of how far the plate's normal leans out of the plane, a segment if not (np.linalg.norm(flat, axis=1) > 1e-3).all() or not (upright > 1e-3).all(): raise Refused(f"{where} lies along {cage.name!r}'s surface where it meets it: a rib needs a plane that crosses the plate; nothing changed.") - inward = -flat / np.linalg.norm(flat, axis=1)[:, None] - # The plate is `inner` thick and the rib stands `standoff` off it along the plate's own normal: along the plane, where - # the rib lies, both are longer by 1 / upright, and the rib's edge on the side the plate leans over is half a - # thickness nearer still. One distance for each segment of the section. - slope, back = 1.0 / upright, ((inner + self.standoff) + self.thickness / 2.0 * np.abs(facing @ normal)) / upright + inward = -flat / np.linalg.norm(flat, axis=1)[:, None] # square in from the plate, along the plane + beside = (lambda of: np.maximum(of, np.roll(of, 1))) if closed else (lambda of: np.maximum(np.concatenate([of, of[-1:]]), np.concatenate([of[:1], of]))) # a point's greater of its two segments' + slope = beside(1.0 / upright) ahead = np.roll(P, -1, axis=0) - np.roll(P, 1, axis=0) if closed else np.gradient(P, axis=0) turn = np.cross(ahead, inward) @ normal # which side of the section its normals stand on: one sign all the way along if (turn > 0).any() and (turn < 0).any(): @@ -1061,17 +1091,83 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): "recalculate its normals so they all face out of the plate; nothing changed.") aside = np.roll(P, -1, axis=0) - P if closed else np.vstack([np.diff(P, axis=0), P[-2:-1] - P[-1:]]) # toward the next point; an open chain's last, toward the one before aside = aside / np.linalg.norm(aside, axis=1)[:, None] * NUDGE + # Where the offset surface stands behind each point of the section, square in along the plane: a point of the rib's + # edge. One that stands nearer the plate than the standoff landed where the offset surface has passed through itself, + # behind a corner of the section or inside a curve tighter than the standoff: it is left out. The rib's edge on + # the side the plate leans over is half a thickness nearer the plate than its middle, which the offset surface was + # cut at: along the plane that is `leaned`, from the lean of the offset face the point landed on. + edge, near, leaned, landed, steep = np.zeros_like(P), np.full(len(P), np.inf), np.zeros(len(P)), np.zeros_like(P), np.ones(len(P)) + for k, (p, n) in enumerate(zip(P, inward)): + for start in (p, p + aside[k]): # a ray along the offset surface's own rim can slip past it: an end of the section looks again from just inside + hit = offset.ray_cast(Vector(start - n * 1e-5), Vector(n), (plate + self.standoff) * (2.0 * slope[k] + 2.0) + 1e-3) + if hit[0] is not None: + break + if hit[0] is not None: + tilt = min(abs(float(np.array(hit[1]) @ normal)), 1.0 - 1e-6) + steep[k] = 1.0 / math.sqrt(1.0 - tilt * tilt) # along the plane, over along the normal, where the point landed: the offset surface leans more than the plate where the wall is round + edge[k], near[k], landed[k], leaned[k] = p + n * (hit[3] - 1e-5), short([hit[0]]), hit[1], self.thickness / 2.0 * tilt * steep[k] # the point itself moved along its way: the tree's own point is a float32 + + def met(a, b): + """The edge's corner between two of its points that landed on different faces of the offset surface: where + those faces' lines in the plane meet. None where they do not meet between the two points, or meet nearer + the plate than the standoff (faces either side of a fold).""" + ways = np.stack([np.cross(normal, landed[a]), -np.cross(normal, landed[b])], axis=1) + (s, t), _, rank, _ = np.linalg.lstsq(ways, edge[b] - edge[a], rcond=None) + corner, apart = edge[a] + s * ways[:, 0], edge[b] - edge[a] + if (rank == 2 and np.linalg.norm(corner - (edge[b] - t * ways[:, 1])) < 1e-6 and 0.0 < (corner - edge[a]) @ apart < apart @ apart + and np.linalg.norm(corner - edge[a]) < 4.0 * np.linalg.norm(apart) + self.step and short([corner]) <= clip): + return corner + return None + reach = LIFT + 1.25 * plate + 1e-4 opened = [whole.ray_cast(Vector(p + n * (outer + LIFT)), Vector(-n), reach)[0] is None for p, n in zip(P + aside, out)] lengths = np.linalg.norm(np.diff(np.vstack([P, P[:1]]) if closed else P, axis=0), axis=1) - row["lines"].append((P + inward * (np.resize(back, len(P)) + self.depth / 2.0)[:, None], closed)) # about where a rib would run: only asked whether a longeron crosses it + row["lines"].append((P + inward * ((inner + self.standoff) * slope + self.depth / 2.0)[:, None], closed)) # about where a rib would run: only asked whether a longeron crosses it for piece in core.spans(opened, lengths, closed, self.bridge, self.clearance): ring = closed and len(piece) == len(P) - try: - rib = core.band(P[piece], ring, normal, inward[piece], back[piece if ring else piece[:-1]], self.depth, self.thickness) - except core.KitError as error: - raise Refused(f"{where}: {error}: lower standoff or depth; nothing changed.") from None - row["ribs"].append({"band": rib, "ring": ring, "P": P[piece], "inward": inward[piece], "back": back[piece if ring else piece[:-1]], "slope": slope[piece if ring else piece[:-1]]}) + kept = piece[near[piece] <= clip] + if len(kept) < (3 if ring else 2): + raise Refused(f"{where}: the section leaves a rib no room: it turns or closes in tighter than the rib reaches: lower standoff or depth; nothing changed.") + node = lambda k: [edge[k], inward[k], steep[k], leaned[k], False, ahead[k]] # noqa: E731 a point of the edge: where, which way in, its slope, its lean, whether it is a corner, and the section's way there + nodes = [] + for k in range(len(kept) if ring else len(kept) - 1): + a, b = kept[k], kept[(k + 1) % len(kept)] + nodes.append(node(a)) + corner = met(a, b) if np.abs(landed[a] - landed[b]).max() > 1e-6 else None # the rays only sample the edge: its corners are the offset surface's own + if corner is not None: + nodes.append([corner, (inward[a] + inward[b]) / np.linalg.norm(inward[a] + inward[b]), max(steep[a], steep[b]), max(leaned[a], leaned[b]), True, ahead[a] + ahead[b]]) + if not ring: + nodes.append(node(kept[-1])) + run = nodes[:1] + onward = lambda u, v: (v[0] - u[0]) @ v[5] > 1e-5 * np.linalg.norm(v[5]) # noqa: E731 v stands on from u the way the section runs, by more than a hundredth of a millimetre + for here in nodes[1:]: # an edge that steps back against its section has folded there: the point that did it is left out + if onward(run[-1], here): + run.append(here) + while ring and len(run) > 3 and not onward(run[-1], run[0]): + run.pop() + if len(run) < (3 if ring else 2): + raise Refused(f"{where}: the section leaves a rib no room: it turns or closes in tighter than the rib reaches: lower standoff or depth; nothing changed.") + Q, into = (np.array([here[field] for here in run]) for field in (0, 1)) + # a segment's half thickness is laid off by its own wall's lean: beside a corner, the lean of its end that is no corner + back = np.array([v[3] if u[4] and not v[4] else u[3] if v[4] and not u[4] else max(u[3], v[3]) for u, v in zip(run, run[1:] + run[:1] if ring else run[1:])]) + grade, more, gain, lack = np.array([max(u[2], v[2]) for u, v in zip(run, run[1:] + run[:1] if ring else run[1:])]), 0.0, 1.0, 0.0 + for _ in range(STANDOFF_ROUNDS): + # What is left is of the second order (half a thickness laid off along the plane beside a curved or tilted + # wall, a chord across a facet): measured on the rib's own edge, and the edge moved in by what it is short. + try: + rib = core.band(Q, ring, normal, into, back + more * grade, self.depth, self.thickness) + except core.KitError as error: + raise Refused(f"{where}: {error}: lower standoff or depth; nothing changed.") from None + before, lack = lack, short(rib.shell.V[:2 * len(rib.outer)]) + if lack <= STANDOFF_HELD: + break + if lack < before: # the last move closed this much of what was short: the next is sized by it (a steep wall gives back less than it is given) + gain = min(gain * before / (before - lack), 8.0) + more += 1.05 * gain * lack + STANDOFF_HELD + else: + raise Refused(f"{where}: a rib there cannot be stood {self.standoff:.6g} off the plate (it comes {lack:.3g} too near where the wall turns): lower standoff or thickness; nothing changed.") + row["ribs"].append({"band": rib, "ring": ring, "inward": into, "edge": Q, "back": back + more * grade, "section": P[piece], "into": inward[piece], + "slope": slope[piece]}) row["pieces"] += 1 row["length"] += float(np.linalg.norm(np.diff(np.vstack([P[piece], P[piece][:1]]) if ring else P[piece], axis=0), axis=1).sum()) webs.append((index, rib.shell)) @@ -1082,15 +1178,34 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): raise Refused(f"No rib: the plate of {cage.name!r} is open along every section; nothing changed.") for row in sections: # posts stand on the kept runs only for rib in row["ribs"] if self.posts > 0 else (): - P, up = rib["P"], planes[row["plane"]]["normal"] + P, up = rib["section"], planes[row["plane"]]["normal"] for point, segment, fraction in along(P, rib["ring"], self.posts): - n, back, slope = rib["inward"][segment] + (rib["inward"][(segment + 1) % len(P)] - rib["inward"][segment]) * fraction, rib["back"][segment], rib["slope"][segment] + n = rib["into"][segment] + (rib["into"][(segment + 1) % len(P)] - rib["into"][segment]) * fraction n = n / np.linalg.norm(n) - foot = point + n * (back + 0.3 * self.depth) - if core.away(foot, P, rib["ring"])[0] < back: # inside a turn the rib was clipped at: a post there would end outside it + grade = max(rib["slope"][segment], rib["slope"][(segment + 1) % len(P)]) + hit = offset.ray_cast(Vector(point - n * 1e-5), Vector(n), (plate + self.standoff) * (2.0 * grade + 2.0) + 1e-3)[3] + if hit is None: continue - rods.append(core.sweep([point + n * slope * (inner - outer) / 2.0, foot], core.circle(self.post_r, POST_SEGMENTS), up)) - rods.append(core.sweep([point + n * slope * inner, point + n * (slope * inner + self.post_r)], core.circle(2.4 * self.post_r, PAD_SEGMENTS), up)) + foot = point + n * (hit - 1e-5 + float(rib["back"].max()) + 0.3 * self.depth) + if short([foot]) > clip or core.away(foot, rib["edge"], rib["ring"], rib["back"])[0] < -1e-9: # inside a turn the rib was clipped at: a post there would end outside it + continue + # A post starts inside the plate, midway between its faces where it stands, and deeper where it leans: its end, + # a disc across its own line, must stay under the outer face. + (face, normal, _, _), under = nearest.find_nearest(Vector(point)), skin.find_nearest(Vector(point))[0] + top = np.array(hide.find_nearest(Vector(point))[0]) + normal, thick = np.array(normal), float(np.linalg.norm(top - np.array(under))) + line = foot - (top + np.array(under)) / 2.0 + line = line / np.linalg.norm(line) + proud = self.post_r * math.sqrt(max(0.0, 1.0 - float(line @ normal) ** 2)) # how far the end's rim stands out of its middle, toward the outer face + sunk = min(thick, max(thick * POST_SUNK, 1.5 * proud)) + if thick > 0.0 and proud >= sunk: + continue # a plate thinner than the post's end leans: no post there + start = top - normal * sunk + across = np.cross(normal, up) + pad = skin.ray_cast(Vector(start), Vector(foot - start), float(np.linalg.norm(foot - start)))[0] + pad = np.array(pad if pad is not None else under) + rods.append(core.sweep([start, foot], core.circle(self.post_r, POST_SEGMENTS), across)) + rods.append(core.sweep([pad, pad - normal * self.post_r], core.circle(2.4 * self.post_r, PAD_SEGMENTS), across)) for index, longeron in enumerate(longerons): where, stations, ups = f"longerons[{index}]", [], [] for row in sections: diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index d2906e9..f663d11 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -569,7 +569,7 @@ }, { "name": "brokkr_kitbash.ribs", - "doc": "Derive the frame under an armor cage from the cage itself, so it fits the armor by construction: a rib along each plane's section of the cage's surface, set the standoff behind the plate's inner face (along the plate's normal, however it leans out of the plane) and reaching depth inward, clipped inside a crease tighter than that; lightening holes through the ribs; posts that stand the plate off them; longerons through the ribs. The plate's thickness is read from the cage's one Solidify. A rib stops where the plate is open (a port cut through it), runs behind an opening shorter than bridge (a panel break) and under a recess: openings are read from the cage as it is cut, so cut first. Inward is the side the cage's normals face away from. Makes one mesh object, a child of the cage, baked at this call: after the cage or its cuts change, delete it and run ribs again (its kit_ribs property keeps the request). Every plane and longeron is checked before anything is written. Reports ribs, thickness, sections [{plane, chains, pieces, length, open}], posts, holes, longerons [{index, stations}], faces, volume and nonManifoldEdges.", + "doc": "Derive the frame under an armor cage from the cage itself, so it fits the armor by construction: a rib along each plane's section of the cage's surface, set the standoff behind the plate's inner face (along the plate's normal, at any tilt of the plane and any curvature of the wall: its edge is cut from the inner face offset inward, then measured against the plate) and reaching depth inward, clipped inside a crease tighter than that; lightening holes through the ribs; posts that stand the plate off them; longerons through the ribs. The plate's two faces are read from the cage's one Solidify as it evaluates, whatever its thickness mode. A rib stops where the plate is open (a port cut through it), runs behind an opening shorter than bridge (a panel break) and under a recess: openings are read from the cage as it is cut, so cut first. Inward is the side the cage's normals face away from. Makes one mesh object, a child of the cage, baked at this call: after the cage or its cuts change, delete it and run ribs again (its kit_ribs property keeps the request). Every plane and longeron is checked before anything is written. Reports ribs, thickness, sections [{plane, chains, pieces, length, open}], posts, holes, longerons [{index, stations}], faces, volume and nonManifoldEdges.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index cce0f57..6e3b6ef 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -20,7 +20,8 @@ whatever the roll: what closes a loop the tree of connections cannot state. The structure under an armor cage is built, not kit parts: PROFILES are the sections (I, C, T, L, box), sweep takes an outline along a polyline with mitred joints (a longeron, a post), band is the rib beside a section in its plane, offset and clipped so that it follows a crease instead of folding in it (away, the distance to a polyline, is what -clips it), crossings finds where a section line meets a half-plane, resample fills a section's points in, and spans +clips it), inset is the step that offsets a mesh inward by its own faces (the surface a rib's edge is cut from), crossings +finds where a section line meets a half-plane, resample fills a section's points in, and spans says which runs of a section keep their frame where the plate over them is open. brokkr_kitbash.ribs is the bpy around them. @@ -756,6 +757,39 @@ def resample(points, closed: bool, step: float) -> np.ndarray: return np.array(made if closed else made + [loop[-1]]) +INSET_RANK = 2.5e-3 # of a vertex's face normals, as eigenvalues of their sum of squares: a direction they span by under 0.05 of the widest is not solved for + + +def inset(V, faces) -> np.ndarray: + """For each vertex of a mesh, the step that takes it one unit behind the plane of every face it is a corner of, + against the faces' normals (a face's normal is its winding's, counter-clockwise seen from outside): the mitre of + those planes moved in by 1. `V + d * inset(V, faces)`, with the same faces, is the surface offset inward by d. A + flat or smooth vertex steps along its normal; a crease's or a corner's steps to where its faces' offsets meet, + exactly where they meet in a point or a line. Where no step holds every face's distance (four faces that do not + share a point), the least-squares step is lengthened until the nearest face's plane stands 1 off: further than + asked from the others, never nearer. `faces` is a list of index tuples. A vertex of no face, or of faces that + fold back on each other, steps nowhere.""" + V = np.asarray(V, dtype=np.float64).reshape(-1, 3) + corners = np.fromiter((v for face in faces for v in face), dtype=np.int64) + counts = np.fromiter((len(face) for face in faces), dtype=np.int64, count=len(faces)) + owner, first = np.repeat(np.arange(len(faces)), counts), np.concatenate([[0], np.cumsum(counts)[:-1]]) + ahead = np.arange(len(corners)) + 1 + ahead[first + counts - 1] = first # the next corner round each face + normals = np.zeros((len(faces), 3)) + np.add.at(normals, owner, np.cross(V[corners], V[corners[ahead]])) # Newell: twice the face's area along its normal + size = np.linalg.norm(normals, axis=1) + normals = normals / np.maximum(size, 1e-300)[:, None] + n = normals[owner] * (size[owner] > 0)[:, None] # a corner's face normal; a face of no area asks nothing + squares, wanted = np.zeros((len(V), 3, 3)), np.zeros((len(V), 3)) + np.add.at(squares, corners, n[:, :, None] * n[:, None, :]) + np.add.at(wanted, corners, -n) + step = np.einsum("vij,vj->vi", np.linalg.pinv(squares, rcond=INSET_RANK, hermitian=True), wanted) + behind = np.full(len(V), np.inf) + np.minimum.at(behind, corners, np.where(size[owner] > 0, -np.einsum("ij,ij->i", n, step[corners]), np.inf)) # how far behind its nearest face's plane the step ends + held = np.isfinite(behind) & (behind > 1e-6) + return np.where(held[:, None], step / np.where(held, behind, 1.0)[:, None], 0.0) + + AWAY_SPAN = 64 # points, and segments, that away takes at a time: a block of points skips the blocks of segments too far off to matter diff --git a/surfaces/blender/tests/live/kitbash_ribs.py b/surfaces/blender/tests/live/kitbash_ribs.py index 3446c07..4793887 100644 --- a/surfaces/blender/tests/live/kitbash_ribs.py +++ b/surfaces/blender/tests/live/kitbash_ribs.py @@ -62,23 +62,39 @@ COUNT, SECTION = [0], ["setup"] STANDOFF, DEPTH, THICKNESS = 0.04, 0.06, 0.014 SIZES = {"standoff": STANDOFF, "depth": DEPTH, "thickness": THICKNESS} # Metres between the standoff and how near a rib's outer edge comes to the plate's inner face, at each point of the edge, -# on the pod: a doubly curved wall that leans up to 30 degrees out of a rib's plane. Shipped worst 0.0011 (a facet's rib -# is straight where the wall is curved); least claimed mutant 0.0036 (O2, the rib's half thickness, which a leaning plate -# comes nearer, left out); the geometric mean, separation 1.8 each side. O3 (only the plate's thickness laid off along -# its normal) reads 0.0067, O1 (both laid off along the plane, as before cut-kit-ribs.h2) 0.011, K12 (the standoff taken -# from the outer face) 0.06. -FIT = 0.002 +# on the pod: a doubly curved wall that leans up to 30 degrees out of a rib's plane. Shipped worst 7.5e-05 (the edge is +# moved in by one distance for the whole rib, what its nearest vertex was short); least claimed mutant 0.00081 (O2, the +# rib's half thickness, which a leaning plate comes nearer, left out of the edge: the measure then moves the whole rib); +# the geometric mean, separation 3.3 each side. U1 reads 0.00017 and M2 0.00013 and die at STOOD and RING; S1 0.025. +FIT = 2.5e-4 # The same on cages of flat facets, where it is exact: cones whose wall leans 0, 30, 45 and 60 degrees out of the plane, a -# cylinder whose Solidify is negative, a hipped box, and a crease. Shipped worst 5.3e-08 (float32 meshes); least claimed mutant 0.006 -# (O2 at 60 degrees); the geometric mean, separation 340 each side. O3 reads 0.026, O1 0.036, S1 (a negative -# thickness read as its size alone) 0.06. -STOOD = 1.8e-5 +# cylinder whose Solidify is negative, a hipped box, a crease and a dish. Shipped worst 6.4e-08 (float32 meshes); least +# claimed mutant 0.0003 (O2 at 60 degrees); the geometric mean, separation 68 each side. U1 (every Solidify read as not +# even) reads 0.00051, V1 0.003, S1 (the plate's outer face taken for its inner) 0.032. +STOOD = 4.4e-6 # A cone's rib or a hipped box's, over the ring between the section's two offsets times the thickness, less 1. Shipped worst 2.1e-06; -# least claimed mutant 0.034 (O2); the geometric mean, separation 130 each side. -RING = 2.7e-4 -# A rib inside a crease, over the true clipped offset's area times the thickness, less 1: tests/test_kitbash.py CREASED, -# the same polyline. Shipped 0.0013; least claimed mutant 0.079 (C1, nothing clipped); separation 7.9 each side. -CREASED = 0.0099 +# least claimed mutant 1.8e-05 (L1, a corner of two distances never mitred); the geometric mean, separation 2.9 each side. +# M2 (the edge's corners left as chords) reads 0.00047, O2 0.0017. +RING = 6.1e-6 +# A rib inside a crease, over the true clipped offset's area times the thickness, less 1. Shipped 2.3e-07 (the edge's +# corner is where the offset faces meet); least claimed mutant 0.00051 (M2, a chord across it); the geometric mean, +# separation 47 each side. U2 reads 0.0014, U1 0.031, A2 (an end of the section that finds no offset surface) 0.051, X1 +# (nothing left out where the offset surface folded) 0.07. tests/test_kitbash.py CREASED is core.band's own, on the same polyline. +CREASED = 1.1e-5 +# Metres between the standoff and how near the rib comes to the plate where a plane tilted 64 degrees cuts a prism of 24 +# flat sides. Shipped 2.1e-05 (one move for the whole rib, 0.0006 along the plane); least claimed mutant 5.5e-05 (V1, an +# offset clipped at its own distance); the geometric mean, separation 1.6 each side. U1 reads 0.00014, O2 0.00032, E1 +# (the edge never measured against the plate and moved in) 0.00059, G1 0.037. Before cut-kit-ribs.h3 it read 0.007. +TILTED = 3.4e-5 +# The same on spheres of radius 1 and 0.6 cut 60 degrees off their middle, standoffs 0.04 and 0.01. Shipped worst 9.7e-08; +# least claimed mutant 5.9e-07 (U2, every Solidify read as even: an icosphere's faces meet at unequal angles); the +# geometric mean, separation 2.5 each side. C1 reads 1.5e-05, U1 5.6e-05, O2 0.00016, E1 0.0014, G1 0.024. Before +# cut-kit-ribs.h3 they read 0.020, and at radius 0.6 and standoff 0.01 the rib stood 0.006 through the inner face. +ROUND = 2.4e-7 +# The same on a box whose Solidify is not even (Blender's default). Shipped 8.3e-09; least claimed mutant 0.018 (U2, the +# plate read as its Solidify's thickness behind every face, as before cut-kit-ribs.h3); the geometric mean, separation +# 1500 each side. S1 reads 0.038. +UNEVEN = 1.2e-5 # Metres a rib vertex stands off its plane beyond half the rib's thickness. Shipped worst 1.4e-07 (float32 meshes); # least claimed mutant 0.007 (KP, a rib twice as thick across its plane); separation 220 each side. PLANAR = 3.1e-5 @@ -94,6 +110,11 @@ STATIONED = 3.3e-5 # Shipped 2.7e-08; least claimed mutant 22 (K11, each plane's Manifold Boolean taken over all five ribs' webs, which # cross, with the action's own check of the cut off); separation 28000 each side. HOLED = 7.7e-4 +# Metres under the plate's outer face that the nearest vertex of a frame stands: the least is the worst, and under 0 a post is +# through the plate. Shipped worst 0.0047 (the rim of a post's end on a cone leaning 60 degrees whose wall is 0.02); least +# claimed mutant 0.0015 (P2, every post started a tenth of the plate under its outer face); the geometric mean, +# separation 1.8 each side. P3 (a leaning post not started deeper) reads 0.00013; S1 and G1 put vertices outside: -0.01. +SUNK = 0.0027 def check(name, ok, detail=None): @@ -284,10 +305,18 @@ try: for a in (2 * math.pi * (k + 0.5) / SIDES for k in range(SIDES))] for z in (0.3, 0.7)] return mesh_object(name, rows[0] + rows[1], [(k, (k + 1) % SIDES, SIDES + (k + 1) % SIDES, SIDES + k) for k in range(SIDES)], Matrix.Translation(at), wall=0.06) - def stood(cage, ribs, standoff=STANDOFF): + def stood(cage, ribs, standoff=STANDOFF, name="stood"): """How near the ribs come to the cage's plate as it is evaluated, less the standoff.""" plate = tree(cage) - return reading("stood", abs(min(plate.find_nearest(Vector(v))[3] for v in points(ribs)) - standoff)) + return reading(name, abs(min(plate.find_nearest(Vector(v))[3] for v in points(ribs)) - standoff)) + + def under(cage, ribs): + """How far under the cage's outer face (its designed surface: every wall here grows inward) the frame's nearest vertex stands: under 0, a vertex is outside the plate.""" + outer, worst = tree(cage, ("SOLIDIFY", "BEVEL", "BOOLEAN")), 1.0 + for v in points(ribs): + on, normal, _, _ = outer.find_nearest(Vector(v)) + worst = min(worst, -(Vector(v) - on).dot(normal)) + return reading("sunk", worst, least=True) leaned = [] for k, lean in enumerate((0, 30, 45, 60)): @@ -336,6 +365,9 @@ try: and reading("creased", abs(measure(ribs.data)["volume"] / THICKNESS / area - 1.0)) < CREASED and stood(creased, ribs, 0.03) < STOOD and float(off.min()) > near - 1e-6 and float(off.max()) < far + 1e-6, [receipt["message"], report, off.min(), off.max(), R["readings"]]) receipt, report = send("brokkr_kitbash.ribs", ribs_name="CreaseFrame", **CREASE, holes=0.1, posts=0.05) + _, shallow = send("brokkr_kitbash.ribs", ribs_name="CreaseShallow", **{**CREASE, "depth": 0.02}, posts=0.05) + check("a post behind the crease's facet that would end outside a shallow rib, short of where the rib's edges meet, is left out: ten of the thirteen stations (mutant P1 posts eleven)", + shallow is not None and (shallow["posts"], shallow["nonManifoldEdges"]) == (10, 0), shallow) check("the creased rib takes holes along its clipped centre line, cut clean, and posts", receipt["status"] == "accepted" and (report["holes"], report["posts"], report["nonManifoldEdges"]) == (3, 11, 0), [receipt["message"], report]) # the centre line is 0.3 + 0.048 - 0.13 tan 49.4 = 0.196 a run: 0.39 holds three holes 0.1 apart; the section, 0.662, thirteen post stations, one each side of the facet clipped angle = mesh_object("Angle", [(x, y, z) for y in (-0.3, 0.3) for x, z in ((-0.4, 0.0), (0.0, 0.0), (0.0, -0.4))], [(0, 1, 4, 3), (1, 2, 5, 4)], Matrix.Translation((3.0, 12.0, 0.0)), wall=0.05) @@ -343,6 +375,47 @@ try: check("inside a right angle no post stands nearer the corner than the rib's outer edge is set back, 0.09: twelve of the sixteen stations (mutant P1 posts all sixteen, four through the other wall)", receipt["status"] == "accepted" and (report["ribs"], report["posts"], report["nonManifoldEdges"]) == (1, 12, 0) and abs(report["sections"][0]["length"] - 0.8) < 1e-6, [receipt["message"], report]) + # --- standoff-curved-and-tilted: the standoff where the plate's lean changes across the rib's reach -------------------------------- + section("standoff-curved-and-tilted") + prism = mesh_object("Prism", [(0.6 * math.cos(a), 0.6 * math.sin(a), z) for z in (-1.0, 2.0) for a in (2 * math.pi * (k + 0.5) / SIDES for k in range(SIDES))], + [(k, (k + 1) % SIDES, SIDES + (k + 1) % SIDES, SIDES + k) for k in range(SIDES)], Matrix.Translation((18.0, 9.0, 0.0)), wall=0.06) + receipt, report = send("brokkr_kitbash.ribs", object_name="Prism", ribs_name="PrismRibs", planes=json.dumps([{"origin": [0.0, 0.0, 0.5], "normal": [0.0, 0.9, 0.436]}]), **SIZES) + ribs = bpy.data.objects.get("PrismRibs") + check("a plane tilted 64 degrees through a prism of 24 flat sides: every facet leans differently out of the plane, and the rib stands the standoff off each (the finding: 0.007 short)", + receipt["status"] == "accepted" and (report["ribs"], report["nonManifoldEdges"]) == (1, 0) and stood(prism, ribs, STANDOFF, "tilted") < TILTED, [receipt["message"], report, R["readings"]]) + + def ball(name, radius, at): + made = bmesh.new() + bmesh.ops.create_icosphere(made, subdivisions=5, radius=radius) + vertices, faces = [tuple(v.co) for v in made.verts], [tuple(v.index for v in f.verts) for f in made.faces] + made.free() + return mesh_object(name, vertices, faces, Matrix.Translation(at), wall=0.06) + + rounds = [] + for k, (radius, standoff, depth) in enumerate(((1.0, 0.04, 0.06), (1.0, 0.01, 0.06), (0.6, 0.01, 0.03))): + sphere = ball(f"Ball{k}", radius, (3.0 * k, 18.0, 0.0)) + ROUND_RIB = {"object_name": sphere.name, "planes": flat([radius * math.sin(math.radians(60))]), "standoff": standoff, "depth": depth, "thickness": THICKNESS} + receipt, report = send("brokkr_kitbash.ribs", ribs_name=f"BallRibs{k}", **ROUND_RIB) + _, posted = send("brokkr_kitbash.ribs", ribs_name=f"BallPosts{k}", **ROUND_RIB, posts=0.2) + ribs, frame = bpy.data.objects.get(f"BallRibs{k}"), bpy.data.objects.get(f"BallPosts{k}") + rounds.append(receipt["status"] == "accepted" and (report["ribs"], report["nonManifoldEdges"]) == (1, 0) and stood(sphere, ribs, standoff, "round") < ROUND + and posted is not None and posted["posts"] > 3 and under(sphere, frame) > SUNK) + check("spheres of radius 1 and 0.6 cut 60 degrees off the middle, standoffs 0.04 and 0.01: a wall curved both ways, leaning 60 degrees, and the rib and its posts stand the standoff off it " + "(the finding: 0.020 short, and at radius 0.6 and standoff 0.01 through the inner face)", rounds == [True] * 3, [rounds, R["readings"]]) + ball("Ball3", 0.6, (9.0, 18.0, 0.0)) + refused("at radius 0.6 a standoff of 0.04 has no rib in that plane: 0.1 inside the wall the sphere is 0.5, and the plane passes 0.52 from its middle", + {"object_name": "Ball3", "ribs_name": "BallRibs3", "planes": flat([0.6 * math.sin(math.radians(60))]), "standoff": 0.04, "depth": 0.03, "thickness": THICKNESS}, "planes[0]: the section leaves a rib no room") + tight = ball("Tight", 0.15, (15.0, 18.0, 0.0)) + refused("a standoff greater than the plate's inner radius: the offset surface has passed through itself everywhere", {"object_name": "Tight", "ribs_name": "TightRibs", "planes": flat([0.0]), "standoff": 0.12, + "depth": 0.02, "thickness": THICKNESS}, "planes[0]: the section leaves a rib no room") + plain = mesh_object("Plain", [(sx * 0.5, sy * 0.5, z) for z in (0.3, 0.7) for sx, sy in ((1, -1), (1, 1), (-1, 1), (-1, -1))], [(k, (k + 1) % 4, 4 + (k + 1) % 4, 4 + k) for k in range(4)], + Matrix.Translation((21.0, 9.0, 0.0)), wall=0.06) + plain.modifiers["Solidify"].use_even_offset = False # Blender's default: each vertex 0.06 along its own normal, so the plate is 0.0424 thick beside a right angle + bpy.context.view_layer.update() + receipt, report = send("brokkr_kitbash.ribs", object_name="Plain", ribs_name="PlainRibs", planes=flat([0.5]), **SIZES) + check("solidify-default-unbounded: a box whose Solidify is not even is 0.0424 thick, not its 0.06, and the rib stands the standoff off the inner face it has (read as 0.06: 0.0176 over)", + receipt["status"] == "accepted" and report["thickness"] == 0.06 and stood(plain, bpy.data.objects["PlainRibs"], STANDOFF, "uneven") < UNEVEN, [receipt["message"], report, R["readings"]]) + # --- plate-window-unpinned: how deep the ray that asks "is the plate here" looks --------------------------------------------------- section("the-plate-window") sunk = mesh_object("Sunk", [(-0.5, -0.2, 0.0), (0.5, -0.2, 0.0), (0.5, 0.2, 0.0), (-0.5, 0.2, 0.0)], [(0, 1, 2, 3)], Matrix.Translation((0.0, 15.0, 0.0)), wall=0.05) @@ -395,7 +468,7 @@ try: from_axis = np.hypot(points(ribs)[:, 0], points(ribs)[:, 2] - 1.0) if ribs is not None else np.zeros(1) check("ribs-from-normals: a dish whose normals face its hollow side gets its rib on the other, the round side, though its section's middle lies in the hollow; a cage with no Solidify has a plate of no thickness", receipt["status"] == "accepted" and up_facing and report["thickness"] == 0.0 and report["ribs"] == 1 and report["sections"][0]["open"] == 0.0 - and abs(float(from_axis.min()) - (1.0 + STANDOFF)) < 1e-3 and float(from_axis.max()) > 1.0 + STANDOFF + DEPTH - 1e-6, [receipt["message"], report, from_axis.min(), from_axis.max()]) + and stood(dish, ribs) < STOOD and float(from_axis.min()) > 1.0 and float(from_axis.max()) > 1.0 + STANDOFF + DEPTH - 1e-6, [receipt["message"], report, from_axis.min(), from_axis.max(), R["readings"]]) for polygon in list(dish.data.polygons)[:4]: polygon.flip() dish.data.update() @@ -440,6 +513,18 @@ try: and (report["ribs"], len(report["longerons"]), report["nonManifoldEdges"]) == (5, 4, 0) and report["posts"] > 40 and report["holes"] > 80 and all(len(r["stations"]) == 5 for r in report["longerons"]), [receipt["message"], report]) + # --- posts-under-the-plate ---------------------------------------------------------------------------------------------------------- + section("posts-under-the-plate") + receipt, report = send("brokkr_kitbash.ribs", object_name="Cone60", ribs_name="ConePosts", planes=flat([0.5]), **SIZES, posts=0.2) + thin = frustum("Thin", 60, (24.0, 9.0, 0.0)) + thin.modifiers["Solidify"].thickness = 0.02 # thinner than a post's end leans out of its middle, twice over + bpy.context.view_layer.update() + _, leaning = send("brokkr_kitbash.ribs", object_name="Thin", ribs_name="ThinPosts", planes=flat([0.5]), **SIZES, posts=0.2) + depths = [under(cage, bpy.data.objects[name]) for cage, name in ((deck, "DeckRibs"), (creased, "CreaseFrame"), (angle, "AngleRibs"), (pod, "Frame"), (bpy.data.objects["Cone60"], "ConePosts"), (thin, "ThinPosts"))] + check("posts-under-the-plate: a post starts inside the plate, half its thickness under the outer face where it stands square and deeper where it leans, and no vertex of a frame stands outside the outer face: " + "a flat deck, a crease, a right angle, the pod, a cone leaning 60 degrees, the same cone with a wall of 0.02 (and the spheres above)", receipt["status"] == "accepted" and report["posts"] > 10 and leaning is not None and leaning["posts"] > 10 and min(depths) > SUNK + and abs(depths[0] - 0.025) < 1e-6, [receipt["message"], depths, R["readings"]]) + # --- holes-manifold: an egg-crate of five ribs that cross --------------------------------------------------------------------- section("holes-manifold") crate = mesh_object("Crate", [(-0.5, -0.5, 0.0), (0.5, -0.5, 0.0), (0.5, 0.5, 0.0), (-0.5, 0.5, 0.0)], [(0, 1, 2, 3)], Matrix.Translation((0.0, -5.0, 0.0)), wall=0.05) diff --git a/surfaces/blender/tests/live/kitbash_ribs.result.json b/surfaces/blender/tests/live/kitbash_ribs.result.json index c9d7f01..302a69f 100644 --- a/surfaces/blender/tests/live/kitbash_ribs.result.json +++ b/surfaces/blender/tests/live/kitbash_ribs.result.json @@ -41,6 +41,11 @@ "ok": true, "detail": null }, + { + "name": "a post behind the crease's facet that would end outside a shallow rib, short of where the rib's edges meet, is left out: ten of the thirteen stations (mutant P1 posts eleven)", + "ok": true, + "detail": null + }, { "name": "the creased rib takes holes along its clipped centre line, cut clean, and posts", "ok": true, @@ -51,6 +56,31 @@ "ok": true, "detail": null }, + { + "name": "a plane tilted 64 degrees through a prism of 24 flat sides: every facet leans differently out of the plane, and the rib stands the standoff off each (the finding: 0.007 short)", + "ok": true, + "detail": null + }, + { + "name": "spheres of radius 1 and 0.6 cut 60 degrees off the middle, standoffs 0.04 and 0.01: a wall curved both ways, leaning 60 degrees, and the rib and its posts stand the standoff off it (the finding: 0.020 short, and at radius 0.6 and standoff 0.01 through the inner face)", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: at radius 0.6 a standoff of 0.04 has no rib in that plane: 0.1 inside the wall the sphere is 0.5, and the plane passes 0.52 from its middle", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a standoff greater than the plate's inner radius: the offset surface has passed through itself everywhere", + "ok": true, + "detail": null + }, + { + "name": "solidify-default-unbounded: a box whose Solidify is not even is 0.0424 thick, not its 0.06, and the rib stands the standoff off the inner face it has (read as 0.06: 0.0176 over)", + "ok": true, + "detail": null + }, { "name": "a recess 0.8 of the plate deep is plate: the rib runs on under it (the ray looks 1.25 of the plate deep; mutant N5 looks 0.5)", "ok": true, @@ -116,6 +146,11 @@ "ok": true, "detail": null }, + { + "name": "posts-under-the-plate: a post starts inside the plate, half its thickness under the outer face where it stands square and deeper where it leans, and no vertex of a frame stands outside the outer face: a flat deck, a crease, a right angle, the pod, a cone leaning 60 degrees, the same cone with a wall of 0.02 (and the spheres above)", + "ok": true, + "detail": null + }, { "name": "holes-manifold: five ribs that cross each get their eleven holes, cut a plane at a time: closed shells, and the volume gone is the holes' own", "ok": true, @@ -210,13 +245,17 @@ "hostErrors": [], "readings": { "cleared": 0.031, - "creased": 0.0013, - "fit": 0.0011, - "holed": 2.7e-08, + "creased": 2.3e-07, + "fit": 7.5e-05, + "holed": 5.5e-08, "planar": 1.4e-07, "ring": 2.1e-06, + "round": 9.7e-08, "stationed": 5.2e-07, - "stood": 5.3e-08 + "stood": 6.4e-08, + "sunk": 0.0047, + "tilted": 2.1e-05, + "uneven": 8.3e-09 }, "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 b1609eb..c03845a 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1283,6 +1283,26 @@ class StructureTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, "runs along the axis"): core.crossings(chain, True, origin, axis, (0.0, 0.0, 2.0)) + def test_inset_steps_each_vertex_behind_every_face_it_is_a_corner_of(self): + """A flat vertex steps along its normal, a crease's to where its two faces' offsets meet, a corner's to where three do; four faces that share no + point are each held at least 1 off (mutant I1, a step along the mean normal, leaves a crease's faces cos 45 off).""" + cube = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0), (1.0, 0.0, 1.0), (1.0, 1.0, 1.0), (0.0, 1.0, 1.0)] + faces = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)] # wound outward + self.assertTrue(np.allclose(core.inset(cube, faces), [[1.0 - 2.0 * v for v in corner] for corner in cube], atol=1e-12)) # every corner toward the middle, 1 behind each of its three faces + self.assertTrue(np.allclose(core.inset(cube, faces[:1]), [[0.0, 0.0, 1.0]] * 4 + [[0.0, 0.0, 0.0]] * 4, atol=1e-12)) # one face: along its normal's back; a vertex of no face, nowhere + self.assertTrue(np.allclose(core.inset(cube, faces[2:4])[[1, 5]], [[-1.0, 1.0, 0.0]] * 2, atol=1e-12)) # a right-angle crease: its mitre, root 2 long + lean = math.tan(math.radians(20.0)) + hip = [(sx * (1.0 + z), sy * (1.0 + z * lean), z) for z in (0.0, 1.0) for sx, sy in ((1, -1), (1, 1), (-1, 1), (-1, -1))] # walls that lean 45 and 20 degrees + walls = [(k, (k + 1) % 4, 4 + (k + 1) % 4, 4 + k) for k in range(4)] + step, normals = core.inset(hip, walls), [np.array(n) / np.linalg.norm(n) for n in ((1.0, 0.0, -1.0), (0.0, 1.0, -lean), (-1.0, 0.0, -1.0), (0.0, -1.0, -lean))] + for face, normal in zip(walls, normals): + self.assertTrue(np.allclose(step[list(face)] @ normal, -1.0, atol=1e-12)) # unequal leans: still exactly 1 behind both walls + spire = [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (-1.0, 0.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 0.3), (0.4, 0.0, 0.0)] + sides = [(0, 1, 4), (1, 2, 4), (2, 3, 4), (3, 5, 4), (5, 0, 4)] # five faces round an apex that share no point once moved + behind = [-(core.inset(spire, sides)[4] @ (np.cross(np.subtract(spire[b], spire[a]), np.subtract(spire[c], spire[a])) / np.linalg.norm(np.cross(np.subtract(spire[b], spire[a]), np.subtract(spire[c], spire[a]))))) + for a, b, c in sides] + self.assertTrue(1.0 - 1e-9 < min(behind) < 1.0 + 1e-9 and max(behind) < 2.0, behind) # the nearest face 1 off, the others further, never nearer + def test_resample_keeps_every_corner_and_fills_between(self): """A corner stays a point of the chain, and no two points stand over the step apart.""" line = core.resample([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.5, 0.0)], False, 0.3) @@ -1561,7 +1581,7 @@ class OwnershipTests(unittest.TestCase): self.assertIn("evaluated_get(", source.split("def evaluated_of(")[1].split("\n\n\n")[0]) bodies = {body.split("(")[0]: body.split("\n\n\n")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:]} self.assertEqual([name for name, body in bodies.items() if "evaluated_of(" in body], ["boolean", "apply", "ribs"]) - self.assertEqual(source.count("evaluated_of("), 6) # its def, evaluable, boolean, apply, and ribs for the designed surface and for its holes + self.assertEqual(source.count("evaluated_of("), 7) # its def, evaluable, boolean, apply, and ribs for the designed surface, for the plate's two faces and for its holes self.assertIn("evaluated_of(", source.split("def evaluable(")[1].split("\n\n\n")[0]) place = source.split("def place_cutters(")[1].split("\n\n\n")[0] # cut and cut_many place through it: one evaluation, with the Booleans off self.assertEqual((place.count("evaluable("), place.count("evaluated_of(")), (1, 0)) @@ -1579,7 +1599,7 @@ class OwnershipTests(unittest.TestCase): for body in (place, *(source.split(f"class BROKKR_KITBASH_OT_{name}(")[1].split("class BROKKR_KITBASH_OT_")[0] for name in ("cut", "cut_many"))): self.assertNotIn("view_layer.update", body) # an update after a cutter joins would evaluate the Boolean self.assertEqual(body.count("place_cutters("), 0 if body is place else 1) - self.assertEqual(source.count("to_mesh("), 3) # boolean's report, and in ribs the designed surface and the holed webs + self.assertEqual(source.count("to_mesh("), 4) # boolean's report, and in ribs the designed surface, the plate's two faces and the holed webs def test_only_ribs_writes_kit_ribs(self): """kit_ribs is the request a ribs object was derived from: ribs assigns it once and nothing reads it back to From 8e6141fa61c30c5daa598799b31fd9356e3e4102 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 10:37:23 +0100 Subject: [PATCH 097/223] brokkr_kitbash.ribs: a Solidify whose faces are not the surface's vertices twice is taken at its thickness; docs/kitbash.md: ribs as built in h3 and what a call costs A Subsurf after the Solidify remakes the plate's vertices, and the two faces cannot be read off them: such a cage was refused by the commit before, and is a cage the probes and the renders use. It is taken as h2 took every cage, the Solidify's thickness behind every face of the designed surface, and the docs say what that is off by. docs/kitbash.md, Ribs from a shell: the edge cut from the offset surface, the measure against the plate, the plate's faces read from the Solidify, where a post starts, and the cost measured on the pod against 585ece4 (the action's own work 0.66 s and 0.42 s, from 0.31 s and 0.14 s). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 13 ++-- surfaces/blender/docs/kitbash.md | 62 +++++++++++++------ surfaces/blender/tests/live/kitbash_ribs.py | 7 +++ .../tests/live/kitbash_ribs.result.json | 5 ++ 4 files changed, 62 insertions(+), 25 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 22b2c3d..32edca1 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1040,12 +1040,13 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): wall.vertices.foreach_get("co", both) walled.to_mesh_clear() walls[0].show_viewport = False - if len(both) != 6 * len(at): - raise Refused(f"{cage.name!r}'s Solidify {walls[0].name!r} does not make the plate's two faces from the surface's own vertices ({len(both) // 3} vertices from {len(at)}): " - "ribs reads the plate from a simple Solidify with nothing after it but Bevel and Booleans; nothing changed.") - both = both.reshape(2, -1, 3).astype(np.float64) - out_of = [float(np.einsum("ij,ij->", face - at, np.array([v.normal for v in surface.verts]))) for face in both] # the inner face is the one further against the normals - inner_at, outer_at = (both[0], both[1]) if out_of[0] < out_of[1] else (both[1], both[0]) + if len(both) == 6 * len(at): + both = both.reshape(2, -1, 3).astype(np.float64) + out_of = [float(np.einsum("ij,ij->", face - at, np.array([v.normal for v in surface.verts]))) for face in both] # the inner face is the one further against the normals + inner_at, outer_at = (both[0], both[1]) if out_of[0] < out_of[1] else (both[1], both[0]) + else: # a modifier after the Solidify remade its vertices (a Subsurf), or it is not a simple one: the plate is taken as its thickness behind every face of the surface + behind = core.inset(at, polygons) + inner_at, outer_at = at + inner * behind, at - outer * behind skin = BVHTree.FromPolygons(inner_at.tolist(), polygons) # the plate's inner face: what the standoff is measured from hide = BVHTree.FromPolygons(outer_at.tolist(), polygons) if self.posts > 0 else None # its outer face: what no post may stand through # The inner face offset inward by the standoff, along its own faces' normals: a rib's outer edge is cut from this, so it diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 404579a..92c1b8e 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -376,22 +376,37 @@ all the same, and is cut. takes planes in the cage's own frame and makes, as one mesh object under the cage: - a rib along each plane's section of the cage's surface: `thickness` across the plane, set `standoff` behind - the plate's inner face and reaching `depth` further in. `standoff` is measured along the plate's own normal: - where the plate leans out of the rib's plane, the rib is set further back along the plane (the plate's - thickness and the standoff over the cosine of the lean, and what half the rib's thickness needs on the side the - plate leans over), so that no part of the rib comes nearer the inner face than `standoff`; + the plate's inner face and reaching `depth` further in along the plane. `standoff` is measured along the + plate's own normal, at any tilt of the plane and any curvature of the wall: the rib's outer edge is cut from + the inner face offset inward by `standoff` (every face moved along its own normal, creases mitred), then set + in by what half the rib's thickness needs on the side the plate leans over, and no part of the rib comes + nearer the inner face than `standoff`; - lightening holes through each rib every `holes` of its length (radius 0.3 of `depth`; 0 for none); -- posts every `posts` that stand the plate off the rib: a rod from the middle of the plate into the rib, and a pad - on the plate's inner face (0 for none); +- posts every `posts` that stand the plate off the rib: a rod from inside the plate into the rib, and a pad flat + on the plate's inner face (0 for none). A post starts midway between the plate's faces where it stands square + to them and deeper where it leans, so its end stays under the outer face; where the plate is thinner than the + lean of the post's end, no post stands; - longerons through the ribs: each `{origin, axis, toward}` is the half-plane from the line through `origin` along `axis`, on `toward`'s side. Where it crosses a plane's rib, at the rib's mid-depth, is a station; the longeron runs through the stations in the planes' order and 0.12 of the end gaps past the end ribs, a section `longeron` (`I`, `C`, `T`, `L` or `box`; `longeron_w`, `longeron_h`, `longeron_t`) with its up toward the plate. -A rib is a band beside its section (`core.band`): the section offset twice in its plane, with mitred corners, -and clipped as a polygon offset is. Inside a turn tighter than the rib reaches (the corner of a creased shell, a -facet shorter than its two corners set the rib back) the rib's edges cut the corner and the rib follows the -crease; the cut is a chord between points `step` apart, so it leaves out less than a `step` of the true corner. +A rib's outer edge is where its plane cuts the offset surface (`core.inset` makes it: each vertex of the inner +face stepped to where its faces, moved in by `standoff`, meet). Points `step` apart along the section each look +square in from the plate for it, and the edge's corners are put where the offset faces they landed on meet. Where +the offset surface has passed through itself (behind a crease, or inside a curve tighter than `standoff`) its +points measure nearer the plate than `standoff`: they are left out, and the edge closes across them at the corner +the faces either side make. Where nothing is left (a `standoff` greater than the wall's inner radius, a plane +that does not reach the offset surface) the call is refused. The rib is the band beside that edge +(`core.band`): the edge offset in its plane by `depth`, with mitred corners, and clipped as a polygon offset is, +so inside a turn tighter than the rib reaches the inner edge cuts the corner and the rib follows the crease. +The finished outer edge is then measured against the inner face, vertex by vertex, and moved in until none is +nearer than `standoff` (to 1e-7, what a float32 mesh holds). What the measure corrects is the half thickness, +which is laid off along the plane by the lean of the offset face: beside a tilted or curved wall that is right +to first order (it moved a rib 0.0006 on a prism cut at 64 degrees, and 0.005 on a sphere of radius 1 cut 60 +degrees off its middle, where the offset surface leans 74 degrees). A rib that 8 moves do not stand off is +refused. The move is one distance for the whole rib, so elsewhere along it the rib stands further off than +`standoff` by up to that much. Lightening holes stand on the band's centre line, clipped the same way, so a hole (0.3 of `depth`) keeps 0.2 of `depth` of web on both sides; a post that would end outside the rib inside such a turn is left out. Posts and longerons are a sweep of an outline along a path with mitred corners (`core.sweep`). @@ -405,18 +420,25 @@ shallower than the plate is plate, and the far wall of a narrow cage is not. Whe short, and no post or hole stands there. A recess that does not go through is plate. `ribs` reads no cutter: cut the cage first, in any way, and the ribs follow what the plate became. -The plate's thickness and which way it grows are read from the cage's one Solidify (a cage with none has a plate -of no thickness; one with two is refused; a negative thickness is the same plate grown to the other side of the -surface, and is read so). The plate is taken to be that thick along its normal everywhere. Solidify's even -thickness is not, where a vertex's faces meet at unequal angles: a wall of 0.06 on a box whose sides lean 45 and -20 degrees is 0.057 and 0.066 thick, and the standoff there is off by as much. Inward is the side the cage's normals face away from, not a guess from +The plate's two faces are read from the cage's one Solidify as Blender evaluates it (a cage with none has a +plate of no thickness; one with two is refused; a negative thickness is the same plate grown to the other side +of the surface). A simple Solidify writes the surface's vertices twice, in the surface's order, and the inner +face is the copy further against the normals: so the standoff is from the face the plate has, whatever the +thickness mode. Blender's default (even thickness off) moves each vertex the thickness along its own normal, +which makes a wall of 0.06 on a box 0.0424 thick beside each right angle; even thickness on a box whose sides +lean 45 and 20 degrees makes it 0.057 and 0.066. The report's `thickness` is the Solidify's own number, not a +measure. Where the Solidify does not write the two faces that way (complex mode, or a modifier after it that +remakes the vertices, such as a Subsurf after the Solidify) the plate is taken instead as the Solidify's +thickness behind every face of the designed surface, and the standoff is off by whatever the plate differs from +that: 0.0176 too far for a wall of 0.06 beside a right angle with even thickness off. Put the Solidify last +before Bevel and Booleans for the plate as it is. Inward is the side the cage's normals face away from, not a guess from the section's shape: a cage whose normals change sides along a section is refused, and one whose normals all face inward gets its frame outside. A rib is built at the section's own corners, so its faces lie along the cage's facets, and it does not depend on which way round the section was followed. Everything is checked before the ribs object is written, and a refusal names the plane or longeron: a plane that misses the cage or lies along its surface; a section that leaves a rib no room, closing in on itself nearer than -the rib reaches everywhere (lower `standoff` or `depth`); a longeron that meets a plane's ribs twice, not at all, or in an opening; +the rib reaches everywhere (lower `standoff` or `depth`); a rib that cannot be stood `standoff` off the plate; a longeron that meets a plane's ribs twice, not at all, or in an opening; holes that overlap or leave the rib; a cage that is scaled or that Blender does not evaluate; more than 64 planes or 16 longerons. @@ -428,12 +450,14 @@ the holes' own. Manifold is used here and nowhere else because these shells are live Booleans stay Exact. On a pod (2560 faces subdivided, a wall of 0.06, a port, a panel break and a recess; one whole evaluation -1.36 s), five ribs with 91 holes, 51 posts and four longerons took 1.70 s and the five ribs alone -1.51 s, medians of 3 interleaved with that evaluation (Blender 5.3 on Starfire). The hole cut is the Manifold +1.60 s), five ribs with 91 holes, 51 posts and four longerons took 2.26 s and the five ribs alone +2.02 s, medians of 5 calls in each of 3 processes interleaved with that evaluation (Blender 5.3 on Starfire). The hole cut is the Manifold Boolean: 0.017 s a call for those holes against 0.44 s with Exact, 26 times. Each call costs one whole evaluation of the cage, which scales with the cage's Exact Booleans: the action's own -work is the rest, 0.34 s and 0.15 s here. No cheaper route was found in Blender 5.3. The designed surface is read by hiding the cage's +work is the rest, 0.66 s and 0.42 s here: a second, light evaluation for the plate's two faces, three tree +queries for each point of a section, and the measure of each rib's edge against the plate, which builds a rib +again for each move (two to five on the pod). No cheaper route was found in Blender 5.3. The designed surface is read by hiding the cage's Solidify, Bevel and Boolean modifiers for the call, which tags the cage, and Blender evaluates it whole again afterwards. Reading the surface from a temporary copy without those modifiers costs 0.001 s to link and evaluate, but deleting the copy costs the same whole evaluation (1.44 to 1.54 s on the pod against 1.45 to diff --git a/surfaces/blender/tests/live/kitbash_ribs.py b/surfaces/blender/tests/live/kitbash_ribs.py index 4793887..4b8d756 100644 --- a/surfaces/blender/tests/live/kitbash_ribs.py +++ b/surfaces/blender/tests/live/kitbash_ribs.py @@ -415,6 +415,13 @@ try: receipt, report = send("brokkr_kitbash.ribs", object_name="Plain", ribs_name="PlainRibs", planes=flat([0.5]), **SIZES) check("solidify-default-unbounded: a box whose Solidify is not even is 0.0424 thick, not its 0.06, and the rib stands the standoff off the inner face it has (read as 0.06: 0.0176 over)", receipt["status"] == "accepted" and report["thickness"] == 0.06 and stood(plain, bpy.data.objects["PlainRibs"], STANDOFF, "uneven") < UNEVEN, [receipt["message"], report, R["readings"]]) + late = frustum("Late", 30, (27.0, 9.0, 0.0)) + late.modifiers.new("Subsurf", "SUBSURF").levels = 2 # after the Solidify: the plate is the wall subdivided, and its faces are not the surface's vertices twice + bpy.context.view_layer.update() + receipt, report = send("brokkr_kitbash.ribs", object_name="Late", ribs_name="LateRibs", planes=flat([0.5]), **SIZES) + check("a cage subdivided after its Solidify is taken as that thick behind every face: a rib, clear of the plate", + receipt["status"] == "accepted" and (report["ribs"], report["thickness"], report["nonManifoldEdges"]) == (1, 0.06, 0) + and min(tree(late).find_nearest(Vector(v))[3] for v in points(bpy.data.objects["LateRibs"])) > 0.5 * STANDOFF, [receipt["message"], report]) # --- plate-window-unpinned: how deep the ray that asks "is the plate here" looks --------------------------------------------------- section("the-plate-window") diff --git a/surfaces/blender/tests/live/kitbash_ribs.result.json b/surfaces/blender/tests/live/kitbash_ribs.result.json index 302a69f..396fca8 100644 --- a/surfaces/blender/tests/live/kitbash_ribs.result.json +++ b/surfaces/blender/tests/live/kitbash_ribs.result.json @@ -81,6 +81,11 @@ "ok": true, "detail": null }, + { + "name": "a cage subdivided after its Solidify is taken as that thick behind every face: a rib, clear of the plate", + "ok": true, + "detail": null + }, { "name": "a recess 0.8 of the plate deep is plate: the rib runs on under it (the ray looks 1.25 of the plate deep; mutant N5 looks 0.5)", "ok": true, From eaf063a1203cde9b18ca0d3490500e0d278df6e4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 11:23:23 +0100 Subject: [PATCH 098/223] kitbash core: sheet, the cage and creases of a shell description Sheet and sheet(document): a loft of rings as quads wound by a stated rule, crease runs along ring and column edges, a rim weight, a mirror in x. SheetTests pin the grid, the mirror, the runs and every refusal. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/core.py | 161 ++++++++++++++++++++++++ surfaces/blender/tests/test_kitbash.py | 120 ++++++++++++++++++ 2 files changed, 281 insertions(+) diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 6e3b6ef..d6156c9 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -25,6 +25,10 @@ finds where a section line meets a half-plane, resample fills a section's points says which runs of a section keep their frame where the plate over them is open. brokkr_kitbash.ribs is the bpy around them. +An armor shell is a loft, not a kit part: sheet turns a shell description (rings of points, crease runs along ring +and column edges, a rim weight, a mirror in x) into a quad cage wound by a stated rule and the creases a subdivision +surface keeps on it. brokkr_kitbash.shell is the bpy around it. + A pin's roll is its one degree of freedom, and it is solved in closed form: roll_terms gives how a point or an axis of the child moves along a world direction as the roll turns (a cosine, a sine and a constant), aim_roll the roll that points an axis of the child at a direction, reach_roll the roll that brings a point of the child to a plane. @@ -973,6 +977,163 @@ def spans(flags, lengths, closed: bool, bridge: float, clearance: float) -> list return kept +# --- shells: a loft of rings and its creases ------------------------------------------------------------------- + +SHEET_LIMIT = 64 # rings in a sheet, and authored points in a ring +SHEET_AREA = 1e-8 # square metres: a cage quad under this is a collapsed corner +MIRROR_EPS = 1e-6 # metres a mirrored ring's point 0 may stand off x = 0, and any of its points behind it +SHEET_KEYS = ("closed", "mirror", "creases", "rim", "flip") + + +class Sheet(NamedTuple): + """A shell's cage, in the shell's frame, metres: the five fields a mesh is written from (every face a quad, + shaded smooth, no sharp edge) and what a subdivision surface creases. creases is an (E, 2) array of vertex index + pairs with weights (E,) in (0, 1]; corners (K,) are vertex indices with corner_weights (K,) in (0, 1]. Vertex + i * points + j is ring i's point j, of rings rings of points points (2C - 1 when mirrored).""" + V: np.ndarray + faces: np.ndarray + counts: np.ndarray + smooth: np.ndarray + sharp: np.ndarray + creases: np.ndarray + weights: np.ndarray + corners: np.ndarray + corner_weights: np.ndarray + rings: int + points: int + + +def _index(value: Any, where: str, least: int, most: int) -> int: + if isinstance(value, bool) or not isinstance(value, int) or not least <= value <= most: + raise KitError(f"{where} must be a whole number from {least} to {most}, not {value!r}") + return value + + +def _weight(value: Any, where: str) -> float: + if not finite(value) or not 0.0 <= value <= 1.0: + raise KitError(f"{where} must be a number from 0 to 1, not {value!r}") + return float(value) + + +def sheet(document: Any) -> Sheet: + """The cage of a shell description {rings, closed, mirror, creases, rim, flip}. + + rings: 2 to 64 rings of 2 to 64 [x, y, z] points, equal counts. Quad (i, j) is P[i][j], P[i][j+1], P[i+1][j+1], + P[i+1][j], so its normal (P[i][j+1] - P[i][j]) x (P[i+1][j] - P[i][j]) faces out: seen from outside, a ring's + points run left to right and the rings run upward. flip reverses every face. closed joins each ring's last + point to its first. mirror: each ring is authored from its point 0 on x = 0 toward +x and becomes its mirrored + points in reverse, then itself (2C - 1 points); a crease names authored indices and lands on both halves. + + creases: {ring, from, to, weight} creases ring's edges from point `from` to point `to` (on a closed ring `to` + may be the count: the edge back to point 0); {column, from, to, weight} a column's edges from ring `from` to + ring `to`; {point: [ring, point], weight} one vertex. rim is the weight of every boundary edge no run names. + An edge has one weight: two runs that give it different ones are refused.""" + _keys(document, "sheet", ("rings",), SHEET_KEYS) + flags = {} + for key in ("closed", "mirror", "flip"): + flags[key] = document.get(key, False) + if not isinstance(flags[key], bool): + raise KitError(f"sheet.{key} must be true or false, not {flags[key]!r}") + closed, mirror, flip = flags["closed"], flags["mirror"], flags["flip"] + if mirror and closed: + raise KitError("sheet.mirror with sheet.closed: a mirrored ring runs from -x to +x and has two ends; state one of them") + rim = _weight(document.get("rim", 1.0), "sheet.rim") + rings = document["rings"] + if not isinstance(rings, list) or not 2 <= len(rings) <= SHEET_LIMIT: + raise KitError(f"sheet.rings must be 2 to {SHEET_LIMIT} rings, not {len(rings) if isinstance(rings, list) else rings!r}") + for i, ring in enumerate(rings): + if not isinstance(ring, list) or not 2 <= len(ring) <= SHEET_LIMIT: + raise KitError(f"sheet.rings[{i}] must be 2 to {SHEET_LIMIT} points, not {len(ring) if isinstance(ring, list) else ring!r}") + if len(ring) != len(rings[0]): + raise KitError(f"sheet.rings[{i}] has {len(ring)} points and sheet.rings[0] has {len(rings[0])}: a loft's rings have equal counts") + for j, point in enumerate(ring): + if not isinstance(point, list) or len(point) != 3 or not all(finite(v) for v in point): + raise KitError(f"sheet.rings[{i}][{j}] must be three finite numbers [x, y, z]") + P = np.array(rings, dtype=np.float64) + R, C = P.shape[:2] + if mirror: + for i in range(R): + if abs(P[i, 0, 0]) > MIRROR_EPS: + raise KitError(f"sheet.rings[{i}][0] has x = {P[i, 0, 0]:.6g}: a mirrored ring starts on x = 0") + for j in range(C): + if P[i, j, 0] < -MIRROR_EPS: + raise KitError(f"sheet.rings[{i}][{j}] has x = {P[i, j, 0]:.6g}: a mirrored ring is authored on the +x side") + P[:, 0, 0] = 0.0 + P = np.concatenate([P[:, :0:-1] * (-1.0, 1.0, 1.0), P], axis=1) + N = P.shape[1] # points in a ring as built + wrap = N if closed else N - 1 # quads, and ring edges, around a ring + columns = (lambda j: (C - 1 - j, C - 1 + j) if j else (C - 1,)) if mirror else (lambda j: (j,)) + vertex = lambda i, j: i * N + j % N # noqa: E731 + quads = np.array([[vertex(i, j), vertex(i, j + 1), vertex(i + 1, j + 1), vertex(i + 1, j)] for i in range(R - 1) for j in range(wrap)], dtype=np.int32) + V = P.reshape(-1, 3) + corners = V[quads] + areas = 0.5 * (np.linalg.norm(np.cross(corners[:, 1] - corners[:, 0], corners[:, 3] - corners[:, 0]), axis=1) + + np.linalg.norm(np.cross(corners[:, 3] - corners[:, 2], corners[:, 1] - corners[:, 2]), axis=1)) + if areas.min() < SHEET_AREA: + worst = int(areas.argmin()) + raise KitError(f"sheet: the quad between rings {worst // wrap} and {worst // wrap + 1} at point {worst % wrap} (as built) has area {areas[worst]:.3g} m2, " + f"under {SHEET_AREA:g}: a collapsed corner. Move its points apart") + if flip: + quads = quads[:, ::-1] + + edges, verts = {}, {} # (low, high) or vertex -> (weight, the run that stated it) + + def state(table, key, weight, where): + if key in table and table[key][0] != weight: + raise KitError(f"{where} gives an edge weight {weight:g} that {table[key][1]} gives {table[key][0]:g}: an edge has one weight" if table is edges else + f"{where} gives a point weight {weight:g} that {table[key][1]} gives {table[key][0]:g}: a point has one weight") + table.setdefault(key, (weight, where)) + + def edge(a, b): + return (min(a, b), max(a, b)) + + creases = document.get("creases", []) + if not isinstance(creases, list): + raise KitError("sheet.creases must be an array") + for k, run in enumerate(creases): + where = f"sheet.creases[{k}]" + if isinstance(run, dict) and "point" in run: + _keys(run, where, ("point", "weight")) + at = run["point"] + if not isinstance(at, list) or len(at) != 2: + raise KitError(f"{where}.point must be [ring, point]") + i, j = _index(at[0], f"{where}.point[0]", 0, R - 1), _index(at[1], f"{where}.point[1]", 0, C - 1) + weight = _weight(run["weight"], f"{where}.weight") + for column in columns(j): + state(verts, vertex(i, column), weight, where) + continue + if not isinstance(run, dict) or ("ring" in run) == ("column" in run): + raise KitError(f"{where} must be {{ring, from, to, weight}}, {{column, from, to, weight}} or {{point, weight}}") + along_ring = "ring" in run + _keys(run, where, ("ring" if along_ring else "column", "from", "to", "weight")) + weight = _weight(run["weight"], f"{where}.weight") + if along_ring: + i = _index(run["ring"], f"{where}.ring", 0, R - 1) + first, last = _index(run["from"], f"{where}.from", 0, C - 1), _index(run["to"], f"{where}.to", 0, C if closed else C - 1) + else: + j = _index(run["column"], f"{where}.column", 0, C - 1) + first, last = _index(run["from"], f"{where}.from", 0, R - 1), _index(run["to"], f"{where}.to", 0, R - 1) + if first >= last: + raise KitError(f"{where}: from {first} must be under to {last}") + for step in range(first, last): + if along_ring: + for a, b in zip(columns(step), columns(step + 1)) if step or not mirror else ((C - 1, C - 2), (C - 1, C)): + state(edges, edge(vertex(i, a), vertex(i, b)), weight, where) + else: + for column in columns(j): + state(edges, edge(vertex(step, column), vertex(step + 1, column)), weight, where) + boundary = [edge(vertex(i, j), vertex(i, j + 1)) for i in (0, R - 1) for j in range(wrap)] + if not closed: + boundary += [edge(vertex(i, j), vertex(i + 1, j)) for j in (0, N - 1) for i in range(R - 1)] + for key in boundary: + edges.setdefault(key, (rim, "sheet.rim")) + kept = sorted((key, weight) for key, (weight, _) in edges.items() if weight > 0) + pinned = sorted((key, weight) for key, (weight, _) in verts.items() if weight > 0) + return Sheet(V=V.copy(), faces=quads.ravel().astype(np.int32), counts=np.full(len(quads), 4, dtype=np.int32), smooth=np.ones(len(quads), dtype=bool), + sharp=NO_SHARP, creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64), + corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N) + + # --- reports ------------------------------------------------------------------------------------------------- def rows(matrix) -> list[list[float]]: diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index c03845a..1606308 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1439,6 +1439,126 @@ class StructureTests(unittest.TestCase): self.assertEqual((len(core.joined([]).V), len(core.joined([]).counts)), (0, 0)) +class SheetTests(unittest.TestCase): + """core.sheet: the cage and creases of a shell description. Exact arithmetic: each assertion is the built value + and names the mutant it kills.""" + + @staticmethod + def rings(count=3, points=4, x0=0.0): + """Rings upward in z, points toward +x, bowed toward -y: by the winding rule their outside is -y.""" + return [[[x0 + 0.2 * j, -0.3 + 0.05 * j * j, 0.25 * i] for j in range(points)] for i in range(count)] + + @staticmethod + def normals(built): + V = built.V[built.faces.reshape(-1, 4)] + return np.cross(V[:, 1] - V[:, 0], V[:, 3] - V[:, 0]) + + @staticmethod + def weights(built) -> dict: + return {tuple(pair): weight for pair, weight in zip(built.creases.tolist(), built.weights.tolist())} + + def test_a_grid_of_quads_wound_by_the_rule(self): + """sheet-grid. S2 (winding reversed): every quad's normal faces the known outside, -y; flip turns all.""" + built = core.sheet({"rings": self.rings(3, 4)}) + self.assertEqual((built.rings, built.points, len(built.V), len(built.counts), set(built.counts.tolist())), (3, 4, 12, 6, {4})) + self.assertEqual(built.faces[:4].tolist(), [0, 1, 5, 4]) # P[0][0], P[0][1], P[1][1], P[1][0] + self.assertTrue((self.normals(built)[:, 1] < 0).all()) + self.assertTrue(built.smooth.all() and len(built.sharp) == 0) + flipped = core.sheet({"rings": self.rings(3, 4), "flip": True}) + self.assertTrue((self.normals(flipped)[:, 1] > 0).all()) + self.assertEqual(flipped.faces[:4].tolist(), [4, 5, 1, 0]) + ring = [[math.cos(a), math.sin(a)] for a in (0.0, 2.0, 4.0)] # counter-clockwise from above, rings upward: outward + tube = core.sheet({"rings": [[[x, y, z] for x, y in ring] for z in (0.0, 1.0, 2.0)], "closed": True}) + self.assertEqual((tube.points, len(tube.counts)), (3, 6)) + centres = tube.V[tube.faces.reshape(-1, 4)].mean(axis=1) + self.assertTrue((np.einsum("ij,ij->i", self.normals(tube)[:, :2], centres[:, :2]) > 0).all()) + self.assertEqual(sorted(self.weights(tube)), [(0, 1), (0, 2), (1, 2), (6, 7), (6, 8), (7, 8)]) # a closed loft's rim: its two end rings + + def test_a_mirrored_sheet_is_symmetric(self): + """sheet-mirror. S3 (the mirrored half not reversed): the ring runs from -x to +x through point 0, vertex for + vertex the mirror of itself, and every quad faces the same outside. S10 (creases on one half).""" + built = core.sheet({"rings": self.rings(3, 3), "mirror": True, "rim": 0.0, "creases": [ + {"ring": 1, "from": 0, "to": 2, "weight": 0.75}, {"column": 1, "from": 0, "to": 2, "weight": 0.5}, {"point": [2, 2], "weight": 0.25}, + {"point": [1, 0], "weight": 1.0}]}) + self.assertEqual((built.rings, built.points, len(built.V)), (3, 5, 15)) + P = built.V.reshape(3, 5, 3) + self.assertEqual(P[:, :, 0].tolist(), [[-0.4, -0.2, 0.0, 0.2, 0.4]] * 3) + np.testing.assert_array_equal(P[:, ::-1] * (-1.0, 1.0, 1.0), P) + self.assertTrue((self.normals(built)[:, 1] < 0).all()) + quads = {tuple(q) for q in built.faces.reshape(-1, 4).tolist()} + across = lambda v: v // 5 * 5 + 4 - v % 5 # noqa: E731 + self.assertEqual({tuple(across(v) for v in (q[1], q[0], q[3], q[2])) for q in quads}, quads) # mirrored and rewound, the same faces + self.assertEqual(self.weights(built), {(5, 6): 0.75, (6, 7): 0.75, (7, 8): 0.75, (8, 9): 0.75, # ring 1, joined across point 0 + (1, 6): 0.5, (6, 11): 0.5, (3, 8): 0.5, (8, 13): 0.5}) # column 1, on both halves + self.assertEqual((built.corners.tolist(), built.corner_weights.tolist()), ([7, 10, 14], [1.0, 0.25, 0.25])) + + def test_runs_map_to_edges_and_the_rim_takes_the_rest(self): + """sheet-creases. S4 (rim ignored): every boundary edge no run names carries rim. S9 (a second run wins).""" + built = core.sheet({"rings": self.rings(3, 4), "rim": 0.4, "creases": [ + {"ring": 1, "from": 1, "to": 3, "weight": 1.0}, {"column": 2, "from": 0, "to": 1, "weight": 0.6}, {"ring": 0, "from": 0, "to": 1, "weight": 0.0}, + {"ring": 2, "from": 2, "to": 3, "weight": 0.9}, {"point": [0, 3], "weight": 0.7}]}) + rim = {(1, 2), (2, 3), (8, 9), (9, 10), (0, 4), (4, 8), (3, 7), (7, 11)} # the boundary less (0, 1), stated 0, and (10, 11), stated 0.9 + self.assertEqual(self.weights(built), {**{e: 0.4 for e in rim}, (5, 6): 1.0, (6, 7): 1.0, (2, 6): 0.6, (10, 11): 0.9}) + self.assertEqual((built.corners.tolist(), built.corner_weights.tolist()), ([3], [0.7])) + self.assertEqual(len(core.sheet({"rings": self.rings(3, 4), "rim": 0.0}).creases), 0) + self.assertEqual(set(core.sheet({"rings": self.rings(3, 4)}).weights.tolist()), {1.0}) + ring = [[math.cos(a), math.sin(a), 0.0] for a in (0.0, 1.5, 3.0, 4.5)] + tube = core.sheet({"rings": [[[x, y, z] for x, y, _ in ring] for z in (0.0, 1.0, 2.0)], "closed": True, "rim": 0.0, + "creases": [{"ring": 1, "from": 2, "to": 4, "weight": 1.0}]}) + self.assertEqual(self.weights(tube), {(6, 7): 1.0, (4, 7): 1.0}) # points 2-3, and 3 back to 0 + same = {"rings": self.rings(3, 4), "creases": [{"ring": 1, "from": 0, "to": 2, "weight": 0.5}, {"ring": 1, "from": 1, "to": 3, "weight": 0.5}]} + self.assertEqual(self.weights(core.sheet({**same, "rim": 0.0})), {(4, 5): 0.5, (5, 6): 0.5, (6, 7): 0.5}) + same["creases"][1]["weight"] = 0.6 + with self.assertRaisesRegex(core.KitError, r"sheet\.creases\[1\] gives an edge weight 0\.6 that sheet\.creases\[0\] gives 0\.5"): + core.sheet(same) + with self.assertRaisesRegex(core.KitError, r"sheet\.creases\[1\] gives a point weight 1 that sheet\.creases\[0\] gives 0\.5"): + core.sheet({"rings": self.rings(), "creases": [{"point": [0, 0], "weight": 0.5}, {"point": [0, 0], "weight": 1.0}]}) + + def test_refusals_name_the_field_and_index(self): + """sheet-refusals.""" + good = self.rings(3, 4) + bad_ring, short, nan, collapsed = copy.deepcopy(good), copy.deepcopy(good), copy.deepcopy(good), copy.deepcopy(good) + bad_ring[2] = bad_ring[2][:3] + short[1][2] = [0.0, 1.0] + nan[1][2][0] = math.nan + collapsed[1][1] = collapsed[1][2] = collapsed[0][1] = list(collapsed[0][2]) + off, behind = self.rings(3, 3, 0.01), self.rings(3, 3) + behind[1][2][0] = -0.2 + run = lambda **keys: {"rings": good, "creases": [keys]} # noqa: E731 + cases = [ + ([], "sheet must be an object"), ({}, "sheet lacks 'rings'"), ({"rings": good, "ring": 1}, "sheet has no key 'ring'"), + ({"rings": good[:1]}, r"sheet\.rings must be 2 to 64 rings, not 1"), ({"rings": [good[0]] * 65}, r"2 to 64 rings, not 65"), + ({"rings": [[[0, 0, 0]], [[0, 0, 1]]]}, r"sheet\.rings\[0\] must be 2 to 64 points, not 1"), + ({"rings": [[[float(j), 0.0, float(i)] for j in range(65)] for i in range(2)]}, r"sheet\.rings\[0\] must be 2 to 64 points, not 65"), + ({"rings": bad_ring}, r"sheet\.rings\[2\] has 3 points and sheet\.rings\[0\] has 4"), + ({"rings": short}, r"sheet\.rings\[1\]\[2\] must be three finite numbers"), ({"rings": nan}, r"sheet\.rings\[1\]\[2\] must be three finite"), + ({"rings": collapsed}, r"the quad between rings 0 and 1 at point 1 \(as built\) has area 0 m2"), + ({"rings": off, "mirror": True}, r"sheet\.rings\[0\]\[0\] has x = 0\.01: a mirrored ring starts on x = 0"), + ({"rings": behind, "mirror": True}, r"sheet\.rings\[1\]\[2\] has x = -0\.2: a mirrored ring is authored on the \+x side"), + ({"rings": self.rings(3, 3), "mirror": True, "closed": True}, r"sheet\.mirror with sheet\.closed"), + ({"rings": good, "closed": 1}, r"sheet\.closed must be true or false"), ({"rings": good, "rim": 1.5}, r"sheet\.rim must be a number from 0 to 1"), + ({"rings": good, "rim": math.inf}, r"sheet\.rim must be"), ({"rings": good, "creases": {}}, r"sheet\.creases must be an array"), + (run(ring=3, **{"from": 0, "to": 1}, weight=1), r"sheet\.creases\[0\]\.ring must be a whole number from 0 to 2, not 3"), + (run(ring=0, **{"from": 0, "to": 4}, weight=1), r"sheet\.creases\[0\]\.to must be a whole number from 0 to 3, not 4"), + (run(column=4, **{"from": 0, "to": 1}, weight=1), r"sheet\.creases\[0\]\.column must be a whole number from 0 to 3"), + (run(column=0, **{"from": 0, "to": 3}, weight=1), r"sheet\.creases\[0\]\.to must be a whole number from 0 to 2"), + (run(ring=0, **{"from": 2, "to": 2}, weight=1), r"sheet\.creases\[0\]: from 2 must be under to 2"), + (run(ring=0, **{"from": 0, "to": 1}, weight=1.01), r"sheet\.creases\[0\]\.weight must be a number from 0 to 1"), + (run(ring=0, **{"from": 0, "to": 1}), r"sheet\.creases\[0\] lacks 'weight'"), + (run(ring=0, **{"from": 0.0, "to": 1}, weight=1), r"sheet\.creases\[0\]\.from must be a whole number"), + (run(ring=0, column=0, **{"from": 0, "to": 1}, weight=1), r"sheet\.creases\[0\] must be \{ring, from, to, weight\}"), + (run(weight=1), r"sheet\.creases\[0\] must be \{ring"), (run(point=[0, 4], weight=1), r"sheet\.creases\[0\]\.point\[1\] must be a whole number from 0 to 3"), + (run(point=[0], weight=1), r"sheet\.creases\[0\]\.point must be \[ring, point\]"), (run(point=[0, 0], weight=1, ring=0), r"sheet\.creases\[0\] has no key 'ring'"), + ] + for document, message in cases: + with self.assertRaisesRegex(core.KitError, message, msg=message): + core.sheet(document) + closed = {"rings": [[[math.cos(a), math.sin(a), z] for a in (0.0, 2.0, 4.0)] for z in (0.0, 1.0)], "closed": True} + core.sheet({**closed, "creases": [{"ring": 0, "from": 0, "to": 3, "weight": 1}]}) # a closed ring's run may end at the count + with self.assertRaisesRegex(core.KitError, r"\.to must be a whole number from 0 to 3, not 4"): + core.sheet({**closed, "creases": [{"ring": 0, "from": 0, "to": 4, "weight": 1}]}) + + ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs"] From 1510bac6cf1f815224171909ed6f68c24f884b41 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 11:36:24 +0100 Subject: [PATCH 099/223] brokkr_kitbash.shell: a faceted, hollow armor shell from a loft of rings shell writes the cage core.sheet builds, its crease_edge and crease_vert, Kit Subsurf (creases, corners preserved) and Kit Solidify (even, rim), and kit_shell, the request. On a shell it rewrites the mesh in place under its cutters, ribs and Booleans. It evaluates nothing. The action row, the host and ownership tests, and tests/live/kitbash_faceted.py with its result: crisp 52 deg on the creased column against 5.8 elsewhere. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 81 +++- .../brokkr_kitbash/brokkr_actions.json | 57 +++ .../blender/tests/live/kitbash_faceted.py | 383 ++++++++++++++++++ .../tests/live/kitbash_faceted.result.json | 166 ++++++++ surfaces/blender/tests/test_kitbash.py | 37 +- 5 files changed, 721 insertions(+), 3 deletions(-) create mode 100644 surfaces/blender/tests/live/kitbash_faceted.py create mode 100644 surfaces/blender/tests/live/kitbash_faceted.result.json diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 32edca1..95204fb 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -43,6 +43,12 @@ a cutter. The ribs object is a bake of the cage at that call, and kit_ribs on it nothing reads it to decide geometry, and ribs is its one writer. The one Manifold Boolean in the package is the hole cut inside ribs, on webs it built as closed shells that do not cross; a target's live Booleans stay Exact. +shell makes the cage that cut and ribs work on: a loft of rings with crease runs (core.sheet) under a Kit Subsurf +and a Kit Solidify. kit_shell on the object is the request, and it owns the cage mesh as kit_params owns a part's: +shell is the one writer of the mesh, its crease attributes and those two modifiers, and calling it again on the +object rewrites the mesh in place, leaving the object, its cutters, ribs, Booleans and material slots. shell +evaluates nothing: Blender's own update after the action evaluates the plate once. + Connections are a tree. A loop (a brace from one branch to another) is closed by a closure: three ID properties on the closing part, kit_close_socket, kit_close_to (a pointer to the other part) and kit_close_to_socket. close writes them, only when the two sockets already meet, and writes nothing else; detach clears them. Nothing here @@ -79,6 +85,9 @@ BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0) REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates RIBS_LIMIT = 64 # planes in one ribs LONGERONS_LIMIT = 16 # longerons in one ribs +SHELL = "kit_shell" # on a shell: the request its cage is derived from, as JSON; its presence admits a rebuild, and nothing reads it to decide geometry +SUBSURF, SOLIDIFY = "Kit Subsurf", "Kit Solidify" # a shell's own modifiers, in that order, before any of its Booleans and the Kit Bevel +SHELL_FACES_LIMIT = 262144 # faces of a shell's subdivided surface: cage quads times 4 to the levels def kit_work(work): @@ -1283,6 +1292,75 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): return report +class BROKKR_KITBASH_OT_shell(PolishOperator): + """Make a faceted, hollow armor shell from a loft of rings: a quad cage with crease runs and a creased rim, under + a Subdivision and a Solidify; on an object that is already a shell, rebuild its cage in place under its cutters, + ribs and Booleans""" + bl_idname = "brokkr_kitbash.shell" + bl_label = "Make A Shell" + object_name: bpy.props.StringProperty(name="Object", description="The shell's name: a new object, or a shell to rebuild") + sheet: bpy.props.StringProperty(name="Sheet", description="A JSON object {rings, closed, mirror, creases, rim, flip}: rings of [x, y, z] points in the shell's own frame") + thickness: bpy.props.FloatProperty(name="Thickness", default=0.05, min=0.0009, max=1.0, description="The wall's thickness") + offset: bpy.props.FloatProperty(name="Offset", default=-1.0, min=-1.0, max=1.0, description="-1: the wall grows inward from the designed surface; 1: outward") + levels: bpy.props.IntProperty(name="Levels", default=3, min=1, max=4, description="Subdivision levels") + bevel: bpy.props.FloatProperty(name="Bevel", default=0.0, min=0.0, max=0.1, description="Width of the Kit Bevel on the plate's edges; 0: none") + + # the action table states thickness from 0.001: a float property rounds 0.001 up, so its bound stands just under + @kit_work + def work(self, context): + if not 1 <= len(self.object_name) <= 63: + raise Refused(f"object_name {self.object_name!r} must be 1 to 63 characters; nothing changed.") + obj = bpy.data.objects.get(self.object_name) + if obj is not None: + if obj.type != "MESH" or SHELL not in obj: + raise Refused(f"An object named {obj.name!r} exists and is no shell (it carries no {SHELL}): shell rebuilds only what shell made; nothing changed.") + rigid(obj) + own_mesh(obj, "rebuilding") + try: + document = json.loads(self.sheet) + except ValueError as error: + raise Refused(f"sheet is not JSON ({error}); nothing changed.") from None + built = core.sheet(document) + cage_faces = len(built.counts) + if cage_faces * 4 ** self.levels > SHELL_FACES_LIMIT: + raise Refused(f"sheet: {cage_faces} cage quads at {self.levels} levels subdivide to {cage_faces * 4 ** self.levels} faces, over {SHELL_FACES_LIMIT}. " + "Use fewer levels or a sparser sheet; nothing changed.") + rebuilt = obj is not None + if rebuilt: + mesh = obj.data + mesh.clear_geometry() + else: + mesh = bpy.data.meshes.new(self.object_name) + write_mesh(mesh, built) + ends = np.zeros(2 * len(mesh.edges), dtype=np.int32) + mesh.edges.foreach_get("vertices", ends) + ends = np.sort(ends.reshape(-1, 2), axis=1).astype(np.int64) + order = np.argsort(ends[:, 0] * len(built.V) + ends[:, 1]) # core.sheet lists its creases low vertex first, sorted: the edges in that order + at = np.searchsorted((ends[:, 0] * len(built.V) + ends[:, 1])[order], built.creases[:, 0] * len(built.V) + built.creases[:, 1]) + edge_weights, point_weights = np.zeros(len(mesh.edges), dtype=np.float32), np.zeros(len(built.V), dtype=np.float32) + edge_weights[order[at]] = built.weights + point_weights[built.corners] = built.corner_weights + for name, domain, weights in (("crease_edge", "EDGE", edge_weights), ("crease_vert", "POINT", point_weights)): + (mesh.attributes.get(name) or mesh.attributes.new(name, "FLOAT", domain)).data.foreach_set("value", weights) + if not rebuilt: + obj = bpy.data.objects.new(self.object_name, mesh) + context.scene.collection.objects.link(obj) + smooth = obj.modifiers.get(SUBSURF) or obj.modifiers.new(SUBSURF, "SUBSURF") + smooth.levels = smooth.render_levels = self.levels + smooth.subdivision_type, smooth.boundary_smooth, smooth.use_creases = "CATMULL_CLARK", "PRESERVE_CORNERS", True + wall = obj.modifiers.get(SOLIDIFY) or obj.modifiers.new(SOLIDIFY, "SOLIDIFY") + wall.thickness, wall.offset, wall.use_even_offset, wall.use_rim = self.thickness, self.offset, True, True + sync_bevel(obj, self.bevel) + obj[SHELL] = json.dumps({"sheet": document, "thickness": self.thickness, "offset": self.offset, "levels": self.levels, "bevel": self.bevel}) + corners = built.V[built.faces.reshape(-1, 4)] + facing = np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]).sum(axis=0) # twice the quads' vector areas, summed + cancels = np.linalg.norm(facing) <= 1e-9 * np.linalg.norm(np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]), axis=1).sum() + return {"object": obj.name, "rebuilt": rebuilt, "rings": built.rings, "points": built.points, "cageFaces": cage_faces, "creases": len(built.creases), + "corners": len(built.corners), "subdividedFaces": cage_faces * 4 ** self.levels, + "facing": None if cancels else [round(float(v), 6) for v in facing / np.linalg.norm(facing)], + "thickness": round(self.thickness, 6), "offset": round(self.offset, 6), "levels": self.levels, "children": sorted(child.name for child in obj.children)} + + class BROKKR_KITBASH_OT_describe(PolishOperator): """List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame at default params""" @@ -1314,7 +1392,8 @@ class BROKKR_KITBASH_OT_report(PolishOperator): classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report, BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach, - BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply, BROKKR_KITBASH_OT_ribs) + BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply, BROKKR_KITBASH_OT_ribs, + BROKKR_KITBASH_OT_shell) def register(): diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index f663d11..2b5face 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -716,6 +716,63 @@ "doc": "the section's wall" } ] + }, + { + "name": "brokkr_kitbash.shell", + "doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings, points, cageFaces, creases, corners, subdividedFaces, facing, thickness, offset, levels and children.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the shell's name: no object's name, or a shell's, which is then rebuilt" + }, + { + "name": "sheet", + "type": "string", + "required": true, + "minLength": 2, + "maxLength": 32000, + "doc": "the shell description, a JSON object: rings, closed, mirror, creases, rim, flip" + }, + { + "name": "thickness", + "type": "number", + "minimum": 0.001, + "maximum": 1, + "default": 0.05, + "doc": "the wall's thickness" + }, + { + "name": "offset", + "type": "number", + "minimum": -1, + "maximum": 1, + "default": -1, + "doc": "-1: the wall grows inward from the designed surface; 1: outward" + }, + { + "name": "levels", + "type": "integer", + "minimum": 1, + "maximum": 4, + "default": 3, + "doc": "subdivision levels; cage quads times 4 to the levels may not pass 262144" + }, + { + "name": "bevel", + "type": "number", + "minimum": 0, + "maximum": 0.1, + "default": 0, + "doc": "width of the Kit Bevel on the plate's edges; 0: none" + } + ] } ] } diff --git a/surfaces/blender/tests/live/kitbash_faceted.py b/surfaces/blender/tests/live/kitbash_faceted.py new file mode 100644 index 0000000..e178482 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_faceted.py @@ -0,0 +1,383 @@ +"""Live proof, in a background Blender, of brokkr_kitbash.shell through run_intent: a loft of rings becomes a cage whose +crease runs stay crisp under subdivision while the rest stays smooth, a wall of even thickness with a filled rim, a +mirror, a rebuild in place under cutters and ribs, cut_many and ribs on the shell, and the refusals. Not part of the +unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_faceted.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). is an absolute path; writes .result.json and exits 1 when a check failed. + +Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped worst reading +and the least claimed mutant's, both written beside it; the result file carries the readings. Costs are wall times +of this run, reported and never bounded. The checks run inside one try: an uncaught error is a failed check that +names its section, and the result file is always written. +""" +import importlib.util +import json +import math +import os +import statistics +import sys +import tempfile +import time +import traceback +import types +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix, Vector +from mathutils.bvhtree import BVHTree + +SURFACE = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(SURFACE / "tools")) +import private_dirs # noqa: E402 + +_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) +if _refused: + raise SystemExit(_refused) +OUT = sys.argv[sys.argv.index("--") + 1] +if not Path(OUT).is_absolute(): + raise SystemExit(f"{OUT!r} is not an absolute path") +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules["brokkr_bridge"] = package +from brokkr_bridge import blender_target as bt # noqa: E402 + +import addon_utils # noqa: E402 + +spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_reference", SURFACE / "brokkr_kitbash" / "core.py") +core = importlib.util.module_from_spec(spec) # core as the unit tests load it +spec.loader.exec_module(core) + +sys.path.append(str(SURFACE)) +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_kitbash"): + addon_utils.enable(module, default_set=True) +target = bt.BrokkrBlenderTarget(bpy) +WORK = Path(tempfile.mkdtemp(prefix="brokkr-kitbash-faceted-")) +target.configure_action_dirs("", str(WORK)) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}, "costs": {}} +COUNT, SECTION = [0], ["setup"] +WALL = 0.06 +# Degrees: the largest dihedral angle anywhere inside the subdivided pauldron (not on its rim), which is on its creased +# column. Shipped 52; least claimed mutant 6.5 (S1, crease_edge not written: the cage subdivides smooth); the geometric +# mean, separation 2.8 each side. +CRISP = 18.0 +# Degrees: the largest dihedral angle across a subdivided edge that carries no crease. Shipped 5.8; least claimed +# mutant 51 (C1, a Subdivision that only splits, SIMPLE: every cage edge stays an edge); the geometric mean, separation +# 3 each side. S1 reads 6.5 here, 1.13 of shipped: CRISP claims it. +SOFT = 17.0 +# Metres from a corner of a sheet whose rim is 0 to the nearest vertex of its subdivided surface: with corners preserved +# the surface keeps the cage's corner. Shipped 0 (read as 1e-7, what a float32 mesh is good to); least claimed mutant +# 0.15 (S5, boundary_smooth ALL: the corner rounds off); the geometric mean, separation 900 each side. +CORNER = 1.6e-4 +# The wall's volume over the designed surface's area times the thickness, less 1, as a magnitude. Shipped 0.027 (a wall +# grown inward loses volume inside the crown's curve); least claimed mutant 0.036 (S6, the Solidify above the +# Subdivision: the wall's own edges are rounded off); the geometric mean, a total separation of 1.34. +SOLID = 0.0313 +# Metres between the thickness and the distance from a vertex of the wall's inner face to the designed surface. Shipped +# 0.0001 (a float32 mesh under three levels of subdivision); least claimed mutant 0.024 (S6: the inner face is subdivided again and pulls in); the geometric mean, separation 15 each side. +EVEN = 1.5e-3 + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) + + +def reading(name, value, least=False): + """The worst of a metric: the largest, or with `least` the smallest.""" + R["readings"][name] = (min if least else max)(R["readings"].get(name, float(value)), float(value)) + return float(value) + + +def section(name): + SECTION[0] = name + + +def send(action, **fields): + COUNT[0] += 1 + receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "nibu/hands", "action": action, **fields}) + result = None + if receipt.get("hostResult"): + try: + result = json.loads(receipt["hostResult"]) + except ValueError: + result = None + print("SEND", action, receipt["status"], str(receipt["message"])[:300], flush=True) + return receipt, result + + +def scene_state(): + return {o.name: (o.parent and o.parent.name, np.round(np.array(o.matrix_basis), 6).tolist(), {k: repr(o[k]) for k in sorted(o.keys()) if k.startswith("kit_")}, + [(m.name, m.type, m.show_viewport) for m in o.modifiers], o.data.name if o.type == "MESH" else None, len(o.data.polygons) if o.type == "MESH" else None, + np.round(points(o), 6).tolist() if o.type == "MESH" else None) + for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes), sorted(c.name for c in bpy.data.collections) + + +def refused(label, fields, expected): + state = scene_state() + receipt, _ = send("brokkr_kitbash.shell", **fields) + check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state, + [receipt["status"], receipt["message"]]) + + +def points(obj): + V = np.zeros(3 * len(obj.data.vertices)) + obj.data.vertices.foreach_get("co", V) + return V.reshape(-1, 3) + + +def evaluated(obj, off=()): + """This script's own copy of an object evaluated with the modifiers of the named types off, as a bmesh in its frame.""" + hidden = [m for m in obj.modifiers if m.type in off and m.show_viewport] + for m in hidden: + m.show_viewport = False + try: + bpy.context.view_layer.update() + owner = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()) + bm = bmesh.new() + bm.from_mesh(owner.to_mesh()) + owner.to_mesh_clear() + finally: + for m in hidden: + m.show_viewport = True + bpy.context.view_layer.update() + bm.normal_update() + return bm + + +def dihedrals(bm): + """(degrees, crease weight, convex) of every edge between two faces.""" + layer = bm.edges.layers.float.get("crease_edge") + rows = [] + for e in bm.edges: + if len(e.link_faces) == 2: + a, b = e.link_faces + rows.append((math.degrees(a.normal.angle(b.normal, 0.0)), e[layer] if layer else 0.0, (b.calc_center_median() - a.calc_center_median()).dot(a.normal) < 0)) + return rows + + +def crease_weights(obj) -> dict: + """{(low vertex, high vertex): weight} of the cage's crease_edge attribute, weights over 0 only.""" + attribute = obj.data.attributes.get("crease_edge") + if attribute is None: + return {} + return {tuple(sorted(e.vertices)): round(attribute.data[e.index].value, 6) for e in obj.data.edges if attribute.data[e.index].value > 0} + + +def stack(obj): + return [m.name for m in obj.modifiers] + + +def ring(y, s, dip=0.0): + """One ring of the pauldron: over the crown from inboard (+x) to outboard and down the outer face, at y.""" + return [[x * s, y, z * s] for x, z in ((0.55, 1.2), (-0.2, 1.5), (-0.9, 1.35 - dip), (-1.35, 1.0), (-1.55, 0.3), (-1.65, -0.35))] + + +# A pauldron-like sheet, the one the cut's probes measured: 6 rings of 6 points running aft to fore, a concave dip in ring +# 2, the shoulder line (column 3) creased. Its rings run toward +y and its points toward -x, so by the winding rule the +# crown would face down: flip turns it up. +RINGS = [ring(-1.35, 0.85), ring(-0.8, 0.97), ring(-0.2, 1.0, dip=0.25), ring(0.4, 1.0), ring(0.9, 0.95), ring(1.2, 0.8)] +PAULDRON = {"rings": RINGS, "flip": True, "creases": [{"column": 3, "from": 0, "to": 5, "weight": 1.0}]} +CUTS = [{"name": f"Line{k}", "part": "slab", "params": "gap=0.02; length=0.8; depth=0.025", "origin": [x, y, 3.0], "direction": [0, 0, -1], **({"roll": 90} if k % 2 else {})} + for k, (x, y) in enumerate(((-0.3, -0.5), (-0.3, 0.1), (-0.6, 0.6), (0.1, 0.7)))] + [ + {"name": f"Inset{k}", "part": "box", "params": "width=0.25; height=0.2; depth=0.03", "origin": [-3.0, y, 0.5], "direction": [1, 0, 0]} for k, y in enumerate((-0.5, 0.5))] +PLANES = json.dumps([{"origin": [0.0, y, 0.0], "normal": [0.0, 1.0, 0.0]} for y in (-0.6, 0.0, 0.6)]) + +try: + # --- shell-crisp ------------------------------------------------------------------------------------------------------------ + section("shell-crisp") + request = {"object_name": "Pauldron", "sheet": json.dumps(PAULDRON), "thickness": WALL, "bevel": 0.004} + receipt, report = send("brokkr_kitbash.shell", **request) + pauldron = bpy.data.objects.get("Pauldron") + stored = json.loads(pauldron["kit_shell"]) if pauldron is not None and "kit_shell" in pauldron else {} + built = core.sheet(PAULDRON) + check("shell makes one mesh object in the scene: the cage as core.sheet builds it, vertex for vertex, and kit_shell the request", + receipt["status"] == "accepted" and pauldron is not None and pauldron.users_collection == (bpy.context.scene.collection,) and pauldron.parent is None + and np.abs(points(pauldron) - built.V).max() < 1e-6 and [tuple(p.vertices) for p in pauldron.data.polygons] == [tuple(q) for q in built.faces.reshape(-1, 4).tolist()] + and sorted(stored) == ["bevel", "levels", "offset", "sheet", "thickness"] and stored["sheet"] == PAULDRON + and (stored["levels"], stored["offset"]) == (3, -1.0) and abs(stored["thickness"] - WALL) < 1e-7, [receipt["message"], stored]) + check("shell reports cage facts: rings, points, quads, creased edges, the subdivided count, an upward facing, no children", + report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"] + and (report["object"], report["rebuilt"], report["rings"], report["points"], report["cageFaces"], report["creases"], report["corners"], report["subdividedFaces"], report["levels"], + report["thickness"], report["offset"], report["children"]) == ("Pauldron", False, 6, 6, 25, 25, 0, 1600, 3, 0.06, -1.0, []) + and report["facing"][2] > 0.5 and abs(np.linalg.norm(report["facing"]) - 1.0) < 1e-5, report) + smooth, wall = pauldron.modifiers.get("Kit Subsurf"), pauldron.modifiers.get("Kit Solidify") + check("the stack is Kit Subsurf, Kit Solidify, Kit Bevel: creases used, corners preserved, an even wall inward with its rim filled", + stack(pauldron) == ["Kit Subsurf", "Kit Solidify", "Kit Bevel"] and (smooth.levels, smooth.render_levels, smooth.use_creases, smooth.boundary_smooth) == (3, 3, True, "PRESERVE_CORNERS") + and (wall.use_even_offset, wall.use_rim, wall.offset) == (True, True, -1.0) and abs(wall.thickness - WALL) < 1e-7 and abs(pauldron.modifiers["Kit Bevel"].width - 0.004) < 1e-7, + stack(pauldron)) + expected = {tuple(pair): round(weight, 6) for pair, weight in zip(built.creases.tolist(), built.weights.tolist())} + check("crease_edge on the cage is the sheet's creases, edge for edge, and crease_vert is all zero", crease_weights(pauldron) == expected and len(expected) == 25 + and pauldron.data.attributes.get("crease_vert") is not None and max(d.value for d in pauldron.data.attributes["crease_vert"].data) == 0.0, crease_weights(pauldron)) + designed = evaluated(pauldron, ("SOLIDIFY", "BEVEL", "BOOLEAN")) + rows = dihedrals(designed) + reading("crisp", max(angle for angle, _, _ in rows), least=True) + reading("soft", max([angle for angle, weight, _ in rows if weight == 0.0] or [180.0])) + concave = sum(1 for angle, _, convex in rows if not convex and angle > 1.0) + check("shell-crisp: the creased column stays a facet edge under three levels of subdivision, every other edge inside the plate stays smooth, and the dip is concave", + R["readings"]["crisp"] > CRISP and R["readings"]["soft"] < SOFT and len(designed.faces) == report["subdividedFaces"] and concave > 20, + [R["readings"], len(designed.faces), concave]) + + # a semi-sharp ring, a vertex crease and a soft rim, written edge for edge + MIXED = {"rings": RINGS, "flip": True, "rim": 0.0, "creases": [{"ring": 2, "from": 1, "to": 4, "weight": 0.6}, {"column": 3, "from": 0, "to": 5, "weight": 1.0}, + {"point": [4, 1], "weight": 0.8}]} + receipt, report = send("brokkr_kitbash.shell", object_name="Mixed", sheet=json.dumps(MIXED), thickness=WALL, levels=2) + mixed, built = bpy.data.objects.get("Mixed"), core.sheet(MIXED) + expected = {tuple(pair): round(weight, 6) for pair, weight in zip(built.creases.tolist(), built.weights.tolist())} + corner = [round(d.value, 6) for d in mixed.data.attributes["crease_vert"].data] if mixed is not None else [] + check("a semi-sharp ring run, a column run and a point land on their own edges and vertex; with rim 0 the boundary carries no crease", + receipt["status"] == "accepted" and crease_weights(mixed) == expected and sorted(set(expected.values())) == [0.6, 1.0] and len(expected) == 8 + and corner == [0.8 if k == 4 * 6 + 1 else 0.0 for k in range(36)] and (report["creases"], report["corners"], report["subdividedFaces"]) == (8, 1, 400) and "Kit Bevel" not in stack(mixed), + [receipt["message"], crease_weights(mixed)]) + surface = evaluated(mixed, ("SOLIDIFY",)) + for corner_at in (RINGS[0][0], RINGS[0][-1], RINGS[-1][0], RINGS[-1][-1]): + reading("corner", max(1e-7, min((v.co - Vector(corner_at)).length for v in surface.verts))) + surface.free() + check("shell-crisp: a sheet whose rim is soft keeps its four corners", R["readings"]["corner"] < CORNER, R["readings"]) + + # --- shell-solid ------------------------------------------------------------------------------------------------------------ + section("shell-solid") + pauldron.modifiers["Kit Bevel"].show_viewport = False # the wall alone: a bevel rounds its edges + whole = evaluated(pauldron) + pauldron.modifiers["Kit Bevel"].show_viewport = True + area = sum(f.calc_area() for f in designed.faces) + outer = BVHTree.FromBMesh(designed) + inner = [v.co for v in whole.verts if all(outer.find_nearest(f.calc_center_median())[3] > WALL / 2 for f in v.link_faces)] + reading("solid", abs(whole.calc_volume(signed=True) / (area * WALL) - 1.0)) + for co in inner: + reading("even", abs(outer.find_nearest(co)[3] - WALL)) + check("shell-solid: the plate is a closed wall of even thickness behind the designed surface, its rim filled", + sum(1 for e in whole.edges if not e.is_manifold) == 0 and whole.calc_volume(signed=True) > 0 and len(whole.faces) == 2 * 1600 + 4 * 40 and len(inner) > 0.9 * len(designed.verts) + and R["readings"]["solid"] < SOLID and R["readings"]["even"] < EVEN, [R["readings"], len(whole.faces), len(inner), len(designed.verts)]) + whole.free() + + # a mirrored breast sheet: symmetric as evaluated + half = [[[0.0, -0.5 - 0.05 * i, 0.3 * i], [0.3, -0.45 - 0.05 * i, 0.3 * i], [0.6, -0.2, 0.3 * i + 0.05], [0.7, 0.2, 0.3 * i]] for i in range(4)] + BREAST = {"rings": half, "mirror": True, "creases": [{"column": 1, "from": 0, "to": 3, "weight": 1.0}, {"ring": 2, "from": 0, "to": 1, "weight": 0.7}]} + receipt, report = send("brokkr_kitbash.shell", object_name="Breast", sheet=json.dumps(BREAST), thickness=0.05, levels=2) + breast = bpy.data.objects.get("Breast") + plate = evaluated(breast) if breast is not None else None + V = np.array([v.co[:] for v in plate.verts]) if plate is not None else np.zeros((1, 3)) + mirrored = {tuple(np.round(v * (-1.0, 1.0, 1.0), 5) + 0.0) for v in V} == {tuple(np.round(v, 5) + 0.0) for v in V} + check("a mirrored sheet is a plate symmetric in x, facing forward (-y), its creases on both halves", receipt["status"] == "accepted" and mirrored and report["points"] == 7 + and report["facing"][1] < -0.5 and abs(report["facing"][0]) < 1e-6 and report["creases"] == 2 * 6 + 2 * 3 + 2 * 3 + 2 + and sum(1 for e in plate.edges if not e.is_manifold) == 0, [receipt["message"], report]) + if plate is not None: + plate.free() + + # --- shell-composes --------------------------------------------------------------------------------------------------------- + section("shell-composes") + receipt, cut = send("brokkr_kitbash.cut_many", object_name="Pauldron", cuts=json.dumps(CUTS)) + check("shell-composes: cut_many takes four panel lines and two insets on a shell, and its Boolean goes after the wall and above the bevel", + receipt["status"] == "accepted" and stack(pauldron) == ["Kit Subsurf", "Kit Solidify", "Kit Difference", "Kit Bevel"] + and sorted(c.name for c in pauldron.children) == sorted(c["name"] for c in CUTS), [receipt["message"], stack(pauldron)]) + receipt, ribbed = send("brokkr_kitbash.ribs", object_name="Pauldron", ribs_name="PauldronRibs", planes=PLANES, standoff=0.01, depth=0.03, thickness=0.014) + ribs = bpy.data.objects.get("PauldronRibs") + behind = ribs is not None + for v in (points(ribs) if ribs is not None else ()): + on, normal, _, _ = outer.find_nearest(Vector(v)) + behind = behind and (Vector(v) - on).dot(normal) < 0 + check("shell-composes: ribs takes a shell, reads its thickness from Kit Solidify, and stands behind the plate: on the side the cage's normals face away from", + receipt["status"] == "accepted" and behind and ribs.parent == pauldron and ribbed["thickness"] == 0.06 and ribbed["ribs"] >= 3 and ribbed["nonManifoldEdges"] == 0, + [receipt["message"], ribbed]) + receipt, deep = send("brokkr_kitbash.ribs", object_name="Pauldron", ribs_name="PauldronDeep", planes=PLANES, standoff=0.03, depth=0.08, thickness=0.014) + R["readings"]["ribsAcrossTheCrease"] = 1.0 if receipt["status"] == "accepted" else 0.0 # a reading, not a check: deep ribs behind a creased plate are ribs' to clip or refuse + R["creaseRibs"] = str(receipt["message"])[:300] + if bpy.data.objects.get("PauldronDeep") is not None: + bpy.data.objects.remove(bpy.data.objects["PauldronDeep"]) + bpy.context.view_layer.update() + + # --- shell-rebuild ---------------------------------------------------------------------------------------------------------- + section("shell-rebuild") + before = {"pointer": pauldron.as_pointer(), "mesh": pauldron.data.as_pointer(), "children": {c.name: (c.as_pointer(), np.array(c.matrix_basis).tolist(), c.parent.name) for c in pauldron.children}, + "cutters": sorted(o.name for o in pauldron.modifiers["Kit Difference"].collection.objects), "collection": pauldron.modifiers["Kit Difference"].collection.as_pointer(), + "ribs": points(ribs).copy(), "slots": len(pauldron.material_slots)} + MOVED = {**PAULDRON, "rings": [[[x, y, z + 0.1 * (1.0 - abs(y))] for x, y, z in r] for r in RINGS]} # the crown lifted, most in the middle + receipt, report = send("brokkr_kitbash.shell", object_name="Pauldron", sheet=json.dumps(MOVED), thickness=0.05, levels=2, bevel=0.004) + again = bpy.data.objects.get("Pauldron") + wall = again.modifiers.get("Kit Solidify") + check("shell-rebuild: the same object and mesh datablock, its cutters and ribs still its children at unchanged matrices, the Boolean's collection untouched, the stack in order", + receipt["status"] == "accepted" and again is not None and (again.as_pointer(), again.data.as_pointer()) == (before["pointer"], before["mesh"]) + and {c.name: (c.as_pointer(), np.array(c.matrix_basis).tolist(), c.parent.name) for c in again.children} == before["children"] and len(before["children"]) == 7 + and (sorted(o.name for o in again.modifiers["Kit Difference"].collection.objects), again.modifiers["Kit Difference"].collection.as_pointer()) == (before["cutters"], before["collection"]) + and len(before["cutters"]) == 6 and stack(again) == ["Kit Subsurf", "Kit Solidify", "Kit Difference", "Kit Bevel"] and np.array_equal(points(ribs), before["ribs"]), + [receipt["message"], stack(again), sorted(c.name for c in again.children)]) + check("shell-rebuild: the cage is the new sheet's, the modifiers' settings and kit_shell follow, and the report says rebuilt and names the children", + report and report["rebuilt"] is True and report["children"] == sorted(before["children"]) and (report["levels"], report["thickness"], report["subdividedFaces"]) == (2, 0.05, 400) + and np.abs(points(again) - core.sheet(MOVED).V).max() < 1e-6 and abs(points(again)[:, 2].max() - (1.5 + 0.1 * 0.8)) < 1e-6 and (again.modifiers["Kit Subsurf"].levels, again.modifiers["Kit Subsurf"].render_levels) == (2, 2) + and abs(wall.thickness - 0.05) < 1e-7 and json.loads(again["kit_shell"])["sheet"] == MOVED and json.loads(again["kit_shell"])["levels"] == 2 + and crease_weights(again) == {tuple(pair): round(weight, 6) for pair, weight in zip(core.sheet(MOVED).creases.tolist(), core.sheet(MOVED).weights.tolist())}, report) + plate = evaluated(again) + check("shell-rebuild: the rebuilt plate is still cut, and closed", sum(1 for e in plate.edges if not e.is_manifold) == 0 and len(plate.faces) > 2 * 400 + 4 * 20 + 20, len(plate.faces)) + plate.free() + + # --- costs: wall times of this run, never bounded ----------------------------------------------------------------------------- + section("costs") + times = {"shell": [], "evaluation": [], "rebuildUnderCuts": []} + for k in range(3): + name = f"Timed{k}" + start = time.perf_counter() + bpy.ops.brokkr_kitbash.shell(object_name=name, sheet=json.dumps(PAULDRON), thickness=WALL) + times["shell"].append(time.perf_counter() - start) + bpy.data.objects[name].update_tag() # Blender's own update after the action evaluated it already: once more, alone + start = time.perf_counter() + faces = len(bpy.data.objects[name].evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) # one whole evaluation: Subdivision and Solidify + times["evaluation"].append(time.perf_counter() - start) + start = time.perf_counter() + bpy.ops.brokkr_kitbash.shell(object_name="Pauldron", sheet=json.dumps(MOVED if k % 2 else PAULDRON), thickness=WALL, bevel=0.004) + cut_faces = len(pauldron.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) # with its one Boolean of six cutters + times["rebuildUnderCuts"].append(time.perf_counter() - start) + R["costs"] = {name: float(f"{statistics.median(values):.2g}") for name, values in times.items()} + check("costs: the timed shells evaluated whole", faces == 3360 and cut_faces > 3360, [faces, cut_faces]) + + # --- shell-refusals --------------------------------------------------------------------------------------------------------- + section("shell-refusals") + SHEET = json.dumps(PAULDRON) + plain = bpy.data.objects.new("Plain", bpy.data.meshes.new("Plain")) + plain.data.from_pydata([(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], [], [(0, 1, 2, 3)]) + bpy.context.scene.collection.objects.link(plain) + empty = bpy.data.objects.new("Empty", None) + bpy.context.scene.collection.objects.link(empty) + bpy.context.view_layer.update() + refused("a mesh of that name that is no shell", {"object_name": "Plain", "sheet": SHEET}, "An object named 'Plain' exists and is no shell") + refused("an object of that name that is no mesh", {"object_name": "Empty", "sheet": SHEET}, "An object named 'Empty' exists and is no shell") + refused("a ribs object", {"object_name": "PauldronRibs", "sheet": SHEET}, "An object named 'PauldronRibs' exists and is no shell") + mixed.scale = (1.0, 1.0, 1.01) + bpy.context.view_layer.update() + refused("a scaled shell", {"object_name": "Mixed", "sheet": SHEET}, "'Mixed' is scaled, mirrored or sheared in the world") + mixed.scale = (1.0, 1.0, 1.0) + twin = bpy.data.objects.new("Twin", mixed.data) + bpy.context.scene.collection.objects.link(twin) + bpy.context.view_layer.update() + refused("a shell that shares its mesh", {"object_name": "Mixed", "sheet": SHEET}, "'Mixed' shares its mesh 'Mixed' with 1 other user(s)") + bpy.data.objects.remove(twin) + bpy.context.view_layer.update() + uneven = {"rings": [RINGS[0], RINGS[1][:5]]} + refused("a sheet of unequal rings, on a new name", {"object_name": "New", "sheet": json.dumps(uneven)}, "sheet.rings[1] has 5 points and sheet.rings[0] has 6") + refused("a sheet of unequal rings, on a shell", {"object_name": "Mixed", "sheet": json.dumps(uneven)}, "sheet.rings[1] has 5 points and sheet.rings[0] has 6") + refused("a run past the ring", {"object_name": "Mixed", "sheet": json.dumps({**PAULDRON, "creases": [{"ring": 0, "from": 0, "to": 6, "weight": 1}]})}, + "sheet.creases[0].to must be a whole number from 0 to 5, not 6") + refused("two weights on one edge", {"object_name": "Mixed", "sheet": json.dumps({**PAULDRON, "creases": [{"ring": 1, "from": 0, "to": 2, "weight": 1}, {"ring": 1, "from": 1, "to": 3, "weight": 0.5}]})}, + "sheet.creases[1] gives an edge weight 0.5 that sheet.creases[0] gives 1") + refused("a sheet that is not JSON", {"object_name": "Mixed", "sheet": "{rings"}, "sheet is not JSON") + refused("a sheet with an unknown key", {"object_name": "New", "sheet": json.dumps({**PAULDRON, "inside": [0, 0, 0]})}, "sheet has no key 'inside'") + dense = {"rings": [[[j / 10, 0, i / 10] for j in range(34)] for i in range(34)]} + refused("too many faces", {"object_name": "New", "sheet": json.dumps(dense), "levels": 4}, "1089 cage quads at 4 levels subdivide to 278784 faces, over 262144") + receipt, report = send("brokkr_kitbash.shell", object_name="Dense", sheet=json.dumps(dense), levels=3, thickness=0.01) + check("the same sheet at three levels is taken", receipt["status"] == "accepted" and report["subdividedFaces"] == 69696, receipt["message"]) + check("no refusal made an object", "New" not in bpy.data.objects, None) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file + check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:]) +finally: + R["ok"] = all(c["ok"] for c in R["checks"]) + R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} + Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") + for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) + print("READINGS", R["readings"], R["costs"], flush=True) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_faceted.result.json b/surfaces/blender/tests/live/kitbash_faceted.result.json new file mode 100644 index 0000000..783d9fc --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_faceted.result.json @@ -0,0 +1,166 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "shell makes one mesh object in the scene: the cage as core.sheet builds it, vertex for vertex, and kit_shell the request", + "ok": true, + "detail": null + }, + { + "name": "shell reports cage facts: rings, points, quads, creased edges, the subdivided count, an upward facing, no children", + "ok": true, + "detail": null + }, + { + "name": "the stack is Kit Subsurf, Kit Solidify, Kit Bevel: creases used, corners preserved, an even wall inward with its rim filled", + "ok": true, + "detail": null + }, + { + "name": "crease_edge on the cage is the sheet's creases, edge for edge, and crease_vert is all zero", + "ok": true, + "detail": null + }, + { + "name": "shell-crisp: the creased column stays a facet edge under three levels of subdivision, every other edge inside the plate stays smooth, and the dip is concave", + "ok": true, + "detail": null + }, + { + "name": "a semi-sharp ring run, a column run and a point land on their own edges and vertex; with rim 0 the boundary carries no crease", + "ok": true, + "detail": null + }, + { + "name": "shell-crisp: a sheet whose rim is soft keeps its four corners", + "ok": true, + "detail": null + }, + { + "name": "shell-solid: the plate is a closed wall of even thickness behind the designed surface, its rim filled", + "ok": true, + "detail": null + }, + { + "name": "a mirrored sheet is a plate symmetric in x, facing forward (-y), its creases on both halves", + "ok": true, + "detail": null + }, + { + "name": "shell-composes: cut_many takes four panel lines and two insets on a shell, and its Boolean goes after the wall and above the bevel", + "ok": true, + "detail": null + }, + { + "name": "shell-composes: ribs takes a shell, reads its thickness from Kit Solidify, and stands behind the plate: on the side the cage's normals face away from", + "ok": true, + "detail": null + }, + { + "name": "shell-rebuild: the same object and mesh datablock, its cutters and ribs still its children at unchanged matrices, the Boolean's collection untouched, the stack in order", + "ok": true, + "detail": null + }, + { + "name": "shell-rebuild: the cage is the new sheet's, the modifiers' settings and kit_shell follow, and the report says rebuilt and names the children", + "ok": true, + "detail": null + }, + { + "name": "shell-rebuild: the rebuilt plate is still cut, and closed", + "ok": true, + "detail": null + }, + { + "name": "costs: the timed shells evaluated whole", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a mesh of that name that is no shell", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an object of that name that is no mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a ribs object", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a scaled shell", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a shell that shares its mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a sheet of unequal rings, on a new name", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a sheet of unequal rings, on a shell", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a run past the ring", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: two weights on one edge", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a sheet that is not JSON", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a sheet with an unknown key", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: too many faces", + "ok": true, + "detail": null + }, + { + "name": "the same sheet at three levels is taken", + "ok": true, + "detail": null + }, + { + "name": "no refusal made an object", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "readings": { + "corner": 1.8e-07, + "crisp": 52.0, + "even": 0.0001, + "ribsAcrossTheCrease": 1.0, + "soft": 5.8, + "solid": 0.027 + }, + "costs": { + "shell": 0.0035, + "evaluation": 0.0017, + "rebuildUnderCuts": 0.92 + }, + "creaseRibs": "Operator brokkr_kitbash.ribs finished.", + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 1606308..ab0d8c5 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1561,7 +1561,8 @@ class SheetTests(unittest.TestCase): ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", - "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs"] + "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs", + "brokkr_kitbash.shell"] class HostFileTests(unittest.TestCase): @@ -1627,7 +1628,18 @@ class HostFileTests(unittest.TestCase): with self.assertRaises(at.IntentInvalid, msg=str(bad)): at.validate(bad, host) for row in self.document["actions"][4:]: - self.assertTrue(all(field["type"] in ("string", "number") for field in row["fields"]), row["name"]) + self.assertTrue(all(field["type"] in ("string", "number", "integer") for field in row["fields"]), row["name"]) + self.assertEqual([(row["name"], field["name"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "integer"], + [("brokkr_kitbash.shell", "levels")]) + sheet = json.dumps({"rings": [[[0, 0, 0], [1, 0, 0]], [[0, 0, 1], [1, 0, 1]]]}) + shell = {**envelope, "action": "brokkr_kitbash.shell", "object_name": "Plate", "sheet": sheet} + self.assertEqual([at.validate(shell, host)[k] for k in ("thickness", "offset", "levels", "bevel")], [0.05, -1, 3, 0]) + self.assertEqual(at.validate({**shell, "thickness": 0.001, "levels": 4}, host)["levels"], 4) + for bad in ({**shell, "levels": 5}, {**shell, "levels": 2.5}, {**shell, "levels": 0}, {**shell, "thickness": 0.0005}, {**shell, "offset": 1.5}, {**shell, "bevel": 0.2}, + {**shell, "sheet": "{" + " " * 32000}, {**shell, "sheet": ""}, {k: v for k, v in shell.items() if k != "sheet"}, {**shell, "object_name": "x" * 64}, + {**shell, "rings": []}): + with self.assertRaises(at.IntentInvalid, msg=str(bad)[:200]): + at.validate(bad, host) def test_the_ribs_row_takes_64_planes_and_16_longerons_at_full_precision(self): """planes-string-cap-below-64. A float's longest repr is 24 characters (-1.2345678901234567e-05): 64 planes of @@ -1719,6 +1731,13 @@ class OwnershipTests(unittest.TestCase): for body in (place, *(source.split(f"class BROKKR_KITBASH_OT_{name}(")[1].split("class BROKKR_KITBASH_OT_")[0] for name in ("cut", "cut_many"))): self.assertNotIn("view_layer.update", body) # an update after a cutter joins would evaluate the Boolean self.assertEqual(body.count("place_cutters("), 0 if body is place else 1) + shell = bodies["shell"] # shell evaluates nothing: Blender's own update after the action evaluates the plate once + for call in ("evaluated_of(", "evaluable(", "to_mesh(", "view_layer.update", "evaluated_get(", "depsgraph"): + self.assertNotIn(call, shell) + self.assertLess(shell.rindex("raise Refused("), shell.index("clear_geometry()")) # every refusal before any write + self.assertLess(shell.index("core.sheet("), shell.index("clear_geometry()")) + self.assertLess(shell.index("clear_geometry()"), shell.index("bpy.data.meshes.new(")) + self.assertNotIn("objects.remove(", shell) # a rebuild rewrites the mesh in place: a new object would orphan its cutters and ribs self.assertEqual(source.count("to_mesh("), 4) # boolean's report, and in ribs the designed surface, the plate's two faces and the holed webs def test_only_ribs_writes_kit_ribs(self): @@ -1730,6 +1749,20 @@ class OwnershipTests(unittest.TestCase): self.assertIn(writes[0], source.split("class BROKKR_KITBASH_OT_ribs(")[1].split("class BROKKR_KITBASH_OT_")[0]) self.assertEqual(len(re.findall(r'\[RIBS\]|\bRIBS\b(?! =)|"kit_ribs"', source)), 2) # the constant's own line, and that write + def test_only_shell_writes_kit_shell(self): + """kit_shell is the request a shell's cage is derived from: shell assigns it once, and elsewhere it is only + asked for (its presence admits a rebuild); shell alone names its two modifiers and its crease attributes.""" + source = self.sources()["__init__.py"] + body = source.split("class BROKKR_KITBASH_OT_shell(")[1].split("class BROKKR_KITBASH_OT_")[0] + writes = re.findall(r'[^\n]*\[(?:SHELL|"kit_shell")\]\s*=(?!=)[^\n]*', source) + self.assertEqual(len(writes), 1) + self.assertIn(writes[0], body) + self.assertEqual(len(re.findall(r'\bSHELL\b|"kit_shell"', source.replace(body, ""))), 2) # outside shell: the constant's own line, its name and its value + self.assertEqual(re.findall(r"\[SHELL\]|SHELL not in obj|SHELL in obj", body), ["SHELL not in obj", "[SHELL]"]) + for name in ("SUBSURF", "SOLIDIFY", '"crease_edge"', '"crease_vert"'): + self.assertEqual(len(re.findall(rf"(? Date: Wed, 2 Dec 2026 11:37:49 +0100 Subject: [PATCH 100/223] docs/kitbash.md: Making a shell The sheet format with a worked pauldron, the winding rule, crease runs and rim, what a rebuild keeps, outlines by through cuts, ribs on a shell, the refusals and the measured costs. The operator count is sixteen. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 78 ++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 3 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 92c1b8e..7459c67 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1,12 +1,12 @@ # Kitbash parts: machinery from kits `surfaces/blender/brokkr_kitbash` is a Blender add-on that places parametric machine parts from a **kit**, mates -them **socket** to socket, cuts them with booleans and bakes them. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks, +them **socket** to socket, cuts them with booleans and bakes them, and makes the faceted armor **shell** they sit under. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks, actuators, housings and plumbing an agent assembles offline under a hand-fit armor cage, baked once. It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish` and `brokkr_rig`: it imports the polish package's operator base, `Refused` and `mesh_object`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish` first; `brokkr_kitbash` refuses to register without it. `brokkr_actions.json` beside -its `__init__.py` lists the fourteen operators agents may run. Every action writes a JSON report to +its `__init__.py` lists the sixteen operators agents may run. Every action writes a JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. Who owns what: @@ -306,9 +306,80 @@ so what is attached to it stays attached and new parts can attach to it, and it `set_params` refuses it, since the params no longer make the mesh. `exportGltf` with `applyModifiers` already exports the evaluated mesh; `apply` is for a baked `.blend`. +## Making a shell + +`shell` makes an armor plate the way one is modelled by hand: fit a sparse subdivision cage, crease the edges that +are facets' borders, give it a wall, then cut into it. The cage is a **loft**: rings of points with equal counts, +quads between neighbouring rings. The description is a JSON object, `sheet`: + +| key | default | what it says | +| --- | --- | --- | +| `rings` | required | 2 to 64 rings of 2 to 64 `[x, y, z]` points in the shell's own frame, equal counts | +| `closed` | `false` | each ring joins back to its first point (a sleeve); not with `mirror` | +| `mirror` | `false` | each ring is authored from its point 0 on x = 0 toward +x and mirrored across x: 2C - 1 points | +| `creases` | `[]` | runs: `{"ring": i, "from": a, "to": b, "weight": w}`, `{"column": j, "from": a, "to": b, "weight": w}`, `{"point": [i, j], "weight": w}` | +| `rim` | `1` | the weight of every boundary edge no run names | +| `flip` | `false` | reverse every face | + +**Winding.** Quad (i, j) is `P[i][j], P[i][j+1], P[i+1][j+1], P[i+1][j]`: the surface faces out where, seen from +outside, a ring's points run left to right and the rings run upward. If the report's `facing` (the cage's mean +normal) points into the machine, set `flip` or author the rings the other way. Outward matters: the wall grows +inward from the designed surface (`offset` -1), `cut` rays must meet the outer face, and `ribs` stands on the +side the normals face away from. + +**Creases.** A ring run creases ring `i`'s edges from point `from` to point `to`; a column run creases column +`j`'s edges from ring `from` to ring `to`; a point is one vertex. A weight of 1 is a hard facet edge, and lower +weights are semi-sharp: on the pauldron below, 1.0 holds 52 degrees across the shoulder line and 0.6 holds 35, +while every edge that carries no crease stays under 6. Runs are partial on purpose: a facet edge that dies out +halfway along a plate is a run that stops there. An edge has one weight; two runs that give it different ones are +refused, naming both. On a mirrored sheet a run names authored indices and lands on both halves, and a ring run +from point 0 joins across the middle. `rim` 1 keeps the outline as drawn, corners included; with `rim` 0 the +outline rounds between the corners, which stay (the Subdivision preserves them). + +```json +{"action": "brokkr_kitbash.shell", "object_name": "Pauldron", "thickness": 0.06, "bevel": 0.004, + "sheet": "{\"flip\": true, \"creases\": [{\"column\": 3, \"from\": 0, \"to\": 5, \"weight\": 1.0}], \"rings\": [[[0.47, -1.35, 1.02], [-0.17, -1.35, 1.28], [-0.77, -1.35, 1.15], [-1.15, -1.35, 0.85], [-1.32, -1.35, 0.26], [-1.4, -1.35, -0.3]], ...]}"} +``` + +Six rings of six points run aft to fore; each goes over the crown from inboard and down the outer face, and +column 3, the shoulder line, is creased, so the crown and the steep outer face are two facets of one plate. Ring 2 +dips: the plate is concave there, which no convex hull can be. + +The object carries the cage, `crease_edge` and `crease_vert`, and the modifiers `Kit Subsurf` (`levels`, creases +used) then `Kit Solidify` (`thickness`, `offset`, even, rim filled), then any Booleans `cut` adds, then the `Kit +Bevel` when `bevel` is over 0. `kit_shell` on it is the request, and it owns the cage as `kit_params` owns a +part's mesh: an edit of the cage by hand is lost at the next `shell` call. `shell` reports `object`, `rebuilt`, +`rings`, `points`, `cageFaces`, `creases` (edges with a weight over 0), `corners`, `subdividedFaces`, `facing`, +`thickness`, `offset`, `levels` and `children`, all facts of the cage: it reads no evaluated mesh. + +**Rebuilding.** `shell` on a name that is already a shell rewrites its cage in place. The object, its mesh +datablock, its material slots, its cutters, its ribs and its Booleans stay, so a plate can be reshaped after it is +cut. Cutters stay at their frames in the shell's frame: where the surface moved away from a cutter the cut is +shallower or floats, so raise the cutter's `lift` or `depth` (`set_params`), or cut again. Ribs are a bake: after a +rebuild, delete them and run `ribs` again. A name that is some other object is refused, as are a scaled shell and +one that shares its mesh. + +**Outlines.** A loft's outline is its first and last rings and its end columns. Notches and tabs in it are +through cuts at the rim: a `box` or `slot` cutter deeper than the wall, placed across the edge, takes a bite out of +the outline, and the plate left between two bites is a tab. + +**With ribs.** `ribs` reads the plate's thickness from `Kit Solidify` and follows a crease, clipping a rib inside +it; a rib deeper than the room a tight crease leaves is refused with the size to lower. + +Refused, each before anything is written and naming the field and index: a missing or unknown key; a non-finite +number; fewer than 2 or more than 64 rings or points; rings of unequal counts; a quad under 1e-8 m2 (a collapsed +corner); a mirrored ring that does not start on x = 0 or has a point behind it; `mirror` with `closed`; a run out +of range or with `from` not under `to`; a weight outside 0 to 1; more than 262144 subdivided faces (cage quads +times 4 to the `levels`). + +On the pauldron (25 cage quads, 1600 subdivided faces, 3360 with the wall), `shell` took 3.5 ms a call with +Blender's own update after it, and one whole evaluation of the Subdivision and Solidify 1.7 ms. With six cutters +(four panel lines, two insets) and ribs under it, a rebuild took 0.92 s, which is its one Boolean evaluation. +Medians of 3, interleaved, Blender 5.3 on Starfire (`tests/live/kitbash_faceted.py`, `costs`). + ## Cutting a shell -An armor plate is not a kit part: it is any mesh, usually a subdivided cage with a Solidify. `cut` cuts it, or a +An armor plate is not a kit part: it is any mesh, usually one made by `shell`. `cut` cuts it, or a kit part, where a ray meets it, and what it places is itself a kit part, of the kit `cutters`: | part | params (besides `depth`, `lift`) | socket | @@ -498,6 +569,7 @@ vertices overflow. | `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | +| `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored value (`set_params`). A value outside its bounds is refused with the bounds in the message. From 39a3b7a3dd7b8f54224d02b6884d8d0e6156b901 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 11:48:55 +0100 Subject: [PATCH 101/223] docs/kitbash.md: a closed loop of crease runs needs point creases at its corners Found building Seraph's pectoral block: the face's border rounded into a disc. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 7459c67..7dd057d 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -333,7 +333,9 @@ weights are semi-sharp: on the pauldron below, 1.0 holds 52 degrees across the s while every edge that carries no crease stays under 6. Runs are partial on purpose: a facet edge that dies out halfway along a plate is a run that stops there. An edge has one weight; two runs that give it different ones are refused, naming both. On a mirrored sheet a run names authored indices and lands on both halves, and a ring run -from point 0 joins across the middle. `rim` 1 keeps the outline as drawn, corners included; with `rim` 0 the +from point 0 joins across the middle. A vertex where exactly two creased edges meet is smoothed along them, so a +closed loop of runs (a raised face's border) rounds into a disc unless each of its corners is also a `point`; +where three or more meet, or a run ends on the rim, the corner holds by itself. `rim` 1 keeps the outline as drawn, corners included; with `rim` 0 the outline rounds between the corners, which stay (the Subdivision preserves them). ```json From dddef79d8df4695be20d697c9bff16daf3ae78a3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 12:10:30 +0100 Subject: [PATCH 102/223] live kitbash, kitbash_assembly: the rows the host must load are the action table's, read from brokkr_actions.json Both suites listed the kitbash rows by hand, ending at ribs, and failed once shell added a row. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/kitbash.py | 5 +++-- surfaces/blender/tests/live/kitbash.result.json | 3 ++- surfaces/blender/tests/live/kitbash_assembly.py | 5 +++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 9c48891..609051a 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -49,6 +49,8 @@ target.reload_host_actions() R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "hostRows": [row["name"] for row in target.host_actions()[0]]} COUNT = [0] +# the rows the add-on's action table names, in its order: what the host must load, whatever rows the table grows +TABLE = [row["name"] for row in json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))["actions"]] def check(name, ok, detail=None): @@ -74,8 +76,7 @@ def extent(obj, axis=2): check("the kitbash rows load as host actions with no errors", not R["hostErrors"] - and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == [f"brokkr_kitbash.{name}" for name in ( - "place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply", "ribs")], [R["hostErrors"], R["hostRows"]]) + and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == TABLE != [], [R["hostErrors"], R["hostRows"]]) # --- describe --------------------------------------------------------------------------------------------------------- kit = core.load_kit("mechanical") diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 7d2950a..8e751b7 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -420,7 +420,8 @@ "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", - "brokkr_kitbash.ribs" + "brokkr_kitbash.ribs", + "brokkr_kitbash.shell" ], "placed": { "nozzle": { diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 3802282..5e73eac 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -59,6 +59,8 @@ target.configure_action_dirs("", str(WORK)) target.reload_host_actions() R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}} COUNT = [0] +# the rows the add-on's action table names, in its order: what the host must load, whatever rows the table grows +TABLE = [row["name"] for row in json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))["actions"]] kit = core.load_kit("mechanical") # Metres (or a difference of unit vectors) between where a seated socket is and where its mate puts it, read from # the two world matrices. Shipped worst 1.5e-07 (float32 matrices, parts a few metres from the origin); least @@ -176,8 +178,7 @@ def evaluated(obj): rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] -check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == [f"brokkr_kitbash.{n}" for n in ( - "place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply", "ribs")], [R["hostErrors"], rows]) +check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == TABLE != [], [R["hostErrors"], rows]) # --- attach ------------------------------------------------------------------------------------------------------------- tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088 From b5b32efe94b0dde8f8dd3953a2bd739779e98ef4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 12:10:30 +0100 Subject: [PATCH 103/223] live kitbash_faceted: a failed check whose detail is keyed by vertex pairs is written, not a crash; W1 claimed by the edge-for-edge check json.dumps refused the tuple keys of a failed crease check's detail, so a mutant that broke the crease order ended in a traceback with no FAIL line. shell's comment says why the weights are looked up by vertex pair: the mesh's edge order is not core.sheet's. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 2 +- surfaces/blender/tests/live/kitbash_faceted.py | 7 +++++++ surfaces/blender/tests/live/kitbash_faceted.result.json | 6 +++--- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 95204fb..6dfab56 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1335,7 +1335,7 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): ends = np.zeros(2 * len(mesh.edges), dtype=np.int32) mesh.edges.foreach_get("vertices", ends) ends = np.sort(ends.reshape(-1, 2), axis=1).astype(np.int64) - order = np.argsort(ends[:, 0] * len(built.V) + ends[:, 1]) # core.sheet lists its creases low vertex first, sorted: the edges in that order + order = np.argsort(ends[:, 0] * len(built.V) + ends[:, 1]) # the mesh lists its edges in calc_edges' order, not by vertex pair: each of core.sheet's creases is found by its pair at = np.searchsorted((ends[:, 0] * len(built.V) + ends[:, 1])[order], built.creases[:, 0] * len(built.V) + built.creases[:, 1]) edge_weights, point_weights = np.zeros(len(mesh.edges), dtype=np.float32), np.zeros(len(built.V), dtype=np.float32) edge_weights[order[at]] = built.weights diff --git a/surfaces/blender/tests/live/kitbash_faceted.py b/surfaces/blender/tests/live/kitbash_faceted.py index e178482..90f018b 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.py +++ b/surfaces/blender/tests/live/kitbash_faceted.py @@ -70,6 +70,8 @@ CRISP = 18.0 # Degrees: the largest dihedral angle across a subdivided edge that carries no crease. Shipped 5.8; least claimed # mutant 51 (C1, a Subdivision that only splits, SIMPLE: every cage edge stays an edge); the geometric mean, separation # 3 each side. S1 reads 6.5 here, 1.13 of shipped: CRISP claims it. +# W1 (the weights written at the creases' own indices, not at the edges found by vertex pair) reads 25 here and is +# claimed by the exact check below, crease_edge edge for edge: it has no bound to sit under. SOFT = 17.0 # Metres from a corner of a sheet whose rim is 0 to the nearest vertex of its subdivided surface: with corners preserved # the surface keeps the cage's corner. Shipped 0 (read as 1e-7, what a float32 mesh is good to); least claimed mutant @@ -85,6 +87,10 @@ EVEN = 1.5e-3 def check(name, ok, detail=None): + try: + json.dumps(detail, default=str) + except TypeError: # a detail keyed by vertex pairs: the result file takes it as text, so a failed check is written and not a crash + detail = repr(detail) R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) @@ -211,6 +217,7 @@ try: stack(pauldron) == ["Kit Subsurf", "Kit Solidify", "Kit Bevel"] and (smooth.levels, smooth.render_levels, smooth.use_creases, smooth.boundary_smooth) == (3, 3, True, "PRESERVE_CORNERS") and (wall.use_even_offset, wall.use_rim, wall.offset) == (True, True, -1.0) and abs(wall.thickness - WALL) < 1e-7 and abs(pauldron.modifiers["Kit Bevel"].width - 0.004) < 1e-7, stack(pauldron)) + # W1 dies here: the mesh's edges are not in the order core.sheet lists its creases, so the weights must be looked up by pair expected = {tuple(pair): round(weight, 6) for pair, weight in zip(built.creases.tolist(), built.weights.tolist())} check("crease_edge on the cage is the sheet's creases, edge for edge, and crease_vert is all zero", crease_weights(pauldron) == expected and len(expected) == 25 and pauldron.data.attributes.get("crease_vert") is not None and max(d.value for d in pauldron.data.attributes["crease_vert"].data) == 0.0, crease_weights(pauldron)) diff --git a/surfaces/blender/tests/live/kitbash_faceted.result.json b/surfaces/blender/tests/live/kitbash_faceted.result.json index 783d9fc..f1594a2 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.result.json +++ b/surfaces/blender/tests/live/kitbash_faceted.result.json @@ -157,9 +157,9 @@ "solid": 0.027 }, "costs": { - "shell": 0.0035, - "evaluation": 0.0017, - "rebuildUnderCuts": 0.92 + "shell": 0.0036, + "evaluation": 0.0018, + "rebuildUnderCuts": 0.97 }, "creaseRibs": "Operator brokkr_kitbash.ribs finished.", "ok": true From 2e22a58bd794dc1e01e80cf0939da09e027da5c1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 12:10:31 +0100 Subject: [PATCH 104/223] docs/kitbash.md: the thickness a crease holds, as measured Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 7dd057d..7b3816b 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -368,6 +368,19 @@ the outline, and the plate left between two bites is a tab. **With ribs.** `ribs` reads the plate's thickness from `Kit Solidify` and follows a crease, clipping a rib inside it; a rib deeper than the room a tight crease leaves is refused with the size to lower. +**Thickness at a crease.** `shell` takes any `thickness` in its range and does not refuse one the cage cannot +hold: it reads no evaluated mesh, and the limit is a fact of the subdivided one. Even thickness moves a vertex on a +full crease along the crease's bisector, which slides it `thickness` x tan(phi) across each facet, phi being half +the angle between the two facets' normals; the vertices beside it move straight in. Where that slide is longer than +the first row of subdivided faces, the wall's inner face folds over itself beside the crease: at a `thickness` over +(W / 2^`levels`) / tan(phi), W the facet's width across the crease. Measured on a ridge of two flat facets under a +wall grown inward, a crease of 1.0: the fold starts at 1.00 of that figure in 13 readings (W 1 and 0.4; phi 30, 45, +60; levels 1 to 3), which is 0.217 for W 1, phi 30, levels 3, and 0.029 for W 0.4, phi 60, levels 3. A crease of +0.5 folds at 1.02 to 1.3 of it, and an uncreased ridge folds too, at 1.1 to 4.2 of it. The fold is inside the +wall and one subdivided row wide: the designed surface is unchanged and the mesh has no open or non-manifold +edge, but the solid passes through itself there, and a cut through that place is untested. Keep `thickness` +under the figure where a creased plate is cut near its crease: a thinner wall, fewer `levels`, or wider facets. + Refused, each before anything is written and naming the field and index: a missing or unknown key; a non-finite number; fewer than 2 or more than 64 rings or points; rings of unequal counts; a quad under 1e-8 m2 (a collapsed corner); a mirrored ring that does not start on x = 0 or has a point behind it; `mirror` with `closed`; a run out From 9556d1337c2843f5cafc6fcc704d419ccbff955c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 12:46:53 +0100 Subject: [PATCH 105/223] brokkr_kitbash.shell: the receipt names the thickness at which the cage says the wall folds; live suites print before they write shell reports fold {onset, margin, edge, weight} from the cage alone (core.fold_depths: every edge between two quads as a full crease between flat facets, the narrower facet's reach, the wall's share on the edge's concave side from offset). It reads no evaluated mesh. An estimate: on the Seraph's fourteen creased plates the evaluated wall first folded at 0.74 to 1.2 of it in thirteen and at 2.6 in one. kitbash_faceted checks it against the evaluated wall on a wedge of unequal facets (no turned inner face at onset / 1.2, some at onset x 1.2). docs/kitbash.md: the narrower facet binds; 23 of 23 readings, ridge and valley; the fold receipt. kitbash_faceted: SOFT sits at 12, between shipped 5.8 and W1's 25, and its comment says W1 is its least mutant. kitbash, kitbash_assembly, kitbash_pose, mesh_polish, rig: check() takes a detail the result file cannot, and the CHECK lines are printed before the file is written. kitbash, kitbash_assembly: the action table is also held against the operators the add-on registered, so a row lost from the table fails live. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 9 + .../brokkr_kitbash/brokkr_actions.json | 2 +- surfaces/blender/brokkr_kitbash/core.py | 37 ++++ surfaces/blender/docs/kitbash.md | 36 +++- surfaces/blender/tests/live/kitbash.py | 10 +- .../blender/tests/live/kitbash_assembly.py | 10 +- .../blender/tests/live/kitbash_faceted.py | 46 ++++- .../tests/live/kitbash_faceted.result.json | 18 +- surfaces/blender/tests/live/kitbash_pose.py | 6 +- surfaces/blender/tests/live/mesh_polish.py | 6 +- .../tests/live/mesh_polish.result.json | 189 ++++-------------- surfaces/blender/tests/live/rig.py | 6 +- surfaces/blender/tests/live/rig.result.json | 10 +- surfaces/blender/tests/test_kitbash.py | 28 +++ 14 files changed, 225 insertions(+), 188 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 6dfab56..c557c76 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1355,7 +1355,16 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): corners = built.V[built.faces.reshape(-1, 4)] facing = np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]).sum(axis=0) # twice the quads' vector areas, summed cancels = np.linalg.norm(facing) <= 1e-9 * np.linalg.norm(np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]), axis=1).sum() + pairs, depths, ridges, weights = core.fold_depths(built, self.levels) + behind, front = 0.5 * (1.0 - self.offset), 0.5 * (1.0 + self.offset) # the wall's share behind the designed surface, and in front of it + with np.errstate(divide="ignore"): + onsets = depths / np.where(ridges, behind, front) # the thickness at which each cage edge's concave side holds its fold depth + first = int(onsets.argmin()) if len(onsets) and np.isfinite(onsets.min()) else None + fold = None if first is None else { + "onset": round(float(onsets[first]), 6), "margin": round(float(onsets[first]) / self.thickness, 4), + "edge": [[int(v) // built.points, int(v) % built.points] for v in pairs[first]], "weight": round(float(weights[first]), 6)} return {"object": obj.name, "rebuilt": rebuilt, "rings": built.rings, "points": built.points, "cageFaces": cage_faces, "creases": len(built.creases), + "fold": fold, "corners": len(built.corners), "subdividedFaces": cage_faces * 4 ** self.levels, "facing": None if cancels else [round(float(v), 6) for v in facing / np.linalg.norm(facing)], "thickness": round(self.thickness, 6), "offset": round(self.offset, 6), "levels": self.levels, "children": sorted(child.name for child in obj.children)} diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 2b5face..f286fd1 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -719,7 +719,7 @@ }, { "name": "brokkr_kitbash.shell", - "doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings, points, cageFaces, creases, corners, subdividedFaces, facing, thickness, offset, levels and children.", + "doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings, points, cageFaces, creases, fold ({onset, margin, edge, weight}: the thickness at which the cage says the wall first folds over itself beside an edge, onset over the thickness asked, the edge as two [ring, point] and its crease; null where no edge can fold; an estimate from the cage, margin under 1 is a folded wall), corners, subdividedFaces, facing, thickness, offset, levels and children.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index d6156c9..f932bd5 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1134,6 +1134,43 @@ def sheet(document: Any) -> Sheet: corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N) +def fold_depths(built: Sheet, levels: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Where an even wall on a shell's cage would fold, from the cage alone: for every cage edge between two quads, + (pairs (E, 2) of vertex indices, depth (E,), ridge (E,), weight (E,)). depth is the wall depth on the edge's + concave side at which the wall's far face first folds over itself beside the edge when the edge is a full + crease between flat facets: (W / 2^levels) / tan(phi), W the lesser perpendicular reach of the two quads from + the edge (the narrower facet binds) and phi half the angle between their normals; infinite where they are + coplanar. ridge: the facets fall away from their normals, so the concave side is behind the surface (a wall + grown inward); else it is in front. weight is the edge's crease, 0 where it has none: under a full crease a + softer edge folds later than its depth, never sooner.""" + quads = built.faces.reshape(-1, 4) + V = built.V + normals = np.cross(V[quads[:, 2]] - V[quads[:, 0]], V[quads[:, 3]] - V[quads[:, 1]]) + normals /= np.linalg.norm(normals, axis=1)[:, None] + centres = V[quads].mean(axis=1) + sides = {} + for face, quad in enumerate(quads): + for k in range(4): + a, b = int(quad[k]), int(quad[(k + 1) % 4]) + sides.setdefault((min(a, b), max(a, b)), []).append((face, int(quad[(k + 2) % 4]), int(quad[(k + 3) % 4]))) + creased = {(int(a), int(b)): float(w) for (a, b), w in zip(built.creases, built.weights)} + pairs, depths, ridges, weights = [], [], [], [] + for (a, b), faces in sorted(sides.items()): + if len(faces) != 2: + continue + along = V[b] - V[a] + along /= np.linalg.norm(along) + reach = min(float(np.linalg.norm((V[v] - V[a]) - along * ((V[v] - V[a]) @ along))) for _, c, d in faces for v in (c, d)) + (f0, _, _), (f1, _, _) = faces + middle = 0.5 * (V[a] + V[b]) + phi = 0.5 * math.acos(float(np.clip(normals[f0] @ normals[f1], -1.0, 1.0))) + pairs.append((a, b)) + depths.append(reach / 2 ** levels / math.tan(phi) if phi > 1e-9 else math.inf) + ridges.append(bool(normals[f0] @ (centres[f1] - middle) + normals[f1] @ (centres[f0] - middle) < 0)) + weights.append(creased.get((a, b), 0.0)) + return np.array(pairs, dtype=np.int64).reshape(-1, 2), np.array(depths), np.array(ridges, dtype=bool), np.array(weights) + + # --- reports ------------------------------------------------------------------------------------------------- def rows(matrix) -> list[list[float]]: diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 7b3816b..32fea95 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -351,8 +351,9 @@ The object carries the cage, `crease_edge` and `crease_vert`, and the modifiers used) then `Kit Solidify` (`thickness`, `offset`, even, rim filled), then any Booleans `cut` adds, then the `Kit Bevel` when `bevel` is over 0. `kit_shell` on it is the request, and it owns the cage as `kit_params` owns a part's mesh: an edit of the cage by hand is lost at the next `shell` call. `shell` reports `object`, `rebuilt`, -`rings`, `points`, `cageFaces`, `creases` (edges with a weight over 0), `corners`, `subdividedFaces`, `facing`, -`thickness`, `offset`, `levels` and `children`, all facts of the cage: it reads no evaluated mesh. +`rings`, `points`, `cageFaces`, `creases` (edges with a weight over 0), `fold` (see Thickness at a crease), +`corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`, all facts of the cage: it +reads no evaluated mesh. **Rebuilding.** `shell` on a name that is already a shell rewrites its cage in place. The object, its mesh datablock, its material slots, its cutters, its ribs and its Booleans stay, so a plate can be reshaped after it is @@ -372,14 +373,27 @@ it; a rib deeper than the room a tight crease leaves is refused with the size to hold: it reads no evaluated mesh, and the limit is a fact of the subdivided one. Even thickness moves a vertex on a full crease along the crease's bisector, which slides it `thickness` x tan(phi) across each facet, phi being half the angle between the two facets' normals; the vertices beside it move straight in. Where that slide is longer than -the first row of subdivided faces, the wall's inner face folds over itself beside the crease: at a `thickness` over -(W / 2^`levels`) / tan(phi), W the facet's width across the crease. Measured on a ridge of two flat facets under a -wall grown inward, a crease of 1.0: the fold starts at 1.00 of that figure in 13 readings (W 1 and 0.4; phi 30, 45, -60; levels 1 to 3), which is 0.217 for W 1, phi 30, levels 3, and 0.029 for W 0.4, phi 60, levels 3. A crease of -0.5 folds at 1.02 to 1.3 of it, and an uncreased ridge folds too, at 1.1 to 4.2 of it. The fold is inside the -wall and one subdivided row wide: the designed surface is unchanged and the mesh has no open or non-manifold -edge, but the solid passes through itself there, and a cut through that place is untested. Keep `thickness` -under the figure where a creased plate is cut near its crease: a thinner wall, fewer `levels`, or wider facets. +the first row of subdivided faces, the wall's far face folds over itself beside the crease: at a wall depth over +(W / 2^`levels`) / tan(phi), W the width across the crease of the narrower of its two facets. The fold is on the +crease's concave side: behind a ridge, so under a wall grown inward, and in front of a valley, under a wall grown +outward; the two read the same. Measured on two flat facets, a crease of 1.0: the fold starts at 1.00 of that +figure in 23 of 23 readings (W 1 and 0.4; phi 15 to 60; levels 1 to 3; a ridge and a valley), which is 0.217 for W +1, phi 30, levels 3, and 0.029 for W 0.4, phi 60, levels 3. Facets 1.0 and 0.3 wide at phi 45, levels 2, fold at +0.075, the narrow facet's figure, not the wide one's 0.25. A crease of 0.5 folds at 1.02 to 1.32 of it, and an +uncreased edge folds too, at 1.17 to 4.2 of it. The fold is inside the wall and one subdivided row wide: the +designed surface is unchanged and the mesh has no open or non-manifold edge, but the solid passes through itself +there, and a cut through that place is untested. + +`shell` reports this at the call, from the cage: `fold` is `{onset, margin, edge, weight}`, or null where no cage +edge has a wall on its concave side. `onset` is the least `thickness` at which the figure above says some cage edge +folds, every edge between two quads taken as a full crease between flat facets, and the wall's share on that edge's +concave side taken from `offset`; `margin` is `onset` over the `thickness` asked, so under 1 the wall is expected to +fold; `edge` is that edge as two `[ring, point]` (points as built: 2C - 1 on a mirrored ring), and `weight` its +crease. It is an estimate: a `weight` under 1 folds later than `onset`, and where a crease runs out to the rim +through a tapering quad the wall can fold sooner. On the Seraph's fourteen creased plates the evaluated wall first +folded at 0.74 to 1.2 of `onset` in thirteen and at 2.6 of it in one, whose binding edge had a crease of 0.6 +(`experiments/mechs`, 2026-12-02). Keep `margin` over about 1.4 where a plate is cut near a crease, with a thinner +wall, fewer `levels` or wider facets, and count the turned inner faces of the evaluated wall when it matters. Refused, each before anything is written and naming the field and index: a missing or unknown key; a non-finite number; fewer than 2 or more than 64 rings or points; rings of unequal counts; a quad under 1e-8 m2 (a collapsed @@ -584,7 +598,7 @@ vertices overflow. | `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | -| `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | +| `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `fold` (`{onset, margin, edge, weight}`: the thickness at which the cage says the wall first folds beside an edge, or null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored value (`set_params`). A value outside its bounds is refused with the bounds in the message. diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 609051a..d3d94e2 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -51,9 +51,15 @@ R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_ COUNT = [0] # the rows the add-on's action table names, in its order: what the host must load, whatever rows the table grows TABLE = [row["name"] for row in json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))["actions"]] +# the operators the add-on registered: each is an action the table must have a row for, so a row lost from the table is seen +OPERATORS = sorted(f"brokkr_kitbash.{name}" for name in dir(bpy.ops.brokkr_kitbash)) def check(name, ok, detail=None): + try: + json.dumps(detail, default=str) + except TypeError: # a detail keyed by tuples: the result file takes it as text, so a failed check is written and not a crash + detail = repr(detail) R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised @@ -76,7 +82,7 @@ def extent(obj, axis=2): check("the kitbash rows load as host actions with no errors", not R["hostErrors"] - and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == TABLE != [], [R["hostErrors"], R["hostRows"]]) + and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == TABLE != [] and sorted(TABLE) == OPERATORS, [R["hostErrors"], R["hostRows"], OPERATORS]) # --- describe --------------------------------------------------------------------------------------------------------- kit = core.load_kit("mechanical") @@ -255,7 +261,7 @@ check("exportGltf of all eleven parts succeeds", receipt["status"] == "accepted" R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]} for name, report in placed.items() if report} R["ok"] = all(c["ok"] for c in R["checks"]) -Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 5e73eac..805e576 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -61,6 +61,8 @@ R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_ COUNT = [0] # the rows the add-on's action table names, in its order: what the host must load, whatever rows the table grows TABLE = [row["name"] for row in json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))["actions"]] +# the operators the add-on registered: each is an action the table must have a row for, so a row lost from the table is seen +OPERATORS = sorted(f"brokkr_kitbash.{name}" for name in dir(bpy.ops.brokkr_kitbash)) kit = core.load_kit("mechanical") # Metres (or a difference of unit vectors) between where a seated socket is and where its mate puts it, read from # the two world matrices. Shipped worst 1.5e-07 (float32 matrices, parts a few metres from the origin); least @@ -86,6 +88,10 @@ NUDGE = 3.2e-4 def check(name, ok, detail=None): + try: + json.dumps(detail, default=str) + except TypeError: # a detail keyed by tuples: the result file takes it as text, so a failed check is written and not a crash + detail = repr(detail) R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised @@ -178,7 +184,7 @@ def evaluated(obj): rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] -check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == TABLE != [], [R["hostErrors"], rows]) +check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == TABLE != [] and sorted(TABLE) == OPERATORS, [R["hostErrors"], rows, OPERATORS]) # --- attach ------------------------------------------------------------------------------------------------------------- tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088 @@ -709,8 +715,8 @@ check("and each face keeps its own slot: the cutter's brass faces are brass, the R["ok"] = all(c["ok"] for c in R["checks"]) R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} -Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") print("READINGS", R["readings"], flush=True) sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_faceted.py b/surfaces/blender/tests/live/kitbash_faceted.py index 90f018b..4d04ed4 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.py +++ b/surfaces/blender/tests/live/kitbash_faceted.py @@ -68,11 +68,11 @@ WALL = 0.06 # mean, separation 2.8 each side. CRISP = 18.0 # Degrees: the largest dihedral angle across a subdivided edge that carries no crease. Shipped 5.8; least claimed -# mutant 51 (C1, a Subdivision that only splits, SIMPLE: every cage edge stays an edge); the geometric mean, separation -# 3 each side. S1 reads 6.5 here, 1.13 of shipped: CRISP claims it. -# W1 (the weights written at the creases' own indices, not at the edges found by vertex pair) reads 25 here and is -# claimed by the exact check below, crease_edge edge for edge: it has no bound to sit under. -SOFT = 17.0 +# mutant 25 (W1, the weights written at the creases' own indices, not at the edges found by vertex pair: a crease +# lands on an edge that should have none); the geometric mean, separation 2.07 each side. C1 (a Subdivision that only +# splits, SIMPLE: every cage edge stays an edge) reads 51 here. S1 reads 6.5, 1.13 of shipped: CRISP claims it. W1 is +# also caught by the exact check below, crease_edge edge for edge. +SOFT = 12.0 # Metres from a corner of a sheet whose rim is 0 to the nearest vertex of its subdivided surface: with corners preserved # the surface keeps the cage's corner. Shipped 0 (read as 1e-7, what a float32 mesh is good to); least claimed mutant # 0.15 (S5, boundary_smooth ALL: the corner rounds off); the geometric mean, separation 900 each side. @@ -84,6 +84,11 @@ SOLID = 0.0313 # Metres between the thickness and the distance from a vertex of the wall's inner face to the designed surface. Shipped # 0.0001 (a float32 mesh under three levels of subdivision); least claimed mutant 0.024 (S6: the inner face is subdivided again and pulls in); the geometric mean, separation 15 each side. EVEN = 1.5e-3 +# Metres: the thickness at which the wedge of shell-fold folds, (W / 2^levels) / tan(phi) of its narrower facet. The +# wall is built at FOLD / FOLD_STEP (no inner face turned) and at FOLD x FOLD_STEP (some turned). Least claimed mutant: +# F1, the wider facet's reach taken (max for min in core.fold_depths), which reads 0.25, 3.3 of shipped; FOLD_STEP is +# the 1.2 separation the margin rule asks on each side of the onset. +FOLD, FOLD_STEP = 0.075, 1.2 def check(name, ok, detail=None): @@ -208,7 +213,7 @@ try: and sorted(stored) == ["bevel", "levels", "offset", "sheet", "thickness"] and stored["sheet"] == PAULDRON and (stored["levels"], stored["offset"]) == (3, -1.0) and abs(stored["thickness"] - WALL) < 1e-7, [receipt["message"], stored]) check("shell reports cage facts: rings, points, quads, creased edges, the subdivided count, an upward facing, no children", - report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"] + report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "fold", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"] and (report["object"], report["rebuilt"], report["rings"], report["points"], report["cageFaces"], report["creases"], report["corners"], report["subdividedFaces"], report["levels"], report["thickness"], report["offset"], report["children"]) == ("Pauldron", False, 6, 6, 25, 25, 0, 1600, 3, 0.06, -1.0, []) and report["facing"][2] > 0.5 and abs(np.linalg.norm(report["facing"]) - 1.0) < 1e-5, report) @@ -247,6 +252,35 @@ try: surface.free() check("shell-crisp: a sheet whose rim is soft keeps its four corners", R["readings"]["corner"] < CORNER, R["readings"]) + # --- shell-fold: the receipt's fold onset, against the evaluated wall --------------------------------------------------------- + section("shell-fold") + # a ridge of two flat facets 0.3 and 1.0 wide, each tilted 45 degrees, full crease, levels 2: the narrower facet binds, (0.3 / 4) / tan 45 = 0.075 + wedge = {"rings": [[[-1.0 * math.sqrt(0.5), y, -1.0 * math.sqrt(0.5)], [0.0, y, 0.0], [0.3 * math.sqrt(0.5), y, -0.3 * math.sqrt(0.5)]] for y in (0.0, 0.5, 1.0)], + "creases": [{"column": 1, "from": 0, "to": 2, "weight": 1.0}]} + + def folded(name, thickness, offset=-1.0): + """(the receipt's fold, inner faces of the evaluated wall whose normal runs with their outer face's).""" + _, told = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(wedge), thickness=thickness, offset=offset, levels=2) + wall_mesh = evaluated(bpy.data.objects[name]) + wall_mesh.faces.ensure_lookup_table() + count = len(bpy.data.objects[name].data.polygons) * 4 ** 2 # Solidify lists the outer faces, then their inner twins in the same order, then the rim + turned = sum(1 for k in range(count) if wall_mesh.faces[k].normal.dot(wall_mesh.faces[count + k].normal) > 0) + wall_mesh.free() + return told["fold"], turned + + under, over = folded("FoldUnder", FOLD / FOLD_STEP), folded("FoldOver", FOLD * FOLD_STEP) + reading("foldUnder", under[1]) + reading("foldOver", over[1], least=True) + check("shell-fold: the receipt names the fold onset of a creased ridge by its narrower facet, the margin and the edge, and the evaluated wall folds over it and not under it", + abs(under[0]["onset"] - FOLD) < 1e-6 and abs(under[0]["margin"] - FOLD_STEP) < 1e-3 and abs(over[0]["margin"] - 1 / FOLD_STEP) < 1e-3 + and under[0]["edge"] in ([[0, 1], [1, 1]], [[1, 1], [2, 1]]) and under[0]["weight"] == 1.0 and under[1] == 0 and over[1] > 0, [under, over]) + outward = folded("FoldOut", 0.3, offset=1.0) + half = folded("FoldHalf", FOLD / FOLD_STEP, offset=0.0) + check("shell-fold: a ridge under a wall grown outward has no fold to name, and a wall half behind the surface holds twice the thickness", + outward == (None, 0) and abs(half[0]["onset"] - 2 * FOLD) < 1e-6 and half[1] == 0, [outward, half]) + for name in ("FoldUnder", "FoldOver", "FoldOut", "FoldHalf"): + bpy.data.objects.remove(bpy.data.objects[name]) + # --- shell-solid ------------------------------------------------------------------------------------------------------------ section("shell-solid") pauldron.modifiers["Kit Bevel"].show_viewport = False # the wall alone: a bevel rounds its edges diff --git a/surfaces/blender/tests/live/kitbash_faceted.result.json b/surfaces/blender/tests/live/kitbash_faceted.result.json index f1594a2..5523476 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.result.json +++ b/surfaces/blender/tests/live/kitbash_faceted.result.json @@ -36,6 +36,16 @@ "ok": true, "detail": null }, + { + "name": "shell-fold: the receipt names the fold onset of a creased ridge by its narrower facet, the margin and the edge, and the evaluated wall folds over it and not under it", + "ok": true, + "detail": null + }, + { + "name": "shell-fold: a ridge under a wall grown outward has no fold to name, and a wall half behind the surface holds twice the thickness", + "ok": true, + "detail": null + }, { "name": "shell-solid: the plate is a closed wall of even thickness behind the designed surface, its rim filled", "ok": true, @@ -152,14 +162,16 @@ "corner": 1.8e-07, "crisp": 52.0, "even": 0.0001, + "foldOver": 8.0, + "foldUnder": 0.0, "ribsAcrossTheCrease": 1.0, "soft": 5.8, "solid": 0.027 }, "costs": { - "shell": 0.0036, - "evaluation": 0.0018, - "rebuildUnderCuts": 0.97 + "shell": 0.0074, + "evaluation": 0.0015, + "rebuildUnderCuts": 1.1 }, "creaseRibs": "Operator brokkr_kitbash.ribs finished.", "ok": true diff --git a/surfaces/blender/tests/live/kitbash_pose.py b/surfaces/blender/tests/live/kitbash_pose.py index 95d0b3d..de26a6f 100644 --- a/surfaces/blender/tests/live/kitbash_pose.py +++ b/surfaces/blender/tests/live/kitbash_pose.py @@ -84,6 +84,10 @@ EDGE, PAST = 1e-5, 3.2e-5 def check(name, ok, detail=None): + try: + json.dumps(detail, default=str) + except TypeError: # a detail keyed by tuples: the result file takes it as text, so a failed check is written and not a crash + detail = repr(detail) R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) # what was seen, when it was not what was promised @@ -304,8 +308,8 @@ refused("an axis that is not one of the six, by the action table", "brokkr_kitba R["ok"] = all(c["ok"] for c in R["checks"]) R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} -Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") print("READINGS", R["readings"], flush=True) sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/mesh_polish.py b/surfaces/blender/tests/live/mesh_polish.py index 5659698..e86c3ee 100644 --- a/surfaces/blender/tests/live/mesh_polish.py +++ b/surfaces/blender/tests/live/mesh_polish.py @@ -47,6 +47,10 @@ RATIO_BOUND, DEFICIT_BOUND, SHADE_BOUND = 1.906, 0.136, 0.684 # each derived wh def check(name, ok, detail=None): + try: + json.dumps(detail, default=str) + except TypeError: # a detail keyed by tuples: the result file takes it as text, so a failed check is written and not a crash + detail = repr(detail) R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) @@ -421,7 +425,7 @@ for path in sorted(Path(HULLS).glob("*.glb")) if HULLS else []: bpy.data.objects.remove(hull) R["ok"] = all(c["ok"] for c in R["checks"]) -Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/mesh_polish.result.json b/surfaces/blender/tests/live/mesh_polish.result.json index afe1e82..ead0f7d 100644 --- a/surfaces/blender/tests/live/mesh_polish.result.json +++ b/surfaces/blender/tests/live/mesh_polish.result.json @@ -125,7 +125,7 @@ "undoLabel": "Brokkr test/driver: brokkr_mesh_polish.repair live-2", "lookPath": "", "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"facesCollapsedByWeld\":0,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0,\"windingFlipped\":0,\"customNormalsDropped\":false},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104}}", - "observedAt": "2026-12-01T01:10:29.202522+00:00" + "observedAt": "2026-12-02T11:45:23.730020+00:00" } }, { @@ -231,21 +231,21 @@ "Ball" ], "explainedByLight": { - "before": 0.9718638595466577, - "after": 0.0005166823179215685 + "before": 0.971864311889026, + "after": 0.0005166699920249318 }, "before": { "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0166067038538378, + "upDownLuminanceRatio": 1.0166056941702677, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9857558709602762, - "median": 1.457103285957073, - "max": 3.0649151172981792, + "min": 0.9857550779013501, + "median": 1.4570952973825366, + "max": 3.0649084607569628, "clamped": 0.0 } } @@ -374,21 +374,21 @@ "Twins" ], "explainedByLight": { - "before": 0.9999597575085393, - "after": 0.028075104342772272 + "before": 0.9999597575085379, + "after": 0.028075104345557378 }, "before": { "upDownLuminanceRatio": 1.0000084632254227, "occlusionCorrelation": 0.983967648279407 }, "after": { - "upDownLuminanceRatio": 0.9999964767503613, - "occlusionCorrelation": 0.40471079036691976 + "upDownLuminanceRatio": 0.9999964767501422, + "occlusionCorrelation": 0.4047107903549991 }, "gain": { - "min": 0.9999809983875252, - "median": 1.0000990920451596, - "max": 5.493916964800697, + "min": 0.9999809983874741, + "median": 1.0000990920454487, + "max": 5.493916964791895, "clamped": 0.0 } }, @@ -572,15 +572,15 @@ 5.656854 ], "mirrorError": { - "X": 1.8120748396336225e-08, + "X": 1.8120748391154895e-08, "Y": 0.1508370330678463, - "Z": 1.8363068583553207e-08 + "Z": 1.836306858436306e-08 } }, "knobPivot": [ 1.407290284305418e-09, 1.0, - -1.8218171415895767e-09 + -1.8218169195449718e-09 ], "knobReach": 3.0, "parent": "Block.body" @@ -653,72 +653,6 @@ "name": "a bound miss is denied by Brokkr's table before the operator runs", "ok": true, "detail": "max_gain must be between 1 and 8." - }, - { - "name": "hull fourth.glb: repair turns no face and keeps the shading normals' sides", - "ok": true, - "detail": { - "polygons": 28426, - "polygonsAfter": 28420, - "turned": null, - "againstBefore": 388, - "againstAfter": 387, - "changes": { - "welded": 6437, - "facesCollapsedByWeld": 2, - "degenerateFacesRemoved": 4, - "looseEdgesRemoved": 0, - "looseVertsRemoved": 0, - "shellsRemoved": 0, - "holesFilled": 0, - "windingFlipped": 0, - "customNormalsDropped": false - } - } - }, - { - "name": "hull sub.glb: repair turns no face and keeps the shading normals' sides", - "ok": true, - "detail": { - "polygons": 10406, - "polygonsAfter": 10406, - "turned": 0, - "againstBefore": 64, - "againstAfter": 64, - "changes": { - "welded": 2454, - "facesCollapsedByWeld": 0, - "degenerateFacesRemoved": 0, - "looseEdgesRemoved": 0, - "looseVertsRemoved": 0, - "shellsRemoved": 0, - "holesFilled": 0, - "windingFlipped": 0, - "customNormalsDropped": false - } - } - }, - { - "name": "hull third.glb: repair turns no face and keeps the shading normals' sides", - "ok": true, - "detail": { - "polygons": 23341, - "polygonsAfter": 23340, - "turned": null, - "againstBefore": 189, - "againstAfter": 189, - "changes": { - "welded": 3810, - "facesCollapsedByWeld": 0, - "degenerateFacesRemoved": 1, - "looseEdgesRemoved": 0, - "looseVertsRemoved": 0, - "shellsRemoved": 0, - "holesFilled": 0, - "windingFlipped": 0, - "customNormalsDropped": false - } - } } ], "hostErrors": [], @@ -744,21 +678,21 @@ "Ball" ], "explainedByLight": { - "before": 0.9718638595466577, - "after": 0.0005166823179215685 + "before": 0.971864311889026, + "after": 0.0005166699920249318 }, "before": { "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0166067038538378, + "upDownLuminanceRatio": 1.0166056941702677, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9857558709602762, - "median": 1.457103285957073, - "max": 3.0649151172981792, + "min": 0.9857550779013501, + "median": 1.4570952973825366, + "max": 3.0649084607569628, "clamped": 0.0 } }, @@ -804,21 +738,21 @@ "Twins" ], "explainedByLight": { - "before": 0.9999597575085393, - "after": 0.028075104342772272 + "before": 0.9999597575085379, + "after": 0.028075104345557378 }, "before": { "upDownLuminanceRatio": 1.0000084632254227, "occlusionCorrelation": 0.983967648279407 }, "after": { - "upDownLuminanceRatio": 0.9999964767503613, - "occlusionCorrelation": 0.40471079036691976 + "upDownLuminanceRatio": 0.9999964767501422, + "occlusionCorrelation": 0.4047107903549991 }, "gain": { - "min": 0.9999809983875252, - "median": 1.0000990920451596, - "max": 5.493916964800697, + "min": 0.9999809983874741, + "median": 1.0000990920454487, + "max": 5.493916964791895, "clamped": 0.0 } }, @@ -880,15 +814,15 @@ 5.656854 ], "mirrorError": { - "X": 1.8120748396336225e-08, + "X": 1.8120748391154895e-08, "Y": 0.1508370330678463, - "Z": 1.8363068583553207e-08 + "Z": 1.836306858436306e-08 } }, "knobPivot": [ 1.407290284305418e-09, 1.0, - -1.8218171415895767e-09 + -1.8218169195449718e-09 ], "knobReach": 3.0, "parent": "Block.body" @@ -908,61 +842,6 @@ "inkInsideBefore": 192, "inkInsideAfter": 0 }, - "hulls": { - "fourth.glb": { - "polygons": 28426, - "polygonsAfter": 28420, - "turned": null, - "againstBefore": 388, - "againstAfter": 387, - "changes": { - "welded": 6437, - "facesCollapsedByWeld": 2, - "degenerateFacesRemoved": 4, - "looseEdgesRemoved": 0, - "looseVertsRemoved": 0, - "shellsRemoved": 0, - "holesFilled": 0, - "windingFlipped": 0, - "customNormalsDropped": false - } - }, - "sub.glb": { - "polygons": 10406, - "polygonsAfter": 10406, - "turned": 0, - "againstBefore": 64, - "againstAfter": 64, - "changes": { - "welded": 2454, - "facesCollapsedByWeld": 0, - "degenerateFacesRemoved": 0, - "looseEdgesRemoved": 0, - "looseVertsRemoved": 0, - "shellsRemoved": 0, - "holesFilled": 0, - "windingFlipped": 0, - "customNormalsDropped": false - } - }, - "third.glb": { - "polygons": 23341, - "polygonsAfter": 23340, - "turned": null, - "againstBefore": 189, - "againstAfter": 189, - "changes": { - "welded": 3810, - "facesCollapsedByWeld": 0, - "degenerateFacesRemoved": 1, - "looseEdgesRemoved": 0, - "looseVertsRemoved": 0, - "shellsRemoved": 0, - "holesFilled": 0, - "windingFlipped": 0, - "customNormalsDropped": false - } - } - }, + "hulls": {}, "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/live/rig.py b/surfaces/blender/tests/live/rig.py index 09c4396..a3c665c 100644 --- a/surfaces/blender/tests/live/rig.py +++ b/surfaces/blender/tests/live/rig.py @@ -56,6 +56,10 @@ T0 = time.time() def check(name, ok, detail=None): + try: + json.dumps(detail, default=str) + except TypeError: # a detail keyed by tuples: the result file takes it as text, so a failed check is written and not a crash + detail = repr(detail) R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) @@ -332,7 +336,7 @@ check("and leaves the skin as body made it, with no chain bones", ball_weights() and not any("rig_chain" in b for b in bpy.data.objects["Ball.rig"].data.bones), None) R["ok"] = all(c["ok"] for c in R["checks"]) -Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/rig.result.json b/surfaces/blender/tests/live/rig.result.json index 9cc1424..91255bf 100644 --- a/surfaces/blender/tests/live/rig.result.json +++ b/surfaces/blender/tests/live/rig.result.json @@ -197,8 +197,8 @@ }, { "bone": "spine_04", - "before": 0.106817, - "after": 0.074496 + "before": 0.107081, + "after": 0.07411 } ], "shrunkMax": 0.6571, @@ -210,7 +210,7 @@ { "name": "exportGltf accepted", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-l9ustbpi\\whale.glb (301188 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-s67r7hee\\whale.glb (301168 bytes)." }, { "name": "VRMC_springBone is in extensions and extensionsUsed", @@ -630,8 +630,8 @@ }, { "bone": "spine_04", - "before": 0.106817, - "after": 0.074496 + "before": 0.107081, + "after": 0.07411 } ], "shrunkMax": 0.6571, diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index ab0d8c5..3faf4d3 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1558,6 +1558,34 @@ class SheetTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, r"\.to must be a whole number from 0 to 3, not 4"): core.sheet({**closed, "creases": [{"ring": 0, "from": 0, "to": 4, "weight": 1}]}) + def test_fold_depths_are_the_narrower_facets_first_row_over_the_tangent(self): + """A ridge of two flat facets 1.0 and 0.3 wide, each tilted 45 degrees: the crease's fold depth is + (0.3 / 2^levels) / tan 45, the narrower facet's (F1: the wider facet's reach reads 0.25 at levels 2); the + facets fall away from their normals, a ridge, and turned over they are a valley; coplanar facets never fold.""" + h = math.sqrt(0.5) + + def wedge(sign, flat=False): + return core.sheet({"rings": [[[-h, y, 0.0 if flat else -sign * h], [0.0, y, 0.0], [0.3 * h, y, 0.0 if flat else -sign * 0.3 * h]] for y in (0.0, 0.5, 1.0)], + "creases": [{"column": 1, "from": 0, "to": 2, "weight": 1.0}]}) + + pairs, depths, ridges, weights = core.fold_depths(wedge(1), 2) + crease = [k for k, pair in enumerate(pairs.tolist()) if pair in ([1, 4], [4, 7])] + self.assertEqual(len(pairs), 4) # the two crease edges and the middle ring's edge on each facet: an edge of the rim has one quad and no fold + self.assertEqual(len(crease), 2) + for k in crease: + self.assertAlmostEqual(depths[k], 0.075, places=12) + self.assertTrue(ridges[k]) + self.assertEqual(weights[k], 1.0) + self.assertTrue(all(math.isinf(depths[k]) and weights[k] == 0.0 for k in range(len(pairs)) if k not in crease)) # an edge inside a flat facet + self.assertAlmostEqual(core.fold_depths(wedge(1), 3)[1][crease[0]], 0.0375, places=12) # a level more halves the first row + valley = core.fold_depths(wedge(-1), 2) + self.assertAlmostEqual(valley[1][crease[0]], 0.075, places=12) + self.assertFalse(valley[2][crease[0]]) + self.assertTrue(np.isinf(core.fold_depths(wedge(1, flat=True), 2)[1]).all()) + steep = core.sheet({"rings": [[[-0.5, y, -math.sqrt(0.75)], [0.0, y, 0.0], [0.5, y, -math.sqrt(0.75)]] for y in (0.0, 1.0)]}) # facets 60 degrees off level, no crease stated + self.assertAlmostEqual(core.fold_depths(steep, 1)[1][0], 0.5 / math.tan(math.radians(60)), places=12) + self.assertEqual(core.fold_depths(steep, 1)[3][0], 0.0) + ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", From d3c68edf79ee10952557a9416fc98a451a009532 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 13:29:46 +0100 Subject: [PATCH 106/223] live kitbash, kitbash_assembly, kitbash_pose, mesh_polish, rig: the checks run inside one try An error raised between checks is a failed check that names the check before it; the checks are printed and the result file written whatever happened, and the exit is 1 with or without --python-exit-code. A rig.py copy with a raise after 35 checks, launched bare: exit 1, 35 ok and 1 FAIL printed, result file written (was exit 0 and no CHECK line). Finding: aetheria-release:finding:cut-kit-faceted-shell.s3.midsuite-raise-hides-checks Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/kitbash.py | 341 +++--- .../blender/tests/live/kitbash_assembly.py | 1018 +++++++++-------- surfaces/blender/tests/live/kitbash_pose.py | 262 ++--- surfaces/blender/tests/live/mesh_polish.py | 610 +++++----- .../tests/live/mesh_polish.result.json | 66 +- surfaces/blender/tests/live/rig.py | 334 +++--- surfaces/blender/tests/live/rig.result.json | 2 +- 7 files changed, 1332 insertions(+), 1301 deletions(-) diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index d3d94e2..6b03a2e 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -5,13 +5,16 @@ assignMaterial, set_params, report, the refusals, and exportGltf. Not part of th blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash.py -- Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses -without them). Writes .result.json and exits 1 when a check failed. +without them). Writes .result.json and exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names +the check before it, the checks are printed and the result file written whatever happened, and the exit is 1 with or +without --python-exit-code. """ import importlib.util import json import math import os import sys +import traceback import tempfile import types from pathlib import Path @@ -81,185 +84,189 @@ def extent(obj, axis=2): return float(co[:, axis].max() - co[:, axis].min()) -check("the kitbash rows load as host actions with no errors", not R["hostErrors"] - and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == TABLE != [] and sorted(TABLE) == OPERATORS, [R["hostErrors"], R["hostRows"], OPERATORS]) +try: + check("the kitbash rows load as host actions with no errors", not R["hostErrors"] + and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == TABLE != [] and sorted(TABLE) == OPERATORS, [R["hostErrors"], R["hostRows"], OPERATORS]) -# --- describe --------------------------------------------------------------------------------------------------------- -kit = core.load_kit("mechanical") -receipt, described = send("brokkr_kitbash.describe") -names = [p["name"] for p in described["parts"]] if described else [] -check("describe lists eleven parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 11 - and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")]) -receipt, one = send("brokkr_kitbash.describe", part="actuator") -check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"] - and [p["name"] for p in one["parts"][0]["params"]] == ["body_r", "body_len", "rod_r", "extension", "segments"] - and one["parts"][0]["sockets"] == core.socket_rows(core.build(kit["parts"]["actuator"]).sockets), one) -check("describe changes nothing", len(bpy.data.objects) == 0 and len(bpy.data.meshes) == 0, [len(bpy.data.objects), len(bpy.data.meshes)]) + # --- describe --------------------------------------------------------------------------------------------------------- + kit = core.load_kit("mechanical") + receipt, described = send("brokkr_kitbash.describe") + names = [p["name"] for p in described["parts"]] if described else [] + check("describe lists eleven parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 11 + and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")]) + receipt, one = send("brokkr_kitbash.describe", part="actuator") + check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"] + and [p["name"] for p in one["parts"][0]["params"]] == ["body_r", "body_len", "rod_r", "extension", "segments"] + and one["parts"][0]["sockets"] == core.socket_rows(core.build(kit["parts"]["actuator"]).sockets), one) + check("describe changes nothing", len(bpy.data.objects) == 0 and len(bpy.data.meshes) == 0, [len(bpy.data.objects), len(bpy.data.meshes)]) -# --- place every part at default ----------------------------------------------------------------------------------------- -placed = {} -for index, name in enumerate(names): - receipt, report = send("brokkr_kitbash.place_part", part=name, object_name=f"P_{name}") - obj = bpy.data.objects.get(f"P_{name}") - reference = core.build(kit["parts"][name]) - faces = len(obj.data.polygons) if obj else -1 - clean = obj is not None and not obj.data.validate(verbose=False) - flat = np.zeros(max(faces, 0), dtype=bool) - if obj: - obj.data.attributes["sharp_face"].data.foreach_get("value", flat) - crease = obj.data.attributes.get("sharp_edge") if obj else None - creased = np.zeros(len(obj.data.edges) if crease else 0, dtype=bool) - if crease: - crease.data.foreach_get("value", creased) - marked = sorted(tuple(sorted(edge.vertices)) for edge, on in zip(obj.data.edges, creased) if on) if crease else None - check(f"place_part {name}: sharp_edge is true on exactly core's sharp edges ({len(reference.sharp)})", - marked == sorted(tuple(sorted(pair)) for pair in reference.sharp.tolist()), [marked and len(marked), len(reference.sharp)]) - bevel = obj.modifiers.get("Kit Bevel") if obj else None - evaluated = len(obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) if obj else -1 - placed[name] = report - check(f"place_part {name}: core's faces, a valid mesh, core's flat faces, at the origin", receipt["status"] == "accepted" and report - and faces == len(reference.counts) == report["faces"] and clean and report["shells"] == reference.shell_count - and flat.tolist() == (~reference.smooth).tolist() and list(obj.location) == [0.0, 0.0, 0.0] - and np.allclose(np.array([v.co[:] for v in obj.data.vertices]), reference.V, atol=1e-6), - [receipt["message"], faces, len(reference.counts), clean]) - check(f"place_part {name}: a Bevel of the part's width, 2 segments, angle 30, that evaluates", bevel is not None - and abs(bevel.width - reference.bevel) < 1e-7 and bevel.segments == 2 and bevel.limit_method == "ANGLE" - and abs(bevel.angle_limit - math.radians(30)) < 1e-6 and evaluated > faces, [bevel and bevel.width, reference.bevel, evaluated, faces]) - check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None - and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"] - and report["sockets"] == core.socket_rows(reference.sockets), report) -check("eleven parts are eleven mesh objects", len(bpy.data.objects) == 11 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) + # --- place every part at default ----------------------------------------------------------------------------------------- + placed = {} + for index, name in enumerate(names): + receipt, report = send("brokkr_kitbash.place_part", part=name, object_name=f"P_{name}") + obj = bpy.data.objects.get(f"P_{name}") + reference = core.build(kit["parts"][name]) + faces = len(obj.data.polygons) if obj else -1 + clean = obj is not None and not obj.data.validate(verbose=False) + flat = np.zeros(max(faces, 0), dtype=bool) + if obj: + obj.data.attributes["sharp_face"].data.foreach_get("value", flat) + crease = obj.data.attributes.get("sharp_edge") if obj else None + creased = np.zeros(len(obj.data.edges) if crease else 0, dtype=bool) + if crease: + crease.data.foreach_get("value", creased) + marked = sorted(tuple(sorted(edge.vertices)) for edge, on in zip(obj.data.edges, creased) if on) if crease else None + check(f"place_part {name}: sharp_edge is true on exactly core's sharp edges ({len(reference.sharp)})", + marked == sorted(tuple(sorted(pair)) for pair in reference.sharp.tolist()), [marked and len(marked), len(reference.sharp)]) + bevel = obj.modifiers.get("Kit Bevel") if obj else None + evaluated = len(obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) if obj else -1 + placed[name] = report + check(f"place_part {name}: core's faces, a valid mesh, core's flat faces, at the origin", receipt["status"] == "accepted" and report + and faces == len(reference.counts) == report["faces"] and clean and report["shells"] == reference.shell_count + and flat.tolist() == (~reference.smooth).tolist() and list(obj.location) == [0.0, 0.0, 0.0] + and np.allclose(np.array([v.co[:] for v in obj.data.vertices]), reference.V, atol=1e-6), + [receipt["message"], faces, len(reference.counts), clean]) + check(f"place_part {name}: a Bevel of the part's width, 2 segments, angle 30, that evaluates", bevel is not None + and abs(bevel.width - reference.bevel) < 1e-7 and bevel.segments == 2 and bevel.limit_method == "ANGLE" + and abs(bevel.angle_limit - math.radians(30)) < 1e-6 and evaluated > faces, [bevel and bevel.width, reference.bevel, evaluated, faces]) + check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None + and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"] + and report["sockets"] == core.socket_rows(reference.sockets), report) + check("eleven parts are eleven mesh objects", len(bpy.data.objects) == 11 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) -# --- set_params keeps what is not derived -------------------------------------------------------------------------------- -reducer = bpy.data.objects["P_reducer"] -send("brokkr_kitbash.set_params", object_name="P_reducer", params="segments=12") -creased = np.zeros(len(reducer.data.edges), dtype=bool) -reducer.data.attributes["sharp_edge"].data.foreach_get("value", creased) -rings = [np.array([reducer.data.vertices[v].co[:] for edge, on in zip(reducer.data.edges, creased) if on for v in edge.vertices])] -check("the reducer's creases are its two cone rings, 24 edges each at 24 segments, and set_params writes them again: 12 each at 12", - len(core.build(kit["parts"]["reducer"]).sharp) == 48 and int(creased.sum()) == 24 - and sorted(set(np.round(np.linalg.norm(rings[0][:, :2], axis=1), 5).tolist())) == [0.05, 0.12], int(creased.sum())) -tank = bpy.data.objects["P_tank"] -send("setObjectTransform", targetObjectName="P_tank", location=[1.0, 2.0, 3.0], rotationEuler=[0.3, -0.2, 0.5], scale=[1.0, 1.0, 1.0]) -send("assignMaterial", targetObjectName="P_tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) -send("setObjectParent", targetObjectName="P_tank", parentObjectName="P_plate") -before = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name, - "materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers], - "faces": len(tank.data.polygons)} -receipt, grown = send("brokkr_kitbash.set_params", object_name="P_tank", params="length=1.8") -after = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name, - "materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers], - "faces": len(tank.data.polygons)} -check("set_params doubling the tank's length doubles its z extent", receipt["status"] == "accepted" and abs(before["z"] - 0.9) < 1e-6 - and abs(after["z"] - 1.8) < 1e-6, [before["z"], after["z"]]) -check("set_params keeps the mesh datablock, transform, parent, Bevel and the assigned material", before["parent"] == "P_plate" - and before["materials"] == ["Tank Paint"] and before["modifiers"] == ["Kit Bevel"] - and {k: v for k, v in after.items() if k != "z"} == {k: v for k, v in before.items() if k != "z"} and not tank.data.validate(verbose=False), [before, after]) -check("set_params stores the merged params and reports them", grown and json.loads(tank["kit_params"]) == grown["params"] - == {"radius": 0.22, "length": 1.8, "segments": 24}, grown) -receipt, wide = send("brokkr_kitbash.set_params", object_name="P_tank", params="radius=0.3; segments=12") -check("set_params overlays the stored params, and the Bevel width follows the part's bevel", wide and wide["params"] == {"radius": 0.3, "length": 1.8, "segments": 12} - and abs(tank.modifiers["Kit Bevel"].width - 0.008 * 0.3) < 1e-7 and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], wide["params"]).counts), - [wide and wide["params"], tank.modifiers["Kit Bevel"].width]) + # --- set_params keeps what is not derived -------------------------------------------------------------------------------- + reducer = bpy.data.objects["P_reducer"] + send("brokkr_kitbash.set_params", object_name="P_reducer", params="segments=12") + creased = np.zeros(len(reducer.data.edges), dtype=bool) + reducer.data.attributes["sharp_edge"].data.foreach_get("value", creased) + rings = [np.array([reducer.data.vertices[v].co[:] for edge, on in zip(reducer.data.edges, creased) if on for v in edge.vertices])] + check("the reducer's creases are its two cone rings, 24 edges each at 24 segments, and set_params writes them again: 12 each at 12", + len(core.build(kit["parts"]["reducer"]).sharp) == 48 and int(creased.sum()) == 24 + and sorted(set(np.round(np.linalg.norm(rings[0][:, :2], axis=1), 5).tolist())) == [0.05, 0.12], int(creased.sum())) + tank = bpy.data.objects["P_tank"] + send("setObjectTransform", targetObjectName="P_tank", location=[1.0, 2.0, 3.0], rotationEuler=[0.3, -0.2, 0.5], scale=[1.0, 1.0, 1.0]) + send("assignMaterial", targetObjectName="P_tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) + send("setObjectParent", targetObjectName="P_tank", parentObjectName="P_plate") + before = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name, + "materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers], + "faces": len(tank.data.polygons)} + receipt, grown = send("brokkr_kitbash.set_params", object_name="P_tank", params="length=1.8") + after = {"z": extent(tank), "mesh": tank.data.name, "basis": [list(r) for r in tank.matrix_basis], "parent": tank.parent and tank.parent.name, + "materials": [s.material and s.material.name for s in tank.material_slots], "modifiers": [m.name for m in tank.modifiers], + "faces": len(tank.data.polygons)} + check("set_params doubling the tank's length doubles its z extent", receipt["status"] == "accepted" and abs(before["z"] - 0.9) < 1e-6 + and abs(after["z"] - 1.8) < 1e-6, [before["z"], after["z"]]) + check("set_params keeps the mesh datablock, transform, parent, Bevel and the assigned material", before["parent"] == "P_plate" + and before["materials"] == ["Tank Paint"] and before["modifiers"] == ["Kit Bevel"] + and {k: v for k, v in after.items() if k != "z"} == {k: v for k, v in before.items() if k != "z"} and not tank.data.validate(verbose=False), [before, after]) + check("set_params stores the merged params and reports them", grown and json.loads(tank["kit_params"]) == grown["params"] + == {"radius": 0.22, "length": 1.8, "segments": 24}, grown) + receipt, wide = send("brokkr_kitbash.set_params", object_name="P_tank", params="radius=0.3; segments=12") + check("set_params overlays the stored params, and the Bevel width follows the part's bevel", wide and wide["params"] == {"radius": 0.3, "length": 1.8, "segments": 12} + and abs(tank.modifiers["Kit Bevel"].width - 0.008 * 0.3) < 1e-7 and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], wide["params"]).counts), + [wide and wide["params"], tank.modifiers["Kit Bevel"].width]) -# --- report: sockets in the world ------------------------------------------------------------------------------------------- -send("setObjectTransform", targetObjectName="P_pipe_fitting", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) -receipt, reported = send("brokkr_kitbash.report") # straight after the move, before anything here updates the view layer: the frames are already the moved ones -bpy.context.view_layer.update() -worst, listed = 0.0, [] -for entry in (reported or {}).get("parts", []): - obj = bpy.data.objects[entry["object"]] - listed.append(entry["object"]) - local = core.build(core.part(kit, entry["part"]), entry["params"]).sockets - world = np.array(obj.matrix_world) - for socket, mine in zip(entry["sockets"], local): - worst = max(worst, float(np.abs(np.array(socket["matrix"]) - world @ mine["matrix"]).max())) -check("report lists every kit part with socket frames equal to matrix_world times the local frame", receipt["status"] == "accepted" - and listed == sorted(f"P_{n}" for n in names) and worst < 1e-6, [listed, worst]) -receipt, single = send("brokkr_kitbash.report", object_name="P_tank") -tank_world = np.array(tank.matrix_world) -check("report of the parented, rotated tank carries its parent's and its own transform", single and len(single["parts"]) == 1 - and single["parts"][0]["params"] == wide["params"] and single["parts"][0]["faces"] == len(tank.data.polygons) - and np.abs(np.array(single["parts"][0]["sockets"][2]["matrix"]) - tank_world @ core.build(kit["parts"]["tank"], wide["params"]).sockets[2]["matrix"]).max() < 1e-6 - and np.abs(tank_world[:3, 3] - [1.0, 2.0, 3.0]).max() < 1e-6, single) + # --- report: sockets in the world ------------------------------------------------------------------------------------------- + send("setObjectTransform", targetObjectName="P_pipe_fitting", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) + receipt, reported = send("brokkr_kitbash.report") # straight after the move, before anything here updates the view layer: the frames are already the moved ones + bpy.context.view_layer.update() + worst, listed = 0.0, [] + for entry in (reported or {}).get("parts", []): + obj = bpy.data.objects[entry["object"]] + listed.append(entry["object"]) + local = core.build(core.part(kit, entry["part"]), entry["params"]).sockets + world = np.array(obj.matrix_world) + for socket, mine in zip(entry["sockets"], local): + worst = max(worst, float(np.abs(np.array(socket["matrix"]) - world @ mine["matrix"]).max())) + check("report lists every kit part with socket frames equal to matrix_world times the local frame", receipt["status"] == "accepted" + and listed == sorted(f"P_{n}" for n in names) and worst < 1e-6, [listed, worst]) + receipt, single = send("brokkr_kitbash.report", object_name="P_tank") + tank_world = np.array(tank.matrix_world) + check("report of the parented, rotated tank carries its parent's and its own transform", single and len(single["parts"]) == 1 + and single["parts"][0]["params"] == wide["params"] and single["parts"][0]["faces"] == len(tank.data.polygons) + and np.abs(np.array(single["parts"][0]["sockets"][2]["matrix"]) - tank_world @ core.build(kit["parts"]["tank"], wide["params"]).sockets[2]["matrix"]).max() < 1e-6 + and np.abs(tank_world[:3, 3] - [1.0, 2.0, 3.0]).max() < 1e-6, single) -# --- per-face materials ride on the part's shapes ---------------------------------------------------------------------------- -strut = bpy.data.objects["P_strut"] -send("assignMaterial", targetObjectName="P_strut", materialName="Strut Paint", color=[0.35, 0.35, 0.35]) -strut.data.materials.append(bpy.data.materials.new("Pin Steel")) -PINS = 2 # the strut's third shape: the repeat of two pins -was = core.build(kit["parts"]["strut"]) -strut.data.polygons.foreach_set("material_index", np.where(was.shape == PINS, 1, 0).astype(np.int32)) -receipt, _ = send("brokkr_kitbash.set_params", object_name="P_strut", params="segments=12; length=1.2") -now = core.build(kit["parts"]["strut"], {"segments": 12, "length": 1.2}) -index = np.zeros(len(strut.data.polygons), dtype=np.int32) -strut.data.polygons.foreach_get("material_index", index) -check("set_params with other segments keeps each shape's material: the pins stay Pin Steel, the rest Strut Paint", receipt["status"] == "accepted" - and len(now.counts) != len(was.counts) and index.tolist() == np.where(now.shape == PINS, 1, 0).tolist() and int(index.sum()) == 2 * (12 + 2) - and [s.material.name for s in strut.material_slots] == ["Strut Paint", "Pin Steel"], [receipt["message"], int(index.sum()), len(index)]) + # --- per-face materials ride on the part's shapes ---------------------------------------------------------------------------- + strut = bpy.data.objects["P_strut"] + send("assignMaterial", targetObjectName="P_strut", materialName="Strut Paint", color=[0.35, 0.35, 0.35]) + strut.data.materials.append(bpy.data.materials.new("Pin Steel")) + PINS = 2 # the strut's third shape: the repeat of two pins + was = core.build(kit["parts"]["strut"]) + strut.data.polygons.foreach_set("material_index", np.where(was.shape == PINS, 1, 0).astype(np.int32)) + receipt, _ = send("brokkr_kitbash.set_params", object_name="P_strut", params="segments=12; length=1.2") + now = core.build(kit["parts"]["strut"], {"segments": 12, "length": 1.2}) + index = np.zeros(len(strut.data.polygons), dtype=np.int32) + strut.data.polygons.foreach_get("material_index", index) + check("set_params with other segments keeps each shape's material: the pins stay Pin Steel, the rest Strut Paint", receipt["status"] == "accepted" + and len(now.counts) != len(was.counts) and index.tolist() == np.where(now.shape == PINS, 1, 0).tolist() and int(index.sum()) == 2 * (12 + 2) + and [s.material.name for s in strut.material_slots] == ["Strut Paint", "Pin Steel"], [receipt["message"], int(index.sum()), len(index)]) -# --- refusals leave the scene as it was -------------------------------------------------------------------------------------- -bpy.ops.mesh.primitive_cube_add() -bpy.context.active_object.name = "Plain" -twin = bpy.data.objects["P_vent"].copy() # a linked duplicate: one mesh, two objects, each with its own kit_params -twin.name = "P_vent_twin" -bpy.context.scene.collection.objects.link(twin) -send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[2.0, 2.0, 2.0]) -send("setObjectTransform", targetObjectName="P_actuator", scale=[-1.0, 1.0, 1.0]) + # --- refusals leave the scene as it was -------------------------------------------------------------------------------------- + bpy.ops.mesh.primitive_cube_add() + bpy.context.active_object.name = "Plain" + twin = bpy.data.objects["P_vent"].copy() # a linked duplicate: one mesh, two objects, each with its own kit_params + twin.name = "P_vent_twin" + bpy.context.scene.collection.objects.link(twin) + send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[2.0, 2.0, 2.0]) + send("setObjectTransform", targetObjectName="P_actuator", scale=[-1.0, 1.0, 1.0]) -def scene_state(): - return (sorted(o.name for o in bpy.data.objects), sorted(m.name for m in bpy.data.meshes), - {o.name: (len(o.data.polygons), o.get("kit_params")) for o in bpy.data.objects}) + def scene_state(): + return (sorted(o.name for o in bpy.data.objects), sorted(m.name for m in bpy.data.meshes), + {o.name: (len(o.data.polygons), o.get("kit_params")) for o in bpy.data.objects}) -state = scene_state() -refusals = [ - ("an unknown kit", "brokkr_kitbash.place_part", {"kit": "hydraulic", "part": "tank", "object_name": "X"}, "no kit named 'hydraulic'"), - ("a kit name that spells a path", "brokkr_kitbash.place_part", {"kit": "../x", "part": "tank", "object_name": "X"}, "kit"), - ("a kit name with a dot", "brokkr_kitbash.place_part", {"kit": "mechanical.v0", "part": "tank", "object_name": "X"}, "must be 1 to 32 of"), - ("an unknown part", "brokkr_kitbash.place_part", {"part": "wing", "object_name": "X"}, "has no part 'wing'"), - ("an out-of-range param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "radius=5"}, "param 'radius' = 5.0 is outside [0.12, 0.35]"), - ("a fraction for an integer param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "segments=12.5"}, "is an integer"), - ("an existing name", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "P_plate"}, "An object named 'P_plate' exists"), - ("set_params on a plain mesh", "brokkr_kitbash.set_params", {"object_name": "Plain", "params": "length=1"}, "is not a kit part"), - ("set_params with an unknown param", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "girth=1"}, "has no param 'girth'"), - ("set_params out of range", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=0.1"}, "is outside [0.6, 2.0]"), - ("set_params with a repeated key", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=1; length=1.2"}, "'length' is given twice"), - ("report of a plain mesh", "brokkr_kitbash.report", {"object_name": "Plain"}, "is not a kit part"), - ("set_params on a mesh a linked duplicate shares", "brokkr_kitbash.set_params", {"object_name": "P_vent", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"), - ("set_params on the linked duplicate", "brokkr_kitbash.set_params", {"object_name": "P_vent_twin", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"), - ("report of a scaled part", "brokkr_kitbash.report", {"object_name": "P_radiator_stack"}, "'P_radiator_stack' is scaled, mirrored or sheared in the world (scale 2, 2, 2)"), - ("set_params on a scaled part", "brokkr_kitbash.set_params", {"object_name": "P_radiator_stack", "params": "fins=5"}, "is scaled, mirrored or sheared"), - ("report of a mirrored part", "brokkr_kitbash.report", {"object_name": "P_actuator"}, "'P_actuator' is scaled, mirrored or sheared"), - ("report of every part while one is scaled", "brokkr_kitbash.report", {}, "is scaled, mirrored or sheared"), - ("describe of an unknown part", "brokkr_kitbash.describe", {"part": "wing"}, "has no part 'wing'"), -] -for label, action, fields, expected in refusals: - receipt, _ = send(action, **fields) - check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state, - [receipt["status"], receipt["message"]]) + state = scene_state() + refusals = [ + ("an unknown kit", "brokkr_kitbash.place_part", {"kit": "hydraulic", "part": "tank", "object_name": "X"}, "no kit named 'hydraulic'"), + ("a kit name that spells a path", "brokkr_kitbash.place_part", {"kit": "../x", "part": "tank", "object_name": "X"}, "kit"), + ("a kit name with a dot", "brokkr_kitbash.place_part", {"kit": "mechanical.v0", "part": "tank", "object_name": "X"}, "must be 1 to 32 of"), + ("an unknown part", "brokkr_kitbash.place_part", {"part": "wing", "object_name": "X"}, "has no part 'wing'"), + ("an out-of-range param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "radius=5"}, "param 'radius' = 5.0 is outside [0.12, 0.35]"), + ("a fraction for an integer param", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "X", "params": "segments=12.5"}, "is an integer"), + ("an existing name", "brokkr_kitbash.place_part", {"part": "tank", "object_name": "P_plate"}, "An object named 'P_plate' exists"), + ("set_params on a plain mesh", "brokkr_kitbash.set_params", {"object_name": "Plain", "params": "length=1"}, "is not a kit part"), + ("set_params with an unknown param", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "girth=1"}, "has no param 'girth'"), + ("set_params out of range", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=0.1"}, "is outside [0.6, 2.0]"), + ("set_params with a repeated key", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=1; length=1.2"}, "'length' is given twice"), + ("report of a plain mesh", "brokkr_kitbash.report", {"object_name": "Plain"}, "is not a kit part"), + ("set_params on a mesh a linked duplicate shares", "brokkr_kitbash.set_params", {"object_name": "P_vent", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"), + ("set_params on the linked duplicate", "brokkr_kitbash.set_params", {"object_name": "P_vent_twin", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"), + ("report of a scaled part", "brokkr_kitbash.report", {"object_name": "P_radiator_stack"}, "'P_radiator_stack' is scaled, mirrored or sheared in the world (scale 2, 2, 2)"), + ("set_params on a scaled part", "brokkr_kitbash.set_params", {"object_name": "P_radiator_stack", "params": "fins=5"}, "is scaled, mirrored or sheared"), + ("report of a mirrored part", "brokkr_kitbash.report", {"object_name": "P_actuator"}, "'P_actuator' is scaled, mirrored or sheared"), + ("report of every part while one is scaled", "brokkr_kitbash.report", {}, "is scaled, mirrored or sheared"), + ("describe of an unknown part", "brokkr_kitbash.describe", {"part": "wing"}, "has no part 'wing'"), + ] + for label, action, fields, expected in refusals: + receipt, _ = send(action, **fields) + check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state, + [receipt["status"], receipt["message"]]) -bpy.data.objects.remove(twin) -send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[1.0, 1.0, 1.0]) -send("setObjectTransform", targetObjectName="P_actuator", scale=[1.0, 1.0, 1.0]) -receipt, alone = send("brokkr_kitbash.set_params", object_name="P_vent", params="slats=9") -check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone - and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"]) -receipt, whole = send("brokkr_kitbash.report") -check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 11, receipt["message"]) + bpy.data.objects.remove(twin) + send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[1.0, 1.0, 1.0]) + send("setObjectTransform", targetObjectName="P_actuator", scale=[1.0, 1.0, 1.0]) + receipt, alone = send("brokkr_kitbash.set_params", object_name="P_vent", params="slats=9") + check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone + and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"]) + receipt, whole = send("brokkr_kitbash.report") + check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 11, receipt["message"]) -# --- export --------------------------------------------------------------------------------------------------------------- -receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names]) -glb = WORK / "kit.glb" -meshes = -1 -if glb.is_file(): - blob = glb.read_bytes() - meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", [])) -check("exportGltf of all eleven parts succeeds", receipt["status"] == "accepted" and meshes == 11, [receipt["message"], meshes]) + # --- export --------------------------------------------------------------------------------------------------------------- + receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names]) + glb = WORK / "kit.glb" + meshes = -1 + if glb.is_file(): + blob = glb.read_bytes() + meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", [])) + check("exportGltf of all eleven parts succeeds", receipt["status"] == "accepted" and meshes == 11, [receipt["message"], meshes]) + + R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]} + for name, report in placed.items() if report} +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) -R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]} - for name, report in placed.items() if report} R["ok"] = all(c["ok"] for c in R["checks"]) for c in R["checks"]: print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 805e576..33b580e 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -6,7 +6,9 @@ of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_assembly.py -- Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses -without them). is an absolute path; writes .result.json and exits 1 when a check failed. +without them). is an absolute path; writes .result.json and exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names +the check before it, the checks are printed and the result file written whatever happened, and the exit is 1 with or +without --python-exit-code. An Exact Boolean costs a few tenths of a second a part and evaluation (docs/kitbash.md), so few parts are cut here: the tank, a tee and three plates. Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the @@ -19,6 +21,7 @@ import math import os import re import sys +import traceback import tempfile import types from pathlib import Path @@ -183,535 +186,538 @@ def evaluated(obj): return row, [m.name if m else None for m in shown.data.materials] -rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] -check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == TABLE != [] and sorted(TABLE) == OPERATORS, [R["hostErrors"], rows, OPERATORS]) +try: + rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] + check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == TABLE != [] and sorted(TABLE) == OPERATORS, [R["hostErrors"], rows, OPERATORS]) -# --- attach ------------------------------------------------------------------------------------------------------------- -tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088 -tee = place("Tee", "pipe_fitting", "pipe_r=0.044", location=[-2.0, 0.5, 1.0], rotation=[1.1, 0.4, -0.7]) -nozzle = place("Nozzle", "nozzle", "throat_r=0.044", location=[0.0, 4.0, 0.0]) -spare = place("Spare", "nozzle", "throat_r=0.044", location=[0.0, 6.0, 0.0]) -wide = place("Wide", "nozzle", location=[0.0, 8.0, 0.0]) # throat 0.07: flange size 0.14 -radiator = place("Radiator", "radiator_stack", location=[0.0, 10.0, 0.0]) -send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3) -receipt, report = send("brokkr_kitbash.report", object_name="Tank") -check("a part nobody attached reports connection null and baked false", report and report["parts"][0]["connection"] is None - and report["parts"][0]["baked"] is False, report) + # --- attach ------------------------------------------------------------------------------------------------------------- + tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088 + tee = place("Tee", "pipe_fitting", "pipe_r=0.044", location=[-2.0, 0.5, 1.0], rotation=[1.1, 0.4, -0.7]) + nozzle = place("Nozzle", "nozzle", "throat_r=0.044", location=[0.0, 4.0, 0.0]) + spare = place("Spare", "nozzle", "throat_r=0.044", location=[0.0, 6.0, 0.0]) + wide = place("Wide", "nozzle", location=[0.0, 8.0, 0.0]) # throat 0.07: flange size 0.14 + radiator = place("Radiator", "radiator_stack", location=[0.0, 10.0, 0.0]) + send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3) + receipt, report = send("brokkr_kitbash.report", object_name="Tank") + check("a part nobody attached reports connection null and baked false", report and report["parts"][0]["connection"] is None + and report["parts"][0]["baked"] is False, report) -receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0) -check("attach parents the nozzle to the tee under an identity parent inverse and stores the three properties", receipt["status"] == "accepted" - and nozzle.parent == tee and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)) - and (nozzle["kit_socket"], nozzle["kit_parent_socket"], nozzle["kit_roll"]) == ("mount", "c", 37.0) - and sorted(k for k in nozzle.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_parent_socket", "kit_part", "kit_roll", "kit_socket"], - [receipt["message"], dict(nozzle.items())]) -gap = reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) -check("attach seats the nozzle's mount on the tee's c: origins together, normals opposed, rolled 37 degrees", gap < SEATED and R["readings"]["roll"] < ROLL, dict(R["readings"])) -check("attach reports the child: its connection holds, and its sockets are the seated world frames", report - and report["connection"] == {**report["connection"], "parent": "Tee", "socket": "mount", "parentSocket": "c", "roll": 37.0, "holds": True} - and report["connection"]["residual"] <= 1e-5 and report["object"] == "Nozzle" - and np.abs(np.array(report["sockets"][0]["matrix"]) - frame(nozzle, "mount")).max() < 2e-6, report) -check("report shows the same connection", holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) -receipt, report = send("brokkr_kitbash.attach", object_name="Tee", socket="a", parent_name="Tank", parent_socket="port_b") -check("attach of the tee to the tank's port carries the nozzle with it", receipt["status"] == "accepted" and held(report) and report["connection"]["roll"] == 0.0 and reading("seated", seated(tee, "a", tank, "port_b", 0.0)) < SEATED - and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED and R["readings"]["roll"] < ROLL - and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], [receipt["message"], R["readings"]]) + receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0) + check("attach parents the nozzle to the tee under an identity parent inverse and stores the three properties", receipt["status"] == "accepted" + and nozzle.parent == tee and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)) + and (nozzle["kit_socket"], nozzle["kit_parent_socket"], nozzle["kit_roll"]) == ("mount", "c", 37.0) + and sorted(k for k in nozzle.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_parent_socket", "kit_part", "kit_roll", "kit_socket"], + [receipt["message"], dict(nozzle.items())]) + gap = reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) + check("attach seats the nozzle's mount on the tee's c: origins together, normals opposed, rolled 37 degrees", gap < SEATED and R["readings"]["roll"] < ROLL, dict(R["readings"])) + check("attach reports the child: its connection holds, and its sockets are the seated world frames", report + and report["connection"] == {**report["connection"], "parent": "Tee", "socket": "mount", "parentSocket": "c", "roll": 37.0, "holds": True} + and report["connection"]["residual"] <= 1e-5 and report["object"] == "Nozzle" + and np.abs(np.array(report["sockets"][0]["matrix"]) - frame(nozzle, "mount")).max() < 2e-6, report) + check("report shows the same connection", holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) + receipt, report = send("brokkr_kitbash.attach", object_name="Tee", socket="a", parent_name="Tank", parent_socket="port_b") + check("attach of the tee to the tank's port carries the nozzle with it", receipt["status"] == "accepted" and held(report) and report["connection"]["roll"] == 0.0 and reading("seated", seated(tee, "a", tank, "port_b", 0.0)) < SEATED + and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED and R["readings"]["roll"] < ROLL + and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], [receipt["message"], R["readings"]]) -refused("sockets of different types", "brokkr_kitbash.attach", {"object_name": "Radiator", "socket": "base", "parent_name": "Tee", "parent_socket": "b"}, - "'Radiator' on 'Tee': socket 'base' (mount, size 0.15) and parent socket 'b' (flange, size 0.088) are of different types") -refused("flanges of different sizes", "brokkr_kitbash.attach", {"object_name": "Wide", "socket": "mount", "parent_name": "Tee", "parent_socket": "b"}, - "mate at equal sizes") -refused("a parent socket a child is on", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"}, - "Socket 'c' of 'Tee' is occupied (by 'Nozzle')") -refused("a parent socket the parent is attached by", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "a"}, - "Socket 'a' of 'Tee' is occupied (by 'Tank')") -refused("a loop through a grandchild", "brokkr_kitbash.attach", {"object_name": "Tank", "socket": "port_a", "parent_name": "Nozzle", "parent_socket": "mount"}, - "'Nozzle' is below 'Tank'") -refused("a child that has a parent", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "b"}, - "'Nozzle' has a parent, 'Tee'") -refused("a part to itself", "brokkr_kitbash.attach", {"object_name": "Tank", "socket": "port_a", "parent_name": "Tank", "parent_socket": "port_b"}, - "cannot be attached to itself") -refused("a socket the parent does not have", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "d"}, - "'Spare' on 'Tee': kit 'mechanical' part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c") -refused("a socket the child does not have", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "throat", "parent_name": "Tee", "parent_socket": "b"}, - "part 'nozzle' has no socket 'throat'") -refused("a child that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Plain", "socket": "a", "parent_name": "Tee", "parent_socket": "b"}, - "'Plain' is not a kit part") -refused("a parent that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Plain", "parent_socket": "b"}, - "'Plain' is not a kit part") -refused("detach of a part that is not attached", "brokkr_kitbash.detach", {"object_name": "Spare"}, "'Spare' is not attached (it has no kit_socket property) and states no closure") -send("brokkr_kitbash.detach", object_name="Tee") -send("setObjectTransform", targetObjectName="Tee", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) -refused("a child socket one of its own children is on", "brokkr_kitbash.attach", {"object_name": "Tee", "socket": "c", "parent_name": "Tank", "parent_socket": "port_b"}, - "Socket 'c' of 'Tee' is occupied (by 'Nozzle')") -send("brokkr_kitbash.attach", object_name="Tee", socket="a", parent_name="Tank", parent_socket="port_b") -receipt, report = send("brokkr_kitbash.attach", object_name="Spare", socket="mount", parent_name="Tee", parent_socket="b", roll=-90.0) -check("a second nozzle attaches to the tee's free socket, rolled -90", receipt["status"] == "accepted" and held(report) - and reading("seated", seated(spare, "mount", tee, "b", -90.0)) < SEATED and R["readings"]["roll"] < ROLL, [receipt["message"], R["readings"]]) + refused("sockets of different types", "brokkr_kitbash.attach", {"object_name": "Radiator", "socket": "base", "parent_name": "Tee", "parent_socket": "b"}, + "'Radiator' on 'Tee': socket 'base' (mount, size 0.15) and parent socket 'b' (flange, size 0.088) are of different types") + refused("flanges of different sizes", "brokkr_kitbash.attach", {"object_name": "Wide", "socket": "mount", "parent_name": "Tee", "parent_socket": "b"}, + "mate at equal sizes") + refused("a parent socket a child is on", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"}, + "Socket 'c' of 'Tee' is occupied (by 'Nozzle')") + refused("a parent socket the parent is attached by", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "a"}, + "Socket 'a' of 'Tee' is occupied (by 'Tank')") + refused("a loop through a grandchild", "brokkr_kitbash.attach", {"object_name": "Tank", "socket": "port_a", "parent_name": "Nozzle", "parent_socket": "mount"}, + "'Nozzle' is below 'Tank'") + refused("a child that has a parent", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "b"}, + "'Nozzle' has a parent, 'Tee'") + refused("a part to itself", "brokkr_kitbash.attach", {"object_name": "Tank", "socket": "port_a", "parent_name": "Tank", "parent_socket": "port_b"}, + "cannot be attached to itself") + refused("a socket the parent does not have", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Tee", "parent_socket": "d"}, + "'Spare' on 'Tee': kit 'mechanical' part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c") + refused("a socket the child does not have", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "throat", "parent_name": "Tee", "parent_socket": "b"}, + "part 'nozzle' has no socket 'throat'") + refused("a child that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Plain", "socket": "a", "parent_name": "Tee", "parent_socket": "b"}, + "'Plain' is not a kit part") + refused("a parent that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Plain", "parent_socket": "b"}, + "'Plain' is not a kit part") + refused("detach of a part that is not attached", "brokkr_kitbash.detach", {"object_name": "Spare"}, "'Spare' is not attached (it has no kit_socket property) and states no closure") + send("brokkr_kitbash.detach", object_name="Tee") + send("setObjectTransform", targetObjectName="Tee", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) + refused("a child socket one of its own children is on", "brokkr_kitbash.attach", {"object_name": "Tee", "socket": "c", "parent_name": "Tank", "parent_socket": "port_b"}, + "Socket 'c' of 'Tee' is occupied (by 'Nozzle')") + send("brokkr_kitbash.attach", object_name="Tee", socket="a", parent_name="Tank", parent_socket="port_b") + receipt, report = send("brokkr_kitbash.attach", object_name="Spare", socket="mount", parent_name="Tee", parent_socket="b", roll=-90.0) + check("a second nozzle attaches to the tee's free socket, rolled -90", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(spare, "mount", tee, "b", -90.0)) < SEATED and R["readings"]["roll"] < ROLL, [receipt["message"], R["readings"]]) -# --- set_params seats what is attached again ---------------------------------------------------------------------------------- -was = {name: np.array(bpy.data.objects[name].matrix_world) for name in ("Tank", "Tee", "Nozzle", "Spare")} -receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="length=1.8") -moved = {name: np.array(bpy.data.objects[name].matrix_world) - was[name] for name in was} -port = np.array(tank.matrix_world)[:3, :3] @ [0.0, 0.0, 0.9] # where port_b went: 0.9 along the tank's own z -check("set_params doubling the tank's length moves the tee and both nozzles by the port's displacement, and nothing turns", - receipt["status"] == "accepted" and np.abs(moved["Tank"]).max() == 0.0 - and all(reading("carried", np.abs(moved[n][:3, 3] - port).max()) < CARRIED and np.abs(moved[n][:3, :3]).max() < 1e-6 for n in ("Tee", "Nozzle", "Spare")), - [receipt["message"], {n: m[:3, 3].tolist() for n, m in moved.items()}, port.tolist()]) -check("after it every connection holds", holds("Tee", "Tank", "a", "port_b")[0] and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] - and holds("Spare", "Tee", "mount", "b", -90.0)[0] and reading("seated", seated(tee, "a", tank, "port_b")) < SEATED - and reading("seated", seated(nozzle, "mount", tee, "c")) < SEATED, [connection("Tee"), connection("Nozzle"), connection("Spare")]) -refused("set_params that breaks the part's own connection", "brokkr_kitbash.set_params", {"object_name": "Tee", "params": "pipe_r=0.06"}, - "'Tee' on 'Tank': socket 'a' (flange, size 0.12) and parent socket 'port_b' (flange, size 0.088)") -refused("set_params that breaks a child's connection", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "radius=0.3"}, - "'Tee' on 'Tank': socket 'a' (flange, size 0.088) and parent socket 'port_b' (flange, size 0.12)") -receipt, report = send("brokkr_kitbash.set_params", object_name="Tee", params="branch=0.4; run=0.6") -check("set_params on the tee keeps its own seat and moves each nozzle with its socket", receipt["status"] == "accepted" and held(report) - and reading("seated", seated(tee, "a", tank, "port_b")) < SEATED and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED - and reading("seated", seated(spare, "mount", tee, "b", -90.0)) < SEATED and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] - and holds("Spare", "Tee", "mount", "b", -90.0)[0] and R["readings"]["roll"] < ROLL, [receipt["message"], R["readings"]]) + # --- set_params seats what is attached again ---------------------------------------------------------------------------------- + was = {name: np.array(bpy.data.objects[name].matrix_world) for name in ("Tank", "Tee", "Nozzle", "Spare")} + receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="length=1.8") + moved = {name: np.array(bpy.data.objects[name].matrix_world) - was[name] for name in was} + port = np.array(tank.matrix_world)[:3, :3] @ [0.0, 0.0, 0.9] # where port_b went: 0.9 along the tank's own z + check("set_params doubling the tank's length moves the tee and both nozzles by the port's displacement, and nothing turns", + receipt["status"] == "accepted" and np.abs(moved["Tank"]).max() == 0.0 + and all(reading("carried", np.abs(moved[n][:3, 3] - port).max()) < CARRIED and np.abs(moved[n][:3, :3]).max() < 1e-6 for n in ("Tee", "Nozzle", "Spare")), + [receipt["message"], {n: m[:3, 3].tolist() for n, m in moved.items()}, port.tolist()]) + check("after it every connection holds", holds("Tee", "Tank", "a", "port_b")[0] and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and holds("Spare", "Tee", "mount", "b", -90.0)[0] and reading("seated", seated(tee, "a", tank, "port_b")) < SEATED + and reading("seated", seated(nozzle, "mount", tee, "c")) < SEATED, [connection("Tee"), connection("Nozzle"), connection("Spare")]) + refused("set_params that breaks the part's own connection", "brokkr_kitbash.set_params", {"object_name": "Tee", "params": "pipe_r=0.06"}, + "'Tee' on 'Tank': socket 'a' (flange, size 0.12) and parent socket 'port_b' (flange, size 0.088)") + refused("set_params that breaks a child's connection", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "radius=0.3"}, + "'Tee' on 'Tank': socket 'a' (flange, size 0.088) and parent socket 'port_b' (flange, size 0.12)") + receipt, report = send("brokkr_kitbash.set_params", object_name="Tee", params="branch=0.4; run=0.6") + check("set_params on the tee keeps its own seat and moves each nozzle with its socket", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(tee, "a", tank, "port_b")) < SEATED and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED + and reading("seated", seated(spare, "mount", tee, "b", -90.0)) < SEATED and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and holds("Spare", "Tee", "mount", "b", -90.0)[0] and R["readings"]["roll"] < ROLL, [receipt["message"], R["readings"]]) -# a strut hangs from one actuator's rod, and a second actuator hangs from the strut by its own rod -lift = place("Lift", "actuator", location=[4.0, 0.0, 0.0], rotation=[0.2, 0.9, -0.4]) # pivot size 0.054 -strut = place("Strut", "strut", "width=0.09") -ram = place("Ram", "actuator") -send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Lift", parent_socket="rod_end", roll=90.0) -send("brokkr_kitbash.attach", object_name="Ram", socket="rod_end", parent_name="Strut", parent_socket="end_b") -base = frame(ram, "base") -receipt, report = send("brokkr_kitbash.set_params", object_name="Ram", params="extension=0.5") -back = frame(ram, "base")[:3, 3] - base[:3, 3] -check("extending an actuator that hangs by its rod seats it again: the rod end stays, the body backs off by the travel", - reading("seated", seated(ram, "rod_end", strut, "end_b", 0.0)) < SEATED and receipt["status"] == "accepted" and held(report) - and reading("carried", np.abs(back + base[:3, 1] * 0.35).max()) < CARRIED, [receipt["message"], connection("Ram"), back.tolist()]) # a pivot's y is the part's axis -tip = frame(strut, "end_b") -receipt, report = send("brokkr_kitbash.set_params", object_name="Lift", params="extension=0.6") -check("extending the actuator above moves the strut on its rod and the ram below with it", receipt["status"] == "accepted" - and holds("Strut", "Lift", "end_a", "rod_end", 90.0)[0] and holds("Ram", "Strut", "rod_end", "end_b")[0] - and reading("seated", seated(strut, "end_a", lift, "rod_end", 90.0)) < SEATED - and reading("carried", np.abs(frame(strut, "end_b")[:3, 3] - tip[:3, 3] - np.array(lift.matrix_world)[:3, 2] * 0.45).max()) < CARRIED, - [receipt["message"], connection("Strut"), connection("Ram")]) + # a strut hangs from one actuator's rod, and a second actuator hangs from the strut by its own rod + lift = place("Lift", "actuator", location=[4.0, 0.0, 0.0], rotation=[0.2, 0.9, -0.4]) # pivot size 0.054 + strut = place("Strut", "strut", "width=0.09") + ram = place("Ram", "actuator") + send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Lift", parent_socket="rod_end", roll=90.0) + send("brokkr_kitbash.attach", object_name="Ram", socket="rod_end", parent_name="Strut", parent_socket="end_b") + base = frame(ram, "base") + receipt, report = send("brokkr_kitbash.set_params", object_name="Ram", params="extension=0.5") + back = frame(ram, "base")[:3, 3] - base[:3, 3] + check("extending an actuator that hangs by its rod seats it again: the rod end stays, the body backs off by the travel", + reading("seated", seated(ram, "rod_end", strut, "end_b", 0.0)) < SEATED and receipt["status"] == "accepted" and held(report) + and reading("carried", np.abs(back + base[:3, 1] * 0.35).max()) < CARRIED, [receipt["message"], connection("Ram"), back.tolist()]) # a pivot's y is the part's axis + tip = frame(strut, "end_b") + receipt, report = send("brokkr_kitbash.set_params", object_name="Lift", params="extension=0.6") + check("extending the actuator above moves the strut on its rod and the ram below with it", receipt["status"] == "accepted" + and holds("Strut", "Lift", "end_a", "rod_end", 90.0)[0] and holds("Ram", "Strut", "rod_end", "end_b")[0] + and reading("seated", seated(strut, "end_a", lift, "rod_end", 90.0)) < SEATED + and reading("carried", np.abs(frame(strut, "end_b")[:3, 3] - tip[:3, 3] - np.array(lift.matrix_world)[:3, 2] * 0.45).max()) < CARRIED, + [receipt["message"], connection("Strut"), connection("Ram")]) -# --- a closure: a brace from a second bracket closes on the leg's rod pin ------------------------------------------------------------ -hull = place("Hull", "tank", "radius=0.3; length=1.2", location=[6.0, 0.0, 2.0], rotation=[0.0, math.pi, 0.4]) # lug size 0.09 -upper, lower = place("Upper", "bracket"), place("Lower", "bracket") # pin 0.054, plate 0.09 -send("brokkr_kitbash.attach", object_name="Upper", socket="mount", parent_name="Hull", parent_socket="lug_b") -send("brokkr_kitbash.attach", object_name="Lower", socket="mount", parent_name="Hull", parent_socket="lug_a", roll=180.0) # turned half: its pin face looks back at Upper's -leg, brace, tie = place("Leg", "actuator"), place("Brace", "strut", "width=0.09; length=1.1"), place("Tie", "strut", "width=0.09") -p1, p2 = frame(upper, "pivot"), frame(lower, "pivot") -check("a bracket turned half on the next lug pins on the first one's plane, facing it", abs((p2[:3, 3] - p1[:3, 3]) @ p1[:3, 2]) < SEATED - and np.abs(p1[:3, 2] + p2[:3, 2]).max() < SEATED, [p1.tolist(), p2.tolist()]) -span = {name: core.build(kit["parts"][part], given) for name, part, given in (("leg", "actuator", {}), ("brace", "strut", {"width": 0.09, "length": 1.1}))} -a = next(s for s in span["leg"].sockets if s["name"] == "rod_end")["matrix"][2, 3] - next(s for s in span["leg"].sockets if s["name"] == "base")["matrix"][2, 3] -b = next(s for s in span["brace"].sockets if s["name"] == "end_b")["matrix"][2, 3] - next(s for s in span["brace"].sockets if s["name"] == "end_a")["matrix"][2, 3] -d = float(np.linalg.norm(p2[:3, 3] - p1[:3, 3])) -corner = math.acos((a * a + d * d - b * b) / (2 * a * d)) # the law of cosines: the angle at the upper pin between the hull and the leg -knee = p1[:3, 3] + a * (math.cos(corner) * (p2[:3, 3] - p1[:3, 3]) / d + math.sin(corner) * frame(hull, "lug_b")[:3, 2]) + # --- a closure: a brace from a second bracket closes on the leg's rod pin ------------------------------------------------------------ + hull = place("Hull", "tank", "radius=0.3; length=1.2", location=[6.0, 0.0, 2.0], rotation=[0.0, math.pi, 0.4]) # lug size 0.09 + upper, lower = place("Upper", "bracket"), place("Lower", "bracket") # pin 0.054, plate 0.09 + send("brokkr_kitbash.attach", object_name="Upper", socket="mount", parent_name="Hull", parent_socket="lug_b") + send("brokkr_kitbash.attach", object_name="Lower", socket="mount", parent_name="Hull", parent_socket="lug_a", roll=180.0) # turned half: its pin face looks back at Upper's + leg, brace, tie = place("Leg", "actuator"), place("Brace", "strut", "width=0.09; length=1.1"), place("Tie", "strut", "width=0.09") + p1, p2 = frame(upper, "pivot"), frame(lower, "pivot") + check("a bracket turned half on the next lug pins on the first one's plane, facing it", abs((p2[:3, 3] - p1[:3, 3]) @ p1[:3, 2]) < SEATED + and np.abs(p1[:3, 2] + p2[:3, 2]).max() < SEATED, [p1.tolist(), p2.tolist()]) + span = {name: core.build(kit["parts"][part], given) for name, part, given in (("leg", "actuator", {}), ("brace", "strut", {"width": 0.09, "length": 1.1}))} + a = next(s for s in span["leg"].sockets if s["name"] == "rod_end")["matrix"][2, 3] - next(s for s in span["leg"].sockets if s["name"] == "base")["matrix"][2, 3] + b = next(s for s in span["brace"].sockets if s["name"] == "end_b")["matrix"][2, 3] - next(s for s in span["brace"].sockets if s["name"] == "end_a")["matrix"][2, 3] + d = float(np.linalg.norm(p2[:3, 3] - p1[:3, 3])) + corner = math.acos((a * a + d * d - b * b) / (2 * a * d)) # the law of cosines: the angle at the upper pin between the hull and the leg + knee = p1[:3, 3] + a * (math.cos(corner) * (p2[:3, 3] - p1[:3, 3]) / d + math.sin(corner) * frame(hull, "lug_b")[:3, 2]) -def roll_to(pin, toward): - """The roll that points a pinned member's axis (its socket's y) from this pin toward a point in the pin's plane.""" - toward = (toward - pin[:3, 3]) / np.linalg.norm(toward - pin[:3, 3]) - return math.degrees(math.atan2(np.cross(pin[:3, 1], toward) @ pin[:3, 2], pin[:3, 1] @ toward)) + def roll_to(pin, toward): + """The roll that points a pinned member's axis (its socket's y) from this pin toward a point in the pin's plane.""" + toward = (toward - pin[:3, 3]) / np.linalg.norm(toward - pin[:3, 3]) + return math.degrees(math.atan2(np.cross(pin[:3, 1], toward) @ pin[:3, 2], pin[:3, 1] @ toward)) -def closure_of(name): - receipt, report = send("brokkr_kitbash.report", object_name=name) - return report["parts"][0]["closure"] if report else {"error": receipt["message"]} + def closure_of(name): + receipt, report = send("brokkr_kitbash.report", object_name=name) + return report["parts"][0]["closure"] if report else {"error": receipt["message"]} -def closure_row(name): - return closure_of(name) or {} + def closure_row(name): + return closure_of(name) or {} -def without_closures(state): - return {name: (*row[:3], {k: v for k, v in row[3].items() if not k.startswith("kit_close")}, *row[4:]) for name, row in state[0].items()}, state[1] + def without_closures(state): + return {name: (*row[:3], {k: v for k, v in row[3].items() if not k.startswith("kit_close")}, *row[4:]) for name, row in state[0].items()}, state[1] -CLOSING = {"object_name": "Brace", "socket": "end_b", "other_name": "Leg", "other_socket": "rod_end"} -send("brokkr_kitbash.attach", object_name="Leg", socket="base", parent_name="Upper", parent_socket="pivot", roll=roll_to(p1, knee)) -send("brokkr_kitbash.attach", object_name="Brace", socket="end_a", parent_name="Lower", parent_socket="pivot", roll=roll_to(p2, knee) + 1.0) -apart = core.closure_residual(np.array(leg.matrix_world), next(s for s in span["leg"].sockets if s["name"] == "rod_end"), - np.array(brace.matrix_world), next(s for s in span["brace"].sockets if s["name"] == "end_b")) -state = scene_state() -receipt, _ = send("brokkr_kitbash.close", **CLOSING) -named = re.search(r"Socket 'end_b' of 'Brace' and socket 'rod_end' of 'Leg' stand (\S+) m apart: place them so they meet", str(receipt["message"])) -check("refused, scene unchanged: close of a brace that stands 1 degree off, naming how far apart the two sockets are", receipt["status"] != "accepted" - and named and abs(float(named.group(1)) - apart) < 1e-5 and 0.01 < apart < 0.02 and scene_state() == state, [receipt["message"], apart]) -send("brokkr_kitbash.detach", object_name="Brace") -send("brokkr_kitbash.attach", object_name="Brace", socket="end_a", parent_name="Lower", parent_socket="pivot", roll=roll_to(p2, knee)) -# close-tolerance: the brace moved NUDGE (3.2e-4) off its seat. close accepts up to HELD, 1e-5; least claimed mutant 5e-4 (N2, 50 times -# HELD); NUDGE is 32 times the one and 0.64 of the other, as for the connection's own check below. -seat_was = np.array(brace.matrix_basis)[:3, 3] -send("setObjectTransform", targetObjectName="Brace", location=(seat_was + np.array(lower.matrix_world)[:3, :3].T @ [0.0, 0.0, NUDGE]).tolist()) -state = scene_state() -receipt, _ = send("brokkr_kitbash.close", **CLOSING) -named = re.search(r"stand (\S+) m apart", str(receipt["message"])) -check("refused, scene unchanged: close of a brace moved by NUDGE, which a report would read as not held", receipt["status"] != "accepted" and named - and abs(reading("close nudged", float(named.group(1))) - NUDGE) < 0.1 * NUDGE and scene_state() == state, receipt["message"]) -send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.1") # seats it again -state = scene_state() -receipt, report = send("brokkr_kitbash.close", **CLOSING) -check("close states the closure on the brace when its end_b meets the leg's rod pin, and moves nothing", receipt["status"] == "accepted" - and reading("seated", seated(brace, "end_b", leg, "rod_end")) < SEATED and without_closures(scene_state()) == without_closures(state) - and (brace["kit_close_socket"], brace["kit_close_to"], brace["kit_close_to_socket"]) == ("end_b", leg, "rod_end") - and sorted(k for k in brace.keys() if k.startswith("kit_close")) == ["kit_close_socket", "kit_close_to", "kit_close_to_socket"] - and not [k for k in leg.keys() if k.startswith("kit_close")], [receipt["message"], dict(brace.items())]) -check("close reports the part: its closure holds, and its connection still does", report and report["object"] == "Brace" - and report["closure"] == {**report["closure"], "to": "Leg", "socket": "end_b", "toSocket": "rod_end", "holds": True} - and reading("closed", report["closure"]["residual"]) <= 1e-5 and report["closure"]["reason"] is None and held(report) and closure_of("Brace") == report["closure"] - and closure_of("Leg") is None, report) -refused("a second closure on a part that states one", "brokkr_kitbash.close", - {"object_name": "Brace", "socket": "end_b_back", "other_name": "Leg", "other_socket": "rod_end_back"}, "'Brace' already states a closure (its socket 'end_b')") -refused("close on a socket a closure holds", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end"}, - "Socket 'rod_end' of 'Leg' is occupied (by 'Brace')") -refused("close on the closing socket itself", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Brace", "other_socket": "end_b"}, - "Socket 'end_b' of 'Brace' is occupied (by 'Leg')") -refused("close on a socket a part is attached by", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "base"}, - "Socket 'base' of 'Leg' is occupied (by 'Upper')") -refused("close by a socket a part is attached by", "brokkr_kitbash.close", {"object_name": "Leg", "socket": "base", "other_name": "Tie", "other_socket": "end_a"}, - "Socket 'base' of 'Leg' is occupied (by 'Upper')") -refused("attach onto a socket a closure holds", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Leg", "parent_socket": "rod_end"}, - "Socket 'rod_end' of 'Leg' is occupied (by 'Brace')") -refused("attach onto the closing socket", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Brace", "parent_socket": "end_b"}, - "Socket 'end_b' of 'Brace' is occupied (by 'Leg')") -refused("close of a part on itself", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Tie", "other_socket": "end_b"}, "'Tie' cannot close on itself") -refused("close of sockets that may not mate", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Hull", "other_socket": "lug_a_back"}, - "'Tie' closing on 'Hull': socket 'end_a' (pivot, size 0.054) and parent socket 'lug_a_back' (mount, size 0.09) are of different types") -refused("close of two sockets that are apart", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end_back"}, "m apart: place them so they meet") -refused("close on a mesh that is not a kit part", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Plain", "other_socket": "a"}, "'Plain' is not a kit part") -refused("close of a socket the part does not have", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_c", "other_name": "Leg", "other_socket": "rod_end_back"}, - "part 'strut' has no socket 'end_c'") -was = np.array(brace.matrix_world) -receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") -found = closure_row("Brace") -check("set_params that moves the leg's rod pin is accepted and moves no brace: the closure reads holds false with the rod's travel, here and in the report's closures", - receipt["status"] == "accepted" and report and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": False}] and report["closure"] is None - and found["holds"] is False and 0.05 < found["residual"] <= 0.15 + 1e-5 and np.array_equal(np.array(brace.matrix_world), was) - and holds("Brace", "Lower", "end_a", "pivot", connection("Brace")["roll"])[0], [receipt["message"], report and report.get("closures"), found]) -receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") -check("and with the rod back the closure holds again: it is read from where the parts stand, not stored", receipt["status"] == "accepted" - and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": True}] and closure_row("Brace").get("holds") is True, [report and report.get("closures"), closure_of("Brace")]) -# closures-omitted: a second closure, named to sort first, far from the leg; then a receipt with room for one row. Mutant N5 (never -# omit) lists two rows; rows by name alone would keep Aa_Loose and drop the one this call opened. -anchor, loose = place("Aa_Anchor", "strut", "width=0.09", location=[0.0, -20.0, 0.0]), place("Aa_Loose", "strut", "width=0.09") -meet = Matrix((np.array(anchor.matrix_world) @ core.mate(next(s for s in core.build(kit["parts"]["strut"], {"width": 0.09}).sockets if s["name"] == "end_b"), - next(s for s in core.build(kit["parts"]["strut"], {"width": 0.09}).sockets if s["name"] == "end_a"), 40.0)).tolist()) -send("setObjectTransform", targetObjectName="Aa_Loose", location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) -receipt, report = send("brokkr_kitbash.close", object_name="Aa_Loose", socket="end_a", other_name="Aa_Anchor", other_socket="end_b") -check("a loose part placed to meet a socket closes on it", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) -receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") -ROWS = [{"part": "Brace", "to": "Leg", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] -check("set_params lists the closures its own part is an end of first, then the rest", receipt["status"] == "accepted" and report["closures"] == ROWS - and "closuresOmitted" not in report, report and report.get("closures")) -addon = sys.modules["brokkr_kitbash"] -limit = addon.REPORT_LIMIT -addon.REPORT_LIMIT = len(json.dumps({k: v for k, v in report.items() if k != "closures"}, separators=(",", ":"))) + 40 + len(json.dumps(ROWS[0], separators=(",", ":"))) + 1 -receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") -addon.REPORT_LIMIT = limit -check("with room for one row in the receipt, set_params keeps the closure it opened and counts the other in closuresOmitted", receipt["status"] == "accepted" - and report["closures"] == ROWS[:1] and report.get("closuresOmitted") == 1 and np.array_equal(np.array(brace.matrix_world), was), report and [report.get("closures"), report.get("closuresOmitted")]) -receipt, report = send("brokkr_kitbash.set_params", object_name="Aa_Anchor", params="length=0.9") -check("and a closure another part's set_params opened comes before one that holds", receipt["status"] == "accepted" - and report["closures"] == [{"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}, {"part": "Brace", "to": "Leg", "holds": False}], report and report.get("closures")) -send("brokkr_kitbash.detach", object_name="Aa_Loose") -send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") -leg.scale = (1.0001, 1.0, 1.0) -bpy.context.view_layer.update() -found = closure_row("Brace") -leg.scale = (1.0, 1.0, 1.0) -bpy.context.view_layer.update() -check("a closure on a part scaled by hand reads broken, naming the part and why, not gone", found.get("to") == "Leg" and found.get("holds") is False and found.get("residual") is None - and "'Leg' is scaled, mirrored or sheared" in str(found.get("reason")) and closure_row("Brace").get("holds") is True, found) -twin = brace.copy() # as Shift-D leaves it: a second part stating the same closure -twin.data = brace.data.copy() -twin.name = "Brace_twin" -bpy.context.scene.collection.objects.link(twin) -found, other = closure_row("Brace"), closure_row("Brace_twin") -check("two parts that state a closure on one socket both read not held, each naming the other", found.get("holds") is False and other.get("holds") is False - and "is also closed on by 'Brace_twin'" in str(found.get("reason")) and "is also closed on by 'Brace'" in str(other.get("reason")), [found, other]) -tie["keeper"] = twin # something still points at the copy, so Delete leaves it in the file with its closure properties -with bpy.context.temp_override(selected_objects=[twin], active_object=twin): - bpy.ops.object.delete() -check("and with the copy deleted the closure holds again, though the copy is still in the file stating its own", closure_row("Brace").get("holds") is True - and bpy.data.objects.get("Brace_twin") is not None and "kit_close_to" in bpy.data.objects["Brace_twin"], closure_of("Brace")) -del tie["keeper"] -bpy.data.objects.remove(bpy.data.objects["Brace_twin"]) -refused("set_params on the part a closure names, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Leg", "params": "body_r=0.07"}, - "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.054) and parent socket 'rod_end' (pivot, size 0.063)") -refused("set_params on the closing part, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Brace", "params": "width=0.1"}, - "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.06) and parent socket 'rod_end' (pivot, size 0.054)") -receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") -check("set_params on the closing part that keeps its pin size is accepted and lists its own closure: a brace 0.1 shorter stops 0.1 short of the rod pin", - receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": False}] and report["closure"]["holds"] is False - and held(report) and 0.1 / math.sqrt(3) - 1e-5 <= report["closure"]["residual"] <= 0.1 + 1e-5, [receipt["message"], report and report["closure"]]) -send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.1") -before = np.array(brace.matrix_world) -receipt, report = send("brokkr_kitbash.detach", object_name="Brace") -check("detach clears the brace's closure with its connection, and it stays where it stood", receipt["status"] == "accepted" and report and report["closure"] is None - and report["connection"] is None and not [k for k in brace.keys() if k.startswith(("kit_close", "kit_socket", "kit_parent", "kit_roll"))] and brace.parent is None - and reading("kept", np.abs(np.array(brace.matrix_world) - before).max()) < KEPT, [receipt["message"], dict(brace.items())]) -receipt, report = send("brokkr_kitbash.close", **CLOSING) -check("a loose part that meets a socket may state a closure too", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True and report["connection"] is None, receipt["message"]) -leg.name = "Shin" -found = closure_row("Brace") -check("a closure follows its other part through a rename", found.get("to") == "Shin" and found.get("holds") is True, found) -leg.name = "Leg" -send("brokkr_kitbash.detach", object_name="Leg") -homes = list(leg.users_collection) -for home in homes: - home.objects.unlink(leg) -found = closure_row("Brace") -check("a closure on a part unlinked from every collection reads to null, holds false, with the reason", found.get("to", 0) is None and found.get("holds") is False - and "gone" in str(found.get("reason")) and "Leg" in bpy.data.objects, found) -for home in homes: - home.objects.link(leg) -check("and holds again once the part is linked back", closure_row("Brace").get("holds") is True, closure_of("Brace")) -with bpy.context.temp_override(selected_objects=[leg], active_object=leg): - bpy.ops.object.delete() # the ordinary Delete: the closure's pointer keeps the object in the file as an orphan -found = closure_row("Brace") -check("a closure on a part deleted with the Delete operator reads to null, holds false, though the object is still in the file", found.get("to", 0) is None - and found.get("holds") is False and found.get("residual", 0) is None and bpy.data.objects.get("Leg") is not None and brace.get("kit_close_to") is not None, [found, list(bpy.data.objects.keys())]) -refused("close onto a deleted part that is still in the file", "brokkr_kitbash.close", - {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end_back"}, "'Leg' is in no collection") -if "Leg" in bpy.data.objects: - bpy.data.objects.remove(bpy.data.objects["Leg"]) -found = closure_row("Brace") -receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") -check("a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", found and found == {**found, "to": None, "residual": None, "holds": False} - and found.get("toSocket") == "rod_end" and receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": None, "holds": False}], [found, receipt["message"]]) -before = np.array(brace.matrix_world) -receipt, report = send("brokkr_kitbash.detach", object_name="Brace") -check("detach of a part that states only a closure clears it and leaves the part where it stood", receipt["status"] == "accepted" and report["closure"] is None - and not [k for k in brace.keys() if k.startswith("kit_close")] and np.array_equal(np.array(brace.matrix_world), before), [receipt["message"], dict(brace.items())]) -receipt, report = send("brokkr_kitbash.attach", object_name="Tie", socket="end_a", parent_name="Brace", parent_socket="end_b") -check("and the socket the closure held is free again", receipt["status"] == "accepted" and held(report), receipt["message"]) + CLOSING = {"object_name": "Brace", "socket": "end_b", "other_name": "Leg", "other_socket": "rod_end"} + send("brokkr_kitbash.attach", object_name="Leg", socket="base", parent_name="Upper", parent_socket="pivot", roll=roll_to(p1, knee)) + send("brokkr_kitbash.attach", object_name="Brace", socket="end_a", parent_name="Lower", parent_socket="pivot", roll=roll_to(p2, knee) + 1.0) + apart = core.closure_residual(np.array(leg.matrix_world), next(s for s in span["leg"].sockets if s["name"] == "rod_end"), + np.array(brace.matrix_world), next(s for s in span["brace"].sockets if s["name"] == "end_b")) + state = scene_state() + receipt, _ = send("brokkr_kitbash.close", **CLOSING) + named = re.search(r"Socket 'end_b' of 'Brace' and socket 'rod_end' of 'Leg' stand (\S+) m apart: place them so they meet", str(receipt["message"])) + check("refused, scene unchanged: close of a brace that stands 1 degree off, naming how far apart the two sockets are", receipt["status"] != "accepted" + and named and abs(float(named.group(1)) - apart) < 1e-5 and 0.01 < apart < 0.02 and scene_state() == state, [receipt["message"], apart]) + send("brokkr_kitbash.detach", object_name="Brace") + send("brokkr_kitbash.attach", object_name="Brace", socket="end_a", parent_name="Lower", parent_socket="pivot", roll=roll_to(p2, knee)) + # close-tolerance: the brace moved NUDGE (3.2e-4) off its seat. close accepts up to HELD, 1e-5; least claimed mutant 5e-4 (N2, 50 times + # HELD); NUDGE is 32 times the one and 0.64 of the other, as for the connection's own check below. + seat_was = np.array(brace.matrix_basis)[:3, 3] + send("setObjectTransform", targetObjectName="Brace", location=(seat_was + np.array(lower.matrix_world)[:3, :3].T @ [0.0, 0.0, NUDGE]).tolist()) + state = scene_state() + receipt, _ = send("brokkr_kitbash.close", **CLOSING) + named = re.search(r"stand (\S+) m apart", str(receipt["message"])) + check("refused, scene unchanged: close of a brace moved by NUDGE, which a report would read as not held", receipt["status"] != "accepted" and named + and abs(reading("close nudged", float(named.group(1))) - NUDGE) < 0.1 * NUDGE and scene_state() == state, receipt["message"]) + send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.1") # seats it again + state = scene_state() + receipt, report = send("brokkr_kitbash.close", **CLOSING) + check("close states the closure on the brace when its end_b meets the leg's rod pin, and moves nothing", receipt["status"] == "accepted" + and reading("seated", seated(brace, "end_b", leg, "rod_end")) < SEATED and without_closures(scene_state()) == without_closures(state) + and (brace["kit_close_socket"], brace["kit_close_to"], brace["kit_close_to_socket"]) == ("end_b", leg, "rod_end") + and sorted(k for k in brace.keys() if k.startswith("kit_close")) == ["kit_close_socket", "kit_close_to", "kit_close_to_socket"] + and not [k for k in leg.keys() if k.startswith("kit_close")], [receipt["message"], dict(brace.items())]) + check("close reports the part: its closure holds, and its connection still does", report and report["object"] == "Brace" + and report["closure"] == {**report["closure"], "to": "Leg", "socket": "end_b", "toSocket": "rod_end", "holds": True} + and reading("closed", report["closure"]["residual"]) <= 1e-5 and report["closure"]["reason"] is None and held(report) and closure_of("Brace") == report["closure"] + and closure_of("Leg") is None, report) + refused("a second closure on a part that states one", "brokkr_kitbash.close", + {"object_name": "Brace", "socket": "end_b_back", "other_name": "Leg", "other_socket": "rod_end_back"}, "'Brace' already states a closure (its socket 'end_b')") + refused("close on a socket a closure holds", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end"}, + "Socket 'rod_end' of 'Leg' is occupied (by 'Brace')") + refused("close on the closing socket itself", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Brace", "other_socket": "end_b"}, + "Socket 'end_b' of 'Brace' is occupied (by 'Leg')") + refused("close on a socket a part is attached by", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "base"}, + "Socket 'base' of 'Leg' is occupied (by 'Upper')") + refused("close by a socket a part is attached by", "brokkr_kitbash.close", {"object_name": "Leg", "socket": "base", "other_name": "Tie", "other_socket": "end_a"}, + "Socket 'base' of 'Leg' is occupied (by 'Upper')") + refused("attach onto a socket a closure holds", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Leg", "parent_socket": "rod_end"}, + "Socket 'rod_end' of 'Leg' is occupied (by 'Brace')") + refused("attach onto the closing socket", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Brace", "parent_socket": "end_b"}, + "Socket 'end_b' of 'Brace' is occupied (by 'Leg')") + refused("close of a part on itself", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Tie", "other_socket": "end_b"}, "'Tie' cannot close on itself") + refused("close of sockets that may not mate", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Hull", "other_socket": "lug_a_back"}, + "'Tie' closing on 'Hull': socket 'end_a' (pivot, size 0.054) and parent socket 'lug_a_back' (mount, size 0.09) are of different types") + refused("close of two sockets that are apart", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end_back"}, "m apart: place them so they meet") + refused("close on a mesh that is not a kit part", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Plain", "other_socket": "a"}, "'Plain' is not a kit part") + refused("close of a socket the part does not have", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_c", "other_name": "Leg", "other_socket": "rod_end_back"}, + "part 'strut' has no socket 'end_c'") + was = np.array(brace.matrix_world) + receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") + found = closure_row("Brace") + check("set_params that moves the leg's rod pin is accepted and moves no brace: the closure reads holds false with the rod's travel, here and in the report's closures", + receipt["status"] == "accepted" and report and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": False}] and report["closure"] is None + and found["holds"] is False and 0.05 < found["residual"] <= 0.15 + 1e-5 and np.array_equal(np.array(brace.matrix_world), was) + and holds("Brace", "Lower", "end_a", "pivot", connection("Brace")["roll"])[0], [receipt["message"], report and report.get("closures"), found]) + receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") + check("and with the rod back the closure holds again: it is read from where the parts stand, not stored", receipt["status"] == "accepted" + and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": True}] and closure_row("Brace").get("holds") is True, [report and report.get("closures"), closure_of("Brace")]) + # closures-omitted: a second closure, named to sort first, far from the leg; then a receipt with room for one row. Mutant N5 (never + # omit) lists two rows; rows by name alone would keep Aa_Loose and drop the one this call opened. + anchor, loose = place("Aa_Anchor", "strut", "width=0.09", location=[0.0, -20.0, 0.0]), place("Aa_Loose", "strut", "width=0.09") + meet = Matrix((np.array(anchor.matrix_world) @ core.mate(next(s for s in core.build(kit["parts"]["strut"], {"width": 0.09}).sockets if s["name"] == "end_b"), + next(s for s in core.build(kit["parts"]["strut"], {"width": 0.09}).sockets if s["name"] == "end_a"), 40.0)).tolist()) + send("setObjectTransform", targetObjectName="Aa_Loose", location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) + receipt, report = send("brokkr_kitbash.close", object_name="Aa_Loose", socket="end_a", other_name="Aa_Anchor", other_socket="end_b") + check("a loose part placed to meet a socket closes on it", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) + receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") + ROWS = [{"part": "Brace", "to": "Leg", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] + check("set_params lists the closures its own part is an end of first, then the rest", receipt["status"] == "accepted" and report["closures"] == ROWS + and "closuresOmitted" not in report, report and report.get("closures")) + addon = sys.modules["brokkr_kitbash"] + limit = addon.REPORT_LIMIT + addon.REPORT_LIMIT = len(json.dumps({k: v for k, v in report.items() if k != "closures"}, separators=(",", ":"))) + 40 + len(json.dumps(ROWS[0], separators=(",", ":"))) + 1 + receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") + addon.REPORT_LIMIT = limit + check("with room for one row in the receipt, set_params keeps the closure it opened and counts the other in closuresOmitted", receipt["status"] == "accepted" + and report["closures"] == ROWS[:1] and report.get("closuresOmitted") == 1 and np.array_equal(np.array(brace.matrix_world), was), report and [report.get("closures"), report.get("closuresOmitted")]) + receipt, report = send("brokkr_kitbash.set_params", object_name="Aa_Anchor", params="length=0.9") + check("and a closure another part's set_params opened comes before one that holds", receipt["status"] == "accepted" + and report["closures"] == [{"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}, {"part": "Brace", "to": "Leg", "holds": False}], report and report.get("closures")) + send("brokkr_kitbash.detach", object_name="Aa_Loose") + send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") + leg.scale = (1.0001, 1.0, 1.0) + bpy.context.view_layer.update() + found = closure_row("Brace") + leg.scale = (1.0, 1.0, 1.0) + bpy.context.view_layer.update() + check("a closure on a part scaled by hand reads broken, naming the part and why, not gone", found.get("to") == "Leg" and found.get("holds") is False and found.get("residual") is None + and "'Leg' is scaled, mirrored or sheared" in str(found.get("reason")) and closure_row("Brace").get("holds") is True, found) + twin = brace.copy() # as Shift-D leaves it: a second part stating the same closure + twin.data = brace.data.copy() + twin.name = "Brace_twin" + bpy.context.scene.collection.objects.link(twin) + found, other = closure_row("Brace"), closure_row("Brace_twin") + check("two parts that state a closure on one socket both read not held, each naming the other", found.get("holds") is False and other.get("holds") is False + and "is also closed on by 'Brace_twin'" in str(found.get("reason")) and "is also closed on by 'Brace'" in str(other.get("reason")), [found, other]) + tie["keeper"] = twin # something still points at the copy, so Delete leaves it in the file with its closure properties + with bpy.context.temp_override(selected_objects=[twin], active_object=twin): + bpy.ops.object.delete() + check("and with the copy deleted the closure holds again, though the copy is still in the file stating its own", closure_row("Brace").get("holds") is True + and bpy.data.objects.get("Brace_twin") is not None and "kit_close_to" in bpy.data.objects["Brace_twin"], closure_of("Brace")) + del tie["keeper"] + bpy.data.objects.remove(bpy.data.objects["Brace_twin"]) + refused("set_params on the part a closure names, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Leg", "params": "body_r=0.07"}, + "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.054) and parent socket 'rod_end' (pivot, size 0.063)") + refused("set_params on the closing part, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Brace", "params": "width=0.1"}, + "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.06) and parent socket 'rod_end' (pivot, size 0.054)") + receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") + check("set_params on the closing part that keeps its pin size is accepted and lists its own closure: a brace 0.1 shorter stops 0.1 short of the rod pin", + receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": False}] and report["closure"]["holds"] is False + and held(report) and 0.1 / math.sqrt(3) - 1e-5 <= report["closure"]["residual"] <= 0.1 + 1e-5, [receipt["message"], report and report["closure"]]) + send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.1") + before = np.array(brace.matrix_world) + receipt, report = send("brokkr_kitbash.detach", object_name="Brace") + check("detach clears the brace's closure with its connection, and it stays where it stood", receipt["status"] == "accepted" and report and report["closure"] is None + and report["connection"] is None and not [k for k in brace.keys() if k.startswith(("kit_close", "kit_socket", "kit_parent", "kit_roll"))] and brace.parent is None + and reading("kept", np.abs(np.array(brace.matrix_world) - before).max()) < KEPT, [receipt["message"], dict(brace.items())]) + receipt, report = send("brokkr_kitbash.close", **CLOSING) + check("a loose part that meets a socket may state a closure too", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True and report["connection"] is None, receipt["message"]) + leg.name = "Shin" + found = closure_row("Brace") + check("a closure follows its other part through a rename", found.get("to") == "Shin" and found.get("holds") is True, found) + leg.name = "Leg" + send("brokkr_kitbash.detach", object_name="Leg") + homes = list(leg.users_collection) + for home in homes: + home.objects.unlink(leg) + found = closure_row("Brace") + check("a closure on a part unlinked from every collection reads to null, holds false, with the reason", found.get("to", 0) is None and found.get("holds") is False + and "gone" in str(found.get("reason")) and "Leg" in bpy.data.objects, found) + for home in homes: + home.objects.link(leg) + check("and holds again once the part is linked back", closure_row("Brace").get("holds") is True, closure_of("Brace")) + with bpy.context.temp_override(selected_objects=[leg], active_object=leg): + bpy.ops.object.delete() # the ordinary Delete: the closure's pointer keeps the object in the file as an orphan + found = closure_row("Brace") + check("a closure on a part deleted with the Delete operator reads to null, holds false, though the object is still in the file", found.get("to", 0) is None + and found.get("holds") is False and found.get("residual", 0) is None and bpy.data.objects.get("Leg") is not None and brace.get("kit_close_to") is not None, [found, list(bpy.data.objects.keys())]) + refused("close onto a deleted part that is still in the file", "brokkr_kitbash.close", + {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end_back"}, "'Leg' is in no collection") + if "Leg" in bpy.data.objects: + bpy.data.objects.remove(bpy.data.objects["Leg"]) + found = closure_row("Brace") + receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") + check("a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", found and found == {**found, "to": None, "residual": None, "holds": False} + and found.get("toSocket") == "rod_end" and receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": None, "holds": False}], [found, receipt["message"]]) + before = np.array(brace.matrix_world) + receipt, report = send("brokkr_kitbash.detach", object_name="Brace") + check("detach of a part that states only a closure clears it and leaves the part where it stood", receipt["status"] == "accepted" and report["closure"] is None + and not [k for k in brace.keys() if k.startswith("kit_close")] and np.array_equal(np.array(brace.matrix_world), before), [receipt["message"], dict(brace.items())]) + receipt, report = send("brokkr_kitbash.attach", object_name="Tie", socket="end_a", parent_name="Brace", parent_socket="end_b") + check("and the socket the closure held is free again", receipt["status"] == "accepted" and held(report), receipt["message"]) -# --- drift and detach --------------------------------------------------------------------------------------------------------- -send("setObjectTransform", targetObjectName="Nozzle", location=[0.25, 0.0, 0.0]) -found = connection("Nozzle") or {} -check("setObjectTransform on an attached child shows in its report: holds false, with the residual", found.get("holds") is False and found["parent"] == "Tee" - and found["residual"] > 0.1, found) -refused("attach of a drifted child, which still has its parent", "brokkr_kitbash.attach", - {"object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"}, "'Nozzle' has a parent, 'Tee'") -send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") -check("set_params on its parent seats it again", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED, - connection("Nozzle")) -send("setObjectTransform", targetObjectName="Nozzle", rotationEuler=[0.0, 0.5, 0.0]) -drifted = connection("Nozzle") or {} -send("brokkr_kitbash.set_params", object_name="Nozzle", params="exit_r=0.3") -check("set_params on the drifted child itself seats it again", drifted.get("holds") is False and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] - and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED, [drifted, connection("Nozzle")]) -nozzle.matrix_parent_inverse = nozzle.matrix_basis.inverted() # as parenting by hand in the viewport leaves it; the basis below keeps the nozzle where it is -nozzle.matrix_basis = nozzle.matrix_basis @ nozzle.matrix_basis -bpy.context.view_layer.update() -found = connection("Nozzle") or {} -check("a parent inverse that is not the identity does not hold, wherever the child stands", found.get("holds") is False and found["residual"] <= 1e-5 - and seated(nozzle, "mount", tee, "c") < SEATED, found) -send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") -check("and set_params on the parent writes the identity back", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] - and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)), connection("Nozzle")) -push = np.array(tee.matrix_world)[:3, :3].T @ [NUDGE, 0.0, 0.0] # NUDGE along the world's x, in the tee's frame -send("setObjectTransform", targetObjectName="Nozzle", location=(np.array(nozzle.matrix_basis)[:3, 3] + push).tolist()) -found = connection("Nozzle") or {} -check("a child moved by NUDGE does not hold, and its residual is the move", found.get("holds") is False - and abs(reading("nudged", found.get("residual") or 0.0) - NUDGE) < 0.1 * NUDGE, found) -send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") -check("and set_params on its parent seats it again", holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) -for written in (float("nan"), "x"): # a kit_roll nobody's attach wrote - nozzle["kit_roll"] = written + # --- drift and detach --------------------------------------------------------------------------------------------------------- + send("setObjectTransform", targetObjectName="Nozzle", location=[0.25, 0.0, 0.0]) found = connection("Nozzle") or {} - check(f"a kit_roll of {written!r} reports roll null and does not hold", found.get("roll", 0.0) is None and found.get("holds") is False - and found.get("residual", 0.0) is None and found.get("parent") == "Tee", found) - refused(f"set_params on a child whose kit_roll is {written!r}", "brokkr_kitbash.set_params", {"object_name": "Nozzle", "params": "exit_r=0.3"}, - "'Nozzle' on 'Tee': its kit_roll is not a number: detach it and attach it again") - refused(f"set_params on the parent of a child whose kit_roll is {written!r}", "brokkr_kitbash.set_params", {"object_name": "Tee", "params": "run=0.6"}, - "'Nozzle' on 'Tee': its kit_roll is not a number") -receipt, report = send("brokkr_kitbash.detach", object_name="Nozzle") -check("detach clears a roll that is not a number", receipt["status"] == "accepted" and nozzle.parent is None and report and report["connection"] is None - and "kit_roll" not in nozzle, [receipt["message"], dict(nozzle.items())]) -receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0) -check("and the nozzle attaches again", receipt["status"] == "accepted" and held(report) and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) -send("setObjectParent", targetObjectName="Spare", parentObjectName="") -found = connection("Spare") -check("setObjectParent clearing an attached child's parent shows as a connection with no parent", found and found == {**found, "parent": None, "holds": False, "residual": None}, found) -refused("set_params on a part whose connection has no parent", "brokkr_kitbash.set_params", {"object_name": "Spare", "params": "exit_r=0.3"}, - "'Spare' states a connection and has no parent") -send("setObjectParent", targetObjectName="Spare", parentObjectName="Plain") -found = connection("Spare") or {} -refused("set_params on a part parented to something that is not a kit part", "brokkr_kitbash.set_params", {"object_name": "Spare", "params": "exit_r=0.3"}, - "'Plain' is not a kit part") -receipt, report = send("brokkr_kitbash.detach", object_name="Spare") -check("detach clears what is left of it", found.get("holds") is False and found.get("parent") == "Plain" and receipt["status"] == "accepted" and spare.parent is None - and report and report["connection"] is None and not [k for k in spare.keys() if k in ("kit_socket", "kit_parent_socket", "kit_roll")], [found, report]) + check("setObjectTransform on an attached child shows in its report: holds false, with the residual", found.get("holds") is False and found["parent"] == "Tee" + and found["residual"] > 0.1, found) + refused("attach of a drifted child, which still has its parent", "brokkr_kitbash.attach", + {"object_name": "Nozzle", "socket": "mount", "parent_name": "Tee", "parent_socket": "c"}, "'Nozzle' has a parent, 'Tee'") + send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") + check("set_params on its parent seats it again", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED, + connection("Nozzle")) + send("setObjectTransform", targetObjectName="Nozzle", rotationEuler=[0.0, 0.5, 0.0]) + drifted = connection("Nozzle") or {} + send("brokkr_kitbash.set_params", object_name="Nozzle", params="exit_r=0.3") + check("set_params on the drifted child itself seats it again", drifted.get("holds") is False and holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and reading("seated", seated(nozzle, "mount", tee, "c", 37.0)) < SEATED, [drifted, connection("Nozzle")]) + nozzle.matrix_parent_inverse = nozzle.matrix_basis.inverted() # as parenting by hand in the viewport leaves it; the basis below keeps the nozzle where it is + nozzle.matrix_basis = nozzle.matrix_basis @ nozzle.matrix_basis + bpy.context.view_layer.update() + found = connection("Nozzle") or {} + check("a parent inverse that is not the identity does not hold, wherever the child stands", found.get("holds") is False and found["residual"] <= 1e-5 + and seated(nozzle, "mount", tee, "c") < SEATED, found) + send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") + check("and set_params on the parent writes the identity back", holds("Nozzle", "Tee", "mount", "c", 37.0)[0] + and np.array_equal(np.array(nozzle.matrix_parent_inverse), np.eye(4)), connection("Nozzle")) + push = np.array(tee.matrix_world)[:3, :3].T @ [NUDGE, 0.0, 0.0] # NUDGE along the world's x, in the tee's frame + send("setObjectTransform", targetObjectName="Nozzle", location=(np.array(nozzle.matrix_basis)[:3, 3] + push).tolist()) + found = connection("Nozzle") or {} + check("a child moved by NUDGE does not hold, and its residual is the move", found.get("holds") is False + and abs(reading("nudged", found.get("residual") or 0.0) - NUDGE) < 0.1 * NUDGE, found) + send("brokkr_kitbash.set_params", object_name="Tee", params="run=0.6") + check("and set_params on its parent seats it again", holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) + for written in (float("nan"), "x"): # a kit_roll nobody's attach wrote + nozzle["kit_roll"] = written + found = connection("Nozzle") or {} + check(f"a kit_roll of {written!r} reports roll null and does not hold", found.get("roll", 0.0) is None and found.get("holds") is False + and found.get("residual", 0.0) is None and found.get("parent") == "Tee", found) + refused(f"set_params on a child whose kit_roll is {written!r}", "brokkr_kitbash.set_params", {"object_name": "Nozzle", "params": "exit_r=0.3"}, + "'Nozzle' on 'Tee': its kit_roll is not a number: detach it and attach it again") + refused(f"set_params on the parent of a child whose kit_roll is {written!r}", "brokkr_kitbash.set_params", {"object_name": "Tee", "params": "run=0.6"}, + "'Nozzle' on 'Tee': its kit_roll is not a number") + receipt, report = send("brokkr_kitbash.detach", object_name="Nozzle") + check("detach clears a roll that is not a number", receipt["status"] == "accepted" and nozzle.parent is None and report and report["connection"] is None + and "kit_roll" not in nozzle, [receipt["message"], dict(nozzle.items())]) + receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0) + check("and the nozzle attaches again", receipt["status"] == "accepted" and held(report) and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) + send("setObjectParent", targetObjectName="Spare", parentObjectName="") + found = connection("Spare") + check("setObjectParent clearing an attached child's parent shows as a connection with no parent", found and found == {**found, "parent": None, "holds": False, "residual": None}, found) + refused("set_params on a part whose connection has no parent", "brokkr_kitbash.set_params", {"object_name": "Spare", "params": "exit_r=0.3"}, + "'Spare' states a connection and has no parent") + send("setObjectParent", targetObjectName="Spare", parentObjectName="Plain") + found = connection("Spare") or {} + refused("set_params on a part parented to something that is not a kit part", "brokkr_kitbash.set_params", {"object_name": "Spare", "params": "exit_r=0.3"}, + "'Plain' is not a kit part") + receipt, report = send("brokkr_kitbash.detach", object_name="Spare") + check("detach clears what is left of it", found.get("holds") is False and found.get("parent") == "Plain" and receipt["status"] == "accepted" and spare.parent is None + and report and report["connection"] is None and not [k for k in spare.keys() if k in ("kit_socket", "kit_parent_socket", "kit_roll")], [found, report]) -before = {name: np.array(bpy.data.objects[name].matrix_world) for name in ("Tee", "Nozzle")} -receipt, report = send("brokkr_kitbash.detach", object_name="Tee") -check("detach leaves the tee where it stood, with no parent and no connection", receipt["status"] == "accepted" and tee.parent is None - and report and report["connection"] is None and sorted(k for k in tee.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_part"] - and reading("kept", max(np.abs(np.array(bpy.data.objects[n].matrix_world) - before[n]).max() for n in before)) < KEPT, [receipt["message"], R["readings"]]) -check("and the nozzle stays attached to the tee", nozzle.parent == tee and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) -send("brokkr_kitbash.attach", object_name="Tee", socket="b", parent_name="Tank", parent_socket="port_a", roll=180.0) -check("the freed tee attaches by another socket to the tank's other port", holds("Tee", "Tank", "b", "port_a", 180.0)[0] - and reading("seated", seated(tee, "b", tank, "port_a", 180.0)) < SEATED and R["readings"]["roll"] < ROLL, connection("Tee")) + before = {name: np.array(bpy.data.objects[name].matrix_world) for name in ("Tee", "Nozzle")} + receipt, report = send("brokkr_kitbash.detach", object_name="Tee") + check("detach leaves the tee where it stood, with no parent and no connection", receipt["status"] == "accepted" and tee.parent is None + and report and report["connection"] is None and sorted(k for k in tee.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_part"] + and reading("kept", max(np.abs(np.array(bpy.data.objects[n].matrix_world) - before[n]).max() for n in before)) < KEPT, [receipt["message"], R["readings"]]) + check("and the nozzle stays attached to the tee", nozzle.parent == tee and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], connection("Nozzle")) + send("brokkr_kitbash.attach", object_name="Tee", socket="b", parent_name="Tank", parent_socket="port_a", roll=180.0) + check("the freed tee attaches by another socket to the tank's other port", holds("Tee", "Tank", "b", "port_a", 180.0)[0] + and reading("seated", seated(tee, "b", tank, "port_a", 180.0)) < SEATED and R["readings"]["roll"] < ROLL, connection("Tee")) -# --- boolean: the tank, with two material slots ----------------------------------------------------------------------------------- -send("assignMaterial", targetObjectName="Tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) -send("assignMaterial", targetObjectName="Tank", materialName="Strap Steel", color=[0.2, 0.2, 0.2]) -tank_built = core.build(kit["parts"]["tank"], json.loads(tank["kit_params"])) -STRAPS = 1 # the tank's second shape: the repeat of two straps -tank.data.polygons.foreach_set("material_index", np.where(tank_built.shape == STRAPS, 1, 0).astype(np.int32)) -side = np.array(tank.matrix_world) @ [0.0, -0.22, 0.4564, 1.0] # under the barrel at the lower cradle: cradle, pad, strap and wall -send("createObject", objectType="MESH", name="Box", location=side[:3].tolist(), size=0.3) -box = bpy.data.objects["Box"] -box_was = (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) -raw = measure(tank.data) -receipt, cut = send("brokkr_kitbash.boolean", object_name="Tank", cutter="Box") -modifier = tank.modifiers.get("Kit Difference") -check("boolean adds one Boolean modifier above the Bevel: Exact, self-intersection on, difference, over a collection that holds the cutter and is in no scene", - receipt["status"] == "accepted" and [m.name for m in tank.modifiers] == ["Kit Difference", "Kit Bevel"] and modifier is not None and modifier.type == "BOOLEAN" - and (modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.object) == ("EXACT", True, "DIFFERENCE", "COLLECTION", None) - and modifier.collection.objects[:] == [box] and modifier.collection.name == "Tank difference" - and not any(modifier.collection in c.children_recursive for c in [s.collection for s in bpy.data.scenes]), - [receipt["message"], [m.name for m in tank.modifiers]]) -shown, shown_slots = evaluated(tank) -check("boolean reports the evaluated mesh, with less volume than the uncut tank and no non-manifold edge", cut and cut["evaluated"] == shown - and CUT < reading("cut", cut["evaluated"]["volume"]) < raw["volume"] - 0.005 and cut["evaluated"]["nonManifoldEdges"] == 0 - and int(np.count_nonzero(tank_built.shape == STRAPS)) == 2 * 4 * 24 - and cut["booleans"] == [{"cutter": "Box", "operation": "DIFFERENCE"}] and cut["faces"] == len(tank.data.polygons) == raw["faces"], - [cut and cut["evaluated"], shown, raw]) -R["tank"] = {"raw": raw, "cut": cut and cut["evaluated"]} -check("the cut tank shows the tank's two material slots and no other", shown_slots == ["Tank Paint", "Strap Steel"] and modifier is not None and modifier.material_mode == "TRANSFER", shown_slots) -check("boolean leaves the cutter as it was", (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) == box_was - and "kit_part" not in box and bpy.context.scene.collection in box.users_collection, box_was) -refused("a cutter that already cuts the part", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Box", "operation": "UNION"}, - "'Box' already cuts 'Tank' (its Kit Difference modifier's collection)") -refused("the part as its own cutter", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Tank"}, "cannot cut itself") -refused("a cutter that does not exist", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Nothing"}, "No mesh object named 'Nothing'") -send("createObject", objectType="EMPTY", name="Marker") -refused("a cutter that is not a mesh", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Marker"}, "No mesh object named 'Marker'") -receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="segments=16") -resized, _ = evaluated(tank) -check("set_params on the cut tank rebuilds it under the live Boolean, and the tee stays on its port", receipt["status"] == "accepted" - and [m.name for m in tank.modifiers] == ["Kit Difference", "Kit Bevel"] and tank.modifiers["Kit Difference"].collection.objects[:] == [box] - and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], report["params"]).counts) != raw["faces"] - and CUT < resized["volume"] < measure(tank.data)["volume"] - 0.005 and holds("Tee", "Tank", "b", "port_a", 180.0)[0], [receipt["message"], resized]) + # --- boolean: the tank, with two material slots ----------------------------------------------------------------------------------- + send("assignMaterial", targetObjectName="Tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) + send("assignMaterial", targetObjectName="Tank", materialName="Strap Steel", color=[0.2, 0.2, 0.2]) + tank_built = core.build(kit["parts"]["tank"], json.loads(tank["kit_params"])) + STRAPS = 1 # the tank's second shape: the repeat of two straps + tank.data.polygons.foreach_set("material_index", np.where(tank_built.shape == STRAPS, 1, 0).astype(np.int32)) + side = np.array(tank.matrix_world) @ [0.0, -0.22, 0.4564, 1.0] # under the barrel at the lower cradle: cradle, pad, strap and wall + send("createObject", objectType="MESH", name="Box", location=side[:3].tolist(), size=0.3) + box = bpy.data.objects["Box"] + box_was = (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) + raw = measure(tank.data) + receipt, cut = send("brokkr_kitbash.boolean", object_name="Tank", cutter="Box") + modifier = tank.modifiers.get("Kit Difference") + check("boolean adds one Boolean modifier above the Bevel: Exact, self-intersection on, difference, over a collection that holds the cutter and is in no scene", + receipt["status"] == "accepted" and [m.name for m in tank.modifiers] == ["Kit Difference", "Kit Bevel"] and modifier is not None and modifier.type == "BOOLEAN" + and (modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.object) == ("EXACT", True, "DIFFERENCE", "COLLECTION", None) + and modifier.collection.objects[:] == [box] and modifier.collection.name == "Tank difference" + and not any(modifier.collection in c.children_recursive for c in [s.collection for s in bpy.data.scenes]), + [receipt["message"], [m.name for m in tank.modifiers]]) + shown, shown_slots = evaluated(tank) + check("boolean reports the evaluated mesh, with less volume than the uncut tank and no non-manifold edge", cut and cut["evaluated"] == shown + and CUT < reading("cut", cut["evaluated"]["volume"]) < raw["volume"] - 0.005 and cut["evaluated"]["nonManifoldEdges"] == 0 + and int(np.count_nonzero(tank_built.shape == STRAPS)) == 2 * 4 * 24 + and cut["booleans"] == [{"cutter": "Box", "operation": "DIFFERENCE"}] and cut["faces"] == len(tank.data.polygons) == raw["faces"], + [cut and cut["evaluated"], shown, raw]) + R["tank"] = {"raw": raw, "cut": cut and cut["evaluated"]} + check("the cut tank shows the tank's two material slots and no other", shown_slots == ["Tank Paint", "Strap Steel"] and modifier is not None and modifier.material_mode == "TRANSFER", shown_slots) + check("boolean leaves the cutter as it was", (box.hide_render, box.hide_viewport, len(box.data.polygons), [m.name for m in box.modifiers], box.parent) == box_was + and "kit_part" not in box and bpy.context.scene.collection in box.users_collection, box_was) + refused("a cutter that already cuts the part", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Box", "operation": "UNION"}, + "'Box' already cuts 'Tank' (its Kit Difference modifier's collection)") + refused("the part as its own cutter", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Tank"}, "cannot cut itself") + refused("a cutter that does not exist", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Nothing"}, "No mesh object named 'Nothing'") + send("createObject", objectType="EMPTY", name="Marker") + refused("a cutter that is not a mesh", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Marker"}, "No mesh object named 'Marker'") + receipt, report = send("brokkr_kitbash.set_params", object_name="Tank", params="segments=16") + resized, _ = evaluated(tank) + check("set_params on the cut tank rebuilds it under the live Boolean, and the tee stays on its port", receipt["status"] == "accepted" + and [m.name for m in tank.modifiers] == ["Kit Difference", "Kit Bevel"] and tank.modifiers["Kit Difference"].collection.objects[:] == [box] + and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], report["params"]).counts) != raw["faces"] + and CUT < resized["volume"] < measure(tank.data)["volume"] - 0.005 and holds("Tee", "Tank", "b", "port_a", 180.0)[0], [receipt["message"], resized]) -# --- apply ------------------------------------------------------------------------------------------------------------------------ -refused("apply on a mesh that is not a kit part", "brokkr_kitbash.apply", {"object_name": "Plain"}, "'Plain' is not a kit part") -slots = [s.material and s.material.name for s in tank.material_slots] -shown, shown_slots = evaluated(tank) -index = np.zeros(len(tank.data.polygons), dtype=np.int32) -tank.data.polygons.foreach_get("material_index", index) -mesh_name, meshes, collections = tank.data.name, len(bpy.data.meshes), len(bpy.data.collections) -sockets_before = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["sockets"] -receipt, baked = send("brokkr_kitbash.apply", object_name="Tank") -after = np.zeros(len(tank.data.polygons), dtype=np.int32) -tank.data.polygons.foreach_get("material_index", after) -check("apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name", - receipt["status"] == "accepted" and baked and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown == measure(tank.data) - and len(tank.modifiers) == 0 and tank.data.name == mesh_name and len(bpy.data.meshes) == meshes and baked["cutters"] == ["Box"] - and len(bpy.data.collections) == collections - 1 and "Tank difference" not in bpy.data.collections and "Box" in bpy.context.scene.objects, [receipt["message"], baked, shown]) -check("apply keeps the material slots exactly, and faces of both materials", slots == shown_slots == ["Tank Paint", "Strap Steel"] - and [s.material and s.material.name for s in tank.material_slots] == slots and [m and m.name for m in tank.data.materials] == slots - and index.max() == 1 and sorted(set(after.tolist())) == [0, 1], [slots, [m and m.name for m in tank.data.materials], sorted(set(after.tolist()))]) -check("apply marks the part baked and keeps what it is", tank.get("kit_baked") is True and baked and baked["baked"] is True and tank["kit_part"] == "tank" - and json.loads(tank["kit_params"])["segments"] == 16, dict(tank.items())) -refused("set_params on a baked part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, "'Tank' is baked") -refused("apply on a baked part with no modifiers left", "brokkr_kitbash.apply", {"object_name": "Tank"}, "'Tank' has no modifiers to apply") -receipt, report = send("brokkr_kitbash.report", object_name="Tank") -check("a baked part still reports its sockets where its params put them, and what is attached to it still holds", report and report["parts"][0]["baked"] is True - and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == baked["faces"] and holds("Tee", "Tank", "b", "port_a", 180.0)[0] - and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], report) -receipt, report = send("brokkr_kitbash.attach", object_name="Radiator", socket="base", parent_name="Tank", parent_socket="saddle") -check("a new part attaches to a baked one", receipt["status"] == "accepted" and held(report) - and reading("seated", seated(radiator, "base", tank, "saddle", 0.0)) < SEATED, receipt["message"]) + # --- apply ------------------------------------------------------------------------------------------------------------------------ + refused("apply on a mesh that is not a kit part", "brokkr_kitbash.apply", {"object_name": "Plain"}, "'Plain' is not a kit part") + slots = [s.material and s.material.name for s in tank.material_slots] + shown, shown_slots = evaluated(tank) + index = np.zeros(len(tank.data.polygons), dtype=np.int32) + tank.data.polygons.foreach_get("material_index", index) + mesh_name, meshes, collections = tank.data.name, len(bpy.data.meshes), len(bpy.data.collections) + sockets_before = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["sockets"] + receipt, baked = send("brokkr_kitbash.apply", object_name="Tank") + after = np.zeros(len(tank.data.polygons), dtype=np.int32) + tank.data.polygons.foreach_get("material_index", after) + check("apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name", + receipt["status"] == "accepted" and baked and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown == measure(tank.data) + and len(tank.modifiers) == 0 and tank.data.name == mesh_name and len(bpy.data.meshes) == meshes and baked["cutters"] == ["Box"] + and len(bpy.data.collections) == collections - 1 and "Tank difference" not in bpy.data.collections and "Box" in bpy.context.scene.objects, [receipt["message"], baked, shown]) + check("apply keeps the material slots exactly, and faces of both materials", slots == shown_slots == ["Tank Paint", "Strap Steel"] + and [s.material and s.material.name for s in tank.material_slots] == slots and [m and m.name for m in tank.data.materials] == slots + and index.max() == 1 and sorted(set(after.tolist())) == [0, 1], [slots, [m and m.name for m in tank.data.materials], sorted(set(after.tolist()))]) + check("apply marks the part baked and keeps what it is", tank.get("kit_baked") is True and baked and baked["baked"] is True and tank["kit_part"] == "tank" + and json.loads(tank["kit_params"])["segments"] == 16, dict(tank.items())) + refused("set_params on a baked part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, "'Tank' is baked") + refused("apply on a baked part with no modifiers left", "brokkr_kitbash.apply", {"object_name": "Tank"}, "'Tank' has no modifiers to apply") + receipt, report = send("brokkr_kitbash.report", object_name="Tank") + check("a baked part still reports its sockets where its params put them, and what is attached to it still holds", report and report["parts"][0]["baked"] is True + and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == baked["faces"] and holds("Tee", "Tank", "b", "port_a", 180.0)[0] + and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], report) + receipt, report = send("brokkr_kitbash.attach", object_name="Radiator", socket="base", parent_name="Tank", parent_socket="saddle") + check("a new part attaches to a baked one", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(radiator, "base", tank, "saddle", 0.0)) < SEATED, receipt["message"]) -# --- the second target: a plate with no material slot, cut twice ---------------------------------------------------------------------- -plate = place("Plate", "plate", location=[0.0, -3.0, 0.0]) -send("createObject", objectType="MESH", name="Slot", location=[0.1, -3.0, 0.0], size=0.1) -send("createObject", objectType="MESH", name="Hole", location=[-0.1, -3.0, 0.0], size=0.05) -receipt, first = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Slot") -receipt, second = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Hole") -check("two cutters share one Boolean modifier above the Bevel, in its collection in the order they came", receipt["status"] == "accepted" - and [m.name for m in plate.modifiers] == ["Kit Difference", "Kit Bevel"] - and [o.name for o in plate.modifiers["Kit Difference"].collection.objects] == ["Slot", "Hole"] - and second["booleans"] == [{"cutter": "Slot", "operation": "DIFFERENCE"}, {"cutter": "Hole", "operation": "DIFFERENCE"}] - and second["evaluated"]["volume"] < first["evaluated"]["volume"] and first["evaluated"]["nonManifoldEdges"] == second["evaluated"]["nonManifoldEdges"] == 0 - and all(m.use_self and m.solver == "EXACT" for m in plate.modifiers if m.type == "BOOLEAN"), - [[m.name for m in plate.modifiers], first and first["evaluated"], second and second["evaluated"]]) -R["plate"] = {"raw": measure(plate.data), "slot": first and first["evaluated"], "slotAndHole": second and second["evaluated"]} -twin = plate.copy() -twin.name = "Plate_twin" -bpy.context.scene.collection.objects.link(twin) -refused("apply on a mesh a linked duplicate shares", "brokkr_kitbash.apply", {"object_name": "Plate"}, "shares its mesh 'Plate' with 1 other user(s): baking it") -bpy.data.objects.remove(twin) -shown, shown_slots = evaluated(plate) -receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") -check("apply on a part with no material slot leaves it with none (Blender's Boolean shows it with one empty slot)", receipt["status"] == "accepted" - and shown_slots == [None] and len(plate.data.materials) == 0 and len(plate.material_slots) == 0 and baked["cutters"] == ["Slot", "Hole"] - and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown, [shown_slots, len(plate.data.materials), len(plate.material_slots), baked]) -send("assignMaterial", targetObjectName="Plate", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) -send("createObject", objectType="MESH", name="Boss", location=[0.0, -3.0, 0.1], size=0.06) -send("assignMaterial", targetObjectName="Boss", materialName="Boss Brass", color=[0.6, 0.5, 0.2]) -send("setObjectTransform", targetObjectName="Boss", location=[0.0, -3.0, 0.02]) -receipt, third = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Boss", operation="UNION") -shown, shown_slots = evaluated(plate) -receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") -used = np.zeros(len(plate.data.polygons), dtype=np.int32) -plate.data.polygons.foreach_get("material_index", used) -check("a baked part is cut and baked again; a cutter that has a material brings it after the part's own slots, on the faces it made", - receipt["status"] == "accepted" and third["booleans"] == [{"cutter": "Boss", "operation": "UNION"}] and third["baked"] is True - and third["evaluated"]["volume"] > R["plate"]["slotAndHole"]["volume"] and shown_slots == ["Plate Paint", "Boss Brass"] - and [m and m.name for m in plate.data.materials] == ["Plate Paint", "Boss Brass"] and sorted(set(used.tolist())) == [0, 1] - and len(plate.modifiers) == 0, [third and third["evaluated"], shown_slots, [m and m.name for m in plate.data.materials], sorted(set(used.tolist()))]) -vent = place("Vent", "vent", "width=0.2; height=0.15") -receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Plate", parent_socket="front") -check("a vent that fits attaches to the baked plate's front", receipt["status"] == "accepted" and held(report) - and reading("seated", seated(vent, "back", plate, "front", 0.0)) < SEATED, receipt["message"]) -refused("a loop of two", "brokkr_kitbash.attach", {"object_name": "Plate", "socket": "back", "parent_name": "Vent", "parent_socket": "back"}, - "'Vent' is below 'Plate'") -big = place("Big", "vent", "width=0.8; height=0.6") -refused("a part larger than the seat", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Plate", "parent_socket": "back"}, - "are mount sockets, where the child fits the parent: it is larger") + # --- the second target: a plate with no material slot, cut twice ---------------------------------------------------------------------- + plate = place("Plate", "plate", location=[0.0, -3.0, 0.0]) + send("createObject", objectType="MESH", name="Slot", location=[0.1, -3.0, 0.0], size=0.1) + send("createObject", objectType="MESH", name="Hole", location=[-0.1, -3.0, 0.0], size=0.05) + receipt, first = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Slot") + receipt, second = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Hole") + check("two cutters share one Boolean modifier above the Bevel, in its collection in the order they came", receipt["status"] == "accepted" + and [m.name for m in plate.modifiers] == ["Kit Difference", "Kit Bevel"] + and [o.name for o in plate.modifiers["Kit Difference"].collection.objects] == ["Slot", "Hole"] + and second["booleans"] == [{"cutter": "Slot", "operation": "DIFFERENCE"}, {"cutter": "Hole", "operation": "DIFFERENCE"}] + and second["evaluated"]["volume"] < first["evaluated"]["volume"] and first["evaluated"]["nonManifoldEdges"] == second["evaluated"]["nonManifoldEdges"] == 0 + and all(m.use_self and m.solver == "EXACT" for m in plate.modifiers if m.type == "BOOLEAN"), + [[m.name for m in plate.modifiers], first and first["evaluated"], second and second["evaluated"]]) + R["plate"] = {"raw": measure(plate.data), "slot": first and first["evaluated"], "slotAndHole": second and second["evaluated"]} + twin = plate.copy() + twin.name = "Plate_twin" + bpy.context.scene.collection.objects.link(twin) + refused("apply on a mesh a linked duplicate shares", "brokkr_kitbash.apply", {"object_name": "Plate"}, "shares its mesh 'Plate' with 1 other user(s): baking it") + bpy.data.objects.remove(twin) + shown, shown_slots = evaluated(plate) + receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") + check("apply on a part with no material slot leaves it with none (Blender's Boolean shows it with one empty slot)", receipt["status"] == "accepted" + and shown_slots == [None] and len(plate.data.materials) == 0 and len(plate.material_slots) == 0 and baked["cutters"] == ["Slot", "Hole"] + and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown, [shown_slots, len(plate.data.materials), len(plate.material_slots), baked]) + send("assignMaterial", targetObjectName="Plate", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) + send("createObject", objectType="MESH", name="Boss", location=[0.0, -3.0, 0.1], size=0.06) + send("assignMaterial", targetObjectName="Boss", materialName="Boss Brass", color=[0.6, 0.5, 0.2]) + send("setObjectTransform", targetObjectName="Boss", location=[0.0, -3.0, 0.02]) + receipt, third = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Boss", operation="UNION") + shown, shown_slots = evaluated(plate) + receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") + used = np.zeros(len(plate.data.polygons), dtype=np.int32) + plate.data.polygons.foreach_get("material_index", used) + check("a baked part is cut and baked again; a cutter that has a material brings it after the part's own slots, on the faces it made", + receipt["status"] == "accepted" and third["booleans"] == [{"cutter": "Boss", "operation": "UNION"}] and third["baked"] is True + and third["evaluated"]["volume"] > R["plate"]["slotAndHole"]["volume"] and shown_slots == ["Plate Paint", "Boss Brass"] + and [m and m.name for m in plate.data.materials] == ["Plate Paint", "Boss Brass"] and sorted(set(used.tolist())) == [0, 1] + and len(plate.modifiers) == 0, [third and third["evaluated"], shown_slots, [m and m.name for m in plate.data.materials], sorted(set(used.tolist()))]) + vent = place("Vent", "vent", "width=0.2; height=0.15") + receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Plate", parent_socket="front") + check("a vent that fits attaches to the baked plate's front", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(vent, "back", plate, "front", 0.0)) < SEATED, receipt["message"]) + refused("a loop of two", "brokkr_kitbash.attach", {"object_name": "Plate", "socket": "back", "parent_name": "Vent", "parent_socket": "back"}, + "'Vent' is below 'Plate'") + big = place("Big", "vent", "width=0.8; height=0.6") + refused("a part larger than the seat", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Plate", "parent_socket": "back"}, + "are mount sockets, where the child fits the parent: it is larger") -# --- a tee is one solid under the Boolean ----------------------------------------------------------------------------------------- -place("Cross", "pipe_fitting", location=[0.0, -6.0, 0.0]) # pipe_r 0.05, the default -send("createObject", objectType="MESH", name="Bar", location=[0.0, -6.0, 0.0], size=1.0) -send("setObjectTransform", targetObjectName="Bar", scale=[0.3, 3.0, 0.3]) -receipt, cut = send("brokkr_kitbash.boolean", object_name="Cross", cutter="Bar") -R["tee"] = cut and cut["evaluated"] -check("a tee with a box cut from it has no non-manifold edge: its branch hub is narrower than its run hub", receipt["status"] == "accepted" and cut - and cut["evaluated"]["nonManifoldEdges"] == 0 and 0.004 < cut["evaluated"]["volume"] < 0.008, [receipt["message"], cut and cut["evaluated"]]) + # --- a tee is one solid under the Boolean ----------------------------------------------------------------------------------------- + place("Cross", "pipe_fitting", location=[0.0, -6.0, 0.0]) # pipe_r 0.05, the default + send("createObject", objectType="MESH", name="Bar", location=[0.0, -6.0, 0.0], size=1.0) + send("setObjectTransform", targetObjectName="Bar", scale=[0.3, 3.0, 0.3]) + receipt, cut = send("brokkr_kitbash.boolean", object_name="Cross", cutter="Bar") + R["tee"] = cut and cut["evaluated"] + check("a tee with a box cut from it has no non-manifold edge: its branch hub is narrower than its run hub", receipt["status"] == "accepted" and cut + and cut["evaluated"]["nonManifoldEdges"] == 0 and 0.004 < cut["evaluated"]["volume"] < 0.008, [receipt["message"], cut and cut["evaluated"]]) -# --- apply and empty material slots ----------------------------------------------------------------------------------------------- -keeper = place("Keeper", "plate", location=[0.0, -9.0, 0.0]) -send("assignMaterial", targetObjectName="Keeper", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) -keeper.data.materials.append(None) # an empty last slot the part was given -send("createObject", objectType="MESH", name="Bare", location=[0.1, -9.0, 0.0], size=0.1) -send("brokkr_kitbash.boolean", object_name="Keeper", cutter="Bare") -receipt, baked = send("brokkr_kitbash.apply", object_name="Keeper") -check("apply keeps a part's own empty last slot when the cutter has no material", receipt["status"] == "accepted" - and [m and m.name for m in keeper.data.materials] == ["Plate Paint", None] and len(keeper.material_slots) == 2, - [receipt["message"], [m and m.name for m in keeper.data.materials]]) -gapped = place("Gapped", "plate", location=[0.0, -12.0, 0.0]) -send("assignMaterial", targetObjectName="Gapped", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) -send("createObject", objectType="MESH", name="Gap", location=[0.1, -12.0, 0.0], size=0.1) -gap = bpy.data.objects["Gap"] -gap.data.materials.append(None) # the cutter's faces are in an empty first slot -gap.data.materials.append(bpy.data.materials["Boss Brass"]) -gap.data.polygons[0].material_index = gap.data.polygons[1].material_index = 1 # two of its faces are brass; the rest stay in the empty slot -send("brokkr_kitbash.boolean", object_name="Gapped", cutter="Gap") -receipt, baked = send("brokkr_kitbash.apply", object_name="Gapped") -used = np.zeros(len(gapped.data.polygons), dtype=np.int32) -gapped.data.polygons.foreach_get("material_index", used) -check("apply leaves no face outside the material slots when a cutter's first slot is empty", receipt["status"] == "accepted" and len(used) > 44 - and used.min() >= 0 and used.max() < len(gapped.data.materials) and not gapped.data.validate_material_indices() and not gapped.data.validate(verbose=False), - [receipt["message"], int(used.min()), int(used.max()), [m and m.name for m in gapped.data.materials]]) -names = [m and m.name for m in gapped.data.materials] -brass = [p.index for p in gapped.data.polygons if "Boss Brass" in names and p.material_index == names.index("Boss Brass")] -far = [p.index for p in gapped.data.polygons if (gapped.matrix_world @ p.center).x < -0.05] # the plate's half the cutter does not reach -check("and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", - names[0] == "Plate Paint" and 0 < len(brass) < len(used) and far and all(used[i] == 0 for i in far) - and all(abs((gapped.matrix_world @ gapped.data.polygons[i].center).x - 0.1) < 0.051 for i in brass), [names, len(brass), len(far), sorted(set(used.tolist()))]) + # --- apply and empty material slots ----------------------------------------------------------------------------------------------- + keeper = place("Keeper", "plate", location=[0.0, -9.0, 0.0]) + send("assignMaterial", targetObjectName="Keeper", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) + keeper.data.materials.append(None) # an empty last slot the part was given + send("createObject", objectType="MESH", name="Bare", location=[0.1, -9.0, 0.0], size=0.1) + send("brokkr_kitbash.boolean", object_name="Keeper", cutter="Bare") + receipt, baked = send("brokkr_kitbash.apply", object_name="Keeper") + check("apply keeps a part's own empty last slot when the cutter has no material", receipt["status"] == "accepted" + and [m and m.name for m in keeper.data.materials] == ["Plate Paint", None] and len(keeper.material_slots) == 2, + [receipt["message"], [m and m.name for m in keeper.data.materials]]) + gapped = place("Gapped", "plate", location=[0.0, -12.0, 0.0]) + send("assignMaterial", targetObjectName="Gapped", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) + send("createObject", objectType="MESH", name="Gap", location=[0.1, -12.0, 0.0], size=0.1) + gap = bpy.data.objects["Gap"] + gap.data.materials.append(None) # the cutter's faces are in an empty first slot + gap.data.materials.append(bpy.data.materials["Boss Brass"]) + gap.data.polygons[0].material_index = gap.data.polygons[1].material_index = 1 # two of its faces are brass; the rest stay in the empty slot + send("brokkr_kitbash.boolean", object_name="Gapped", cutter="Gap") + receipt, baked = send("brokkr_kitbash.apply", object_name="Gapped") + used = np.zeros(len(gapped.data.polygons), dtype=np.int32) + gapped.data.polygons.foreach_get("material_index", used) + check("apply leaves no face outside the material slots when a cutter's first slot is empty", receipt["status"] == "accepted" and len(used) > 44 + and used.min() >= 0 and used.max() < len(gapped.data.materials) and not gapped.data.validate_material_indices() and not gapped.data.validate(verbose=False), + [receipt["message"], int(used.min()), int(used.max()), [m and m.name for m in gapped.data.materials]]) + names = [m and m.name for m in gapped.data.materials] + brass = [p.index for p in gapped.data.polygons if "Boss Brass" in names and p.material_index == names.index("Boss Brass")] + far = [p.index for p in gapped.data.polygons if (gapped.matrix_world @ p.center).x < -0.05] # the plate's half the cutter does not reach + check("and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", + names[0] == "Plate Paint" and 0 < len(brass) < len(used) and far and all(used[i] == 0 for i in far) + and all(abs((gapped.matrix_world @ gapped.data.polygons[i].center).x - 0.1) < 0.051 for i in brass), [names, len(brass), len(far), sorted(set(used.tolist()))]) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) R["ok"] = all(c["ok"] for c in R["checks"]) R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} diff --git a/surfaces/blender/tests/live/kitbash_pose.py b/surfaces/blender/tests/live/kitbash_pose.py index de26a6f..cfce1ad 100644 --- a/surfaces/blender/tests/live/kitbash_pose.py +++ b/surfaces/blender/tests/live/kitbash_pose.py @@ -5,7 +5,9 @@ and each refusal changes nothing. Not part of the unittest run: it needs Blender blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_pose.py -- Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses -without them). is an absolute path; writes .result.json and exits 1 when a check failed. +without them). is an absolute path; writes .result.json and exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names +the check before it, the checks are printed and the result file written whatever happened, and the exit is 1 with or +without --python-exit-code. The scene: a tank, a bracket on its lug, a strut pinned in the bracket, an actuator pinned on the strut's far end, and a loose strut whose closure names the actuator's rod pin. Bounds follow lodur:ruling:deterministic-bound-margin: @@ -17,6 +19,7 @@ import json import math import os import sys +import traceback import tempfile import types from pathlib import Path @@ -168,143 +171,146 @@ def refused(label, action, fields, expected): [receipt["status"], receipt["message"]]) -rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] -check("roll, aim and reach load as host actions after detach, with no errors", not R["hostErrors"] and "brokkr_kitbash.detach" in rows - and rows[rows.index("brokkr_kitbash.detach") + 1:][:3] == ["brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach"], [R["hostErrors"], rows]) +try: + rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] + check("roll, aim and reach load as host actions after detach, with no errors", not R["hostErrors"] and "brokkr_kitbash.detach" in rows + and rows[rows.index("brokkr_kitbash.detach") + 1:][:3] == ["brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach"], [R["hostErrors"], rows]) -# --- the scene ---------------------------------------------------------------------------------------------------------- -tank = place("Tank", "tank", "radius=0.3; length=1.2", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # lug size 0.09 -mount = place("Mount", "bracket") # pin 0.054, plate 0.09 -strut, ram = place("Strut", "strut", "width=0.09"), place("Ram", "actuator") -spare, orphan = place("Spare", "strut", "width=0.09", location=[0.0, 6.0, 0.0]), place("Orphan", "bracket") -send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3) -send("brokkr_kitbash.attach", object_name="Mount", socket="mount", parent_name="Tank", parent_socket="lug_b") -send("brokkr_kitbash.attach", object_name="Orphan", socket="mount", parent_name="Tank", parent_socket="lug_a") -send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Mount", parent_socket="pivot", roll=20.0) -receipt, report = send("brokkr_kitbash.attach", object_name="Ram", socket="base", parent_name="Strut", parent_socket="end_b", roll=-35.0) -check("the chain stands: tank, bracket, strut, actuator", receipt["status"] == "accepted" and holds(connection("Strut"), "Mount", "end_a", "pivot", 20.0) - and holds(report["connection"], "Strut", "base", "end_b", -35.0), [receipt["message"], connection("Strut")]) + # --- the scene ---------------------------------------------------------------------------------------------------------- + tank = place("Tank", "tank", "radius=0.3; length=1.2", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # lug size 0.09 + mount = place("Mount", "bracket") # pin 0.054, plate 0.09 + strut, ram = place("Strut", "strut", "width=0.09"), place("Ram", "actuator") + spare, orphan = place("Spare", "strut", "width=0.09", location=[0.0, 6.0, 0.0]), place("Orphan", "bracket") + send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3) + send("brokkr_kitbash.attach", object_name="Mount", socket="mount", parent_name="Tank", parent_socket="lug_b") + send("brokkr_kitbash.attach", object_name="Orphan", socket="mount", parent_name="Tank", parent_socket="lug_a") + send("brokkr_kitbash.attach", object_name="Strut", socket="end_a", parent_name="Mount", parent_socket="pivot", roll=20.0) + receipt, report = send("brokkr_kitbash.attach", object_name="Ram", socket="base", parent_name="Strut", parent_socket="end_b", roll=-35.0) + check("the chain stands: tank, bracket, strut, actuator", receipt["status"] == "accepted" and holds(connection("Strut"), "Mount", "end_a", "pivot", 20.0) + and holds(report["connection"], "Strut", "base", "end_b", -35.0), [receipt["message"], connection("Strut")]) -def meeting(name, other, other_socket, roll): - """Place a loose strut so its end_a meets a socket of another part, and close it there.""" - loose = place(name, "strut", "width=0.09") - meet = Matrix((np.array(other.matrix_world) @ core.mate(socket(other, other_socket), socket(loose, "end_a"), roll)).tolist()) - send("setObjectTransform", targetObjectName=name, location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) - return send("brokkr_kitbash.close", object_name=name, socket="end_a", other_name=other.name, other_socket=other_socket) + def meeting(name, other, other_socket, roll): + """Place a loose strut so its end_a meets a socket of another part, and close it there.""" + loose = place(name, "strut", "width=0.09") + meet = Matrix((np.array(other.matrix_world) @ core.mate(socket(other, other_socket), socket(loose, "end_a"), roll)).tolist()) + send("setObjectTransform", targetObjectName=name, location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) + return send("brokkr_kitbash.close", object_name=name, socket="end_a", other_name=other.name, other_socket=other_socket) -anchor = place("Aa_Anchor", "strut", "width=0.09", location=[0.0, -20.0, 0.0]) -receipt, report = meeting("Brace", ram, "rod_end", 50.0) -check("a brace closes on the actuator's rod pin", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) -receipt, report = meeting("Aa_Loose", anchor, "end_b", 40.0) -check("and a second closure, named to sort first, holds far from it", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) -brace = bpy.data.objects["Brace"] -closing = {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} + anchor = place("Aa_Anchor", "strut", "width=0.09", location=[0.0, -20.0, 0.0]) + receipt, report = meeting("Brace", ram, "rod_end", 50.0) + check("a brace closes on the actuator's rod pin", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) + receipt, report = meeting("Aa_Loose", anchor, "end_b", 40.0) + check("and a second closure, named to sort first, holds far from it", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) + brace = bpy.data.objects["Brace"] + closing = {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} -# --- roll: in place ----------------------------------------------------------------------------------------------------- -for turn in (65.0, -160.0, 35.0): # from the 20 it was attached at - was, pin, before = stated(strut), frame(ram, "base")[:3, 3].copy(), (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) - sent = COUNT[0] - receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=turn) - gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", turn)), R["readings"]["roll"] - check(f"roll {turn:g} turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated", - receipt["status"] == "accepted" and COUNT[0] == sent + 1 and stated(strut) == was and strut["kit_roll"] == turn and gap < SEATED and off < ROLL - and report and report["object"] == "Strut" and holds(report["connection"], "Mount", "end_a", "pivot", turn) and holds(connection("Strut"), "Mount", "end_a", "pivot", turn), - [receipt["message"], report and report["connection"], gap, off]) - moved, gap = least("turned", float(np.linalg.norm(frame(ram, "base")[:3, 3] - pin))), reading("seated", seated(ram, "base", strut, "end_b", -35.0)) - check(f"and the actuator follows through its own connection, which nothing rewrote (roll {turn:g})", - (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) == before and moved > TURNED and gap < SEATED and R["readings"]["roll"] < ROLL - and holds(connection("Ram"), "Strut", "base", "end_b", -35.0), [moved, gap, connection("Ram"), R["readings"]]) + # --- roll: in place ----------------------------------------------------------------------------------------------------- + for turn in (65.0, -160.0, 35.0): # from the 20 it was attached at + was, pin, before = stated(strut), frame(ram, "base")[:3, 3].copy(), (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) + sent = COUNT[0] + receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=turn) + gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", turn)), R["readings"]["roll"] + check(f"roll {turn:g} turns the strut where it hangs: one intent, its parent, sockets and parent inverse as they were, its roll stated and seated", + receipt["status"] == "accepted" and COUNT[0] == sent + 1 and stated(strut) == was and strut["kit_roll"] == turn and gap < SEATED and off < ROLL + and report and report["object"] == "Strut" and holds(report["connection"], "Mount", "end_a", "pivot", turn) and holds(connection("Strut"), "Mount", "end_a", "pivot", turn), + [receipt["message"], report and report["connection"], gap, off]) + moved, gap = least("turned", float(np.linalg.norm(frame(ram, "base")[:3, 3] - pin))), reading("seated", seated(ram, "base", strut, "end_b", -35.0)) + check(f"and the actuator follows through its own connection, which nothing rewrote (roll {turn:g})", + (stated(ram), ram["kit_roll"], np.array(ram.matrix_basis).tolist()) == before and moved > TURNED and gap < SEATED and R["readings"]["roll"] < ROLL + and holds(connection("Ram"), "Strut", "base", "end_b", -35.0), [moved, gap, connection("Ram"), R["readings"]]) -# --- roll: the closures it opens ---------------------------------------------------------------------------------------- -check("the rolls above opened the brace's closure and reported it before the one that holds, whatever its name", (report or {}).get("closures") == [ - {"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] and report["closure"] is None, report and report.get("closures")) -receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=20.0) -check("rolled back to where the brace met it, the closure holds again: read from where the parts stand", receipt["status"] == "accepted" and (report or {}).get("closures") == [ - {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}, {"part": "Brace", "to": "Ram", "holds": True}], report and report.get("closures")) -send("setObjectTransform", targetObjectName="Aa_Loose", location=[0.0, -25.0, 0.0], rotationEuler=[0.0, 0.0, 0.0]) -receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-35.0) -check("a roll lists the closures its own part is an end of first, before a broken one elsewhere", receipt["status"] == "accepted" and (report or {}).get("closures") == [ - {"part": "Brace", "to": "Ram", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}], report and report.get("closures")) -receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-36.0) -check("and a roll of the part a closure names opens it; no roll seats or rewrites a closure", receipt["status"] == "accepted" and (report or {}).get("closures") == [ - {"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}] - and {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} == closing and brace.parent is None, [report and report.get("closures"), dict(brace.items())]) + # --- roll: the closures it opens ---------------------------------------------------------------------------------------- + check("the rolls above opened the brace's closure and reported it before the one that holds, whatever its name", (report or {}).get("closures") == [ + {"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] and report["closure"] is None, report and report.get("closures")) + receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=20.0) + check("rolled back to where the brace met it, the closure holds again: read from where the parts stand", receipt["status"] == "accepted" and (report or {}).get("closures") == [ + {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}, {"part": "Brace", "to": "Ram", "holds": True}], report and report.get("closures")) + send("setObjectTransform", targetObjectName="Aa_Loose", location=[0.0, -25.0, 0.0], rotationEuler=[0.0, 0.0, 0.0]) + receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-35.0) + check("a roll lists the closures its own part is an end of first, before a broken one elsewhere", receipt["status"] == "accepted" and (report or {}).get("closures") == [ + {"part": "Brace", "to": "Ram", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}], report and report.get("closures")) + receipt, report = send("brokkr_kitbash.roll", object_name="Ram", roll=-36.0) + check("and a roll of the part a closure names opens it; no roll seats or rewrites a closure", receipt["status"] == "accepted" and (report or {}).get("closures") == [ + {"part": "Brace", "to": "Ram", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}] + and {k: brace[k] for k in brace.keys() if k.startswith("kit_close")} == closing and brace.parent is None, [report and report.get("closures"), dict(brace.items())]) -# --- aim ---------------------------------------------------------------------------------------------------------------- -for axis, direction in (("+z", (1.0, 0.0, 0.0)), ("-x", (0.0, -3.0, 4.0)), ("+z", (0.2, 0.1, -2.0))): - world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction) - receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis=axis, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2]) - aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9} - read = float(np.array(strut.matrix_world, dtype=np.float64)[:3, :3] @ np.array(core.AXES[axis]) @ unit) - grid = max(float((world @ core.mate(socket(mount, "pivot"), socket(strut, "end_a"), float(r)))[:3, :3] @ np.array(core.AXES[axis]) @ unit) for r in range(-180, 180)) - apart, short = reading("aimed", abs(aimed["dot"] - read)), reading("aimed short", max(grid - read, 0.0)) - check(f"aim points the strut's {axis} at {direction} as far as its pin lets it: the dot it reports is the dot the scene reads, and no roll on a 1-degree grid passes it", - receipt["status"] == "accepted" and apart < AIMED and short < AIMED and 0.2 < aimed["dot"] < 0.999, [receipt["message"], aimed, read, grid]) - gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", aimed["roll"])), R["readings"]["roll"] - check(f"and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported ({axis})", - aimed["roll"] == round(strut["kit_roll"], 6) and -180.0 < aimed["roll"] <= 180.0 and holds(report and report["connection"], "Mount", "end_a", "pivot", aimed["roll"]) - and gap < SEATED and off < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2, - [dict(strut.items()), report and report["connection"], report and report.get("closures"), gap, off]) + # --- aim ---------------------------------------------------------------------------------------------------------------- + for axis, direction in (("+z", (1.0, 0.0, 0.0)), ("-x", (0.0, -3.0, 4.0)), ("+z", (0.2, 0.1, -2.0))): + world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction) + receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis=axis, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2]) + aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9} + read = float(np.array(strut.matrix_world, dtype=np.float64)[:3, :3] @ np.array(core.AXES[axis]) @ unit) + grid = max(float((world @ core.mate(socket(mount, "pivot"), socket(strut, "end_a"), float(r)))[:3, :3] @ np.array(core.AXES[axis]) @ unit) for r in range(-180, 180)) + apart, short = reading("aimed", abs(aimed["dot"] - read)), reading("aimed short", max(grid - read, 0.0)) + check(f"aim points the strut's {axis} at {direction} as far as its pin lets it: the dot it reports is the dot the scene reads, and no roll on a 1-degree grid passes it", + receipt["status"] == "accepted" and apart < AIMED and short < AIMED and 0.2 < aimed["dot"] < 0.999, [receipt["message"], aimed, read, grid]) + gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", aimed["roll"])), R["readings"]["roll"] + check(f"and it is stated and seated as roll's: the connection holds at the aimed roll, the actuator with it, closures reported ({axis})", + aimed["roll"] == round(strut["kit_roll"], 6) and -180.0 < aimed["roll"] <= 180.0 and holds(report and report["connection"], "Mount", "end_a", "pivot", aimed["roll"]) + and gap < SEATED and off < ROLL and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2, + [dict(strut.items()), report and report["connection"], report and report.get("closures"), gap, off]) -# --- reach -------------------------------------------------------------------------------------------------------------- -for direction, part, offset in (((0.0, 0.0, 1.0), 0.5, 40.0), ((0.0, 0.0, 1.0), 0.5, -40.0), ((1.0, 2.0, -0.5), -0.8, 100.0)): - world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction) - A, B, C = core.roll_terms(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], 1.0, unit) - current = float(round(math.degrees(math.atan2(B, A)) + offset)) # the two rolls that reach stand either side of the middle: start nearer one - send("brokkr_kitbash.roll", object_name="Strut", roll=current) - height = round(C + part * math.hypot(A, B), 3) - fields = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} if direction != (0.0, 0.0, 1.0) else {} # world z is the default - receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=height, **fields) + # --- reach -------------------------------------------------------------------------------------------------------------- + for direction, part, offset in (((0.0, 0.0, 1.0), 0.5, 40.0), ((0.0, 0.0, 1.0), 0.5, -40.0), ((1.0, 2.0, -0.5), -0.8, 100.0)): + world, unit = np.array(mount.matrix_world, dtype=np.float64), np.array(direction) / np.linalg.norm(direction) + A, B, C = core.roll_terms(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], 1.0, unit) + current = float(round(math.degrees(math.atan2(B, A)) + offset)) # the two rolls that reach stand either side of the middle: start nearer one + send("brokkr_kitbash.roll", object_name="Strut", roll=current) + height = round(C + part * math.hypot(A, B), 3) + fields = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} if direction != (0.0, 0.0, 1.0) else {} # world z is the default + receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=height, **fields) + reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9} + apart = lambda roll: abs((roll - current + 180.0) % 360.0 - 180.0) # noqa: E731 + off_plane = reading("reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - height)) + farther = least("reach other root", apart(2.0 * math.degrees(math.atan2(B, A)) - reached["roll"]) - apart(reached["roll"])) # the other root mirrors it about the middle + check(f"reach brings the strut's end_b to {height} m along {direction} from roll {current:g}, by the nearer of the two rolls that do", + receipt["status"] == "accepted" and off_plane < REACHED and reached["residual"] < REACHED and farther > NEARER, + [receipt["message"], reached, off_plane, farther]) + gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", reached["roll"])), R["readings"]["roll"] + check(f"and it is stated and seated as roll's ({direction}, from {current:g})", reached["roll"] == round(strut["kit_roll"], 6) and -180.0 < reached["roll"] <= 180.0 + and holds(report and report["connection"], "Mount", "end_a", "pivot", reached["roll"]) and gap < SEATED and off < ROLL + and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2, + [dict(strut.items()), report and report["connection"], gap, off]) + + # --- refusals ----------------------------------------------------------------------------------------------------------- + send("setObjectParent", targetObjectName="Orphan", parentObjectName="") + low, high = C - math.hypot(A, B), C + math.hypot(A, B) + refused("roll of a part nobody attached", "brokkr_kitbash.roll", {"object_name": "Spare", "roll": 10.0}, "'Spare' is not attached (it has no kit_socket property)") + refused("aim of a part nobody attached", "brokkr_kitbash.aim", {"object_name": "Spare", "axis": "+z", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "'Spare' is not attached") + refused("reach of a part nobody attached", "brokkr_kitbash.reach", {"object_name": "Spare", "socket": "end_b", "height": 0.0}, "'Spare' is not attached") + refused("roll of a part whose parent was cleared", "brokkr_kitbash.roll", {"object_name": "Orphan", "roll": 10.0}, "'Orphan' states a connection and has no parent: detach it") + refused("roll of a mesh that is not a kit part", "brokkr_kitbash.roll", {"object_name": "Plain", "roll": 10.0}, "'Plain' is not a kit part") + refused("aim of the axis along the pin", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+y", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, + "'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': the axis (0.0, 1.0, 0.0) of the part or the direction (1.0, 0.0, 0.0) lies along the pin") + refused("aim at no direction", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+z", "direction_x": 0.0, "direction_y": 0.0, "direction_z": 0.0}, "The direction is zero") + refused("reach past the circle the socket turns on, naming what it reaches", "brokkr_kitbash.reach", + {"object_name": "Strut", "socket": "end_b", "height": 900.0, "direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]}, + f"no roll brings the point to 900.000000 m along ({unit[0]:.6f}".rstrip("0")) + receipt, _ = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=900.0, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2]) + check("and the range it names is the one core solves", f"it reaches {low:.6f} m to {high:.6f} m" in str(receipt["message"]) and high - low > 1.0, [receipt["message"], low, high]) + skew = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} + refused("reach a little past the top it names", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": float(f"{high:.6f}") + PAST, **skew}, "no roll brings the point to") + receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=float(f"{high:.6f}"), **skew) reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9} - apart = lambda roll: abs((roll - current + 180.0) % 360.0 - 180.0) # noqa: E731 - off_plane = reading("reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - height)) - farther = least("reach other root", apart(2.0 * math.degrees(math.atan2(B, A)) - reached["roll"]) - apart(reached["roll"])) # the other root mirrors it about the middle - check(f"reach brings the strut's end_b to {height} m along {direction} from roll {current:g}, by the nearer of the two rolls that do", - receipt["status"] == "accepted" and off_plane < REACHED and reached["residual"] < REACHED and farther > NEARER, - [receipt["message"], reached, off_plane, farther]) - gap, off = reading("seated", seated(strut, "end_a", mount, "pivot", reached["roll"])), R["readings"]["roll"] - check(f"and it is stated and seated as roll's ({direction}, from {current:g})", reached["roll"] == round(strut["kit_roll"], 6) and -180.0 < reached["roll"] <= 180.0 - and holds(report and report["connection"], "Mount", "end_a", "pivot", reached["roll"]) and gap < SEATED and off < ROLL - and holds(connection("Ram"), "Strut", "base", "end_b", -36.0) and len((report or {}).get("closures", [])) == 2, - [dict(strut.items()), report and report["connection"], gap, off]) - -# --- refusals ----------------------------------------------------------------------------------------------------------- -send("setObjectParent", targetObjectName="Orphan", parentObjectName="") -low, high = C - math.hypot(A, B), C + math.hypot(A, B) -refused("roll of a part nobody attached", "brokkr_kitbash.roll", {"object_name": "Spare", "roll": 10.0}, "'Spare' is not attached (it has no kit_socket property)") -refused("aim of a part nobody attached", "brokkr_kitbash.aim", {"object_name": "Spare", "axis": "+z", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "'Spare' is not attached") -refused("reach of a part nobody attached", "brokkr_kitbash.reach", {"object_name": "Spare", "socket": "end_b", "height": 0.0}, "'Spare' is not attached") -refused("roll of a part whose parent was cleared", "brokkr_kitbash.roll", {"object_name": "Orphan", "roll": 10.0}, "'Orphan' states a connection and has no parent: detach it") -refused("roll of a mesh that is not a kit part", "brokkr_kitbash.roll", {"object_name": "Plain", "roll": 10.0}, "'Plain' is not a kit part") -refused("aim of the axis along the pin", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+y", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, - "'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': the axis (0.0, 1.0, 0.0) of the part or the direction (1.0, 0.0, 0.0) lies along the pin") -refused("aim at no direction", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "+z", "direction_x": 0.0, "direction_y": 0.0, "direction_z": 0.0}, "The direction is zero") -refused("reach past the circle the socket turns on, naming what it reaches", "brokkr_kitbash.reach", - {"object_name": "Strut", "socket": "end_b", "height": 900.0, "direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]}, - f"no roll brings the point to 900.000000 m along ({unit[0]:.6f}".rstrip("0")) -receipt, _ = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=900.0, direction_x=direction[0], direction_y=direction[1], direction_z=direction[2]) -check("and the range it names is the one core solves", f"it reaches {low:.6f} m to {high:.6f} m" in str(receipt["message"]) and high - low > 1.0, [receipt["message"], low, high]) -skew = {"direction_x": direction[0], "direction_y": direction[1], "direction_z": direction[2]} -refused("reach a little past the top it names", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": float(f"{high:.6f}") + PAST, **skew}, "no roll brings the point to") -receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=float(f"{high:.6f}"), **skew) -reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9} -over, stands = reading("edge typed past", max(float(np.float32(f"{high:.6f}")) - high, 0.0)), reading("edge reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - high)) -check("reach to the top of the circle, typed back from the range the refusal named, is taken: the socket stands at the top", receipt["status"] == "accepted" - and reached["residual"] <= EDGE and over <= EDGE and stands < REACHED and holds(report["connection"], "Mount", "end_a", "pivot", reached["roll"]), - [receipt["message"], reached, over, stands, high]) -refused("reach with the socket the part hangs by: it lies on the pin", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_a", "height": 0.0}, - "'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': no roll moves the point along (0.0, 0.0, 1.0): it lies on the pin") -pin = np.array(mount.matrix_world, dtype=np.float64) @ socket(mount, "pivot")["matrix"] -for label, along in (("as the scene holds it", pin[:3, 2]), ("to 6 decimals", np.round(pin[:3, 2], 6)), ("to 4 decimals", np.round(pin[:3, 2], 4)), ("reversed, to 4 decimals", -np.round(pin[:3, 2], 4))): - refused(f"aim at the pin's own direction {label}", "brokkr_kitbash.aim", - {"object_name": "Strut", "axis": "+z", "direction_x": float(along[0]), "direction_y": float(along[1]), "direction_z": float(along[2])}, "lies along the pin, so no roll turns one toward the other") -refused("reach with a socket the part does not have", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_c", "height": 0.0}, - "'Strut' has no socket 'end_c'; its sockets: end_a, end_a_back, end_b, end_b_back") -refused("reach along no direction", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": 0.0, "direction_z": 0.0}, "The direction is zero") -refused("a roll past a turn, by the action table", "brokkr_kitbash.roll", {"object_name": "Strut", "roll": 361.0}, "roll") -refused("an axis that is not one of the six, by the action table", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "x", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "axis") + over, stands = reading("edge typed past", max(float(np.float32(f"{high:.6f}")) - high, 0.0)), reading("edge reached", abs(float(frame(strut, "end_b")[:3, 3] @ unit) - high)) + check("reach to the top of the circle, typed back from the range the refusal named, is taken: the socket stands at the top", receipt["status"] == "accepted" + and reached["residual"] <= EDGE and over <= EDGE and stands < REACHED and holds(report["connection"], "Mount", "end_a", "pivot", reached["roll"]), + [receipt["message"], reached, over, stands, high]) + refused("reach with the socket the part hangs by: it lies on the pin", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_a", "height": 0.0}, + "'Strut' on 'Mount': socket 'end_a' on parent socket 'pivot': no roll moves the point along (0.0, 0.0, 1.0): it lies on the pin") + pin = np.array(mount.matrix_world, dtype=np.float64) @ socket(mount, "pivot")["matrix"] + for label, along in (("as the scene holds it", pin[:3, 2]), ("to 6 decimals", np.round(pin[:3, 2], 6)), ("to 4 decimals", np.round(pin[:3, 2], 4)), ("reversed, to 4 decimals", -np.round(pin[:3, 2], 4))): + refused(f"aim at the pin's own direction {label}", "brokkr_kitbash.aim", + {"object_name": "Strut", "axis": "+z", "direction_x": float(along[0]), "direction_y": float(along[1]), "direction_z": float(along[2])}, "lies along the pin, so no roll turns one toward the other") + refused("reach with a socket the part does not have", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_c", "height": 0.0}, + "'Strut' has no socket 'end_c'; its sockets: end_a, end_a_back, end_b, end_b_back") + refused("reach along no direction", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": 0.0, "direction_z": 0.0}, "The direction is zero") + refused("a roll past a turn, by the action table", "brokkr_kitbash.roll", {"object_name": "Strut", "roll": 361.0}, "roll") + refused("an axis that is not one of the six, by the action table", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "x", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "axis") +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) R["ok"] = all(c["ok"] for c in R["checks"]) R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} diff --git a/surfaces/blender/tests/live/mesh_polish.py b/surfaces/blender/tests/live/mesh_polish.py index e86c3ee..4845e67 100644 --- a/surfaces/blender/tests/live/mesh_polish.py +++ b/surfaces/blender/tests/live/mesh_polish.py @@ -6,12 +6,15 @@ and does what its doc says to real bpy meshes and images. Not part of the unitte Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses without them). Every action is sent through BrokkrBlenderTarget.run_intent, as tools/run_intents.py sends it. With BROKKR_POLISH_HULLS= it also repairs each and checks that no face was -turned. Writes .result.json and exits 1 when a check failed. +turned. Writes .result.json and exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names +the check before it, the checks are printed and the result file written whatever happened, and the exit is 1 with or +without --python-exit-code. """ import json import math import os import sys +import traceback import types from pathlib import Path @@ -98,331 +101,334 @@ def pixels_of(obj): return flat.reshape(image.size[1], image.size[0], 4)[..., :3], image -check("host file admitted", not R["hostErrors"] and len(R["hostRows"]) == 7, R["hostErrors"] or R["hostRows"]) +try: + check("host file admitted", not R["hostErrors"] and len(R["hostRows"]) == 7, R["hostErrors"] or R["hostRows"]) -# --- audit and repair: a generator's sphere, torn at every edge, half its faces wound inside out under outward -# --- custom normals, is welded back into one closed shell with no face turned and its shading normals intact ------ -size = 256 -rows = np.clip(((np.arange(size) + 0.5) / size - 0.1) / 0.8, 0.0, 1.0) # latitude: 0 at the south pole, 1 at the north -baked = np.repeat((0.8 * (0.2 + 0.8 * rows))[:, None, None], size, axis=1) * np.ones((1, 1, 3)) + # --- audit and repair: a generator's sphere, torn at every edge, half its faces wound inside out under outward + # --- custom normals, is welded back into one closed shell with no face turned and its shading normals intact ------ + size = 256 + rows = np.clip(((np.arange(size) + 0.5) / size - 0.1) / 0.8, 0.0, 1.0) # latitude: 0 at the south pole, 1 at the north + baked = np.repeat((0.8 * (0.2 + 0.8 * rows))[:, None, None], size, axis=1) * np.ones((1, 1, 3)) -def ball(bm): - bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True) - layer = bm.loops.layers.uv.active - for face in bm.faces: # the island sits inside the texture with a margin, as a generator's atlas does - for loop in face.loops: - loop[layer].uv = loop[layer].uv * 0.8 + Vector((0.1, 0.1)) - - -sphere = new_object("Ball", ball, new_image("ball_bake", baked.astype(np.float32))) -sphere.data.polygons.foreach_set("use_smooth", [True] * len(sphere.data.polygons)) -torn = bmesh.new() -torn.from_mesh(sphere.data) -bmesh.ops.split_edges(torn, edges=torn.edges[:]) -inside_out = [f for f in torn.faces if f.calc_center_median().x > 0] -reversed_faces, reversed_triangles = len(inside_out), sum(len(f.verts) - 2 for f in inside_out) -bmesh.ops.reverse_faces(torn, faces=inside_out) -torn.to_mesh(sphere.data) -torn.free() -sphere.data.normals_split_custom_set([tuple(sphere.data.vertices[loop.vertex_index].co.normalized()) for loop in sphere.data.loops]) - - -def polygon_normals(mesh): - flat = np.empty(len(mesh.polygons) * 3, dtype=np.float32) - mesh.polygons.foreach_get("normal", flat) - return flat.reshape(-1, 3) - - -def shading_error(mesh): - """The worst angle, in degrees, between a corner's shading normal and the sphere's own outward direction.""" - flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) - mesh.corner_normals.foreach_get("vector", flat) - outward = np.array([mesh.vertices[loop.vertex_index].co.normalized() for loop in mesh.loops]) - return float(np.degrees(np.arccos(np.clip((flat.reshape(-1, 3) * outward).sum(axis=1), -1, 1))).max()) - - -receipt, before = send("brokkr_mesh_polish.audit", object_name="Ball") -check("audit: accepted, no undo step", receipt["status"] == "accepted" and not receipt.get("undoLabel"), receipt["message"]) -check("audit: welded topology sees one closed shell in the torn sphere", - before["Ball"]["shells"] == 1 and before["Ball"]["boundaryEdges"] == 0 and before["Ball"]["nonManifoldEdges"] == 0, before["Ball"]) -check("audit: texture and UV facts", before["Ball"]["baseColorSize"] == [size, size] and before["Ball"]["uvOverlap"] < 0.02 - and before["Ball"]["texelDensityMedian"] > 0 and 0.55 < before["Ball"]["uvCoverage"] < 0.64, before["Ball"]) # an 0.8 x 0.8 island less the pole gaps -check("audit: counts the triangles wound against their shading normals, and none of them as a mirrored texture", - reversed_triangles > 1000 and before["Ball"]["windingAgainstNormals"] == reversed_triangles - and before["Ball"]["uvMirroredTriangles"] == 0, [reversed_triangles, before["Ball"].get("windingAgainstNormals"), before["Ball"].get("uvMirroredTriangles")]) -torn_vertices, normals_before = len(sphere.data.vertices), polygon_normals(sphere.data) -receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball") -check("repair: accepted as one undo step", receipt["status"] == "accepted" and "repair" in receipt.get("undoLabel", ""), receipt) -check("repair: welds the torn vertices", repaired["changes"]["welded"] == torn_vertices - len(sphere.data.vertices) - and len(sphere.data.vertices) == 48 * 23 + 2, repaired) -check("repair: every edge has two faces again", len(sphere.data.edges) == 48 * 23 + 48 * 24, len(sphere.data.edges)) -normals_after = polygon_normals(sphere.data) -turned = int(((normals_before * normals_after).sum(axis=1) < 0).sum()) if len(normals_before) == len(normals_after) else -1 -R["winding"] = {"reversedTriangles": reversed_triangles, "turnedByDefaultRepair": turned, "shadingErrorDegrees": shading_error(sphere.data)} -check("repair: by default turns no face (a single-sided material would cull a turned one)", - turned == 0 and repaired["changes"]["windingFlipped"] == 0 - and repaired["after"]["windingAgainstNormals"] == repaired["before"]["windingAgainstNormals"] == reversed_triangles, [turned, repaired]) -check("repair: the shading normals survive the weld", "custom_normal" in sphere.data.attributes and R["winding"]["shadingErrorDegrees"] < 0.5 - and not repaired["changes"]["customNormalsDropped"], R["winding"]) - -# --- delight: a bake that darkens with latitude is levelled, reading the shading normals, not the windings -------- -receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=128, occlusion_rays=8, max_gain=8) -after_pixels, after_image = pixels_of(sphere) -column = after_pixels[:, size // 2, 0] -north, south = int(size * (0.1 + 0.8 * 0.9)), int(size * (0.1 + 0.8 * 0.1)) # rows at latitude 0.9 and 0.1 -ratio_before = float(baked[north, 0, 0] / baked[south, 0, 0]) -ratio_after = float(column[north] / column[south]) -# On the island's left border the gain field meets texels no triangle covers. With the field filled outward the -# border reads as the middle of the row does; left unfilled, the neutral gain of the uncovered texels bleeds in. -border = int(math.ceil(size * 0.1)) -deficit = float(np.median(1.0 - after_pixels[south - 8:south + 8, border, 0] / after_pixels[south - 8:south + 8, size // 2, 0])) -R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after, "borderDeficit": deficit} -check("delight: accepted, new packed image on the material, in the old image's colour space", receipt["status"] == "accepted" - and after_image.name == "ball_bake.delit" and after_image.packed_file is not None - and after_image.colorspace_settings.name == "Non-Color", [receipt["message"], after_image.colorspace_settings.name]) -check("delight: finds the baked light", lit["explainedByLight"]["before"] > 0.5 and lit["before"]["upDownLuminanceRatio"] > 2.0, lit) -# bound: shipped ratioAfter 1.114; a no-op leaves 3.261 and so do normals taken from the windings (the inside-out half -# cancels the light the fit could find): sqrt(1.114 * 3.261) = 1.906 -check("delight: levels top against bottom", ratio_before > RATIO_BOUND * 1.2 and ratio_after < RATIO_BOUND / 1.2, [ratio_before, ratio_after]) -# bound: shipped deficit 0.000, an unfilled gain field leaves 0.164; the shipped reading being zero, the bound sits 1.2 under the mutant: 0.136 -check("delight: the gain reaches the island's border unweakened", abs(deficit) < DEFICIT_BOUND, deficit) - -receipt, rewound = send("brokkr_mesh_polish.repair", object_name="Ball", recalc_normals=True, sharp_angle=30) -check("repair: recalc_normals rewinds the inside-out half and says how many faces it turned", - receipt["status"] == "accepted" and rewound["changes"]["windingFlipped"] == reversed_faces - and rewound["changes"]["customNormalsDropped"] and "custom_normal" not in sphere.data.attributes - and rewound["after"]["windingAgainstNormals"] == 0, rewound) - -# --- repair: only holes up to the size asked are filled, and only shells below the share asked are dropped ----- -def holey(bm): - bmesh.ops.create_grid(bm, x_segments=6, y_segments=6, size=3.0, calc_uvs=True) # 36 quads, each 1 x 1 - at = lambda face: (round(face.calc_center_median().x, 1), round(face.calc_center_median().y, 1)) - small = [f for f in bm.faces if at(f) == (1.5, 1.5)] # one quad inside: a 4-edge hole - large = [f for f in bm.faces if at(f)[0] in (-1.5, -0.5) and at(f)[1] in (-1.5, -0.5)] # a 2 x 2 block: an 8-edge hole - bmesh.ops.delete(bm, geom=small + large, context="FACES") - bm.faces.new([bm.verts.new(co) for co in ((9.0, 9.0, 0.0), (9.2, 9.0, 0.0), (9.0, 9.2, 0.0))]) # a far chip: 0.02 of area against 31 - - -sheet = new_object("Sheet", holey) -flipped_sheet = bmesh.new() # the generator's sheet faces down: a fill must follow it, whichever way Blender would guess -flipped_sheet.from_mesh(sheet.data) -bmesh.ops.reverse_faces(flipped_sheet, faces=flipped_sheet.faces[:]) -flipped_sheet.to_mesh(sheet.data) -flipped_sheet.free() -TILT = (0.6, 0.0, -0.8) # the generator's shading normals lean: the old faces must keep them, a fill must not borrow them -sheet.data.normals_split_custom_set([TILT] * len(sheet.data.loops)) -receipt, mended = send("brokkr_mesh_polish.repair", object_name="Sheet", fill_holes_sides=4, min_shell_area=0.01) -R["mend"] = mended -check("repair: fills the 4-edge hole, leaves the 8-edge hole and the rim, drops the chip", - receipt["status"] == "accepted" and mended["changes"]["holesFilled"] == 1 and mended["changes"]["shellsRemoved"] == 1 - and mended["after"]["shells"] == 1 and mended["after"]["boundaryEdges"] == 24 + 8, mended) -facing = polygon_normals(sheet.data)[:, 2] -check("repair: a filled hole is wound as the faces around it", len(facing) == 31 * 1 + 2 and bool((facing < -0.9).all()), [len(facing), float(facing.max())]) -shading = np.empty(len(sheet.data.loops) * 3, dtype=np.float32) -sheet.data.corner_normals.foreach_get("vector", shading) -shading = shading.reshape(-1, 3) -fill_loops = [i for polygon in sheet.data.polygons if abs(polygon.center.x - 1.5) < 0.4 and abs(polygon.center.y - 1.5) < 0.4 for i in polygon.loop_indices] -old_loops = [i for i in range(len(shading)) if i not in set(fill_loops)] -check("repair: old faces keep their shading normals through the weld and the fill; the fill is shaded by its own direction", - len(fill_loops) == 6 and np.allclose(shading[old_loops], TILT, atol=1e-3) and np.allclose(shading[fill_loops], (0.0, 0.0, -1.0), atol=1e-3), - [len(fill_loops), shading[fill_loops].tolist()[:2], shading[old_loops[0]].tolist()]) -bpy.data.objects.remove(sheet) - -# --- delight: darkness that follows occlusion is levelled --------------------------------------------------------- -def pair(bm): - layer = bm.loops.layers.uv.active - for side in (-1.0, 1.0): # two unit spheres 0.1 apart: their facing sides occlude each other - made = bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16, radius=1.0, calc_uvs=True, matrix=Matrix.Translation((side * 1.05, 0, 0))) - for face in {f for v in made["verts"] for f in v.link_faces}: + def ball(bm): + bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True) + layer = bm.loops.layers.uv.active + for face in bm.faces: # the island sits inside the texture with a margin, as a generator's atlas does for loop in face.loops: - loop[layer].uv = Vector((loop[layer].uv.x * 0.5 + (0.0 if side < 0 else 0.5), loop[layer].uv.y)) + loop[layer].uv = loop[layer].uv * 0.8 + Vector((0.1, 0.1)) -import brokkr_mesh_polish as polish # noqa: E402 the fixture's bake uses the add-on's own occlusion, so the light is exactly what it can explain - -twins = new_object("Twins", pair, new_image("twins_bake", np.ones((size, size, 3), dtype=np.float32))) -twins.data.polygons.foreach_set("use_smooth", [True] * len(twins.data.polygons)) -twin = polish.arrays(twins) -twin_sky = polish.ambient_occlusion(twin["V"], twin["T"], twin["N"], 64, 0.35 * float(np.linalg.norm(twin["V"].max(axis=0) - twin["V"].min(axis=0)))) -owner, bary, _ = polish.core.rasterize(twin["UV"], size) -sky_map = polish.core.interpolate(owner, bary, twin_sky[twin["T"]][..., None])[..., 0] -occluded, open_sky = (owner >= 0) & (sky_map < 0.6), (owner >= 0) & (sky_map > 0.95) -twin_bake = np.where((owner >= 0)[..., None], 0.8 * np.clip(sky_map, 0.05, 1.0)[..., None], 0.5) * np.ones((1, 1, 3)) -flat = np.ones((size, size, 4), dtype=np.float32) -flat[..., :3] = twin_bake -bpy.data.images["twins_bake"].pixels.foreach_set(flat.reshape(-1)) -receipt, unshadowed = send("brokkr_mesh_polish.delight", object_name="Twins", clusters=1, fit_size=256, occlusion_rays=64, max_gain=8) -twin_after, _ = pixels_of(twins) -shade_before = float(np.median(twin_bake[..., 0][occluded]) / np.median(twin_bake[..., 0][open_sky])) -shade_after = float(np.median(twin_after[..., 0][occluded]) / np.median(twin_after[..., 0][open_sky])) -R["occlusion"] = {"report": unshadowed, "occludedTexels": int(occluded.sum()), "shadeBefore": shade_before, "shadeAfter": shade_after} -# bound: shipped shadeAfter 1.000; with occlusion ignored (a sky of 1 everywhere) it stays 0.468: sqrt(1.000 * 0.468) = 0.684 -check("delight: lifts occluded surface to the level of open surface", receipt["status"] == "accepted" and occluded.sum() > 500 - and shade_before < SHADE_BOUND / 1.2 and shade_after > SHADE_BOUND * 1.2, R["occlusion"]) -bpy.data.objects.remove(twins) - -# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled; nothing outside it moves ----------------- -slab = new_object("Slab", lambda bm: bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Diagonal((3.0, 1.0, 0.5, 1.0)))) -slab.matrix_world = Matrix.Translation((4, 5, 6)) @ Matrix.Rotation(math.radians(37), 4, (0.3, 0.5, 0.8)) -sphere.location = (20, 0, 0) -bpy.context.view_layer.update() -receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Slab", length=12.0) -corners = np.array([slab.matrix_world @ v.co for v in slab.data.vertices]) -extent = corners.max(axis=0) - corners.min(axis=0) -check("orient: long on Y, thin on Z, scaled to the length, centred", - receipt["status"] == "accepted" and np.allclose(extent, [4.0, 12.0, 2.0], atol=1e-3) - and np.allclose((corners.max(axis=0) + corners.min(axis=0)) / 2, 0, atol=1e-4), [list(map(float, extent)), oriented]) -check("orient: reports the mirror error of a symmetric body as small", max(oriented["mirrorError"].values()) < 0.05, oriented["mirrorError"]) -check("orient: an object outside the named root is not touched", oriented["objects"] == ["Slab"] - and np.allclose(sphere.matrix_world.translation, [20, 0, 0]) and abs(max(v.co.length for v in sphere.data.vertices) - 1.0) < 1e-5, oriented["objects"]) -receipt, _ = send("brokkr_mesh_polish.orient", object_name="Nobody") -check("orient: an unknown root is refused", receipt["status"] == "failed", receipt["message"]) -bpy.data.objects.remove(slab) - -# --- cut_parts: a knob fused to a block is cut off at the crease, capped, and rooted at its cut ----------------- -def knobbed(bm): - bmesh.ops.create_cube(bm, size=2.0) - top = next(f for f in bm.faces if f.normal.z > 0.9) - bmesh.ops.inset_region(bm, faces=[top], thickness=0.6) - extruded = bmesh.ops.extrude_face_region(bm, geom=[top]) - bmesh.ops.translate(bm, verts=[g for g in extruded["geom"] if isinstance(g, bmesh.types.BMVert)], vec=(0, 0, 1.0)) - bmesh.ops.delete(bm, geom=[top], context="FACES") - bmesh.ops.triangulate(bm, faces=bm.faces[:]) - bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + sphere = new_object("Ball", ball, new_image("ball_bake", baked.astype(np.float32))) + sphere.data.polygons.foreach_set("use_smooth", [True] * len(sphere.data.polygons)) + torn = bmesh.new() + torn.from_mesh(sphere.data) + bmesh.ops.split_edges(torn, edges=torn.edges[:]) + inside_out = [f for f in torn.faces if f.calc_center_median().x > 0] + reversed_faces, reversed_triangles = len(inside_out), sum(len(f.verts) - 2 for f in inside_out) + bmesh.ops.reverse_faces(torn, faces=inside_out) + torn.to_mesh(sphere.data) + torn.free() + sphere.data.normals_split_custom_set([tuple(sphere.data.vertices[loop.vertex_index].co.normalized()) for loop in sphere.data.loops]) -block = new_object("Block", knobbed) -receipt, single = send("brokkr_mesh_polish.audit", object_name="Block") -check("cut fixture is one closed skin", single["Block"]["shells"] == 1 and single["Block"]["boundaryEdges"] == 0, single["Block"]) -receipt, cut = send("brokkr_mesh_polish.cut_parts", object_name="Block", seeds="body=0,0,-1; knob=0,0,2", joint_scale=0.5) -R["cut"] = cut -check("cut_parts: accepted, one undo step, the fused object is replaced", receipt["status"] == "accepted" and bool(receipt.get("undoLabel")) - and "Block" not in bpy.data.objects and {"Block.body", "Block.knob"} <= set(bpy.data.objects.keys()), receipt["message"]) -if receipt["status"] == "accepted": - knob, body = bpy.data.objects["Block.knob"], bpy.data.objects["Block.body"] - part = {entry["name"]: entry for entry in cut["parts"]} - check("cut_parts: the knob is cut at the crease and rooted at the centre of the cut", - np.allclose(part["Block.knob"]["root"], [0, 0, 1], atol=1e-5) and np.allclose(knob.matrix_world.translation, [0, 0, 1], atol=1e-5) - and abs(abs(part["Block.knob"]["cutNormal"][2]) - 1) < 1e-5, part["Block.knob"]) - check("cut_parts: the knob hangs from the body and has not moved", knob.parent == body - and abs(max((knob.matrix_world @ v.co).z for v in knob.data.vertices) - 2.0) < 1e-5, None) - _, closed = send("brokkr_mesh_polish.audit") - check("cut_parts: both sides of the cut are capped (closed shells)", - all(closed[name]["boundaryEdges"] == 0 and closed[name]["shells"] == 1 for name in ("Block.body", "Block.knob")), - {name: [closed[name]["boundaryEdges"], closed[name]["shells"]] for name in ("Block.body", "Block.knob")}) - capped = {o.name: sum(1 for polygon in o.data.polygons if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap") for o in (body, knob)} - check("cut_parts: exactly the cap faces carry the cap material", capped["Block.knob"] == part["Block.knob"]["capTriangles"] > 0 - and capped["Block.body"] == part["Block.body"]["capTriangles"] > 0, capped) - cap_normals = {o.name: [polygon.normal.z for polygon in o.data.polygons - if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap"] for o in (body, knob)} - check("cut_parts: each cap faces out of its own part, and no old face was turned", - all(z < -0.9 for z in cap_normals["Block.knob"]) and all(z > 0.9 for z in cap_normals["Block.body"]) - and closed["Block.body"]["windingAgainstNormals"] == 0 and closed["Block.knob"]["windingAgainstNormals"] == 0, cap_normals) - check("cut_parts: a joint sits at the root", "Polish Cap" in [getattr(m, "name", "") for m in knob.data.materials] - and np.allclose(bpy.data.objects[part["Block.knob"]["joint"]].matrix_world.translation, [0, 0, 1], atol=1e-5), part["Block.knob"].get("joint")) - # orient after the cut: the body and what hangs from it turn as one; the knob keeps its parent and its pivot - receipt, turned_parts = send("brokkr_mesh_polish.orient", object_name="Block.body", length=6.0) - pivot = knob.matrix_world.translation - reach = max(abs((knob.matrix_world @ v.co).y) for v in knob.data.vertices) - R["orientParts"] = {"report": turned_parts, "knobPivot": list(pivot), "knobReach": reach, "parent": knob.parent.name if knob.parent else None} - # the 2 x 2 x 3 body-and-knob is laid along Y and doubled: the cut centre (0, 0, 1), half a unit above the middle, lands 1 along Y - check("orient: after a cut the parts keep their parent and their pivot at the cut", receipt["status"] == "accepted" and knob.parent == body - and abs(abs(pivot.y) - 1.0) < 1e-4 and abs(pivot.x) < 1e-4 and abs(pivot.z) < 1e-4 and abs(reach - 3.0) < 1e-4 - and np.allclose(np.array(knob.matrix_world.to_3x3()), np.eye(3), atol=1e-6), R["orientParts"]) -receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Block.body", seeds="only=0,0,-1") -check("cut_parts: one part is refused with nothing changed", receipt["status"] == "failed" and "Block.body" in bpy.data.objects, receipt["message"]) + def polygon_normals(mesh): + flat = np.empty(len(mesh.polygons) * 3, dtype=np.float32) + mesh.polygons.foreach_get("normal", flat) + return flat.reshape(-1, 3) -# --- cut_parts through: a seed on one face of a thin plate also holds the face behind it ----------------------- -def plate_body(bm): - bmesh.ops.create_cube(bm, size=2.0, matrix=Matrix.Diagonal((1.0, 1.0, 0.05, 1.0))) # 2 x 2 x 0.1 - bmesh.ops.subdivide_edges(bm, edges=bm.edges[:], cuts=7, use_grid_fill=True) - bmesh.ops.triangulate(bm, faces=bm.faces[:]) + def shading_error(mesh): + """The worst angle, in degrees, between a corner's shading normal and the sphere's own outward direction.""" + flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) + mesh.corner_normals.foreach_get("vector", flat) + outward = np.array([mesh.vertices[loop.vertex_index].co.normalized() for loop in mesh.loops]) + return float(np.degrees(np.arccos(np.clip((flat.reshape(-1, 3) * outward).sum(axis=1), -1, 1))).max()) -def underside(name): - """Triangles of the part that face down and are surface, not cap.""" - part_object = bpy.data.objects[name] - return sum(1 for polygon in part_object.data.polygons - if polygon.normal.z < -0.9 and getattr(part_object.data.materials[polygon.material_index], "name", "") != "Polish Cap") + receipt, before = send("brokkr_mesh_polish.audit", object_name="Ball") + check("audit: accepted, no undo step", receipt["status"] == "accepted" and not receipt.get("undoLabel"), receipt["message"]) + check("audit: welded topology sees one closed shell in the torn sphere", + before["Ball"]["shells"] == 1 and before["Ball"]["boundaryEdges"] == 0 and before["Ball"]["nonManifoldEdges"] == 0, before["Ball"]) + check("audit: texture and UV facts", before["Ball"]["baseColorSize"] == [size, size] and before["Ball"]["uvOverlap"] < 0.02 + and before["Ball"]["texelDensityMedian"] > 0 and 0.55 < before["Ball"]["uvCoverage"] < 0.64, before["Ball"]) # an 0.8 x 0.8 island less the pole gaps + check("audit: counts the triangles wound against their shading normals, and none of them as a mirrored texture", + reversed_triangles > 1000 and before["Ball"]["windingAgainstNormals"] == reversed_triangles + and before["Ball"]["uvMirroredTriangles"] == 0, [reversed_triangles, before["Ball"].get("windingAgainstNormals"), before["Ball"].get("uvMirroredTriangles")]) + torn_vertices, normals_before = len(sphere.data.vertices), polygon_normals(sphere.data) + receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball") + check("repair: accepted as one undo step", receipt["status"] == "accepted" and "repair" in receipt.get("undoLabel", ""), receipt) + check("repair: welds the torn vertices", repaired["changes"]["welded"] == torn_vertices - len(sphere.data.vertices) + and len(sphere.data.vertices) == 48 * 23 + 2, repaired) + check("repair: every edge has two faces again", len(sphere.data.edges) == 48 * 23 + 48 * 24, len(sphere.data.edges)) + normals_after = polygon_normals(sphere.data) + turned = int(((normals_before * normals_after).sum(axis=1) < 0).sum()) if len(normals_before) == len(normals_after) else -1 + R["winding"] = {"reversedTriangles": reversed_triangles, "turnedByDefaultRepair": turned, "shadingErrorDegrees": shading_error(sphere.data)} + check("repair: by default turns no face (a single-sided material would cull a turned one)", + turned == 0 and repaired["changes"]["windingFlipped"] == 0 + and repaired["after"]["windingAgainstNormals"] == repaired["before"]["windingAgainstNormals"] == reversed_triangles, [turned, repaired]) + check("repair: the shading normals survive the weld", "custom_normal" in sphere.data.attributes and R["winding"]["shadingErrorDegrees"] < 0.5 + and not repaired["changes"]["customNormalsDropped"], R["winding"]) + + # --- delight: a bake that darkens with latitude is levelled, reading the shading normals, not the windings -------- + receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=128, occlusion_rays=8, max_gain=8) + after_pixels, after_image = pixels_of(sphere) + column = after_pixels[:, size // 2, 0] + north, south = int(size * (0.1 + 0.8 * 0.9)), int(size * (0.1 + 0.8 * 0.1)) # rows at latitude 0.9 and 0.1 + ratio_before = float(baked[north, 0, 0] / baked[south, 0, 0]) + ratio_after = float(column[north] / column[south]) + # On the island's left border the gain field meets texels no triangle covers. With the field filled outward the + # border reads as the middle of the row does; left unfilled, the neutral gain of the uncovered texels bleeds in. + border = int(math.ceil(size * 0.1)) + deficit = float(np.median(1.0 - after_pixels[south - 8:south + 8, border, 0] / after_pixels[south - 8:south + 8, size // 2, 0])) + R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after, "borderDeficit": deficit} + check("delight: accepted, new packed image on the material, in the old image's colour space", receipt["status"] == "accepted" + and after_image.name == "ball_bake.delit" and after_image.packed_file is not None + and after_image.colorspace_settings.name == "Non-Color", [receipt["message"], after_image.colorspace_settings.name]) + check("delight: finds the baked light", lit["explainedByLight"]["before"] > 0.5 and lit["before"]["upDownLuminanceRatio"] > 2.0, lit) + # bound: shipped ratioAfter 1.114; a no-op leaves 3.261 and so do normals taken from the windings (the inside-out half + # cancels the light the fit could find): sqrt(1.114 * 3.261) = 1.906 + check("delight: levels top against bottom", ratio_before > RATIO_BOUND * 1.2 and ratio_after < RATIO_BOUND / 1.2, [ratio_before, ratio_after]) + # bound: shipped deficit 0.000, an unfilled gain field leaves 0.164; the shipped reading being zero, the bound sits 1.2 under the mutant: 0.136 + check("delight: the gain reaches the island's border unweakened", abs(deficit) < DEFICIT_BOUND, deficit) + + receipt, rewound = send("brokkr_mesh_polish.repair", object_name="Ball", recalc_normals=True, sharp_angle=30) + check("repair: recalc_normals rewinds the inside-out half and says how many faces it turned", + receipt["status"] == "accepted" and rewound["changes"]["windingFlipped"] == reversed_faces + and rewound["changes"]["customNormalsDropped"] and "custom_normal" not in sphere.data.attributes + and rewound["after"]["windingAgainstNormals"] == 0, rewound) + + # --- repair: only holes up to the size asked are filled, and only shells below the share asked are dropped ----- + def holey(bm): + bmesh.ops.create_grid(bm, x_segments=6, y_segments=6, size=3.0, calc_uvs=True) # 36 quads, each 1 x 1 + at = lambda face: (round(face.calc_center_median().x, 1), round(face.calc_center_median().y, 1)) + small = [f for f in bm.faces if at(f) == (1.5, 1.5)] # one quad inside: a 4-edge hole + large = [f for f in bm.faces if at(f)[0] in (-1.5, -0.5) and at(f)[1] in (-1.5, -0.5)] # a 2 x 2 block: an 8-edge hole + bmesh.ops.delete(bm, geom=small + large, context="FACES") + bm.faces.new([bm.verts.new(co) for co in ((9.0, 9.0, 0.0), (9.2, 9.0, 0.0), (9.0, 9.2, 0.0))]) # a far chip: 0.02 of area against 31 -R["through"] = {} -for label, through in (("without", 0.0), ("with", 0.1)): - new_object("Plate", plate_body) - # by distance alone (no crease cost) the underside's middle is nearer the body's seed, at an underside corner, - # than the lid's seed on top, which must go round the rim; a ray inward from the lid's seed finds it at once - receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Plate", seeds="body=-0.9,-0.9,-0.05; lid=0,0,0.05", crease_cost=0, through=through) - R["through"][label] = underside("Plate.lid") if receipt["status"] == "accepted" else None - for leftover in [o for o in bpy.data.objects if o.name.startswith("Plate")]: - bpy.data.objects.remove(leftover) -check("cut_parts: through seeds the far face of a thin part", R["through"]["without"] == 0 and (R["through"]["with"] or 0) >= 8, R["through"]) + sheet = new_object("Sheet", holey) + flipped_sheet = bmesh.new() # the generator's sheet faces down: a fill must follow it, whichever way Blender would guess + flipped_sheet.from_mesh(sheet.data) + bmesh.ops.reverse_faces(flipped_sheet, faces=flipped_sheet.faces[:]) + flipped_sheet.to_mesh(sheet.data) + flipped_sheet.free() + TILT = (0.6, 0.0, -0.8) # the generator's shading normals lean: the old faces must keep them, a fill must not borrow them + sheet.data.normals_split_custom_set([TILT] * len(sheet.data.loops)) + receipt, mended = send("brokkr_mesh_polish.repair", object_name="Sheet", fill_holes_sides=4, min_shell_area=0.01) + R["mend"] = mended + check("repair: fills the 4-edge hole, leaves the 8-edge hole and the rim, drops the chip", + receipt["status"] == "accepted" and mended["changes"]["holesFilled"] == 1 and mended["changes"]["shellsRemoved"] == 1 + and mended["after"]["shells"] == 1 and mended["after"]["boundaryEdges"] == 24 + 8, mended) + facing = polygon_normals(sheet.data)[:, 2] + check("repair: a filled hole is wound as the faces around it", len(facing) == 31 * 1 + 2 and bool((facing < -0.9).all()), [len(facing), float(facing.max())]) + shading = np.empty(len(sheet.data.loops) * 3, dtype=np.float32) + sheet.data.corner_normals.foreach_get("vector", shading) + shading = shading.reshape(-1, 3) + fill_loops = [i for polygon in sheet.data.polygons if abs(polygon.center.x - 1.5) < 0.4 and abs(polygon.center.y - 1.5) < 0.4 for i in polygon.loop_indices] + old_loops = [i for i in range(len(shading)) if i not in set(fill_loops)] + check("repair: old faces keep their shading normals through the weld and the fill; the fill is shaded by its own direction", + len(fill_loops) == 6 and np.allclose(shading[old_loops], TILT, atol=1e-3) and np.allclose(shading[fill_loops], (0.0, 0.0, -1.0), atol=1e-3), + [len(fill_loops), shading[fill_loops].tolist()[:2], shading[old_loops[0]].tolist()]) + bpy.data.objects.remove(sheet) -# --- pick and scrub_markings: lettering on one panel is found from a camera and painted out ---------------------- -panel = np.full((128, 128, 3), [0.1, 0.35, 0.4], dtype=np.float32) -panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32) -for column_start in range(8, 120, 8): # yellow strokes over the whole texture - panel[:, column_start:column_start + 2] = [0.85, 0.75, 0.2] + # --- delight: darkness that follows occlusion is levelled --------------------------------------------------------- + def pair(bm): + layer = bm.loops.layers.uv.active + for side in (-1.0, 1.0): # two unit spheres 0.1 apart: their facing sides occlude each other + made = bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16, radius=1.0, calc_uvs=True, matrix=Matrix.Translation((side * 1.05, 0, 0))) + for face in {f for v in made["verts"] for f in v.link_faces}: + for loop in face.loops: + loop[layer].uv = Vector((loop[layer].uv.x * 0.5 + (0.0 if side < 0 else 0.5), loop[layer].uv.y)) -def plate(bm): - bmesh.ops.create_grid(bm, x_segments=2, y_segments=1, size=1.0, matrix=Matrix.Diagonal((2.0, 1.0, 1.0, 1.0)), calc_uvs=True) + import brokkr_mesh_polish as polish # noqa: E402 the fixture's bake uses the add-on's own occlusion, so the light is exactly what it can explain + + twins = new_object("Twins", pair, new_image("twins_bake", np.ones((size, size, 3), dtype=np.float32))) + twins.data.polygons.foreach_set("use_smooth", [True] * len(twins.data.polygons)) + twin = polish.arrays(twins) + twin_sky = polish.ambient_occlusion(twin["V"], twin["T"], twin["N"], 64, 0.35 * float(np.linalg.norm(twin["V"].max(axis=0) - twin["V"].min(axis=0)))) + owner, bary, _ = polish.core.rasterize(twin["UV"], size) + sky_map = polish.core.interpolate(owner, bary, twin_sky[twin["T"]][..., None])[..., 0] + occluded, open_sky = (owner >= 0) & (sky_map < 0.6), (owner >= 0) & (sky_map > 0.95) + twin_bake = np.where((owner >= 0)[..., None], 0.8 * np.clip(sky_map, 0.05, 1.0)[..., None], 0.5) * np.ones((1, 1, 3)) + flat = np.ones((size, size, 4), dtype=np.float32) + flat[..., :3] = twin_bake + bpy.data.images["twins_bake"].pixels.foreach_set(flat.reshape(-1)) + receipt, unshadowed = send("brokkr_mesh_polish.delight", object_name="Twins", clusters=1, fit_size=256, occlusion_rays=64, max_gain=8) + twin_after, _ = pixels_of(twins) + shade_before = float(np.median(twin_bake[..., 0][occluded]) / np.median(twin_bake[..., 0][open_sky])) + shade_after = float(np.median(twin_after[..., 0][occluded]) / np.median(twin_after[..., 0][open_sky])) + R["occlusion"] = {"report": unshadowed, "occludedTexels": int(occluded.sum()), "shadeBefore": shade_before, "shadeAfter": shade_after} + # bound: shipped shadeAfter 1.000; with occlusion ignored (a sky of 1 everywhere) it stays 0.468: sqrt(1.000 * 0.468) = 0.684 + check("delight: lifts occluded surface to the level of open surface", receipt["status"] == "accepted" and occluded.sum() > 500 + and shade_before < SHADE_BOUND / 1.2 and shade_after > SHADE_BOUND * 1.2, R["occlusion"]) + bpy.data.objects.remove(twins) + + # --- orient: a turned slab is laid along Y, thin on Z, centred, scaled; nothing outside it moves ----------------- + slab = new_object("Slab", lambda bm: bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Diagonal((3.0, 1.0, 0.5, 1.0)))) + slab.matrix_world = Matrix.Translation((4, 5, 6)) @ Matrix.Rotation(math.radians(37), 4, (0.3, 0.5, 0.8)) + sphere.location = (20, 0, 0) + bpy.context.view_layer.update() + receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Slab", length=12.0) + corners = np.array([slab.matrix_world @ v.co for v in slab.data.vertices]) + extent = corners.max(axis=0) - corners.min(axis=0) + check("orient: long on Y, thin on Z, scaled to the length, centred", + receipt["status"] == "accepted" and np.allclose(extent, [4.0, 12.0, 2.0], atol=1e-3) + and np.allclose((corners.max(axis=0) + corners.min(axis=0)) / 2, 0, atol=1e-4), [list(map(float, extent)), oriented]) + check("orient: reports the mirror error of a symmetric body as small", max(oriented["mirrorError"].values()) < 0.05, oriented["mirrorError"]) + check("orient: an object outside the named root is not touched", oriented["objects"] == ["Slab"] + and np.allclose(sphere.matrix_world.translation, [20, 0, 0]) and abs(max(v.co.length for v in sphere.data.vertices) - 1.0) < 1e-5, oriented["objects"]) + receipt, _ = send("brokkr_mesh_polish.orient", object_name="Nobody") + check("orient: an unknown root is refused", receipt["status"] == "failed", receipt["message"]) + bpy.data.objects.remove(slab) + + # --- cut_parts: a knob fused to a block is cut off at the crease, capped, and rooted at its cut ----------------- + def knobbed(bm): + bmesh.ops.create_cube(bm, size=2.0) + top = next(f for f in bm.faces if f.normal.z > 0.9) + bmesh.ops.inset_region(bm, faces=[top], thickness=0.6) + extruded = bmesh.ops.extrude_face_region(bm, geom=[top]) + bmesh.ops.translate(bm, verts=[g for g in extruded["geom"] if isinstance(g, bmesh.types.BMVert)], vec=(0, 0, 1.0)) + bmesh.ops.delete(bm, geom=[top], context="FACES") + bmesh.ops.triangulate(bm, faces=bm.faces[:]) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) -sign = new_object("Sign", plate, new_image("sign_paint", panel)) # 4 x 2, flat on z = 0, u along x -sign.location = (40, 0, 5) # clear of the block -bpy.context.view_layer.update() -camera = bpy.data.objects.new("Eye", bpy.data.cameras.new("Eye")) -bpy.context.scene.collection.objects.link(camera) -camera.data.type = "ORTHO" -camera.data.ortho_scale = 4.0 -camera.location = (40, 0, 9) -receipt, picked = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.25, v=0.5, resolution_x=400, resolution_y=200) -check("pick: names the surface point under (u, v) of a picture of that shape", receipt["status"] == "accepted" and picked["hit"] - and picked["object"] == "Sign" and np.allclose(picked["point"], [39.0, 0.0, 5.0], atol=1e-4), picked) -receipt, missed = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.5, v=0.99, resolution_x=200, resolution_y=400) -check("pick: off the surface is a miss, not an error", receipt["status"] == "accepted" and missed == {"hit": False}, missed) + block = new_object("Block", knobbed) + receipt, single = send("brokkr_mesh_polish.audit", object_name="Block") + check("cut fixture is one closed skin", single["Block"]["shells"] == 1 and single["Block"]["boundaryEdges"] == 0, single["Block"]) + receipt, cut = send("brokkr_mesh_polish.cut_parts", object_name="Block", seeds="body=0,0,-1; knob=0,0,2", joint_scale=0.5) + R["cut"] = cut + check("cut_parts: accepted, one undo step, the fused object is replaced", receipt["status"] == "accepted" and bool(receipt.get("undoLabel")) + and "Block" not in bpy.data.objects and {"Block.body", "Block.knob"} <= set(bpy.data.objects.keys()), receipt["message"]) + if receipt["status"] == "accepted": + knob, body = bpy.data.objects["Block.knob"], bpy.data.objects["Block.body"] + part = {entry["name"]: entry for entry in cut["parts"]} + check("cut_parts: the knob is cut at the crease and rooted at the centre of the cut", + np.allclose(part["Block.knob"]["root"], [0, 0, 1], atol=1e-5) and np.allclose(knob.matrix_world.translation, [0, 0, 1], atol=1e-5) + and abs(abs(part["Block.knob"]["cutNormal"][2]) - 1) < 1e-5, part["Block.knob"]) + check("cut_parts: the knob hangs from the body and has not moved", knob.parent == body + and abs(max((knob.matrix_world @ v.co).z for v in knob.data.vertices) - 2.0) < 1e-5, None) + _, closed = send("brokkr_mesh_polish.audit") + check("cut_parts: both sides of the cut are capped (closed shells)", + all(closed[name]["boundaryEdges"] == 0 and closed[name]["shells"] == 1 for name in ("Block.body", "Block.knob")), + {name: [closed[name]["boundaryEdges"], closed[name]["shells"]] for name in ("Block.body", "Block.knob")}) + capped = {o.name: sum(1 for polygon in o.data.polygons if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap") for o in (body, knob)} + check("cut_parts: exactly the cap faces carry the cap material", capped["Block.knob"] == part["Block.knob"]["capTriangles"] > 0 + and capped["Block.body"] == part["Block.body"]["capTriangles"] > 0, capped) + cap_normals = {o.name: [polygon.normal.z for polygon in o.data.polygons + if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap"] for o in (body, knob)} + check("cut_parts: each cap faces out of its own part, and no old face was turned", + all(z < -0.9 for z in cap_normals["Block.knob"]) and all(z > 0.9 for z in cap_normals["Block.body"]) + and closed["Block.body"]["windingAgainstNormals"] == 0 and closed["Block.knob"]["windingAgainstNormals"] == 0, cap_normals) + check("cut_parts: a joint sits at the root", "Polish Cap" in [getattr(m, "name", "") for m in knob.data.materials] + and np.allclose(bpy.data.objects[part["Block.knob"]["joint"]].matrix_world.translation, [0, 0, 1], atol=1e-5), part["Block.knob"].get("joint")) + # orient after the cut: the body and what hangs from it turn as one; the knob keeps its parent and its pivot + receipt, turned_parts = send("brokkr_mesh_polish.orient", object_name="Block.body", length=6.0) + pivot = knob.matrix_world.translation + reach = max(abs((knob.matrix_world @ v.co).y) for v in knob.data.vertices) + R["orientParts"] = {"report": turned_parts, "knobPivot": list(pivot), "knobReach": reach, "parent": knob.parent.name if knob.parent else None} + # the 2 x 2 x 3 body-and-knob is laid along Y and doubled: the cut centre (0, 0, 1), half a unit above the middle, lands 1 along Y + check("orient: after a cut the parts keep their parent and their pivot at the cut", receipt["status"] == "accepted" and knob.parent == body + and abs(abs(pivot.y) - 1.0) < 1e-4 and abs(pivot.x) < 1e-4 and abs(pivot.z) < 1e-4 and abs(reach - 3.0) < 1e-4 + and np.allclose(np.array(knob.matrix_world.to_3x3()), np.eye(3), atol=1e-6), R["orientParts"]) + receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Block.body", seeds="only=0,0,-1") + check("cut_parts: one part is refused with nothing changed", receipt["status"] == "failed" and "Block.body" in bpy.data.objects, receipt["message"]) -def ink(pixels): - return np.linalg.norm(pixels - [0.1, 0.35, 0.4], axis=-1) > 0.25 + # --- cut_parts through: a seed on one face of a thin plate also holds the face behind it ----------------------- + def plate_body(bm): + bmesh.ops.create_cube(bm, size=2.0, matrix=Matrix.Diagonal((1.0, 1.0, 0.05, 1.0))) # 2 x 2 x 0.1 + bmesh.ops.subdivide_edges(bm, edges=bm.edges[:], cuts=7, use_grid_fill=True) + bmesh.ops.triangulate(bm, faces=bm.faces[:]) -receipt, scrubbed = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=picked["point"][0], y=0.0, z=5.0, radius=0.5, tolerance=0.25) -after, image = pixels_of(sign) -inside = np.zeros((128, 128), dtype=bool) -inside[48:80, 20:44] = True # well within the sphere: u 0.25 +- 0.09, v 0.5 +- 0.12 -far = np.zeros((128, 128), dtype=bool) -far[:, 72:] = True # the other half of the sign -R["scrub"] = {"report": scrubbed, "inkInsideBefore": int(ink(panel)[inside].sum()), "inkInsideAfter": int(ink(after)[inside].sum())} -check("scrub_markings: accepted, the lettering inside the sphere is gone", receipt["status"] == "accepted" - and ink(panel)[inside].sum() > 100 and ink(after)[inside].sum() == 0, R["scrub"]) -check("scrub_markings: nothing outside the sphere is touched (to the 8 bits the image stores)", np.allclose(after[far], panel[far], atol=0.6 / 255) and image.name == "sign_paint.scrubbed", image.name) -receipt, _ = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=50.0, y=0.0, z=0.0, radius=0.5) -check("scrub_markings: a sphere off the surface is refused", receipt["status"] == "failed", receipt["message"]) -receipt, _ = send("brokkr_mesh_polish.delight", object_name="Sign", max_gain=9) -check("a bound miss is denied by Brokkr's table before the operator runs", receipt["status"] == "denied", receipt["message"]) + def underside(name): + """Triangles of the part that face down and are surface, not cap.""" + part_object = bpy.data.objects[name] + return sum(1 for polygon in part_object.data.polygons + if polygon.normal.z < -0.9 and getattr(part_object.data.materials[polygon.material_index], "name", "") != "Polish Cap") -# --- real generated hulls, when a directory of .glb files is given: repair must turn none of their faces --------- -HULLS = os.environ.get("BROKKR_POLISH_HULLS", "") -R["hulls"] = {} -for path in sorted(Path(HULLS).glob("*.glb")) if HULLS else []: - known = set(bpy.data.objects.keys()) - bpy.ops.import_scene.gltf(filepath=str(path)) - for hull in [o for o in bpy.data.objects if o.name not in known and o.type == "MESH"]: - was = polygon_normals(hull.data) - _, raw = send("brokkr_mesh_polish.audit", object_name=hull.name) - against = raw[hull.name]["windingAgainstNormals"] - receipt, mended = send("brokkr_mesh_polish.repair", object_name=hull.name) - now = polygon_normals(hull.data) - turned = int(((was * now).sum(axis=1) < 0).sum()) if len(was) == len(now) else None - R["hulls"][path.name] = {"polygons": len(was), "polygonsAfter": len(now), "turned": turned, "againstBefore": against, - "againstAfter": mended["after"]["windingAgainstNormals"], "changes": mended["changes"]} - check(f"hull {path.name}: repair turns no face and keeps the shading normals' sides", receipt["status"] == "accepted" - and mended["changes"]["windingFlipped"] == 0 and turned in (0, None) # None: faces were removed, so indices no longer pair - and 0 <= against - mended["after"]["windingAgainstNormals"] <= len(was) - len(now), R["hulls"][path.name]) - bpy.data.objects.remove(hull) + + R["through"] = {} + for label, through in (("without", 0.0), ("with", 0.1)): + new_object("Plate", plate_body) + # by distance alone (no crease cost) the underside's middle is nearer the body's seed, at an underside corner, + # than the lid's seed on top, which must go round the rim; a ray inward from the lid's seed finds it at once + receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Plate", seeds="body=-0.9,-0.9,-0.05; lid=0,0,0.05", crease_cost=0, through=through) + R["through"][label] = underside("Plate.lid") if receipt["status"] == "accepted" else None + for leftover in [o for o in bpy.data.objects if o.name.startswith("Plate")]: + bpy.data.objects.remove(leftover) + check("cut_parts: through seeds the far face of a thin part", R["through"]["without"] == 0 and (R["through"]["with"] or 0) >= 8, R["through"]) + + # --- pick and scrub_markings: lettering on one panel is found from a camera and painted out ---------------------- + panel = np.full((128, 128, 3), [0.1, 0.35, 0.4], dtype=np.float32) + panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32) + for column_start in range(8, 120, 8): # yellow strokes over the whole texture + panel[:, column_start:column_start + 2] = [0.85, 0.75, 0.2] + + + def plate(bm): + bmesh.ops.create_grid(bm, x_segments=2, y_segments=1, size=1.0, matrix=Matrix.Diagonal((2.0, 1.0, 1.0, 1.0)), calc_uvs=True) + + + sign = new_object("Sign", plate, new_image("sign_paint", panel)) # 4 x 2, flat on z = 0, u along x + sign.location = (40, 0, 5) # clear of the block + bpy.context.view_layer.update() + camera = bpy.data.objects.new("Eye", bpy.data.cameras.new("Eye")) + bpy.context.scene.collection.objects.link(camera) + camera.data.type = "ORTHO" + camera.data.ortho_scale = 4.0 + camera.location = (40, 0, 9) + receipt, picked = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.25, v=0.5, resolution_x=400, resolution_y=200) + check("pick: names the surface point under (u, v) of a picture of that shape", receipt["status"] == "accepted" and picked["hit"] + and picked["object"] == "Sign" and np.allclose(picked["point"], [39.0, 0.0, 5.0], atol=1e-4), picked) + receipt, missed = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.5, v=0.99, resolution_x=200, resolution_y=400) + check("pick: off the surface is a miss, not an error", receipt["status"] == "accepted" and missed == {"hit": False}, missed) + + + def ink(pixels): + return np.linalg.norm(pixels - [0.1, 0.35, 0.4], axis=-1) > 0.25 + + + receipt, scrubbed = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=picked["point"][0], y=0.0, z=5.0, radius=0.5, tolerance=0.25) + after, image = pixels_of(sign) + inside = np.zeros((128, 128), dtype=bool) + inside[48:80, 20:44] = True # well within the sphere: u 0.25 +- 0.09, v 0.5 +- 0.12 + far = np.zeros((128, 128), dtype=bool) + far[:, 72:] = True # the other half of the sign + R["scrub"] = {"report": scrubbed, "inkInsideBefore": int(ink(panel)[inside].sum()), "inkInsideAfter": int(ink(after)[inside].sum())} + check("scrub_markings: accepted, the lettering inside the sphere is gone", receipt["status"] == "accepted" + and ink(panel)[inside].sum() > 100 and ink(after)[inside].sum() == 0, R["scrub"]) + check("scrub_markings: nothing outside the sphere is touched (to the 8 bits the image stores)", np.allclose(after[far], panel[far], atol=0.6 / 255) and image.name == "sign_paint.scrubbed", image.name) + receipt, _ = send("brokkr_mesh_polish.scrub_markings", object_name="Sign", x=50.0, y=0.0, z=0.0, radius=0.5) + check("scrub_markings: a sphere off the surface is refused", receipt["status"] == "failed", receipt["message"]) + receipt, _ = send("brokkr_mesh_polish.delight", object_name="Sign", max_gain=9) + check("a bound miss is denied by Brokkr's table before the operator runs", receipt["status"] == "denied", receipt["message"]) + + # --- real generated hulls, when a directory of .glb files is given: repair must turn none of their faces --------- + HULLS = os.environ.get("BROKKR_POLISH_HULLS", "") + R["hulls"] = {} + for path in sorted(Path(HULLS).glob("*.glb")) if HULLS else []: + known = set(bpy.data.objects.keys()) + bpy.ops.import_scene.gltf(filepath=str(path)) + for hull in [o for o in bpy.data.objects if o.name not in known and o.type == "MESH"]: + was = polygon_normals(hull.data) + _, raw = send("brokkr_mesh_polish.audit", object_name=hull.name) + against = raw[hull.name]["windingAgainstNormals"] + receipt, mended = send("brokkr_mesh_polish.repair", object_name=hull.name) + now = polygon_normals(hull.data) + turned = int(((was * now).sum(axis=1) < 0).sum()) if len(was) == len(now) else None + R["hulls"][path.name] = {"polygons": len(was), "polygonsAfter": len(now), "turned": turned, "againstBefore": against, + "againstAfter": mended["after"]["windingAgainstNormals"], "changes": mended["changes"]} + check(f"hull {path.name}: repair turns no face and keeps the shading normals' sides", receipt["status"] == "accepted" + and mended["changes"]["windingFlipped"] == 0 and turned in (0, None) # None: faces were removed, so indices no longer pair + and 0 <= against - mended["after"]["windingAgainstNormals"] <= len(was) - len(now), R["hulls"][path.name]) + bpy.data.objects.remove(hull) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) R["ok"] = all(c["ok"] for c in R["checks"]) for c in R["checks"]: diff --git a/surfaces/blender/tests/live/mesh_polish.result.json b/surfaces/blender/tests/live/mesh_polish.result.json index ead0f7d..0bc76a1 100644 --- a/surfaces/blender/tests/live/mesh_polish.result.json +++ b/surfaces/blender/tests/live/mesh_polish.result.json @@ -125,7 +125,7 @@ "undoLabel": "Brokkr test/driver: brokkr_mesh_polish.repair live-2", "lookPath": "", "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"facesCollapsedByWeld\":0,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0,\"windingFlipped\":0,\"customNormalsDropped\":false},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104}}", - "observedAt": "2026-12-02T11:45:23.730020+00:00" + "observedAt": "2026-12-02T12:26:00.225314+00:00" } }, { @@ -231,21 +231,21 @@ "Ball" ], "explainedByLight": { - "before": 0.971864311889026, - "after": 0.0005166699920249318 + "before": 0.9718639234640993, + "after": 0.0005166608648451421 }, "before": { "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0166056941702677, + "upDownLuminanceRatio": 1.016606182115671, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9857550779013501, - "median": 1.4570952973825366, - "max": 3.0649084607569628, + "min": 0.9857558916878914, + "median": 1.4570992824185989, + "max": 3.0649098409031676, "clamped": 0.0 } } @@ -374,21 +374,21 @@ "Twins" ], "explainedByLight": { - "before": 0.9999597575085379, - "after": 0.028075104345557378 + "before": 0.9999597575085377, + "after": 0.02807510434956728 }, "before": { "upDownLuminanceRatio": 1.0000084632254227, "occlusionCorrelation": 0.983967648279407 }, "after": { - "upDownLuminanceRatio": 0.9999964767501422, - "occlusionCorrelation": 0.4047107903549991 + "upDownLuminanceRatio": 0.9999964767498971, + "occlusionCorrelation": 0.4047107903548106 }, "gain": { - "min": 0.9999809983874741, - "median": 1.0000990920454487, - "max": 5.493916964791895, + "min": 0.9999809983877584, + "median": 1.0000990920471027, + "max": 5.493916964801517, "clamped": 0.0 } }, @@ -572,15 +572,15 @@ 5.656854 ], "mirrorError": { - "X": 1.8120748391154895e-08, + "X": 1.8120748396474917e-08, "Y": 0.1508370330678463, - "Z": 1.836306858436306e-08 + "Z": 1.836306858237196e-08 } }, "knobPivot": [ 1.407290284305418e-09, 1.0, - -1.8218169195449718e-09 + -1.8218171415895767e-09 ], "knobReach": 3.0, "parent": "Block.body" @@ -678,21 +678,21 @@ "Ball" ], "explainedByLight": { - "before": 0.971864311889026, - "after": 0.0005166699920249318 + "before": 0.9718639234640993, + "after": 0.0005166608648451421 }, "before": { "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0166056941702677, + "upDownLuminanceRatio": 1.016606182115671, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9857550779013501, - "median": 1.4570952973825366, - "max": 3.0649084607569628, + "min": 0.9857558916878914, + "median": 1.4570992824185989, + "max": 3.0649098409031676, "clamped": 0.0 } }, @@ -738,21 +738,21 @@ "Twins" ], "explainedByLight": { - "before": 0.9999597575085379, - "after": 0.028075104345557378 + "before": 0.9999597575085377, + "after": 0.02807510434956728 }, "before": { "upDownLuminanceRatio": 1.0000084632254227, "occlusionCorrelation": 0.983967648279407 }, "after": { - "upDownLuminanceRatio": 0.9999964767501422, - "occlusionCorrelation": 0.4047107903549991 + "upDownLuminanceRatio": 0.9999964767498971, + "occlusionCorrelation": 0.4047107903548106 }, "gain": { - "min": 0.9999809983874741, - "median": 1.0000990920454487, - "max": 5.493916964791895, + "min": 0.9999809983877584, + "median": 1.0000990920471027, + "max": 5.493916964801517, "clamped": 0.0 } }, @@ -814,15 +814,15 @@ 5.656854 ], "mirrorError": { - "X": 1.8120748391154895e-08, + "X": 1.8120748396474917e-08, "Y": 0.1508370330678463, - "Z": 1.836306858436306e-08 + "Z": 1.836306858237196e-08 } }, "knobPivot": [ 1.407290284305418e-09, 1.0, - -1.8218169195449718e-09 + -1.8218171415895767e-09 ], "knobReach": 3.0, "parent": "Block.body" diff --git a/surfaces/blender/tests/live/rig.py b/surfaces/blender/tests/live/rig.py index a3c665c..8c85ac1 100644 --- a/surfaces/blender/tests/live/rig.py +++ b/surfaces/blender/tests/live/rig.py @@ -7,7 +7,9 @@ as a GLB the exporter hook has given VRMC_springBone. Not part of the unittest r Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses without them). Writes .result.json and .glb (the synthetic whale's rig, for the runtime's own parse, -Aetheria SpringRigVerify.VerifyGlb) and exits 1 when a check failed. The acceptance is the runtime's parse, not +Aetheria SpringRigVerify.VerifyGlb) and exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names +the check before it, the checks are printed and the result file written whatever happened, and the exit is 1 with or +without --python-exit-code. The acceptance is the runtime's parse, not anything here: the structure checks below are what this builder promised, not the runtime's rules. """ import json @@ -15,6 +17,7 @@ import math import os import struct import sys +import traceback import tempfile import time import types @@ -157,183 +160,186 @@ def world_of(nodes, parent, i): return out -whale = make_whale() -check("host file admitted", not R["hostErrors"] and {"brokkr_rig.body", "brokkr_rig.tendrils", "brokkr_rig.colliders"} <= set(R["hostRows"]), - R["hostErrors"] or R["hostRows"]) -whale.rotation_euler = (0.0, 0.0, math.radians(90)) # lying along x with a non-identity transform and an offset -whale.location = (0.4, -0.2, 0.1) -bpy.context.view_layer.update() -receipt, audit = send("brokkr_mesh_polish.audit", object_name="Whale") -R["audit"] = audit -check("fixture: one fused shell and a detached bead", audit and audit["Whale"]["shells"] == 2, audit) -receipt, _ = send("brokkr_mesh_polish.repair", object_name="Whale") -check("repair accepted", receipt["status"] == "accepted", receipt["message"]) -receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Whale", length=1.0) -check("orient accepted", receipt["status"] == "accepted", receipt["message"]) -receipt, body = send("brokkr_rig.body", object_name="Whale", spine_bones=6, head="+y", seeds="jaw=0,0.45,0.05", smooth_rounds=2) -check("body accepted", receipt["status"] == "accepted", receipt["message"]) -R["body"] = body -if body: - arm = bpy.data.objects[body["armature"]] - check("body: a spine of six, a jaw bone parented to a spine bone", body["spine"] == [f"spine_{i:02d}" for i in range(6)] - and [p["name"] for p in body["parts"]] == ["jaw"] and body["parts"][0]["triangles"] > 0 - and arm.data.bones["jaw"].parent.name in body["spine"], body["parts"]) - head, tail = np.array(body["head"]), np.array(body["tail"]) - check("body: the root bone is at the +y end and the object's transform is baked", head[1] > tail[1] - and np.allclose(np.array(whale.matrix_world), np.eye(4), atol=1e-9) and arm.data.bones["spine_00"].parent is None, [head, tail]) -receipt, tendrils = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) -check("tendrils accepted", receipt["status"] == "accepted", receipt["message"]) -R["tendrils"] = tendrils -if tendrils: - check("tendrils: five chains (the vein folded), the fork made one chain with a rigid branch, the bead attached", - tendrils["chains"] == 5 and tendrils["veinsFolded"] >= 1 and tendrils["branchesRigid"] >= 1 and tendrils["shellsAttached"] >= 1, tendrils) -receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") -check("colliders accepted", receipt["status"] == "accepted", receipt["message"]) -R["colliders"] = colliders +try: + whale = make_whale() + check("host file admitted", not R["hostErrors"] and {"brokkr_rig.body", "brokkr_rig.tendrils", "brokkr_rig.colliders"} <= set(R["hostRows"]), + R["hostErrors"] or R["hostRows"]) + whale.rotation_euler = (0.0, 0.0, math.radians(90)) # lying along x with a non-identity transform and an offset + whale.location = (0.4, -0.2, 0.1) + bpy.context.view_layer.update() + receipt, audit = send("brokkr_mesh_polish.audit", object_name="Whale") + R["audit"] = audit + check("fixture: one fused shell and a detached bead", audit and audit["Whale"]["shells"] == 2, audit) + receipt, _ = send("brokkr_mesh_polish.repair", object_name="Whale") + check("repair accepted", receipt["status"] == "accepted", receipt["message"]) + receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Whale", length=1.0) + check("orient accepted", receipt["status"] == "accepted", receipt["message"]) + receipt, body = send("brokkr_rig.body", object_name="Whale", spine_bones=6, head="+y", seeds="jaw=0,0.45,0.05", smooth_rounds=2) + check("body accepted", receipt["status"] == "accepted", receipt["message"]) + R["body"] = body + if body: + arm = bpy.data.objects[body["armature"]] + check("body: a spine of six, a jaw bone parented to a spine bone", body["spine"] == [f"spine_{i:02d}" for i in range(6)] + and [p["name"] for p in body["parts"]] == ["jaw"] and body["parts"][0]["triangles"] > 0 + and arm.data.bones["jaw"].parent.name in body["spine"], body["parts"]) + head, tail = np.array(body["head"]), np.array(body["tail"]) + check("body: the root bone is at the +y end and the object's transform is baked", head[1] > tail[1] + and np.allclose(np.array(whale.matrix_world), np.eye(4), atol=1e-9) and arm.data.bones["spine_00"].parent is None, [head, tail]) + receipt, tendrils = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) + check("tendrils accepted", receipt["status"] == "accepted", receipt["message"]) + R["tendrils"] = tendrils + if tendrils: + check("tendrils: five chains (the vein folded), the fork made one chain with a rigid branch, the bead attached", + tendrils["chains"] == 5 and tendrils["veinsFolded"] >= 1 and tendrils["branchesRigid"] >= 1 and tendrils["shellsAttached"] >= 1, tendrils) + receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") + check("colliders accepted", receipt["status"] == "accepted", receipt["message"]) + R["colliders"] = colliders -def skin_state(): - """Every vertex's (group name, weight) pairs and every chain bone's properties, exactly as stored.""" - groups = [g.name for g in whale.vertex_groups] - weights = [sorted((groups[e.group], e.weight) for e in v.groups) for v in whale.data.vertices] - props = {b.name: [b[k] for k in ("rig_chain", "rig_index", "rig_stiffness", "rig_drag", "rig_gravity", "rig_hit_radius")] - for b in arm.data.bones if "rig_chain" in b} - return weights, props + def skin_state(): + """Every vertex's (group name, weight) pairs and every chain bone's properties, exactly as stored.""" + groups = [g.name for g in whale.vertex_groups] + weights = [sorted((groups[e.group], e.weight) for e in v.groups) for v in whale.data.vertices] + props = {b.name: [b[k] for k in ("rig_chain", "rig_index", "rig_stiffness", "rig_drag", "rig_gravity", "rig_hit_radius")] + for b in arm.data.bones if "rig_chain" in b} + return weights, props -first = skin_state() -send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.06, dilate=0.02) -other = skin_state() -receipt, again = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) -check("tendrils with other knobs changes the skin", other != first, None) -check("tendrils, other knobs, then the first knobs again restores the weights and bone properties exactly", skin_state() == first, None) -check("the tendrils report says what it sees", tendrils and {"warnings", "largestChainShare", "chainVertexShare", "fusedContacts"} <= set(tendrils) - and len(tendrils["warnings"]) == 1 and "one chain holds" in tendrils["warnings"][0], tendrils) # five chains hold 13% each at most: hull-like by the gauge -receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") -check("the colliders report lists each shrink and the largest share taken", colliders and colliders["shrunk"] > 0 - and len(colliders["shrinks"]) == colliders["shrunk"] and all(x["after"] < x["before"] for x in colliders["shrinks"]) - and abs(colliders["shrunkMax"] - max(1 - x["after"] / x["before"] for x in colliders["shrinks"])) < 1e-3, colliders) -R["colliders"] = colliders + first = skin_state() + send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.06, dilate=0.02) + other = skin_state() + receipt, again = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) + check("tendrils with other knobs changes the skin", other != first, None) + check("tendrils, other knobs, then the first knobs again restores the weights and bone properties exactly", skin_state() == first, None) + check("the tendrils report says what it sees", tendrils and {"warnings", "largestChainShare", "chainVertexShare", "fusedContacts"} <= set(tendrils) + and len(tendrils["warnings"]) == 1 and "one chain holds" in tendrils["warnings"][0], tendrils) # five chains hold 13% each at most: hull-like by the gauge + receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") + check("the colliders report lists each shrink and the largest share taken", colliders and colliders["shrunk"] > 0 + and len(colliders["shrinks"]) == colliders["shrunk"] and all(x["after"] < x["before"] for x in colliders["shrinks"]) + and abs(colliders["shrunkMax"] - max(1 - x["after"] / x["before"] for x in colliders["shrinks"])) < 1e-3, colliders) + R["colliders"] = colliders -# --- export: the five attributes, weights, extension, structure ---------------------------------------------------- -receipt, _ = send("exportGltf", filepath="whale.glb", extras=False, yUp=True, applyModifiers=True) -check("exportGltf accepted", receipt["status"] == "accepted", receipt["message"]) -gltf, blob, bin_at = glb_json(WORK / "whale.glb") -ext = gltf.get("extensions", {}).get("VRMC_springBone") -check("VRMC_springBone is in extensions and extensionsUsed", ext is not None and "VRMC_springBone" in gltf.get("extensionsUsed", []), list(gltf.get("extensions", {}))) -if ext and tendrils and colliders: - check("the springs, joints and colliders are the built ones", len(ext["springs"]) == tendrils["chains"] - and sum(len(s["joints"]) for s in ext["springs"]) == tendrils["springBones"] - and len(ext["colliders"]) == colliders["capsules"] + colliders["spheres"] - and all(s["colliderGroups"] == [0] for s in ext["springs"]) and [g["name"] for g in ext["colliderGroups"]] == ["body"], - [len(ext["springs"]), len(ext["colliders"])]) -check("the extension is not required", "VRMC_springBone" not in gltf.get("extensionsRequired", []), gltf.get("extensionsRequired")) -if ext: - check("stiffness tapers from the root's 3 to the tip's 1.5 and hit radii are half a tube's diameter or less", - all(abs(s["joints"][0]["stiffness"] - 3.0) < 1e-6 and abs(s["joints"][-1]["stiffness"] - 1.5) < 1e-6 - and all(0 <= j["hitRadius"] <= 0.016 for j in s["joints"]) for s in ext["springs"]), - [[j["stiffness"] for j in ext["springs"][0]["joints"]], [j["hitRadius"] for j in ext["springs"][0]["joints"]]]) -prims = [p for m in gltf["meshes"] for p in m["primitives"]] -check("mesh primitives carry exactly the five attributes", all(set(p["attributes"]) == {"POSITION", "NORMAL", "TEXCOORD_0", "JOINTS_0", "WEIGHTS_0"} for p in prims), - [sorted(p["attributes"]) for p in prims]) -worst_sum, worst_count = 0.0, 0 -for p in prims: - if "WEIGHTS_0" not in p["attributes"]: - check("every primitive is skinned", False, sorted(p["attributes"])) - continue - acc = gltf["accessors"][p["attributes"]["WEIGHTS_0"]] - view = gltf["bufferViews"][acc["bufferView"]] - W = np.frombuffer(blob, np.float32, acc["count"] * 4, bin_at + view.get("byteOffset", 0) + acc.get("byteOffset", 0)).reshape(-1, 4) - worst_sum = max(worst_sum, float(np.abs(W.sum(axis=1) - 1).max())) - worst_count = max(worst_count, int((W > 0).sum(axis=1).max())) -check("weights sum to 1 with at most four influences", worst_sum < 1e-5 and worst_count <= 4, [worst_sum, worst_count]) -nodes = gltf["nodes"] -parent = {c: i for i, n in enumerate(nodes) for c in n.get("children", [])} -check("no node carries a matrix and every scale is 1", all("matrix" not in n and all(abs(s - 1) < 1e-4 for s in n.get("scale", (1, 1, 1))) for n in nodes), None) -joints = gltf["skins"][0]["joints"] -check("one skin over every bone", len(gltf["skins"]) == 1 and len(joints) == len(arm.data.bones), [len(joints), len(arm.data.bones)]) -if ext: - in_spring = {j["node"] for s in ext["springs"] for j in s["joints"]} - linear = all(parent.get(s["joints"][0]["node"]) in set(joints) - in_spring and all(parent[s["joints"][k]["node"]] == s["joints"][k - 1]["node"] for k in range(1, len(s["joints"]))) - for s in ext["springs"]) - check("each spring is a linear chain, its first joint hung from a body bone, no bone in two springs", linear - and len(in_spring) == sum(len(s["joints"]) for s in ext["springs"]), None) - check("every segment has length", all(np.linalg.norm(nodes[j["node"]].get("translation", (0, 0, 0))) > 1e-6 for s in ext["springs"] for j in s["joints"][1:]), None) - check("colliders sit on body bones", all(c["node"] in set(joints) - in_spring for c in ext["colliders"]), None) - swing = np.array([[1.0, 0, 0], [0, 0, 1.0], [0, -1.0, 0]]) - where = [world_of(nodes, parent, j["node"])[:3, 3] for s in ext["springs"] for j in s["joints"]] - expect = [swing @ np.array(arm.matrix_world @ arm.data.bones[nodes[j["node"]]["name"]].head_local) for s in ext["springs"] for j in s["joints"]] - check("every joint's node stands where its bone's head is in the scene", np.allclose(where, expect, atol=1e-4), float(np.abs(np.array(where) - np.array(expect)).max())) -R["glb"] = {"nodes": len(nodes), "joints": len(joints), "springs": len(ext["springs"]) if ext else 0, "colliders": len(ext["colliders"]) if ext else 0} -Path(OUT + ".glb").write_bytes((WORK / "whale.glb").read_bytes()) + # --- export: the five attributes, weights, extension, structure ---------------------------------------------------- + receipt, _ = send("exportGltf", filepath="whale.glb", extras=False, yUp=True, applyModifiers=True) + check("exportGltf accepted", receipt["status"] == "accepted", receipt["message"]) + gltf, blob, bin_at = glb_json(WORK / "whale.glb") + ext = gltf.get("extensions", {}).get("VRMC_springBone") + check("VRMC_springBone is in extensions and extensionsUsed", ext is not None and "VRMC_springBone" in gltf.get("extensionsUsed", []), list(gltf.get("extensions", {}))) + if ext and tendrils and colliders: + check("the springs, joints and colliders are the built ones", len(ext["springs"]) == tendrils["chains"] + and sum(len(s["joints"]) for s in ext["springs"]) == tendrils["springBones"] + and len(ext["colliders"]) == colliders["capsules"] + colliders["spheres"] + and all(s["colliderGroups"] == [0] for s in ext["springs"]) and [g["name"] for g in ext["colliderGroups"]] == ["body"], + [len(ext["springs"]), len(ext["colliders"])]) + check("the extension is not required", "VRMC_springBone" not in gltf.get("extensionsRequired", []), gltf.get("extensionsRequired")) + if ext: + check("stiffness tapers from the root's 3 to the tip's 1.5 and hit radii are half a tube's diameter or less", + all(abs(s["joints"][0]["stiffness"] - 3.0) < 1e-6 and abs(s["joints"][-1]["stiffness"] - 1.5) < 1e-6 + and all(0 <= j["hitRadius"] <= 0.016 for j in s["joints"]) for s in ext["springs"]), + [[j["stiffness"] for j in ext["springs"][0]["joints"]], [j["hitRadius"] for j in ext["springs"][0]["joints"]]]) + prims = [p for m in gltf["meshes"] for p in m["primitives"]] + check("mesh primitives carry exactly the five attributes", all(set(p["attributes"]) == {"POSITION", "NORMAL", "TEXCOORD_0", "JOINTS_0", "WEIGHTS_0"} for p in prims), + [sorted(p["attributes"]) for p in prims]) + worst_sum, worst_count = 0.0, 0 + for p in prims: + if "WEIGHTS_0" not in p["attributes"]: + check("every primitive is skinned", False, sorted(p["attributes"])) + continue + acc = gltf["accessors"][p["attributes"]["WEIGHTS_0"]] + view = gltf["bufferViews"][acc["bufferView"]] + W = np.frombuffer(blob, np.float32, acc["count"] * 4, bin_at + view.get("byteOffset", 0) + acc.get("byteOffset", 0)).reshape(-1, 4) + worst_sum = max(worst_sum, float(np.abs(W.sum(axis=1) - 1).max())) + worst_count = max(worst_count, int((W > 0).sum(axis=1).max())) + check("weights sum to 1 with at most four influences", worst_sum < 1e-5 and worst_count <= 4, [worst_sum, worst_count]) + nodes = gltf["nodes"] + parent = {c: i for i, n in enumerate(nodes) for c in n.get("children", [])} + check("no node carries a matrix and every scale is 1", all("matrix" not in n and all(abs(s - 1) < 1e-4 for s in n.get("scale", (1, 1, 1))) for n in nodes), None) + joints = gltf["skins"][0]["joints"] + check("one skin over every bone", len(gltf["skins"]) == 1 and len(joints) == len(arm.data.bones), [len(joints), len(arm.data.bones)]) + if ext: + in_spring = {j["node"] for s in ext["springs"] for j in s["joints"]} + linear = all(parent.get(s["joints"][0]["node"]) in set(joints) - in_spring and all(parent[s["joints"][k]["node"]] == s["joints"][k - 1]["node"] for k in range(1, len(s["joints"]))) + for s in ext["springs"]) + check("each spring is a linear chain, its first joint hung from a body bone, no bone in two springs", linear + and len(in_spring) == sum(len(s["joints"]) for s in ext["springs"]), None) + check("every segment has length", all(np.linalg.norm(nodes[j["node"]].get("translation", (0, 0, 0))) > 1e-6 for s in ext["springs"] for j in s["joints"][1:]), None) + check("colliders sit on body bones", all(c["node"] in set(joints) - in_spring for c in ext["colliders"]), None) + swing = np.array([[1.0, 0, 0], [0, 0, 1.0], [0, -1.0, 0]]) + where = [world_of(nodes, parent, j["node"])[:3, 3] for s in ext["springs"] for j in s["joints"]] + expect = [swing @ np.array(arm.matrix_world @ arm.data.bones[nodes[j["node"]]["name"]].head_local) for s in ext["springs"] for j in s["joints"]] + check("every joint's node stands where its bone's head is in the scene", np.allclose(where, expect, atol=1e-4), float(np.abs(np.array(where) - np.array(expect)).max())) + R["glb"] = {"nodes": len(nodes), "joints": len(joints), "springs": len(ext["springs"]) if ext else 0, "colliders": len(ext["colliders"]) if ext else 0} + Path(OUT + ".glb").write_bytes((WORK / "whale.glb").read_bytes()) -# --- determinism, yUp, and a scene with no rig ------------------------------------------------------------------------ -send("exportGltf", filepath="again.glb", extras=False, yUp=True, applyModifiers=True) -a, b = glb_json(WORK / "whale.glb")[0], glb_json(WORK / "again.glb")[0] -check("two exports have identical JSON chunks", json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True), None) -send("exportGltf", filepath="flat.glb", extras=False, yUp=False, applyModifiers=True) -flat, _, _ = glb_json(WORK / "flat.glb") -fext = flat.get("extensions", {}).get("VRMC_springBone") -if ext and fext: - nodes_f = flat["nodes"] - parent_f = {c: i for i, n in enumerate(nodes_f) for c in n.get("children", [])} - names = {n["name"]: i for i, n in enumerate(nodes)} + # --- determinism, yUp, and a scene with no rig ------------------------------------------------------------------------ + send("exportGltf", filepath="again.glb", extras=False, yUp=True, applyModifiers=True) + a, b = glb_json(WORK / "whale.glb")[0], glb_json(WORK / "again.glb")[0] + check("two exports have identical JSON chunks", json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True), None) + send("exportGltf", filepath="flat.glb", extras=False, yUp=False, applyModifiers=True) + flat, _, _ = glb_json(WORK / "flat.glb") + fext = flat.get("extensions", {}).get("VRMC_springBone") + if ext and fext: + nodes_f = flat["nodes"] + parent_f = {c: i for i, n in enumerate(nodes_f) for c in n.get("children", [])} + names = {n["name"]: i for i, n in enumerate(nodes)} - def collider_world(gl, nd, par, c, key): - return (world_of(nd, par, c["node"]) @ np.append(c["shape"][list(c["shape"])[0]][key], 1.0))[:3] + def collider_world(gl, nd, par, c, key): + return (world_of(nd, par, c["node"]) @ np.append(c["shape"][list(c["shape"])[0]][key], 1.0))[:3] - pairs = [(collider_world(gltf, nodes, parent, c, "offset"), collider_world(flat, nodes_f, parent_f, f, "offset")) - for c, f in zip(ext["colliders"], fext["colliders"])] - check("yUp false: a collider's node-local offset composes to the same scene point (up to the axis swing)", - bool(pairs) and all(np.allclose(up, swing @ flat_point, atol=1e-4) for up, flat_point in pairs), pairs[:1]) -bpy.ops.mesh.primitive_cube_add() -cube = bpy.context.active_object -cube.name = "Cube" -send("exportGltf", filepath="cube.glb", extras=False, yUp=True, applyModifiers=True, selection=["Cube"]) -cube_json, _, _ = glb_json(WORK / "cube.glb") -check("a scene with no rig springs exports no VRMC_springBone", "VRMC_springBone" not in cube_json.get("extensions", {}) - and "VRMC_springBone" not in cube_json.get("extensionsUsed", []), list(cube_json.get("extensions", {}))) + pairs = [(collider_world(gltf, nodes, parent, c, "offset"), collider_world(flat, nodes_f, parent_f, f, "offset")) + for c, f in zip(ext["colliders"], fext["colliders"])] + check("yUp false: a collider's node-local offset composes to the same scene point (up to the axis swing)", + bool(pairs) and all(np.allclose(up, swing @ flat_point, atol=1e-4) for up, flat_point in pairs), pairs[:1]) + bpy.ops.mesh.primitive_cube_add() + cube = bpy.context.active_object + cube.name = "Cube" + send("exportGltf", filepath="cube.glb", extras=False, yUp=True, applyModifiers=True, selection=["Cube"]) + cube_json, _, _ = glb_json(WORK / "cube.glb") + check("a scene with no rig springs exports no VRMC_springBone", "VRMC_springBone" not in cube_json.get("extensions", {}) + and "VRMC_springBone" not in cube_json.get("extensionsUsed", []), list(cube_json.get("extensions", {}))) -# --- body again on its own armature: the chains go, nothing is left weighing nothing; colliders alone export no springs -chain_bones = sum(1 for b in arm.data.bones if "rig_chain" in b) -receipt, rebody = send("brokkr_rig.body", object_name="Whale", armature_name=arm.name, seeds="jaw=0,0.45,0.05") -check("body again clears the chain bones it would orphan", - rebody and rebody["chainBonesCleared"] == chain_bones > 0 and not any("rig_chain" in b for b in arm.data.bones), rebody) -check("body again leaves no collider from the old body", not any("rig_colliders" in b for b in arm.data.bones), None) -send("exportGltf", filepath="cleared.glb", extras=False, yUp=True, applyModifiers=True) -cleared_json, _, _ = glb_json(WORK / "cleared.glb") -check("an armature with no chains exports no springs", "VRMC_springBone" not in cleared_json.get("extensions", {}), None) -receipt, lone = send("brokkr_rig.colliders", object_name="Whale") -send("exportGltf", filepath="colliders_only.glb", extras=False, yUp=True, applyModifiers=True) -only_json, _, _ = glb_json(WORK / "colliders_only.glb") -check("colliders without chains export no VRMC_springBone", lone and lone["capsules"] > 0 and "VRMC_springBone" not in only_json.get("extensions", {}) - and "VRMC_springBone" not in only_json.get("extensionsUsed", []), lone) -receipt, rerun = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) -check("tendrils after the second body rebuilds the same chains", rerun and tendrils and rerun["chains"] == tendrils["chains"] - and rerun["springBones"] == tendrils["springBones"], [rerun, tendrils]) + # --- body again on its own armature: the chains go, nothing is left weighing nothing; colliders alone export no springs + chain_bones = sum(1 for b in arm.data.bones if "rig_chain" in b) + receipt, rebody = send("brokkr_rig.body", object_name="Whale", armature_name=arm.name, seeds="jaw=0,0.45,0.05") + check("body again clears the chain bones it would orphan", + rebody and rebody["chainBonesCleared"] == chain_bones > 0 and not any("rig_chain" in b for b in arm.data.bones), rebody) + check("body again leaves no collider from the old body", not any("rig_colliders" in b for b in arm.data.bones), None) + send("exportGltf", filepath="cleared.glb", extras=False, yUp=True, applyModifiers=True) + cleared_json, _, _ = glb_json(WORK / "cleared.glb") + check("an armature with no chains exports no springs", "VRMC_springBone" not in cleared_json.get("extensions", {}), None) + receipt, lone = send("brokkr_rig.colliders", object_name="Whale") + send("exportGltf", filepath="colliders_only.glb", extras=False, yUp=True, applyModifiers=True) + only_json, _, _ = glb_json(WORK / "colliders_only.glb") + check("colliders without chains export no VRMC_springBone", lone and lone["capsules"] > 0 and "VRMC_springBone" not in only_json.get("extensions", {}) + and "VRMC_springBone" not in only_json.get("extensionsUsed", []), lone) + receipt, rerun = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) + check("tendrils after the second body rebuilds the same chains", rerun and tendrils and rerun["chains"] == tendrils["chains"] + and rerun["springBones"] == tendrils["springBones"], [rerun, tendrils]) -# --- a mesh with no thin part: no chains is an outcome, not a crash, and the skin stays the body's -------------------------- -ball = bmesh.new() -bmesh.ops.create_uvsphere(ball, u_segments=24, v_segments=12, radius=0.3, calc_uvs=True) -ball_mesh = bpy.data.meshes.new("Ball") -ball.to_mesh(ball_mesh) -ball.free() -ball_obj = bpy.data.objects.new("Ball", ball_mesh) -bpy.context.scene.collection.objects.link(ball_obj) -send("brokkr_rig.body", object_name="Ball", spine_bones=4) + # --- a mesh with no thin part: no chains is an outcome, not a crash, and the skin stays the body's -------------------------- + ball = bmesh.new() + bmesh.ops.create_uvsphere(ball, u_segments=24, v_segments=12, radius=0.3, calc_uvs=True) + ball_mesh = bpy.data.meshes.new("Ball") + ball.to_mesh(ball_mesh) + ball.free() + ball_obj = bpy.data.objects.new("Ball", ball_mesh) + bpy.context.scene.collection.objects.link(ball_obj) + send("brokkr_rig.body", object_name="Ball", spine_bones=4) -def ball_weights(): - names = [g.name for g in ball_obj.vertex_groups] - return [sorted((names[e.group], e.weight) for e in v.groups) for v in ball_obj.data.vertices] + def ball_weights(): + names = [g.name for g in ball_obj.vertex_groups] + return [sorted((names[e.group], e.weight) for e in v.groups) for v in ball_obj.data.vertices] -before = ball_weights() -receipt, bald = send("brokkr_rig.tendrils", object_name="Ball", tau=0.05, band=0.04, dilate=0.01) -check("tendrils on a mesh with no thin part is accepted and reports no chains", receipt["status"] == "accepted" and bald and bald["chains"] == 0 - and bald["springBones"] == 0 and bald["rings"] == 0 and bald["fusedContacts"] == 0, [receipt["message"], bald]) -check("and leaves the skin as body made it, with no chain bones", ball_weights() == before - and not any("rig_chain" in b for b in bpy.data.objects["Ball.rig"].data.bones), None) + before = ball_weights() + receipt, bald = send("brokkr_rig.tendrils", object_name="Ball", tau=0.05, band=0.04, dilate=0.01) + check("tendrils on a mesh with no thin part is accepted and reports no chains", receipt["status"] == "accepted" and bald and bald["chains"] == 0 + and bald["springBones"] == 0 and bald["rings"] == 0 and bald["fusedContacts"] == 0, [receipt["message"], bald]) + check("and leaves the skin as body made it, with no chain bones", ball_weights() == before + and not any("rig_chain" in b for b in bpy.data.objects["Ball.rig"].data.bones), None) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) R["ok"] = all(c["ok"] for c in R["checks"]) for c in R["checks"]: diff --git a/surfaces/blender/tests/live/rig.result.json b/surfaces/blender/tests/live/rig.result.json index 91255bf..e54abae 100644 --- a/surfaces/blender/tests/live/rig.result.json +++ b/surfaces/blender/tests/live/rig.result.json @@ -210,7 +210,7 @@ { "name": "exportGltf accepted", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-s67r7hee\\whale.glb (301168 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-qccur36g\\whale.glb (301168 bytes)." }, { "name": "VRMC_springBone is in extensions and extensionsUsed", From 617eb2acbcd36433b84f96135751fb20cde6d1d0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 13:29:46 +0100 Subject: [PATCH 107/223] brokkr_kitbash.shell: count_folds counts the folded faces of the evaluated wall; the cage estimate is gone The fold receipt read from the cage ({onset, margin, edge, weight}) was no bound in either direction: seeded lofts fold at 0.03 to 0.44 of it, and it warned on Seraph plates that do not fold. core.fold_depths and the receipt are deleted. With count_folds, shell evaluates the wall alone (Kit Subsurf and Kit Solidify, every other modifier hidden for the reading and shown again) and reports folded: inner faces with a corner turned to run with their outer twin's normal. Without it folded is null and nothing is evaluated. Measured: 3.9 ms on a new plate of 1600 subdivided faces; nothing separable on a rebuild under six cutters (0.94 s against 0.92 s). Live kitbash_faceted holds the count to its own, face for face, on the wedge, on three of Soul's seeded lofts (seed 5185 offset -1, 5101 offset 0, 5196 offset 1; tests/fixtures/fold_lofts.json) and on a rebuild under cutters. Mutants caught there: never folded, all corners for any, stack left hidden. docs/kitbash.md: folded 0 is not yet a wall an Exact Boolean takes cleanly; on the Seraph's cap and breast it left open edges from 0.91 of the first folding thickness, on one hand of a mirrored pair. Finding: aetheria-release:finding:cut-kit-faceted-shell.s3.fold-receipt-margin-is-not-a-bound Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 53 +- .../brokkr_kitbash/brokkr_actions.json | 8 +- surfaces/blender/brokkr_kitbash/core.py | 37 -- surfaces/blender/docs/kitbash.md | 41 +- .../blender/tests/fixtures/fold_lofts.json | 543 ++++++++++++++++++ .../blender/tests/live/kitbash_faceted.py | 76 ++- .../tests/live/kitbash_faceted.result.json | 50 +- surfaces/blender/tests/test_kitbash.py | 54 +- 8 files changed, 735 insertions(+), 127 deletions(-) create mode 100644 surfaces/blender/tests/fixtures/fold_lofts.json diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index c557c76..076453a 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -57,6 +57,7 @@ solves a loop: a closure never places a part, and a report says how far its two bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (5, 3, 0), "category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."} +import contextlib import json import math @@ -1304,6 +1305,7 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): offset: bpy.props.FloatProperty(name="Offset", default=-1.0, min=-1.0, max=1.0, description="-1: the wall grows inward from the designed surface; 1: outward") levels: bpy.props.IntProperty(name="Levels", default=3, min=1, max=4, description="Subdivision levels") bevel: bpy.props.FloatProperty(name="Bevel", default=0.0, min=0.0, max=0.1, description="Width of the Kit Bevel on the plate's edges; 0: none") + count_folds: bpy.props.BoolProperty(name="Count Folds", default=False, description="Evaluate the wall and report how many of its inner faces fold") # the action table states thickness from 0.001: a float property rounds 0.001 up, so its bound stands just under @kit_work @@ -1316,6 +1318,13 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): raise Refused(f"An object named {obj.name!r} exists and is no shell (it carries no {SHELL}): shell rebuilds only what shell made; nothing changed.") rigid(obj) own_mesh(obj, "rebuilding") + if self.count_folds: + unseen = [modifier.name for modifier in obj.modifiers if modifier.name in (SUBSURF, SOLIDIFY) and not modifier.show_viewport] + if unseen: + raise Refused(f"{obj.name!r} has its {' and '.join(unseen)} hidden in viewports, and count_folds reads the wall those two make. " + "Show them, or leave count_folds off; nothing changed.") + with self.wall_alone(obj): + evaluable(context, obj) try: document = json.loads(self.sheet) except ValueError as error: @@ -1355,20 +1364,46 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): corners = built.V[built.faces.reshape(-1, 4)] facing = np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]).sum(axis=0) # twice the quads' vector areas, summed cancels = np.linalg.norm(facing) <= 1e-9 * np.linalg.norm(np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]), axis=1).sum() - pairs, depths, ridges, weights = core.fold_depths(built, self.levels) - behind, front = 0.5 * (1.0 - self.offset), 0.5 * (1.0 + self.offset) # the wall's share behind the designed surface, and in front of it - with np.errstate(divide="ignore"): - onsets = depths / np.where(ridges, behind, front) # the thickness at which each cage edge's concave side holds its fold depth - first = int(onsets.argmin()) if len(onsets) and np.isfinite(onsets.min()) else None - fold = None if first is None else { - "onset": round(float(onsets[first]), 6), "margin": round(float(onsets[first]) / self.thickness, 4), - "edge": [[int(v) // built.points, int(v) % built.points] for v in pairs[first]], "weight": round(float(weights[first]), 6)} return {"object": obj.name, "rebuilt": rebuilt, "rings": built.rings, "points": built.points, "cageFaces": cage_faces, "creases": len(built.creases), - "fold": fold, + "folded": self.folded_faces(context, obj, cage_faces * 4 ** self.levels) if self.count_folds else None, "corners": len(built.corners), "subdividedFaces": cage_faces * 4 ** self.levels, "facing": None if cancels else [round(float(v), 6) for v in facing / np.linalg.norm(facing)], "thickness": round(self.thickness, 6), "offset": round(self.offset, 6), "levels": self.levels, "children": sorted(child.name for child in obj.children)} + @staticmethod + @contextlib.contextmanager + def wall_alone(shell): + """The shell with every modifier but its Kit Subsurf and Kit Solidify hidden, and shown again on the way out: what + an evaluation inside reads is the wall, and no Boolean runs for it.""" + hidden = [modifier for modifier in shell.modifiers if modifier.name not in (SUBSURF, SOLIDIFY) and modifier.show_viewport] + for modifier in hidden: + modifier.show_viewport = False + try: + yield + finally: + for modifier in hidden: + modifier.show_viewport = True + + @staticmethod + def folded_faces(context, shell, faces: int) -> int: + """How many inner faces of a shell's wall fold, counted on the wall as Blender evaluates it (wall_alone): Kit + Solidify lists the `faces` subdivided faces of the designed surface, then their inner twins in the same order, + each wound the other way. An inner face folds when the turn at any of its corners runs with its outer twin's + normal instead of against it: the corner has passed over its neighbour. 0 is a wall that nowhere folds.""" + with BROKKR_KITBASH_OT_shell.wall_alone(shell): + _, evaluated = evaluable(context, shell) + mesh = evaluated.to_mesh() + try: + points, corners = np.zeros(3 * len(mesh.vertices)), np.zeros(len(mesh.loops), dtype=np.int32) + mesh.vertices.foreach_get("co", points) + mesh.loops.foreach_get("vertex_index", corners) + quads = points.reshape(-1, 3)[corners[:8 * faces].reshape(2, faces, 4)] + outward = np.cross(quads[0, :, 2] - quads[0, :, 0], quads[0, :, 3] - quads[0, :, 1]) + turns = np.cross(quads[1] - np.roll(quads[1], 1, axis=1), np.roll(quads[1], -1, axis=1) - quads[1]) + return int((np.einsum("fkc,fc->fk", turns, outward) > 0).any(axis=1).sum()) + finally: + evaluated.to_mesh_clear() + class BROKKR_KITBASH_OT_describe(PolishOperator): """List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index f286fd1..89ed135 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -719,7 +719,7 @@ }, { "name": "brokkr_kitbash.shell", - "doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings, points, cageFaces, creases, fold ({onset, margin, edge, weight}: the thickness at which the cage says the wall first folds over itself beside an edge, onset over the thickness asked, the edge as two [ring, point] and its crease; null where no edge can fold; an estimate from the cage, margin under 1 is a folded wall), corners, subdividedFaces, facing, thickness, offset, levels and children.", + "doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. A thickness the cage cannot hold is not refused: the wall folds over itself beside a tight crease or rim corner, and a cut there is unsound. count_folds evaluates the wall alone (Kit Subsurf and Kit Solidify, no Boolean; 4 ms on a plate of 1600 subdivided faces) and counts the folded inner faces; nothing else in the report reads an evaluated mesh, and no figure of the cage bounds the fold. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings, points, cageFaces, creases, folded (null unless count_folds: then the number of the wall's inner faces that fold over, counted on the evaluated wall; 0 is a wall with no folded face, which an Exact Boolean can still fail on just short of a fold: read nonManifoldEdges after cutting), corners, subdividedFaces, facing, thickness, offset, levels and children.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -771,6 +771,12 @@ "maximum": 0.1, "default": 0, "doc": "width of the Kit Bevel on the plate's edges; 0: none" + }, + { + "name": "count_folds", + "type": "boolean", + "default": false, + "doc": "evaluate the wall (Kit Subsurf and Kit Solidify alone) and report folded, the number of its inner faces that fold over" } ] } diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index f932bd5..d6156c9 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1134,43 +1134,6 @@ def sheet(document: Any) -> Sheet: corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N) -def fold_depths(built: Sheet, levels: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """Where an even wall on a shell's cage would fold, from the cage alone: for every cage edge between two quads, - (pairs (E, 2) of vertex indices, depth (E,), ridge (E,), weight (E,)). depth is the wall depth on the edge's - concave side at which the wall's far face first folds over itself beside the edge when the edge is a full - crease between flat facets: (W / 2^levels) / tan(phi), W the lesser perpendicular reach of the two quads from - the edge (the narrower facet binds) and phi half the angle between their normals; infinite where they are - coplanar. ridge: the facets fall away from their normals, so the concave side is behind the surface (a wall - grown inward); else it is in front. weight is the edge's crease, 0 where it has none: under a full crease a - softer edge folds later than its depth, never sooner.""" - quads = built.faces.reshape(-1, 4) - V = built.V - normals = np.cross(V[quads[:, 2]] - V[quads[:, 0]], V[quads[:, 3]] - V[quads[:, 1]]) - normals /= np.linalg.norm(normals, axis=1)[:, None] - centres = V[quads].mean(axis=1) - sides = {} - for face, quad in enumerate(quads): - for k in range(4): - a, b = int(quad[k]), int(quad[(k + 1) % 4]) - sides.setdefault((min(a, b), max(a, b)), []).append((face, int(quad[(k + 2) % 4]), int(quad[(k + 3) % 4]))) - creased = {(int(a), int(b)): float(w) for (a, b), w in zip(built.creases, built.weights)} - pairs, depths, ridges, weights = [], [], [], [] - for (a, b), faces in sorted(sides.items()): - if len(faces) != 2: - continue - along = V[b] - V[a] - along /= np.linalg.norm(along) - reach = min(float(np.linalg.norm((V[v] - V[a]) - along * ((V[v] - V[a]) @ along))) for _, c, d in faces for v in (c, d)) - (f0, _, _), (f1, _, _) = faces - middle = 0.5 * (V[a] + V[b]) - phi = 0.5 * math.acos(float(np.clip(normals[f0] @ normals[f1], -1.0, 1.0))) - pairs.append((a, b)) - depths.append(reach / 2 ** levels / math.tan(phi) if phi > 1e-9 else math.inf) - ridges.append(bool(normals[f0] @ (centres[f1] - middle) + normals[f1] @ (centres[f0] - middle) < 0)) - weights.append(creased.get((a, b), 0.0)) - return np.array(pairs, dtype=np.int64).reshape(-1, 2), np.array(depths), np.array(ridges, dtype=bool), np.array(weights) - - # --- reports ------------------------------------------------------------------------------------------------- def rows(matrix) -> list[list[float]]: diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 32fea95..1c7f452 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -351,9 +351,9 @@ The object carries the cage, `crease_edge` and `crease_vert`, and the modifiers used) then `Kit Solidify` (`thickness`, `offset`, even, rim filled), then any Booleans `cut` adds, then the `Kit Bevel` when `bevel` is over 0. `kit_shell` on it is the request, and it owns the cage as `kit_params` owns a part's mesh: an edit of the cage by hand is lost at the next `shell` call. `shell` reports `object`, `rebuilt`, -`rings`, `points`, `cageFaces`, `creases` (edges with a weight over 0), `fold` (see Thickness at a crease), -`corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`, all facts of the cage: it -reads no evaluated mesh. +`rings`, `points`, `cageFaces`, `creases` (edges with a weight over 0), `folded` (see Thickness at a crease), +`corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. All but `folded` are facts +of the cage: without `count_folds`, `shell` reads no evaluated mesh. **Rebuilding.** `shell` on a name that is already a shell rewrites its cage in place. The object, its mesh datablock, its material slots, its cutters, its ribs and its Booleans stay, so a plate can be reshaped after it is @@ -370,7 +370,7 @@ the outline, and the plate left between two bites is a tab. it; a rib deeper than the room a tight crease leaves is refused with the size to lower. **Thickness at a crease.** `shell` takes any `thickness` in its range and does not refuse one the cage cannot -hold: it reads no evaluated mesh, and the limit is a fact of the subdivided one. Even thickness moves a vertex on a +hold: the limit is a fact of the subdivided mesh, not of the cage. Even thickness moves a vertex on a full crease along the crease's bisector, which slides it `thickness` x tan(phi) across each facet, phi being half the angle between the two facets' normals; the vertices beside it move straight in. Where that slide is longer than the first row of subdivided faces, the wall's far face folds over itself beside the crease: at a wall depth over @@ -384,16 +384,27 @@ uncreased edge folds too, at 1.17 to 4.2 of it. The fold is inside the wall and designed surface is unchanged and the mesh has no open or non-manifold edge, but the solid passes through itself there, and a cut through that place is untested. -`shell` reports this at the call, from the cage: `fold` is `{onset, margin, edge, weight}`, or null where no cage -edge has a wall on its concave side. `onset` is the least `thickness` at which the figure above says some cage edge -folds, every edge between two quads taken as a full crease between flat facets, and the wall's share on that edge's -concave side taken from `offset`; `margin` is `onset` over the `thickness` asked, so under 1 the wall is expected to -fold; `edge` is that edge as two `[ring, point]` (points as built: 2C - 1 on a mirrored ring), and `weight` its -crease. It is an estimate: a `weight` under 1 folds later than `onset`, and where a crease runs out to the rim -through a tapering quad the wall can fold sooner. On the Seraph's fourteen creased plates the evaluated wall first -folded at 0.74 to 1.2 of `onset` in thirteen and at 2.6 of it in one, whose binding edge had a crease of 0.6 -(`experiments/mechs`, 2026-12-02). Keep `margin` over about 1.4 where a plate is cut near a crease, with a thinner -wall, fewer `levels` or wider facets, and count the turned inner faces of the evaluated wall when it matters. +No figure read from the cage bounds this. The flat-facet figure above, taken over every cage edge, is neither a +floor nor a ceiling on a real plate: on seeded lofts of planar trapezoid facets with partial crease runs the +evaluated wall first folded at 0.44 of it with the wall grown inward, at 0.03 of it at `offset` 0 and at 0.08 of it +grown outward, and on the Seraph's plates a first face normal turned at 0.74 to 2.6 of it (`tests/fixtures/fold_lofts.json` holds three of +those lofts; 2026-12-02). So `shell` counts instead of estimating: with `count_folds` it evaluates the wall alone, +`Kit Subsurf` and `Kit Solidify` with every other modifier hidden for the reading and shown again, and reports +`folded`, the number of the wall's inner faces that fold. An inner face folds when the turn at any of its corners +runs with its outer twin's normal: the corner has passed over its neighbour. That is sooner than the face's own +normal turning: on the Seraph's cap a corner turned at 0.033 and no face normal had at 0.0416. Without `count_folds`, `folded` is null +and nothing is evaluated. The count cost 3.9 ms on a new plate of 1600 subdivided faces (a call of 7.7 ms against +3.8 ms), and nothing measurable on a rebuild under six cutters (0.94 s against 0.92 s, the call's own Boolean), +medians of three interleaved calls in the live suite (Blender 5.3 on Starfire). On a shell whose `Kit Subsurf` or +`Kit Solidify` is hidden in viewports `count_folds` is refused before anything is written. + +`folded` 0 is not yet a wall an Exact Boolean takes cleanly. Short of the fold the inner quads at a tight rim corner +are twisted, and the Boolean, which cuts quads into triangles, can read the wall as passing through itself and +leave edges with four faces. On the Seraph's cap that began at 0.91 of the thickness at which the first face +folds (0.0301 against 0.033), on the left cap and not on its mirror, the right; on its breast plate at 0.91 as +well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, `apply`, or a count on the evaluated +mesh), and keep `thickness` clear of the first folding one with a thinner wall, fewer `levels` or wider facets at +the corner. Refused, each before anything is written and naming the field and index: a missing or unknown key; a non-finite number; fewer than 2 or more than 64 rings or points; rings of unequal counts; a quad under 1e-8 m2 (a collapsed @@ -598,7 +609,7 @@ vertices overflow. | `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | -| `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `fold` (`{onset, margin, edge, weight}`: the thickness at which the cage says the wall first folds beside an edge, or null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | +| `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored value (`set_params`). A value outside its bounds is refused with the bounds in the message. diff --git a/surfaces/blender/tests/fixtures/fold_lofts.json b/surfaces/blender/tests/fixtures/fold_lofts.json new file mode 100644 index 0000000..566c2b0 --- /dev/null +++ b/surfaces/blender/tests/fixtures/fold_lofts.json @@ -0,0 +1,543 @@ +{ + "about": "Lofts of planar trapezoid facets on which a shell's wall folds well under any figure read from the cage: the seeded lofts of Soul's probe of 2026-12-02 (aetheria-release:verdict:cut-kit-faceted-shell.s3), seed, levels and offset as drawn there. thickness is one at which the evaluated wall folds; holds, where the action's range reaches it, one at which it does not.", + "lofts": [ + { + "seed": 5185, + "levels": 1, + "offset": -1.0, + "thickness": 0.006342, + "holds": 0.001, + "sheet": { + "rings": [ + [ + [ + -0.824534, + 0.0, + -0.055726 + ], + [ + -0.20124, + 0.0, + -0.555671 + ], + [ + 0.277571, + 0.0, + -0.326276 + ], + [ + 0.355141, + 0.0, + -0.095203 + ], + [ + 0.451529, + 0.0, + -0.526972 + ], + [ + 0.730665, + 0.0, + -0.126214 + ] + ], + [ + [ + -0.644054, + 0.57461, + -0.007851 + ], + [ + -0.166195, + 0.57461, + -0.391143 + ], + [ + 0.200893, + 0.57461, + -0.215272 + ], + [ + 0.260364, + 0.57461, + -0.038117 + ], + [ + 0.334261, + 0.57461, + -0.36914 + ], + [ + 0.548265, + 0.57461, + -0.061892 + ] + ], + [ + [ + -0.670812, + 0.958364, + 0.100578 + ], + [ + -0.338388, + 0.958364, + -0.16606 + ], + [ + -0.083022, + 0.958364, + -0.043715 + ], + [ + -0.041652, + 0.958364, + 0.079523 + ], + [ + 0.009755, + 0.958364, + -0.150754 + ], + [ + 0.158628, + 0.958364, + 0.062984 + ] + ], + [ + [ + -0.121748, + 1.402066, + -0.069972 + ], + [ + 0.06524, + 1.402066, + -0.219956 + ], + [ + 0.208883, + 1.402066, + -0.151137 + ], + [ + 0.232154, + 1.402066, + -0.081816 + ], + [ + 0.261071, + 1.402066, + -0.211346 + ], + [ + 0.344812, + 1.402066, + -0.091119 + ] + ] + ], + "creases": [ + { + "ring": 1, + "from": 4, + "to": 5, + "weight": 0.3 + }, + { + "column": 3, + "from": 0, + "to": 3, + "weight": 1.0 + }, + { + "ring": 2, + "from": 0, + "to": 3, + "weight": 1.0 + } + ], + "rim": 0.5 + } + }, + { + "seed": 5101, + "levels": 3, + "offset": 0.0, + "thickness": 0.010394, + "holds": null, + "sheet": { + "rings": [ + [ + [ + -0.70481, + 0.0, + 0.07744 + ], + [ + -0.108308, + 0.0, + 0.00574 + ], + [ + 0.492256, + 0.0, + -0.339801 + ], + [ + 0.608357, + 0.0, + -0.456893 + ], + [ + 0.685935, + 0.0, + -0.379315 + ], + [ + 0.817607, + 0.0, + 0.061337 + ] + ], + [ + [ + -0.355146, + 0.797251, + 0.328588 + ], + [ + 0.181707, + 0.797251, + 0.264058 + ], + [ + 0.722214, + 0.797251, + -0.046929 + ], + [ + 0.826705, + 0.797251, + -0.152312 + ], + [ + 0.896525, + 0.797251, + -0.082492 + ], + [ + 1.01503, + 0.797251, + 0.314095 + ] + ], + [ + [ + -0.785461, + 1.527843, + -0.183277 + ], + [ + -0.308259, + 1.527843, + -0.240637 + ], + [ + 0.172192, + 1.527843, + -0.51707 + ], + [ + 0.265072, + 1.527843, + -0.610743 + ], + [ + 0.327135, + 1.527843, + -0.548681 + ], + [ + 0.432473, + 1.527843, + -0.19616 + ] + ], + [ + [ + -0.488084, + 2.123542, + -0.236617 + ], + [ + -0.070532, + 2.123542, + -0.286807 + ], + [ + 0.349863, + 2.123542, + -0.528686 + ], + [ + 0.431133, + 2.123542, + -0.61065 + ], + [ + 0.485438, + 2.123542, + -0.556346 + ], + [ + 0.577608, + 2.123542, + -0.247889 + ] + ], + [ + [ + -0.714517, + 2.852512, + 0.062817 + ], + [ + -0.356616, + 2.852512, + 0.019796 + ], + [ + 0.003723, + 2.852512, + -0.187528 + ], + [ + 0.073383, + 2.852512, + -0.257783 + ], + [ + 0.11993, + 2.852512, + -0.211237 + ], + [ + 0.198933, + 2.852512, + 0.053154 + ] + ] + ], + "creases": [ + { + "ring": 2, + "from": 3, + "to": 5, + "weight": 1.0 + }, + { + "column": 1, + "from": 3, + "to": 4, + "weight": 0.6 + }, + { + "column": 3, + "from": 3, + "to": 4, + "weight": 1.0 + } + ], + "rim": 0.0 + } + }, + { + "seed": 5196, + "levels": 1, + "offset": 1.0, + "thickness": 0.00617, + "holds": null, + "sheet": { + "rings": [ + [ + [ + -0.383345, + 0.0, + -0.359947 + ], + [ + -0.036452, + 0.0, + -0.050835 + ], + [ + 0.567786, + 0.0, + -0.587238 + ], + [ + 0.622834, + 0.0, + -0.467053 + ], + [ + 0.672276, + 0.0, + -0.379683 + ], + [ + 0.730008, + 0.0, + -0.43819 + ] + ], + [ + [ + -0.557286, + 0.459757, + -0.324159 + ], + [ + -0.2711, + 0.459757, + -0.069142 + ], + [ + 0.227397, + 0.459757, + -0.511675 + ], + [ + 0.272811, + 0.459757, + -0.412522 + ], + [ + 0.313601, + 0.459757, + -0.340441 + ], + [ + 0.36123, + 0.459757, + -0.38871 + ] + ], + [ + [ + -0.062837, + 0.80579, + -0.458467 + ], + [ + 0.162644, + 0.80579, + -0.257545 + ], + [ + 0.555399, + 0.80579, + -0.606206 + ], + [ + 0.591179, + 0.80579, + -0.528086 + ], + [ + 0.623317, + 0.80579, + -0.471295 + ], + [ + 0.660843, + 0.80579, + -0.509325 + ] + ], + [ + [ + -0.125811, + 1.151684, + -0.10837 + ], + [ + 0.038964, + 1.151684, + 0.038458 + ], + [ + 0.325977, + 1.151684, + -0.216334 + ], + [ + 0.352124, + 1.151684, + -0.159246 + ], + [ + 0.375609, + 1.151684, + -0.117745 + ], + [ + 0.403032, + 1.151684, + -0.145536 + ] + ], + [ + [ + 0.161946, + 1.542628, + 0.17642 + ], + [ + 0.266014, + 1.542628, + 0.269154 + ], + [ + 0.447285, + 1.542628, + 0.108233 + ], + [ + 0.463799, + 1.542628, + 0.144288 + ], + [ + 0.478632, + 1.542628, + 0.170499 + ], + [ + 0.495952, + 1.542628, + 0.152947 + ] + ] + ], + "creases": [ + { + "ring": 3, + "from": 3, + "to": 4, + "weight": 1.0 + }, + { + "column": 3, + "from": 3, + "to": 4, + "weight": 1.0 + } + ], + "rim": 0.5 + } + } + ] +} diff --git a/surfaces/blender/tests/live/kitbash_faceted.py b/surfaces/blender/tests/live/kitbash_faceted.py index 4d04ed4..ec02c59 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.py +++ b/surfaces/blender/tests/live/kitbash_faceted.py @@ -30,6 +30,7 @@ import bpy import numpy as np from mathutils import Matrix, Vector from mathutils.bvhtree import BVHTree +from mathutils.geometry import normal as triangle_normal SURFACE = Path(__file__).resolve().parents[2] sys.path.insert(0, str(SURFACE / "tools")) @@ -84,10 +85,10 @@ SOLID = 0.0313 # Metres between the thickness and the distance from a vertex of the wall's inner face to the designed surface. Shipped # 0.0001 (a float32 mesh under three levels of subdivision); least claimed mutant 0.024 (S6: the inner face is subdivided again and pulls in); the geometric mean, separation 15 each side. EVEN = 1.5e-3 -# Metres: the thickness at which the wedge of shell-fold folds, (W / 2^levels) / tan(phi) of its narrower facet. The -# wall is built at FOLD / FOLD_STEP (no inner face turned) and at FOLD x FOLD_STEP (some turned). Least claimed mutant: -# F1, the wider facet's reach taken (max for min in core.fold_depths), which reads 0.25, 3.3 of shipped; FOLD_STEP is -# the 1.2 separation the margin rule asks on each side of the onset. +# Metres: the thickness at which the wedge of shell-fold folds, (W / 2^levels) / tan(phi) of its narrower facet, as +# measured on flat facets (docs/kitbash.md, Thickness at a crease). The wall is built at FOLD / FOLD_STEP (no inner +# face folded) and at FOLD x FOLD_STEP (some folded); FOLD_STEP is the 1.2 separation the margin rule asks on each +# side of the onset. The counts themselves are exact: count_folds is held to this script's own count, face for face. FOLD, FOLD_STEP = 0.075, 1.2 @@ -213,7 +214,7 @@ try: and sorted(stored) == ["bevel", "levels", "offset", "sheet", "thickness"] and stored["sheet"] == PAULDRON and (stored["levels"], stored["offset"]) == (3, -1.0) and abs(stored["thickness"] - WALL) < 1e-7, [receipt["message"], stored]) check("shell reports cage facts: rings, points, quads, creased edges, the subdivided count, an upward facing, no children", - report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "fold", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"] + report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "folded", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"] and (report["object"], report["rebuilt"], report["rings"], report["points"], report["cageFaces"], report["creases"], report["corners"], report["subdividedFaces"], report["levels"], report["thickness"], report["offset"], report["children"]) == ("Pauldron", False, 6, 6, 25, 25, 0, 1600, 3, 0.06, -1.0, []) and report["facing"][2] > 0.5 and abs(np.linalg.norm(report["facing"]) - 1.0) < 1e-5, report) @@ -252,34 +253,47 @@ try: surface.free() check("shell-crisp: a sheet whose rim is soft keeps its four corners", R["readings"]["corner"] < CORNER, R["readings"]) - # --- shell-fold: the receipt's fold onset, against the evaluated wall --------------------------------------------------------- + # --- shell-fold: count_folds, against this script's own count on the evaluated wall ------------------------------------------- section("shell-fold") # a ridge of two flat facets 0.3 and 1.0 wide, each tilted 45 degrees, full crease, levels 2: the narrower facet binds, (0.3 / 4) / tan 45 = 0.075 wedge = {"rings": [[[-1.0 * math.sqrt(0.5), y, -1.0 * math.sqrt(0.5)], [0.0, y, 0.0], [0.3 * math.sqrt(0.5), y, -0.3 * math.sqrt(0.5)]] for y in (0.0, 0.5, 1.0)], "creases": [{"column": 1, "from": 0, "to": 2, "weight": 1.0}]} - def folded(name, thickness, offset=-1.0): - """(the receipt's fold, inner faces of the evaluated wall whose normal runs with their outer face's).""" - _, told = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(wedge), thickness=thickness, offset=offset, levels=2) - wall_mesh = evaluated(bpy.data.objects[name]) + def own_folds(obj): + """This script's count on its own evaluation: inner faces of the wall (Subsurf and Solidify alone) with a corner + whose triangle, the corner and its two neighbours, faces with their outer twin's normal (mathutils' normals).""" + wall_mesh = evaluated(obj, off=("BOOLEAN", "BEVEL")) wall_mesh.faces.ensure_lookup_table() - count = len(bpy.data.objects[name].data.polygons) * 4 ** 2 # Solidify lists the outer faces, then their inner twins in the same order, then the rim - turned = sum(1 for k in range(count) if wall_mesh.faces[k].normal.dot(wall_mesh.faces[count + k].normal) > 0) + count = len(obj.data.polygons) * 4 ** obj.modifiers["Kit Subsurf"].levels # Solidify lists the outer faces, then their inner twins in the same order, then the rim + found = 0 + for k in range(count): + at = [v.co for v in wall_mesh.faces[count + k].verts] + found += any(triangle_normal(at[i - 1], at[i], at[(i + 1) % len(at)]).dot(wall_mesh.faces[k].normal) > 0 for i in range(len(at))) wall_mesh.free() - return told["fold"], turned + return found - under, over = folded("FoldUnder", FOLD / FOLD_STEP), folded("FoldOver", FOLD * FOLD_STEP) + def folded(name, sheet, thickness, offset=-1.0, levels=2, **asked): + """[the report's folded (-1: no report), this script's own count].""" + _, told = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(sheet), thickness=thickness, offset=offset, levels=levels, **asked) + return [told.get("folded", -1) if told else -1, own_folds(bpy.data.objects[name]) if name in bpy.data.objects else -1] + + under, over = folded("FoldUnder", wedge, FOLD / FOLD_STEP, count_folds=True), folded("FoldOver", wedge, FOLD * FOLD_STEP, count_folds=True) reading("foldUnder", under[1]) reading("foldOver", over[1], least=True) - check("shell-fold: the receipt names the fold onset of a creased ridge by its narrower facet, the margin and the edge, and the evaluated wall folds over it and not under it", - abs(under[0]["onset"] - FOLD) < 1e-6 and abs(under[0]["margin"] - FOLD_STEP) < 1e-3 and abs(over[0]["margin"] - 1 / FOLD_STEP) < 1e-3 - and under[0]["edge"] in ([[0, 1], [1, 1]], [[1, 1], [2, 1]]) and under[0]["weight"] == 1.0 and under[1] == 0 and over[1] > 0, [under, over]) - outward = folded("FoldOut", 0.3, offset=1.0) - half = folded("FoldHalf", FOLD / FOLD_STEP, offset=0.0) - check("shell-fold: a ridge under a wall grown outward has no fold to name, and a wall half behind the surface holds twice the thickness", - outward == (None, 0) and abs(half[0]["onset"] - 2 * FOLD) < 1e-6 and half[1] == 0, [outward, half]) - for name in ("FoldUnder", "FoldOver", "FoldOut", "FoldHalf"): - bpy.data.objects.remove(bpy.data.objects[name]) + check("shell-fold: count_folds counts no folded face on a creased ridge under the thickness its narrower facet holds, and the faces this script counts over it", + under == [0, 0] and over[0] == over[1] > 0, [under, over]) + unasked, outward = folded("FoldUnasked", wedge, FOLD * FOLD_STEP), folded("FoldOut", wedge, 0.3, offset=1.0, count_folds=True) + check("shell-fold: folded is null unless count_folds asks, whatever the wall does, and a ridge under a wall grown outward folds nowhere", + unasked[0] is None and unasked[1] == over[1] and outward == [0, 0], [unasked, outward]) + lofts = json.loads((SURFACE / "tests" / "fixtures" / "fold_lofts.json").read_text(encoding="utf-8"))["lofts"] + seeded = {f"{loft['seed']} offset {loft['offset']:g}": folded(f"Loft{loft['seed']}", loft["sheet"], loft["thickness"], offset=loft["offset"], levels=loft["levels"], count_folds=True) for loft in lofts} + held = {f"{loft['seed']} offset {loft['offset']:g}": folded(f"Held{loft['seed']}", loft["sheet"], loft["holds"], offset=loft["offset"], levels=loft["levels"], count_folds=True) for loft in lofts if loft["holds"]} + R["folds"] = {"seeded": seeded, "held": held} + check("shell-fold: on seeded lofts whose walls fold under any figure of the cage, at offsets -1, 0 and 1, count_folds counts the faces this script counts, and none at a thickness the wall holds", + len(seeded) == 3 and all(told == own > 0 for told, own in seeded.values()) and held and all(pair == [0, 0] for pair in held.values()), [seeded, held]) + for name in ["FoldUnder", "FoldOver", "FoldUnasked", "FoldOut"] + [f"{kind}{loft['seed']}" for loft in lofts for kind in ("Loft", "Held")]: + if name in bpy.data.objects: + bpy.data.objects.remove(bpy.data.objects[name]) # --- shell-solid ------------------------------------------------------------------------------------------------------------ section("shell-solid") @@ -356,15 +370,22 @@ try: plate = evaluated(again) check("shell-rebuild: the rebuilt plate is still cut, and closed", sum(1 for e in plate.edges if not e.is_manifold) == 0 and len(plate.faces) > 2 * 400 + 4 * 20 + 20, len(plate.faces)) plate.free() + receipt, report = send("brokkr_kitbash.shell", object_name="Pauldron", sheet=json.dumps(MOVED), thickness=0.05, levels=2, bevel=0.004, count_folds=True) + check("shell-rebuild: count_folds under cutters counts the wall as this script does and leaves the stack shown, in order", + receipt["status"] == "accepted" and report and report["folded"] == own_folds(again) and [(m.name, m.show_viewport) for m in again.modifiers] + == [("Kit Subsurf", True), ("Kit Solidify", True), ("Kit Difference", True), ("Kit Bevel", True)], [receipt["message"], report and report.get("folded"), [(m.name, m.show_viewport) for m in again.modifiers]]) # --- costs: wall times of this run, never bounded ----------------------------------------------------------------------------- section("costs") - times = {"shell": [], "evaluation": [], "rebuildUnderCuts": []} + times = {"shell": [], "shellCountingFolds": [], "evaluation": [], "rebuildUnderCuts": [], "rebuildCall": [], "rebuildCallCountingFolds": []} for k in range(3): name = f"Timed{k}" start = time.perf_counter() bpy.ops.brokkr_kitbash.shell(object_name=name, sheet=json.dumps(PAULDRON), thickness=WALL) times["shell"].append(time.perf_counter() - start) + start = time.perf_counter() + bpy.ops.brokkr_kitbash.shell(object_name=name + "Counted", sheet=json.dumps(PAULDRON), thickness=WALL, count_folds=True) + times["shellCountingFolds"].append(time.perf_counter() - start) bpy.data.objects[name].update_tag() # Blender's own update after the action evaluated it already: once more, alone start = time.perf_counter() faces = len(bpy.data.objects[name].evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) # one whole evaluation: Subdivision and Solidify @@ -373,6 +394,10 @@ try: bpy.ops.brokkr_kitbash.shell(object_name="Pauldron", sheet=json.dumps(MOVED if k % 2 else PAULDRON), thickness=WALL, bevel=0.004) cut_faces = len(pauldron.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) # with its one Boolean of six cutters times["rebuildUnderCuts"].append(time.perf_counter() - start) + for counting in (False, True): # the call alone: what count_folds adds to a rebuild under six cutters + start = time.perf_counter() + bpy.ops.brokkr_kitbash.shell(object_name="Pauldron", sheet=json.dumps(MOVED if k % 2 else PAULDRON), thickness=WALL, bevel=0.004, count_folds=counting) + times["rebuildCallCountingFolds" if counting else "rebuildCall"].append(time.perf_counter() - start) R["costs"] = {name: float(f"{statistics.median(values):.2g}") for name, values in times.items()} check("costs: the timed shells evaluated whole", faces == 3360 and cut_faces > 3360, [faces, cut_faces]) @@ -405,6 +430,9 @@ try: "sheet.creases[0].to must be a whole number from 0 to 5, not 6") refused("two weights on one edge", {"object_name": "Mixed", "sheet": json.dumps({**PAULDRON, "creases": [{"ring": 1, "from": 0, "to": 2, "weight": 1}, {"ring": 1, "from": 1, "to": 3, "weight": 0.5}]})}, "sheet.creases[1] gives an edge weight 0.5 that sheet.creases[0] gives 1") + mixed.modifiers["Kit Solidify"].show_viewport = False + refused("count_folds on a shell whose Kit Solidify is hidden", {"object_name": "Mixed", "sheet": SHEET, "count_folds": True}, "'Mixed' has its Kit Solidify hidden in viewports") + mixed.modifiers["Kit Solidify"].show_viewport = True refused("a sheet that is not JSON", {"object_name": "Mixed", "sheet": "{rings"}, "sheet is not JSON") refused("a sheet with an unknown key", {"object_name": "New", "sheet": json.dumps({**PAULDRON, "inside": [0, 0, 0]})}, "sheet has no key 'inside'") dense = {"rings": [[[j / 10, 0, i / 10] for j in range(34)] for i in range(34)]} diff --git a/surfaces/blender/tests/live/kitbash_faceted.result.json b/surfaces/blender/tests/live/kitbash_faceted.result.json index 5523476..1ec749c 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.result.json +++ b/surfaces/blender/tests/live/kitbash_faceted.result.json @@ -37,12 +37,17 @@ "detail": null }, { - "name": "shell-fold: the receipt names the fold onset of a creased ridge by its narrower facet, the margin and the edge, and the evaluated wall folds over it and not under it", + "name": "shell-fold: count_folds counts no folded face on a creased ridge under the thickness its narrower facet holds, and the faces this script counts over it", "ok": true, "detail": null }, { - "name": "shell-fold: a ridge under a wall grown outward has no fold to name, and a wall half behind the surface holds twice the thickness", + "name": "shell-fold: folded is null unless count_folds asks, whatever the wall does, and a ridge under a wall grown outward folds nowhere", + "ok": true, + "detail": null + }, + { + "name": "shell-fold: on seeded lofts whose walls fold under any figure of the cage, at offsets -1, 0 and 1, count_folds counts the faces this script counts, and none at a thickness the wall holds", "ok": true, "detail": null }, @@ -81,6 +86,11 @@ "ok": true, "detail": null }, + { + "name": "shell-rebuild: count_folds under cutters counts the wall as this script does and leaves the stack shown, in order", + "ok": true, + "detail": null + }, { "name": "costs: the timed shells evaluated whole", "ok": true, @@ -131,6 +141,11 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: count_folds on a shell whose Kit Solidify is hidden", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: a sheet that is not JSON", "ok": true, @@ -169,9 +184,34 @@ "solid": 0.027 }, "costs": { - "shell": 0.0074, - "evaluation": 0.0015, - "rebuildUnderCuts": 1.1 + "shell": 0.0059, + "shellCountingFolds": 0.0091, + "evaluation": 0.0022, + "rebuildUnderCuts": 1.7, + "rebuildCall": 1.6, + "rebuildCallCountingFolds": 1.6 + }, + "folds": { + "seeded": { + "5185 offset -1": [ + 2, + 2 + ], + "5101 offset 0": [ + 13, + 13 + ], + "5196 offset 1": [ + 4, + 4 + ] + }, + "held": { + "5185 offset -1": [ + 0, + 0 + ] + } }, "creaseRibs": "Operator brokkr_kitbash.ribs finished.", "ok": true diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 3faf4d3..1d66c66 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1558,34 +1558,6 @@ class SheetTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, r"\.to must be a whole number from 0 to 3, not 4"): core.sheet({**closed, "creases": [{"ring": 0, "from": 0, "to": 4, "weight": 1}]}) - def test_fold_depths_are_the_narrower_facets_first_row_over_the_tangent(self): - """A ridge of two flat facets 1.0 and 0.3 wide, each tilted 45 degrees: the crease's fold depth is - (0.3 / 2^levels) / tan 45, the narrower facet's (F1: the wider facet's reach reads 0.25 at levels 2); the - facets fall away from their normals, a ridge, and turned over they are a valley; coplanar facets never fold.""" - h = math.sqrt(0.5) - - def wedge(sign, flat=False): - return core.sheet({"rings": [[[-h, y, 0.0 if flat else -sign * h], [0.0, y, 0.0], [0.3 * h, y, 0.0 if flat else -sign * 0.3 * h]] for y in (0.0, 0.5, 1.0)], - "creases": [{"column": 1, "from": 0, "to": 2, "weight": 1.0}]}) - - pairs, depths, ridges, weights = core.fold_depths(wedge(1), 2) - crease = [k for k, pair in enumerate(pairs.tolist()) if pair in ([1, 4], [4, 7])] - self.assertEqual(len(pairs), 4) # the two crease edges and the middle ring's edge on each facet: an edge of the rim has one quad and no fold - self.assertEqual(len(crease), 2) - for k in crease: - self.assertAlmostEqual(depths[k], 0.075, places=12) - self.assertTrue(ridges[k]) - self.assertEqual(weights[k], 1.0) - self.assertTrue(all(math.isinf(depths[k]) and weights[k] == 0.0 for k in range(len(pairs)) if k not in crease)) # an edge inside a flat facet - self.assertAlmostEqual(core.fold_depths(wedge(1), 3)[1][crease[0]], 0.0375, places=12) # a level more halves the first row - valley = core.fold_depths(wedge(-1), 2) - self.assertAlmostEqual(valley[1][crease[0]], 0.075, places=12) - self.assertFalse(valley[2][crease[0]]) - self.assertTrue(np.isinf(core.fold_depths(wedge(1, flat=True), 2)[1]).all()) - steep = core.sheet({"rings": [[[-0.5, y, -math.sqrt(0.75)], [0.0, y, 0.0], [0.5, y, -math.sqrt(0.75)]] for y in (0.0, 1.0)]}) # facets 60 degrees off level, no crease stated - self.assertAlmostEqual(core.fold_depths(steep, 1)[1][0], 0.5 / math.tan(math.radians(60)), places=12) - self.assertEqual(core.fold_depths(steep, 1)[3][0], 0.0) - ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", @@ -1656,16 +1628,18 @@ class HostFileTests(unittest.TestCase): with self.assertRaises(at.IntentInvalid, msg=str(bad)): at.validate(bad, host) for row in self.document["actions"][4:]: - self.assertTrue(all(field["type"] in ("string", "number", "integer") for field in row["fields"]), row["name"]) + self.assertTrue(all(field["type"] in ("string", "number", "integer", "boolean") for field in row["fields"]), row["name"]) + self.assertEqual([(row["name"], field["name"], field["default"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "boolean"], + [("brokkr_kitbash.shell", "count_folds", False)]) # the one evaluation shell makes is asked for, never the default self.assertEqual([(row["name"], field["name"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "integer"], [("brokkr_kitbash.shell", "levels")]) sheet = json.dumps({"rings": [[[0, 0, 0], [1, 0, 0]], [[0, 0, 1], [1, 0, 1]]]}) shell = {**envelope, "action": "brokkr_kitbash.shell", "object_name": "Plate", "sheet": sheet} - self.assertEqual([at.validate(shell, host)[k] for k in ("thickness", "offset", "levels", "bevel")], [0.05, -1, 3, 0]) + self.assertEqual([at.validate(shell, host)[k] for k in ("thickness", "offset", "levels", "bevel", "count_folds")], [0.05, -1, 3, 0, False]) self.assertEqual(at.validate({**shell, "thickness": 0.001, "levels": 4}, host)["levels"], 4) for bad in ({**shell, "levels": 5}, {**shell, "levels": 2.5}, {**shell, "levels": 0}, {**shell, "thickness": 0.0005}, {**shell, "offset": 1.5}, {**shell, "bevel": 0.2}, {**shell, "sheet": "{" + " " * 32000}, {**shell, "sheet": ""}, {k: v for k, v in shell.items() if k != "sheet"}, {**shell, "object_name": "x" * 64}, - {**shell, "rings": []}): + {**shell, "rings": []}, {**shell, "count_folds": 1}): with self.assertRaises(at.IntentInvalid, msg=str(bad)[:200]): at.validate(bad, host) @@ -1749,9 +1723,9 @@ class OwnershipTests(unittest.TestCase): self.assertLess(place.index("evaluable("), place.index("modifier.show_viewport = True")) # unevaluable-target: every action that evaluates refuses an object Blender does not evaluate before its first write for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["apply"], "bpy.data.meshes.new_from_object("), - (bodies["ribs"], "show_viewport = False")): + (bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()")): self.assertLess(body.index("evaluable("), body.index(first_write)) - self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs"]) + self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs", "shell"]) ribs = bodies["ribs"] # every refusal before the ribs object is written, and the cage's modifiers shown again whatever happened self.assertLess(ribs.rindex("raise Refused("), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)")) self.assertLess(ribs.index("finally:"), ribs.index("modifier.show_viewport = True")) @@ -1759,14 +1733,22 @@ class OwnershipTests(unittest.TestCase): for body in (place, *(source.split(f"class BROKKR_KITBASH_OT_{name}(")[1].split("class BROKKR_KITBASH_OT_")[0] for name in ("cut", "cut_many"))): self.assertNotIn("view_layer.update", body) # an update after a cutter joins would evaluate the Boolean self.assertEqual(body.count("place_cutters("), 0 if body is place else 1) - shell = bodies["shell"] # shell evaluates nothing: Blender's own update after the action evaluates the plate once - for call in ("evaluated_of(", "evaluable(", "to_mesh(", "view_layer.update", "evaluated_get(", "depsgraph"): + shell, count = bodies["shell"].split(" def folded_faces(") # shell evaluates nothing unless count_folds asks, and then the wall alone: no Boolean runs for it + shell, alone = shell.split(" def wall_alone(") + for call in ("evaluated_of(", "to_mesh(", "view_layer.update", "evaluated_get(", "depsgraph"): self.assertNotIn(call, shell) + self.assertEqual((shell.count("evaluable("), shell.count("folded_faces("), shell.count("self.count_folds")), (1, 1, 2)) + self.assertLess(shell.index("if self.count_folds:"), shell.index("with self.wall_alone(obj):")) + self.assertLess(shell.index("with self.wall_alone(obj):"), shell.index("evaluable(")) + self.assertIn("self.folded_faces(context, obj, cage_faces * 4 ** self.levels) if self.count_folds else None", shell) + self.assertLess(count.index("wall_alone(shell):"), count.index("evaluable(")) + self.assertEqual((count.count("evaluable("), count.count("to_mesh("), source.count("folded_faces("), source.count("wall_alone(")), (1, 1, 2, 3)) + self.assertLess(alone.index("finally:"), alone.index("modifier.show_viewport = True")) self.assertLess(shell.rindex("raise Refused("), shell.index("clear_geometry()")) # every refusal before any write self.assertLess(shell.index("core.sheet("), shell.index("clear_geometry()")) self.assertLess(shell.index("clear_geometry()"), shell.index("bpy.data.meshes.new(")) self.assertNotIn("objects.remove(", shell) # a rebuild rewrites the mesh in place: a new object would orphan its cutters and ribs - self.assertEqual(source.count("to_mesh("), 4) # boolean's report, and in ribs the designed surface, the plate's two faces and the holed webs + self.assertEqual(source.count("to_mesh("), 5) # boolean's report, in ribs the designed surface, the plate's two faces and the holed webs, and shell's fold count def test_only_ribs_writes_kit_ribs(self): """kit_ribs is the request a ribs object was derived from: ribs assigns it once and nothing reads it back to From 19c36b984f655477c6e996bfa50375629ee45cf5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 16:10:21 +0100 Subject: [PATCH 108/223] brokkr.kit.v0: an extrude shape, a PROFILES section along a polyline through core.sweep; wedge and gusset sections core.SHAPES gains extrude (section, w, h, t, path, up, loop?, at?, rot?). check_kit refuses a section PROFILES does not have, a path outside 2 to 64 points (3 with loop), and anything that is not an expression where one belongs; _extrude builds through profile and sweep and re-raises what either refuses under the shape's name. PROFILES gains wedge (a right trapezoid) and gusset (a right triangle with its tips cut square). No sweep, profile or circle signature changes. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/core.py | 54 ++++++++++++--- surfaces/blender/tests/test_kitbash.py | 88 ++++++++++++++++++++++++- 2 files changed, 132 insertions(+), 10 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index d6156c9..e4b68ba 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -2,9 +2,10 @@ 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: 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 +places to cut a mesh, each with its recess floor as a socket; and frame, the beams, truss, portal, gusset and wedge +of a chassis). A part is a list of shapes (tube, box, lathe, extrude: a PROFILES section along a polyline through +sweep; 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 whitelist; nothing in a kit is ever run as Python. @@ -17,8 +18,9 @@ both kits declare the socket's type with the same match rule. surface_frame is t 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. -The structure under an armor cage is built, not kit parts: PROFILES are the sections (I, C, T, L, box), sweep takes -an outline along a polyline with mitred joints (a longeron, a post), band is the rib beside a section in its plane, +PROFILES are the seven sections (I, C, T, L, box, wedge, gusset) and sweep takes an outline along a polyline with +mitred joints: an extrude shape is the two together, and so is a longeron or a post of the structure under an armor +cage, which is built, not kit parts: band is the rib beside a section in its plane, offset and clipped so that it follows a crease instead of folding in it (away, the distance to a polyline, is what clips it), inset is the step that offsets a mesh inward by its own faces (the surface a rib's edge is cut from), crossings finds where a section line meets a half-plane, resample fills a section's points in, and spans @@ -57,8 +59,10 @@ PLACED = ("at", "rot") SHAPES = {"tube": (("r0", "r1", "length", "segments"), ("inner0", "inner1", "smooth") + PLACED), "box": (("size",), PLACED), "lathe": (("profile", "segments"), ("loop", "smooth") + PLACED), + "extrude": (("section", "w", "h", "t", "path", "up"), ("loop",) + PLACED), "repeat": (("count", "of"), ("step", "around", "center"))} SEGMENTS = (3, 128) +PATH = 64 # the most points an extrude's path may list COPIES = (1, 256) @@ -233,6 +237,21 @@ def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict: if kind == "box": made["size"] = _vector(shape["size"], names, f"{where} size") return made + if kind == "extrude": + section, path = shape["section"], shape["path"] + if not isinstance(section, str) or section not in PROFILES: + raise KitError(f"{where} section: {section!r} is not one of {', '.join(PROFILES)}") + if not isinstance(shape.get("loop", False), bool): + raise KitError(f"{where} loop must be true or false") + made["section"], made["loop"] = section, shape.get("loop", False) + for key in ("w", "h", "t"): + made[key] = parse(shape[key], names, f"{where} {key}") + least = 3 if made["loop"] else 2 + if not isinstance(path, list) or not least <= len(path) <= PATH: + raise KitError(f"{where} path must be an array of {least} to {PATH} [x, y, z] points{' (it is a loop)' if made['loop'] else ''}") + made["path"] = [_vector(point, names, f"{where} path[{i}]") for i, point in enumerate(path)] + made["up"] = _vector(shape["up"], names, f"{where} up") + return made for key in ("loop", "smooth"): if not isinstance(shape.get(key, False), bool): raise KitError(f"{where} {key} must be true or false") @@ -550,8 +569,22 @@ def _box(shape: dict, env): return BOX_SIGNS * size, BOX_FACES.ravel(), np.full(6, 4), np.zeros(6, dtype=bool), NO_SHARP +def _extrude(shape: dict, env): + """A PROFILES section swept along the path: profile and sweep own the geometry (the outline's x is up cross the + path's tangent, its y is up taken off the tangent, the joints are mitred), and what either refuses is refused + here under the shape's name. Every face is flat.""" + size = [shape[key].value(env) for key in ("w", "h", "t")] + path = [[e.value(env) for e in point] for point in shape["path"]] + up = [e.value(env) for e in shape["up"]] + try: + swept = sweep(path, profile(shape["section"], *size), up, shape["loop"]) + except KitError as error: + raise KitError(f"{shape['where']}: {error}") from None + return swept.V, swept.faces, swept.counts, swept.smooth, NO_SHARP + + def _placed(shape: dict, env): - V, faces, counts, smooth, sharp = {"tube": _tube, "box": _box, "lathe": _lathe}[shape["shape"]](shape, env) + V, faces, counts, smooth, sharp = {"tube": _tube, "box": _box, "lathe": _lathe, "extrude": _extrude}[shape["shape"]](shape, env) rotation = _rotation([e.value(env) for e in shape["rot"]]) return V @ rotation.T + np.array([e.value(env) for e in shape["at"]]), faces, counts, smooth, sharp @@ -606,6 +639,7 @@ def build(part: dict, params: dict | None = None) -> Built: # --- structure: sections swept along paths -------------------------------------------------------------------- PROFILES = { # (w, h, t) -> the outline, counter-clockwise in (x across, y along up): flange width, height, wall + # (a wedge's t is its front height and a gusset's the flat that cuts each acute tip square) "I": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (t / 2, -h / 2 + t), (t / 2, h / 2 - t), (w / 2, h / 2 - t), (w / 2, h / 2), (-w / 2, h / 2), (-w / 2, h / 2 - t), (-t / 2, h / 2 - t), (-t / 2, -h / 2 + t), (-w / 2, -h / 2 + t)], "C": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (-w / 2 + t, -h / 2 + t), (-w / 2 + t, h / 2 - t), (w / 2, h / 2 - t), @@ -613,6 +647,8 @@ PROFILES = { # (w, h, t) -> the outline, counter-clockwise in (x across, y alon "T": lambda w, h, t: [(-t / 2, -h / 2), (t / 2, -h / 2), (t / 2, h / 2 - t), (w / 2, h / 2 - t), (w / 2, h / 2), (-w / 2, h / 2), (-w / 2, h / 2 - t), (-t / 2, h / 2 - t)], "L": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (-w / 2 + t, -h / 2 + t), (-w / 2 + t, h / 2), (-w / 2, h / 2)], "box": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2), (-w / 2, h / 2)], + "wedge": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (-w / 2, h / 2)], + "gusset": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (-w / 2 + t, h / 2), (-w / 2, h / 2)], } TURN_LIMIT = 150.0 # degrees a swept path may turn at one point: past it a mitre runs 3.9 times the section's width @@ -620,10 +656,12 @@ TURN_LIMIT = 150.0 # degrees a swept path may turn at one point: past it a mitr def profile(kind: str, w: float, h: float, t: float) -> np.ndarray: """PROFILES[kind] at a width, height and wall, as an (M, 2) array. Refuses a kind PROFILES does not have, a size that is not above 0, and a wall that leaves no section: as wide as the flange, or as thick as the height its - flanges share (two on an I and a C, one on a T and an L). A box has no wall.""" + flanges share (two on an I and a C, one on a T and an L). A box has no wall. A wedge is a right trapezoid, base w, + back height h and front height t, under h; a gusset a right triangle on legs w and h whose two acute tips are cut + square by a flat t long, under half the shorter leg.""" if kind not in PROFILES: raise KitError(f"profile {kind!r} is not one of {', '.join(PROFILES)}") - limit = min(w, h / 2 if kind in ("I", "C") else h) + limit = h if kind == "wedge" else min(w, h) / 2 if kind == "gusset" else min(w, h / 2 if kind in ("I", "C") else h) if not all(finite(v) and v > 0 for v in (w, h, t)) or (kind != "box" and not t < limit): raise KitError(f"profile {kind!r} of width {w}, height {h}, wall {t}: every size must be above 0 and the wall under {limit:.6g}") return np.array(PROFILES[kind](w, h, t), dtype=np.float64) diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 1d66c66..36ccec5 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -187,6 +187,7 @@ class CheckKitTests(unittest.TestCase): """check-kit-refusals. Mutant M2 (skip the unknown-key check): the 'colour' and 'radius' documents are admitted.""" socket = {"name": "s", "type": "mount", "size": 1, "at": [0, 0, 0], "z": "+z", "y": "+y"} box = {"shape": "box", "size": [1, 1, 1]} + beam = {"shape": "extrude", "section": "I", "w": 0.06, "h": 0.1, "t": 0.012, "path": [[0, 0, 0], [0, 0, 1]], "up": [0, 1, 0]} cases = [ ({**document(), "schema": "brokkr.kit.v1"}, r"schema must be brokkr\.kit\.v0"), ({**document(), "colour": 1}, r"kit has no key 'colour'"), @@ -209,7 +210,20 @@ class CheckKitTests(unittest.TestCase): (document(sockets=[{**socket, "z": {}}]), r"part 'p' socket 's': z must be one of"), (document([{"shape": ["box"], "size": [1, 1, 1]}]), r"part 'p' shape 0: unknown shape \['box'\]"), (document(sockets=[{**socket, "at": [0, 0, 10 ** 400]}]), r"part 'p' socket 's' at\[2\]: 1000\d+ is not a finite number"), + # extrude-refusals. Mutants E2 (the section checked only at build) and E9 (a 65-point path admitted) + (document([{**beam, "section": "Z"}]), r"part 'p' shape 0 \(extrude\) section: 'Z' is not one of I, C, T, L, box, wedge, gusset"), + (document([{**beam, "section": ["I"]}]), r"part 'p' shape 0 \(extrude\) section: \['I'\] is not one of"), + (document([{**beam, "path": [[0, 0, 0]]}]), r"part 'p' shape 0 \(extrude\) path must be an array of 2 to 64 \[x, y, z\] points$"), + (document([{**beam, "loop": True}]), r"part 'p' shape 0 \(extrude\) path must be an array of 3 to 64 \[x, y, z\] points \(it is a loop\)"), + (document([{**beam, "path": [[0, 0, k] for k in range(65)]}]), r"part 'p' shape 0 \(extrude\) path must be an array of 2 to 64"), + (document([{**beam, "path": [[0, 0, 0], [0, 1]]}]), r"part 'p' shape 0 \(extrude\) path\[1\] must be an array of three"), + (document([{**beam, "up": "+y"}]), r"part 'p' shape 0 \(extrude\) up must be an array of three"), + (document([{**beam, "loop": "yes"}]), r"part 'p' shape 0 \(extrude\) loop must be true or false"), + (document([{**beam, "w": "q"}]), r"part 'p' shape 0 \(extrude\) w: 'q' names 'q'"), + (document([{**beam, "smooth": True}]), r"part 'p' shape 0 \(extrude\) has no key 'smooth'"), + (document([{k: v for k, v in beam.items() if k != "t"}]), r"part 'p' shape 0 \(extrude\) lacks 't'"), ] + self.assertEqual(len(core.check_kit(document([{**beam, "path": [[0, 0, k] for k in range(64)]}]))["parts"]["p"]["shapes"][0]["path"]), 64) for doc, message in cases: with self.assertRaisesRegex(core.KitError, message): core.check_kit(doc) @@ -406,6 +420,70 @@ class ShapeTests(unittest.TestCase): self.assertEqual(b.shape.tolist(), [0] * 6 + [1] * 18 + [2] * 10) self.assertEqual((b.shape.dtype, b.shell_count), (np.int32, 5)) + BEAM = {"shape": "extrude", "section": "I", "w": 0.06, "h": 0.1, "t": 0.012, "path": [[0, 0, 0], [0, 0, 0.3]], "up": [0, 1, 0]} + + def test_an_extrude_is_a_section_swept_along_its_path(self): + """extrude-holds. Each of the seven sections along a straight path is one closed shell, wound outward, of the + section's area times the length, every face flat, the outline's x on up cross the tangent and its y on up. + Mutant E6 (up ignored, +z always): the path along z is refused, and the one along x stands its height on z + whatever up says.""" + w, h, t = 0.06, 0.1, 0.012 + self.assertEqual(list(core.PROFILES), ["I", "C", "T", "L", "box", "wedge", "gusset"]) + for section in core.PROFILES: + outline = core.profile(section, w, h, t) + x, y = outline.T + area = float(0.5 * np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y)) + b = built([{**self.BEAM, "section": section, "w": "a", "path": [[0, 0, 0], [0, 0, "5*a"]]}], [param("a", 0.01, 1, w)]) + self.assertTrue(closed_and_oriented(b), section) + self.assertLess(abs(signed_volume(b) - area * 0.3), 1e-12, section) + self.assertEqual((b.shell_count, b.counts.tolist(), bool(b.smooth.any()), b.sharp.shape), (1, [4] * len(outline) + [len(outline)] * 2, False, (0, 2)), section) + self.assertEqual(b.V[:len(outline)].tolist(), [[px, py, 0.0] for px, py in outline.tolist()], section) + self.assertEqual(b.V[len(outline):, 2].tolist(), [0.06 * 5] * len(outline)) + extent = lambda up: np.round(np.ptp(built([{**self.BEAM, "path": [[0, 0, 0], [0.3, 0, 0]], "up": up}]).V, axis=0), 12).tolist() # noqa: E731 + self.assertEqual((extent([0, 0, 1]), extent([0, 1, 0]), extent([0, 5, 5])), ([0.3, w, h], [0.3, h, w], [0.3, round((w + h) / 2 ** 0.5, 12), round((w + h) / 2 ** 0.5, 12)])) + + def test_an_extrude_is_placed_and_repeated_as_every_shape(self): + """extrude-holds, extrude-in-repeat-and-loop. Mutants E1 (an extrude ignores at and rot: the box section stands + at the origin, unturned), E5 (repeat refuses an extrude) and E7 (loop ignored: the ring is an open path with + two caps, 14 faces and three quarters of the volume).""" + rot, at, size = [30, 40, 50], [1, 2, 3], [0.06, 0.1, 0.3] + lifted = (np.array(at) + core._rotation(rot) @ [0, 0, 0.15]).tolist() + swept = built([{**self.BEAM, "section": "box", "rot": rot, "at": at}]) + box = built([{"shape": "box", "size": size, "rot": rot, "at": lifted}]) + order = lambda V: V[np.lexsort(np.round(V, 9).T)] # noqa: E731 + self.assertLess(float(np.abs(order(swept.V) - order(box.V)).max()), 1e-12) + self.assertLess(abs(signed_volume(swept) - 0.06 * 0.1 * 0.3), 1e-12) + area = 2 * 0.06 * 0.012 + (0.1 - 2 * 0.012) * 0.012 + for change, centres in (({"step": [0.5, 0, "a"]}, [[0, 0, 0.15], [0.5, 0, 1.15], [1.0, 0, 2.15]]), + ({"around": "+y", "center": [1, 0, 0]}, [[0, 0, 0.15], [1.5 + 0.15 * 0.75 ** 0.5, 0, 0.75 ** 0.5 - 0.075], [1.5 - 0.15 * 0.75 ** 0.5, 0, -0.75 ** 0.5 - 0.075]])): + b = built([{"shape": "box", "size": [1, 1, 1]}, {"shape": "repeat", "count": 3, **change, "of": self.BEAM}], [param("a")]) + self.assertEqual((b.shell_count, b.shape.tolist()), (4, [0] * 6 + [1] * 14 * 3)) + self.assertTrue(closed_and_oriented(b)) + self.assertLess(abs(signed_volume(b) - 1.0 - 3 * area * 0.3), 1e-12) + self.assertTrue(np.allclose(b.V[8:].reshape(3, 24, 3).mean(axis=1), centres, atol=1e-12), change) + ring = built([{**self.BEAM, "section": "box", "w": 0.1, "h": 0.2, "loop": True, "path": [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], "up": [0, 0, 1]}]) + self.assertEqual((ring.shell_count, ring.counts.tolist(), len(ring.V)), (1, [4] * 16, 16)) + self.assertTrue(closed_and_oriented(ring)) + self.assertLess(abs(signed_volume(ring) - 0.1 * 0.2 * 4.0), 1e-12) # mitred: the area times the path's length + + def test_what_a_sweep_refuses_an_extrude_refuses_by_name(self): + """extrude-refusals, at build. Mutant E8 (the where prefix dropped): each message starts at 'path point' or + 'profile' and names no kit, part or shape.""" + here = r"^kit 't' part 'p' shape 0 \(extrude\): " + for change, message in ( + ({"path": [[0, 0, 0], [1, 0, 0], [0.015, 0.17, 0]], "up": [0, 0, 1]}, here + r"path point 1: the path turns 170\.2 degrees there, over 150$"), + ({"up": [0, 0, 2]}, here + r"path point 0: up \[0\.0, 0\.0, 2\.0\] runs along the path there"), + ({"up": [0, 0, 0]}, here + r"path point 0: up \[0\.0, 0\.0, 0\.0\] runs along the path there \(or is zero\)"), + ({"w": 0.4, "path": [[0, 0, 0], [1, 0, 0], [1, 0.05, 0]], "up": [0, 0, 1]}, here + r"path point 1: the section folds there"), + ({"path": [[0, 0, 0], [0, 0, 0]]}, here + r"path point 0: the segment from it is shorter than 1e-9"), + ({"t": "a"}, here + r"profile 'I' of width 0\.06, height 0\.1, wall 0\.05: every size must be above 0 and the wall under 0\.05$"), + ({"w": "a-0.05"}, here + r"profile 'I' of width 0\.0, ")): + with self.assertRaisesRegex(core.KitError, message): + built([{**self.BEAM, **change}], [param("a", 0, 1, 0.05)]) + with self.assertRaisesRegex(core.KitError, r"^kit 't' part 'p' shape 1 \(repeat\) of \(extrude\): path point 0: up"): + built([{"shape": "box", "size": [1, 1, 1]}, {"shape": "repeat", "count": 2, "step": [1, 0, 0], "of": {**self.BEAM, "up": [0, 0, 1]}}]) + self.assertEqual(len(built([{**self.BEAM, "t": "a"}], [param("a", 0, 1, 0.05)], {"a": 0.04}).counts), 14) + def test_sockets_are_right_handed_frames(self): socket = {"name": "s", "type": "mount", "size": "2*a", "at": ["a", 2, 3], "z": "+x", "y": "+z"} kit = core.check_kit(document(params=[param("a")], sockets=[socket])) @@ -1178,7 +1256,8 @@ class StructureTests(unittest.TestCase): def test_the_profiles_are_counter_clockwise_sections(self): w, h, t = 0.06, 0.1, 0.012 - areas = {"I": 2 * w * t + (h - 2 * t) * t, "C": 2 * w * t + (h - 2 * t) * t, "T": w * t + (h - t) * t, "L": w * t + (h - t) * t, "box": w * h} + areas = {"I": 2 * w * t + (h - 2 * t) * t, "C": 2 * w * t + (h - 2 * t) * t, "T": w * t + (h - t) * t, "L": w * t + (h - t) * t, "box": w * h, + "wedge": w * (h + t) / 2, "gusset": 0.003888} # the gusset's five corners by the shoelace: t*h + (w - t)*(h + t)/2 self.assertEqual(sorted(core.PROFILES), sorted(areas)) for kind, area in areas.items(): outline = core.profile(kind, w, h, t) @@ -1187,7 +1266,12 @@ class StructureTests(unittest.TestCase): self.assertAlmostEqual(float(outline[:, 1].max() - outline[:, 1].min()), h, places=15) self.assertAlmostEqual(self.area(core.circle(0.5, 16)), 0.5 * 16 * 0.25 * math.sin(2 * math.pi / 16), places=15) self.assertEqual(core.circle(0.5, 16)[0].tolist(), [0.5, 0.0]) - for bad in (("Z", w, h, t), ("I", w, h, h / 2), ("T", w, h, w), ("L", 0.0, h, t), ("C", w, h, float("nan")), ("box", w, h, 0.0)): + # profiles-seven. Mutants E3 (a wedge admits t = h: a box) and E4 (a gusset ignores t: three corners, sharp tips) + self.assertEqual(core.profile("wedge", w, h, t).tolist(), [[-w / 2, -h / 2], [w / 2, -h / 2], [w / 2, -h / 2 + t], [-w / 2, h / 2]]) + self.assertEqual(core.profile("gusset", w, h, t).tolist(), [[-w / 2, -h / 2], [w / 2, -h / 2], [w / 2, -h / 2 + t], [-w / 2 + t, h / 2], [-w / 2, h / 2]]) + self.assertEqual((len(core.profile("wedge", w, h, 0.99 * h)), len(core.profile("gusset", w, h, 0.49 * w))), (4, 5)) + for bad in (("Z", w, h, t), ("I", w, h, h / 2), ("T", w, h, w), ("L", 0.0, h, t), ("C", w, h, float("nan")), ("box", w, h, 0.0), + ("wedge", w, h, h), ("gusset", w, h, min(w, h) / 2), ("gusset", h, w, min(w, h) / 2), ("wedge", w, h, 0.0)): with self.assertRaisesRegex(core.KitError, "profile"): core.profile(*bad) for bad in ((0.0, 16), (0.5, 2), (0.5, 129)): From 1882c9c73b9e0be240c90e2b9400ec96d8c9c33c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 16:19:18 +0100 Subject: [PATCH 109/223] kits/frame.v0.json: beams in five sections, a truss, a portal, a gusset and a wedge, each an extrude Nine parts over core.sweep and PROFILES; mount and pivot are mechanical's lines, so a frame part seats on a mechanical one. A truss's diagonals are two repeats a double bay apart (expressions have no floor). FrameKitTests holds every part at its default, minimum, maximum and 16 draws, with a socket seat that reads a section's concave cap by Newell's normal and a crossing count. Co-Authored-By: Claude Fable 5.2 --- .../blender/brokkr_kitbash/kits/frame.v0.json | 172 ++++++++++++++++++ surfaces/blender/tests/test_kitbash.py | 131 ++++++++++++- 2 files changed, 301 insertions(+), 2 deletions(-) create mode 100644 surfaces/blender/brokkr_kitbash/kits/frame.v0.json diff --git a/surfaces/blender/brokkr_kitbash/kits/frame.v0.json b/surfaces/blender/brokkr_kitbash/kits/frame.v0.json new file mode 100644 index 0000000..a61f3c7 --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/kits/frame.v0.json @@ -0,0 +1,172 @@ +{ + "schema": "brokkr.kit.v0", + "kit": "frame", + "doc": "Chassis structure: sectioned beams, a truss, a portal, a gusset and a wedge, each a section swept along a path. Metres.", + "socketTypes": { + "mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"}, + "pivot": {"match": "equal", "doc": "pin joint; size is the pin diameter"} + }, + "parts": [ + { + "name": "beam_i", + "doc": "I beam along +z: two flanges across x joined by a web along y.", + "params": [ + {"name": "length", "type": "number", "min": 0.1, "max": 6.0, "default": 1.0, "doc": "end face to end face (z)"}, + {"name": "w", "type": "number", "min": 0.03, "max": 0.4, "default": 0.08, "doc": "width (x)"}, + {"name": "h", "type": "number", "min": 0.03, "max": 0.4, "default": 0.12, "doc": "height (y)"}, + {"name": "t", "type": "number", "min": 0.003, "max": 0.05, "default": 0.01, "doc": "wall thickness; held under 0.45 of the smaller of w and h"} + ], + "shapes": [ + {"shape": "extrude", "section": "I", "w": "w", "h": "h", "t": "min(t,0.45*min(w,h))", "path": [[0, 0, 0], [0, 0, "length"]], "up": [0, 1, 0]} + ], + "sockets": [ + {"name": "end_a", "type": "mount", "size": "min(w,h)", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "end_b", "type": "mount", "size": "min(w,h)", "at": [0, 0, "length"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "channel", + "doc": "Channel (C section) along +z: the web on -x, the flanges opening toward +x. Its end sockets sit on the web.", + "params": [ + {"name": "length", "type": "number", "min": 0.1, "max": 6.0, "default": 1.0, "doc": "end face to end face (z)"}, + {"name": "w", "type": "number", "min": 0.03, "max": 0.4, "default": 0.08, "doc": "width (x)"}, + {"name": "h", "type": "number", "min": 0.03, "max": 0.4, "default": 0.12, "doc": "height (y)"}, + {"name": "t", "type": "number", "min": 0.003, "max": 0.05, "default": 0.01, "doc": "wall thickness; held under 0.45 of the smaller of w and h"} + ], + "shapes": [ + {"shape": "extrude", "section": "C", "w": "w", "h": "h", "t": "min(t,0.45*min(w,h))", "path": [[0, 0, 0], [0, 0, "length"]], "up": [0, 1, 0]} + ], + "sockets": [ + {"name": "end_a", "type": "mount", "size": "min(w,h)", "at": ["min(t,0.45*min(w,h))/2-w/2", 0, 0], "z": "-z", "y": "+y"}, + {"name": "end_b", "type": "mount", "size": "min(w,h)", "at": ["min(t,0.45*min(w,h))/2-w/2", 0, "length"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "tee", + "doc": "Tee along +z: the flange across x at +y, the stem down the middle.", + "params": [ + {"name": "length", "type": "number", "min": 0.1, "max": 6.0, "default": 1.0, "doc": "end face to end face (z)"}, + {"name": "w", "type": "number", "min": 0.03, "max": 0.4, "default": 0.08, "doc": "width (x)"}, + {"name": "h", "type": "number", "min": 0.03, "max": 0.4, "default": 0.12, "doc": "height (y)"}, + {"name": "t", "type": "number", "min": 0.003, "max": 0.05, "default": 0.01, "doc": "wall thickness; held under 0.45 of the smaller of w and h"} + ], + "shapes": [ + {"shape": "extrude", "section": "T", "w": "w", "h": "h", "t": "min(t,0.45*min(w,h))", "path": [[0, 0, 0], [0, 0, "length"]], "up": [0, 1, 0]} + ], + "sockets": [ + {"name": "end_a", "type": "mount", "size": "min(w,h)", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "end_b", "type": "mount", "size": "min(w,h)", "at": [0, 0, "length"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "angle", + "doc": "Angle (L section) along +z: one leg along x at -y, one along y at -x. Its end sockets sit on the upright leg.", + "params": [ + {"name": "length", "type": "number", "min": 0.1, "max": 6.0, "default": 1.0, "doc": "end face to end face (z)"}, + {"name": "w", "type": "number", "min": 0.03, "max": 0.4, "default": 0.08, "doc": "width (x)"}, + {"name": "h", "type": "number", "min": 0.03, "max": 0.4, "default": 0.12, "doc": "height (y)"}, + {"name": "t", "type": "number", "min": 0.003, "max": 0.05, "default": 0.01, "doc": "wall thickness; held under 0.45 of the smaller of w and h"} + ], + "shapes": [ + {"shape": "extrude", "section": "L", "w": "w", "h": "h", "t": "min(t,0.45*min(w,h))", "path": [[0, 0, 0], [0, 0, "length"]], "up": [0, 1, 0]} + ], + "sockets": [ + {"name": "end_a", "type": "mount", "size": "min(w,h)", "at": ["min(t,0.45*min(w,h))/2-w/2", 0, 0], "z": "-z", "y": "+y"}, + {"name": "end_b", "type": "mount", "size": "min(w,h)", "at": ["min(t,0.45*min(w,h))/2-w/2", 0, "length"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "box_beam", + "doc": "Solid rectangular bar along +z.", + "params": [ + {"name": "length", "type": "number", "min": 0.1, "max": 6.0, "default": 1.0, "doc": "end face to end face (z)"}, + {"name": "w", "type": "number", "min": 0.03, "max": 0.4, "default": 0.08, "doc": "width (x)"}, + {"name": "h", "type": "number", "min": 0.03, "max": 0.4, "default": 0.12, "doc": "height (y)"} + ], + "shapes": [ + {"shape": "extrude", "section": "box", "w": "w", "h": "h", "t": "w", "path": [[0, 0, 0], [0, 0, "length"]], "up": [0, 1, 0]} + ], + "sockets": [ + {"name": "end_a", "type": "mount", "size": "min(w,h)", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "end_b", "type": "mount", "size": "min(w,h)", "at": [0, 0, "length"], "z": "+z", "y": "+y"} + ] + }, + { + "name": "truss", + "doc": "Plane truss along +x in the xz plane: two square chords at z 0 and z height, a vertical at every bay and one diagonal per bay, rising then falling. Bays come in pairs.", + "params": [ + {"name": "length", "type": "number", "min": 0.5, "max": 8.0, "default": 2.0, "doc": "first vertical's axis to the last's (x)"}, + {"name": "height", "type": "number", "min": 0.1, "max": 1.5, "default": 0.3, "doc": "chord axis to chord axis (z)"}, + {"name": "pairs", "type": "integer", "min": 1, "max": 16, "default": 4, "doc": "pairs of bays: a rising diagonal and a falling one"}, + {"name": "chord", "type": "number", "min": 0.02, "max": 0.15, "default": 0.05, "doc": "side of the square chords"}, + {"name": "web", "type": "number", "min": 0.01, "max": 0.1, "default": 0.03, "doc": "side of the square verticals and diagonals"} + ], + "shapes": [ + {"shape": "repeat", "count": 2, "step": [0, 0, "height"], "of": + {"shape": "extrude", "section": "box", "w": "chord", "h": "chord", "t": "chord", "path": [["-web/2", 0, 0], ["length+web/2", 0, 0]], "up": [0, 0, 1]}}, + {"shape": "repeat", "count": "2*pairs+1", "step": ["length/(2*pairs)", 0, 0], "of": + {"shape": "extrude", "section": "box", "w": "web", "h": "web", "t": "web", "path": [[0, 0, 0], [0, 0, "height"]], "up": [0, 1, 0]}}, + {"shape": "repeat", "count": "pairs", "step": ["length/pairs", 0, 0], "of": + {"shape": "extrude", "section": "box", "w": "web", "h": "web", "t": "web", "path": [[0, 0, 0], ["length/(2*pairs)", 0, "height"]], "up": [0, 1, 0]}}, + {"shape": "repeat", "count": "pairs", "step": ["length/pairs", 0, 0], "of": + {"shape": "extrude", "section": "box", "w": "web", "h": "web", "t": "web", "path": [["length/(2*pairs)", 0, "height"], ["length/pairs", 0, 0]], "up": [0, 1, 0]}} + ], + "sockets": [ + {"name": "end_a", "type": "mount", "size": "height", "at": ["-web/2", 0, "height/2"], "z": "-x", "y": "+z"}, + {"name": "end_b", "type": "mount", "size": "height", "at": ["length+web/2", 0, "height/2"], "z": "+x", "y": "+z"} + ] + }, + { + "name": "portal", + "doc": "Portal frame in the xz plane: one I section up a leg, across and down the other, mitred at both corners. Its flanges face +y and -y.", + "params": [ + {"name": "width", "type": "number", "min": 0.5, "max": 4.0, "default": 1.2, "doc": "leg axis to leg axis (x)"}, + {"name": "height", "type": "number", "min": 0.4, "max": 3.0, "default": 0.9, "doc": "feet to the beam's axis (z)"}, + {"name": "w", "type": "number", "min": 0.04, "max": 0.3, "default": 0.1, "doc": "section width, in the frame's plane"}, + {"name": "h", "type": "number", "min": 0.04, "max": 0.3, "default": 0.1, "doc": "section height (y)"}, + {"name": "t", "type": "number", "min": 0.004, "max": 0.04, "default": 0.01, "doc": "wall thickness; held under 0.45 of the smaller of w and h"} + ], + "shapes": [ + {"shape": "extrude", "section": "I", "w": "w", "h": "h", "t": "min(t,0.45*min(w,h))", "path": [["-width/2", 0, 0], ["-width/2", 0, "height"], ["width/2", 0, "height"], ["width/2", 0, 0]], "up": [0, 1, 0]} + ], + "sockets": [ + {"name": "foot_a", "type": "mount", "size": "min(w,h)", "at": ["-width/2", 0, 0], "z": "-z", "y": "+y"}, + {"name": "foot_b", "type": "mount", "size": "min(w,h)", "at": ["width/2", 0, 0], "z": "-z", "y": "+y"} + ] + }, + { + "name": "gusset", + "doc": "Corner plate: a right triangle with its legs along +x and +y from the origin, each acute tip cut square, thickness along +z.", + "params": [ + {"name": "w", "type": "number", "min": 0.04, "max": 0.5, "default": 0.15, "doc": "leg along x"}, + {"name": "h", "type": "number", "min": 0.04, "max": 0.5, "default": 0.15, "doc": "leg along y"}, + {"name": "t", "type": "number", "min": 0.003, "max": 0.05, "default": 0.015, "doc": "flat that cuts each tip; held under 0.45 of the shorter leg"}, + {"name": "thickness", "type": "number", "min": 0.003, "max": 0.05, "default": 0.01, "doc": "plate thickness (z)"} + ], + "shapes": [ + {"shape": "extrude", "section": "gusset", "w": "w", "h": "h", "t": "min(t,0.45*min(w,h))", "path": [[0, 0, 0], [0, 0, "thickness"]], "up": [0, 1, 0], "at": ["w/2", "h/2", 0]} + ], + "sockets": [ + {"name": "leg_a", "type": "mount", "size": "thickness", "at": ["w/2", 0, "thickness/2"], "z": "-y", "y": "+z"}, + {"name": "leg_b", "type": "mount", "size": "thickness", "at": [0, "h/2", "thickness/2"], "z": "-x", "y": "+z"} + ] + }, + { + "name": "wedge", + "doc": "Wedge (a toe cap, a ramp, a chock) along +x: its base on z 0, its tall back at -y, sloping down to a front lip at +y.", + "params": [ + {"name": "length", "type": "number", "min": 0.05, "max": 2.0, "default": 0.3, "doc": "x size"}, + {"name": "w", "type": "number", "min": 0.05, "max": 1.0, "default": 0.25, "doc": "base, back to front (y)"}, + {"name": "h", "type": "number", "min": 0.03, "max": 0.5, "default": 0.12, "doc": "back height (z)"}, + {"name": "t", "type": "number", "min": 0.005, "max": 0.3, "default": 0.03, "doc": "front height; held under 0.9 of h"} + ], + "shapes": [ + {"shape": "extrude", "section": "wedge", "w": "w", "h": "h", "t": "min(t,0.9*h)", "path": [[0, 0, 0], ["length", 0, 0]], "up": [0, 0, 1], "at": [0, 0, "h/2"]} + ], + "sockets": [ + {"name": "base", "type": "mount", "size": "min(length,w)", "at": ["length/2", 0, 0], "z": "-z", "y": "+y"}, + {"name": "back", "type": "mount", "size": "min(length,h)", "at": ["length/2", "-w/2", "h/2"], "z": "-y", "y": "+z"} + ] + } + ] +} diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 36ccec5..a00e264 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -237,7 +237,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: cutters, mechanical"): + with self.assertRaisesRegex(core.KitError, "no kit named 'absent'; kits: cutters, frame, 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") @@ -752,6 +752,133 @@ class CuttersKitTests(unittest.TestCase): 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 FrameKitTests(unittest.TestCase): + """The frame kit: every shell an extrude, a PROFILES section along a path. Its mount and pivot are mechanical's, so a + frame part seats on a mechanical one.""" + PARTS = ["beam_i", "channel", "tee", "angle", "box_beam", "truss", "portal", "gusset", "wedge"] + + @classmethod + def setUpClass(cls): + cls.kit = core.load_kit("frame") + cls.mechanical = core.load_kit("mechanical") + + @staticmethod + def seat(b, socket) -> float: + """How far the socket's origin stands off the nearest face that faces its z and holds it: the face's normal by + Newell's sum and the origin inside its outline by crossing count, since a section's cap is not convex (inf + when no face holds it).""" + origin, z = socket["matrix"][:3, 3], socket["matrix"][:3, 2] + best = math.inf + for face in faces_of(b): + p = b.V[face] + normal = np.cross(p, np.roll(p, -1, axis=0)).sum(axis=0) + normal /= np.linalg.norm(normal) + if np.abs(normal - z).max() > 1e-6: + continue + u = np.cross(normal, [1.0, 0.0, 0.0] if abs(normal[0]) < 0.9 else [0.0, 1.0, 0.0]) + q, o = np.stack([p @ u, p @ np.cross(normal, u)], axis=1), np.array([origin @ u, origin @ np.cross(normal, u)]) + a, c = q, np.roll(q, -1, axis=0) + straddles = (a[:, 1] > o[1]) != (c[:, 1] > o[1]) + with np.errstate(divide="ignore", invalid="ignore"): + crossing = a[:, 0] + (o[1] - a[:, 1]) * (c[:, 0] - a[:, 0]) / (c[:, 1] - a[:, 1]) + if int((straddles & (crossing > o[0])).sum()) % 2: + best = min(best, float(abs((origin - p[0]) @ normal))) + return best + + def draws(self, name): + part = self.kit["parts"][name] + rng = random.Random(f"frame.{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_its_nine_parts_and_two_of_mechanicals_socket_types(self): + """frame-kit-holds. Mutant E10 (frame's mount declared 'equal'): the types differ from mechanical's.""" + self.assertEqual(list(self.kit["parts"]), self.PARTS) + self.assertEqual(self.kit["socketTypes"], {name: self.mechanical["socketTypes"][name] for name in ("mount", "pivot")}) + lines = lambda name: [line for line in (core.KITS / f"{name}.v0.json").read_text(encoding="utf-8").split("\n") if line.startswith((' "mount"', ' "pivot"'))] # noqa: E731 + self.assertEqual((lines("frame"), len(lines("frame"))), (lines("mechanical"), 2)) # byte for byte + ends = [("end_a", "mount"), ("end_b", "mount")] + self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, { + "beam_i": ends, "channel": ends, "tee": ends, "angle": ends, "box_beam": ends, "truss": ends, + "portal": [("foot_a", "mount"), ("foot_b", "mount")], "gusset": [("leg_a", "mount"), ("leg_b", "mount")], + "wedge": [("base", "mount"), ("back", "mount")]}) + kinds = {s["of"]["shape"] if s["shape"] == "repeat" else s["shape"] for part in self.kit["parts"].values() for s in part["shapes"]} + self.assertEqual(kinds, {"extrude"}) + + def test_every_part_holds_everywhere(self): + """frame-kit-holds: at the default, every minimum, every maximum and 16 seeded draws each part is closed shells + wound outward, of positive volume and under 20000 faces, each socket a right-handed frame on a face that + faces its z and holds its origin.""" + for name in self.PARTS: + part, draws = self.draws(name) + for given in draws: + b = core.build(part, given) + self.assertTrue(closed_and_oriented(b), f"{name} {given}") + self.assertLessEqual(len(b.counts), 20000) + self.assertGreater(signed_volume(b), 0.0) + self.assertFalse(bool(b.smooth.any())) + self.assertEqual(len(b.sockets), 2) + for socket in b.sockets: + frame = socket["matrix"][:3, :3] + self.assertLess(np.abs(frame.T @ frame - np.eye(3)).max(), 1e-9) + self.assertLess(abs(np.linalg.det(frame) - 1.0), 1e-9) + self.assertLess(self.seat(b, socket), 1e-9, f"{name}.{socket['name']} {given}") + self.assertGreater(socket["size"], 0.0) + + def test_a_truss_is_two_chords_a_vertical_a_bay_and_a_diagonal_a_bay(self): + """frame-kit-holds: 2 + (2*pairs + 1) + 2*pairs shells; the diagonals rise then fall, bay by bay, each from + one chord's axis to the other's.""" + part = self.kit["parts"]["truss"] + for pairs in (1, 4, 16): + b = core.build(part, {"pairs": pairs, "length": 3.2, "height": 0.4}) + self.assertEqual((b.shell_count, len(b.counts)), (2 + (2 * pairs + 1) + 2 * pairs, 6 * (4 * pairs + 3))) + bay = 3.2 / (2 * pairs) + shells = b.V.reshape(-1, 8, 3) + self.assertTrue(np.allclose(shells[2:2 * pairs + 3].mean(axis=1), [[k * bay, 0, 0.2] for k in range(2 * pairs + 1)], atol=1e-12)) + self.assertTrue(np.allclose(shells[2 * pairs + 3:].mean(axis=1), [[(k + 0.5) * bay, 0, 0.2] for k in list(range(0, 2 * pairs, 2)) + list(range(1, 2 * pairs, 2))], atol=1e-12)) + rising, falling = shells[2 * pairs + 3], shells[3 * pairs + 3] + self.assertTrue(np.allclose([rising[:4].mean(axis=0), rising[4:].mean(axis=0)], [[0, 0, 0], [bay, 0, 0.4]], atol=1e-12)) + self.assertTrue(np.allclose([falling[:4].mean(axis=0), falling[4:].mean(axis=0)], [[bay, 0, 0.4], [2 * bay, 0, 0]], atol=1e-12)) + + def test_the_portals_corners_are_mitred(self): + """frame-kit-holds: at each corner every point of the section stands as far from the leg's axis as from the + beam's, which is its own distance across the section (unmitred, 0.707 of it from each).""" + part, draws = self.draws("portal") + for given in draws[:6]: + b = core.build(part, given) + env = b.params + across = np.abs(core.profile("I", env["w"], env["h"], min(env["t"], 0.45 * min(env["w"], env["h"])))[:, 0]) + for ring, corner in ((1, [-env["width"] / 2, 0.0, env["height"]]), (2, [env["width"] / 2, 0.0, env["height"]])): + off = np.abs(b.V[12 * ring:12 * ring + 12] - corner) + self.assertLess(float(np.abs(off[:, [0, 2]] - across[:, None]).max()), 1e-12, given) + self.assertEqual((b.shell_count, b.counts.tolist()), (1, [4] * 36 + [12, 12])) + + def test_builds_are_deterministic(self): + for part in self.kit["parts"].values(): + a, b = core.build(part), core.build(part) + self.assertEqual((a.V.tobytes(), a.faces.tobytes(), a.counts.tobytes(), a.smooth.tobytes()), + (b.V.tobytes(), b.faces.tobytes(), b.counts.tobytes(), b.smooth.tobytes())) + self.assertEqual((a.V.dtype, a.faces.dtype, a.counts.dtype), (np.float64, np.int32, np.int32)) + + def test_a_beam_seats_on_a_mechanical_bracket(self): + """cross-kit-types. Mutant E10: kit 'frame' declares mount 'equal' and kit 'mechanical' 'fits', and nothing mates.""" + names = ("mechanical", "frame") + bracket, beam = core.build(self.mechanical["parts"]["bracket"]), core.build(self.kit["parts"]["beam_i"]) + mount, end = core.joint(self.mechanical["parts"]["bracket"], bracket, "mount", self.kit["parts"]["beam_i"], beam, "end_a") + self.assertEqual((mount["size"], end["size"]), (0.09, 0.08)) + self.assertIsNone(core.mate_refusal(self.mechanical["socketTypes"], mount, end, self.kit["socketTypes"], names)) + seated = core.mate(mount, end) @ end["matrix"] + self.assertLess(float(np.abs(seated[:3, 3]).max()), 1e-12) + self.assertLess(float(np.abs(seated[:3, 2] - [0.0, 0.0, 1.0]).max()), 1e-12) # the beam's end faces the bracket's foot and the beam runs on along -z + wide = core.build(self.kit["parts"]["box_beam"], {"w": 0.2, "h": 0.2}) + self.assertIn("it is larger", core.mate_refusal(self.mechanical["socketTypes"], mount, wide.sockets[0], self.kit["socketTypes"], names)) + self.assertIn("are of different types", core.mate_refusal(self.mechanical["socketTypes"], bracket.sockets[1], end, self.kit["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 @@ -1774,7 +1901,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", "cutters.v0.json", "mechanical.v0.json"]) + self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json"]) for pattern in self.PACKAGE: for name, text in self.sources().items(): if pattern is self.PACKAGE[2] and name == "__init__.py": From 2d990bf2ea86db538028bbaddc54d5b0c8295afe Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 16:28:02 +0100 Subject: [PATCH 110/223] brokkr_kitbash.ribs row: the longeron enum lists PROFILES' seven sections, as the operator's does The operator's longeron enum is core.PROFILES (__init__.py), and the host refuses a row whose enum differs from its operator's: with wedge and gusset in PROFILES the whole kitbash table failed to load. The row mirrors the seven. This file is outside the cut's stated files (cut-kit-extrude.r1 leaves it to kit-hose); the commit stands alone so it can be dropped for the other answer, an enum of five named in __init__.py. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/brokkr_actions.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 89ed135..2f5db7d 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -686,7 +686,9 @@ "C", "T", "L", - "box" + "box", + "wedge", + "gusset" ], "default": "T", "doc": "the longerons' section; its up faces the plate" From 5bf992ab70ea16b77ccaf7fc993a4f74b9b1c0d3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 16:28:03 +0100 Subject: [PATCH 111/223] live kitbash: the frame kit's nine parts placed, a truss re-parameterised in place, a box_beam seated on a mechanical bracket Blender 5.3.0 background, private user dirs: kitbash 91 checks, kitbash_assembly 118, kitbash_pose 46, kitbash_ribs 49, kitbash_shell 82, kitbash_faceted 34, all ok; only kitbash's result file changes. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/kitbash.py | 43 +++++- .../blender/tests/live/kitbash.result.json | 134 ++++++++++++++++++ 2 files changed, 176 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 6b03a2e..ef5abc9 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -1,6 +1,7 @@ """Live proof, in a background Blender, that the brokkr_kitbash rows are admitted by Brokkr as host actions and that the mechanical kit goes through run_intent: describe, place_part for all eleven parts, setObjectTransform, -assignMaterial, set_params, report, the refusals, and exportGltf. Not part of the unittest run: it needs Blender. +assignMaterial, set_params, report, the refusals, the frame kit's nine parts (placed, a truss re-parameterised, a beam +seated on a mechanical bracket), and exportGltf. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash.py -- @@ -253,6 +254,46 @@ try: receipt, whole = send("brokkr_kitbash.report") check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 11, receipt["message"]) + # --- the frame kit: every shell an extrude, a section swept along a path -------------------------------------------------- + frame = core.load_kit("frame") + receipt, described = send("brokkr_kitbash.describe", kit="frame") + check("describe of the frame kit lists its nine parts, whole", receipt["status"] == "accepted" and described + and [p["name"] for p in described["parts"]] == list(frame["parts"]) and len(described["parts"]) == 9 and "[truncated]" not in receipt["hostResult"], + [receipt["message"], len(receipt.get("hostResult") or "")]) + R["frame"] = {} + for name, part in frame["parts"].items(): + receipt, report = send("brokkr_kitbash.place_part", kit="frame", part=name, object_name=f"F_{name}") + obj = bpy.data.objects.get(f"F_{name}") + reference = core.build(part) + faces = len(obj.data.polygons) if obj else -1 + flat = np.zeros(max(faces, 0), dtype=bool) + if obj: + obj.data.attributes["sharp_face"].data.foreach_get("value", flat) + check(f"place_part frame {name}: core's faces, shells and vertices, a valid mesh, every face flat, no Bevel, sockets in the part frame", + receipt["status"] == "accepted" and report and obj is not None and faces == len(reference.counts) == report["faces"] + and report["shells"] == reference.shell_count and not obj.data.validate(verbose=False) and bool(flat.all()) + and np.allclose(np.array([v.co[:] for v in obj.data.vertices]), reference.V, atol=1e-6) and obj.modifiers.get("Kit Bevel") is None + and (obj["kit_kit"], obj["kit_part"]) == ("frame", name) and report["sockets"] == core.socket_rows(reference.sockets), + [receipt["message"], faces, len(reference.counts)]) + R["frame"][name] = {"faces": faces, "shells": reference.shell_count, "sockets": [s["name"] for s in reference.sockets]} + truss = bpy.data.objects["F_truss"] + truss_mesh = truss.data.name + receipt, report = send("brokkr_kitbash.set_params", object_name="F_truss", params="pairs=6") + reference = core.build(frame["parts"]["truss"], {"pairs": 6}) + check("set_params pairs=6 rebuilds the truss in place: 27 shells of core's faces on the same object and mesh", receipt["status"] == "accepted" and report + and report["shells"] == reference.shell_count == 27 and len(truss.data.polygons) == len(reference.counts) == report["faces"] + and bpy.data.objects.get("F_truss") == truss and truss.data.name == truss_mesh and report["params"]["pairs"] == 6 + and np.allclose(np.array([v.co[:] for v in truss.data.vertices]), reference.V, atol=1e-6), [receipt["message"], report]) + receipt, report = send("brokkr_kitbash.attach", object_name="F_box_beam", socket="end_a", parent_name="P_bracket", parent_socket="mount") + beam, bracket = bpy.data.objects["F_box_beam"], bpy.data.objects["P_bracket"] + seat = np.array(bracket.matrix_world) @ np.array(core.build(kit["parts"]["bracket"], json.loads(bracket["kit_params"])).sockets[0]["matrix"]) + end = np.array(beam.matrix_world) @ np.array(core.build(frame["parts"]["box_beam"]).sockets[0]["matrix"]) + # the connection holds within HELD, 1e-5 m, the rule attach and close share (tests/live/kitbash_assembly.py) + check("a frame box_beam's end_a seats on a mechanical bracket's mount across the two kits, and holds", receipt["status"] == "accepted" and report + and beam.parent == bracket and report["connection"]["holds"] is True and report["connection"]["residual"] <= 1e-5 + and float(np.abs(seat[:3, 3] - end[:3, 3]).max()) < 1e-5 and float(np.abs(seat[:3, 2] + end[:3, 2]).max()) < 1e-5, + [receipt["message"], report and report.get("connection")]) + # --- export --------------------------------------------------------------------------------------------------------------- receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names]) glb = WORK / "kit.glb" diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 8e751b7..bacf88b 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -391,6 +391,66 @@ "ok": true, "detail": null }, + { + "name": "describe of the frame kit lists its nine parts, whole", + "ok": true, + "detail": null + }, + { + "name": "place_part frame beam_i: core's faces, shells and vertices, a valid mesh, every face flat, no Bevel, sockets in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part frame channel: core's faces, shells and vertices, a valid mesh, every face flat, no Bevel, sockets in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part frame tee: core's faces, shells and vertices, a valid mesh, every face flat, no Bevel, sockets in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part frame angle: core's faces, shells and vertices, a valid mesh, every face flat, no Bevel, sockets in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part frame box_beam: core's faces, shells and vertices, a valid mesh, every face flat, no Bevel, sockets in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part frame truss: core's faces, shells and vertices, a valid mesh, every face flat, no Bevel, sockets in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part frame portal: core's faces, shells and vertices, a valid mesh, every face flat, no Bevel, sockets in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part frame gusset: core's faces, shells and vertices, a valid mesh, every face flat, no Bevel, sockets in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part frame wedge: core's faces, shells and vertices, a valid mesh, every face flat, no Bevel, sockets in the part frame", + "ok": true, + "detail": null + }, + { + "name": "set_params pairs=6 rebuilds the truss in place: 27 shells of core's faces on the same object and mesh", + "ok": true, + "detail": null + }, + { + "name": "a frame box_beam's end_a seats on a mechanical bracket's mount across the two kits, and holds", + "ok": true, + "detail": null + }, { "name": "exportGltf of all eleven parts succeeds", "ok": true, @@ -423,6 +483,80 @@ "brokkr_kitbash.ribs", "brokkr_kitbash.shell" ], + "frame": { + "beam_i": { + "faces": 14, + "shells": 1, + "sockets": [ + "end_a", + "end_b" + ] + }, + "channel": { + "faces": 10, + "shells": 1, + "sockets": [ + "end_a", + "end_b" + ] + }, + "tee": { + "faces": 10, + "shells": 1, + "sockets": [ + "end_a", + "end_b" + ] + }, + "angle": { + "faces": 8, + "shells": 1, + "sockets": [ + "end_a", + "end_b" + ] + }, + "box_beam": { + "faces": 6, + "shells": 1, + "sockets": [ + "end_a", + "end_b" + ] + }, + "truss": { + "faces": 114, + "shells": 19, + "sockets": [ + "end_a", + "end_b" + ] + }, + "portal": { + "faces": 38, + "shells": 1, + "sockets": [ + "foot_a", + "foot_b" + ] + }, + "gusset": { + "faces": 7, + "shells": 1, + "sockets": [ + "leg_a", + "leg_b" + ] + }, + "wedge": { + "faces": 6, + "shells": 1, + "sockets": [ + "base", + "back" + ] + } + }, "placed": { "nozzle": { "faces": 994, From 983dfcdd05171ffa2944684a745f135db52fb88c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 16:31:49 +0100 Subject: [PATCH 112/223] docs/kitbash.md: the extrude shape, its frame rule and seven sections, and the frame kit Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 57 +++++++++++++++++++++++++++++--- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 1c7f452..586b9ab 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -76,7 +76,8 @@ then y, then z, about the shape's own origin) place it, rotation first; both def | `tube` | `r0`, `r1`, `length`, `segments`, `inner0`?, `inner1`?, `smooth`? | A frustum on +z from radius `r0` at z=0 to `r1` at z=`length`, with n-gon caps. Inner radii above 0 make it hollow (an inner wall and two flat end rings); they are both above 0 or both 0, and below the outer radius. `segments` is 3 to 128. `smooth` shades the walls smooth; caps stay flat. | | `box` | `size` | A box centred on its origin; every size above 0. | | `lathe` | `profile`, `segments`, `loop`?, `smooth`? | A profile of `[r, z]` points revolved about +z into one shell, a ring of `segments` (3 to 128) vertices per point. An open profile's end on the axis (`r` exactly 0) is a pole; an end off the axis gets a flat n-gon cap. With `loop` true the last point joins the first and there are no caps (a ring: 3 points or more). `smooth` shades the walls smooth; a band between two points of one `z` (an annulus) and the caps stay flat. A point written `[r, z, "sharp"]` is a crease. | -| `repeat` | `count`, `of`, and `step` or `around` with `center`? | `count` copies (1 to 256) of one tube, box or lathe: at `k * step`, k from 0, or turned `k * 360 / count` degrees, right-handed, about the axis `around` (one of `+x -x +y -y +z -z`) through `center` (default the origin). Exactly one of `step` and `around`. A repeat cannot hold a repeat. | +| `extrude` | `section`, `w`, `h`, `t`, `path`, `up`, `loop`? | A section (`I`, `C`, `T`, `L`, `box`, `wedge` or `gusset`: a name, never an expression) of width `w`, height `h` and wall `t`, swept along `path`, 2 to 64 `[x, y, z]` points, into one shell with a flat cap at each end. `up` is one `[x, y, z]` vector the section's height stands along. With `loop` true the last point joins the first and there are no caps (3 points or more). Every face is flat. | +| `repeat` | `count`, `of`, and `step` or `around` with `center`? | `count` copies (1 to 256) of one tube, box, lathe or extrude: at `k * step`, k from 0, or turned `k * 360 / count` degrees, right-handed, about the axis `around` (one of `+x -x +y -y +z -z`) through `center` (default the origin). Exactly one of `step` and `around`. A repeat cannot hold a repeat. | A lathe's profile is listed out along the bottom and up the outside, as this flanged stub is: a cap of radius 0.1 at z=0, the flange's rim, its top face, the pipe, and a cap of radius 0.05 at z=0.3. @@ -109,6 +110,31 @@ refused at an open profile's two ends, which are a cap or a pole. No modifier or Shells may overlap (a pad that runs into a tank), and a part is then not one solid: reports give the shell count. +An extrude stands its section on the path by one rule (`core.sweep`, which also makes a rib's longerons). At each +path point the section lies in the plane that bisects the turn there. Its y axis is `up` with the path's direction +taken out of it, and its x axis is that y cross the path's direction: along +z with `up` +y the section's x is +x +and its y is +y, as drawn; along +x with `up` +z its x is +y. A corner is mitred: the section is stretched in the +plane of the turn by 1 / cos(half the turn), so it keeps its size on both sides of the corner. `at` and `rot` then +place the whole shell as they place any shape. + +| section | outline, counter-clockwise in (x, y), centred on its `w` by `h` box | `t` | `t` must be under | +| --- | --- | --- | --- | +| `I` | two flanges across x joined by a web along y | flange and web thickness | `w` and `h / 2` | +| `C` | the web on -x, two flanges opening toward +x | flange and web thickness | `w` and `h / 2` | +| `T` | the flange across x at +y, the stem down the middle | flange and stem thickness | `w` and `h` | +| `L` | one leg along x at -y, one along y at -x | leg thickness | `w` and `h` | +| `box` | the solid `w` by `h` rectangle | unused, but above 0 | | +| `wedge` | a right trapezoid: base `w` at -y, its back `h` tall at -x, its front `t` tall at +x | front height | `h` | +| `gusset` | a right triangle on legs `w` (along x at -y) and `h` (along y at -x), each acute tip cut square | length of the flat that cuts a tip | half the shorter leg | + +Every size is above 0. A build is refused, naming the kit, part and shape, when the section has no room for its +wall, when `up` runs along the path at a point (or is zero), when two path points are closer than 1e-9, when the +path turns more than 150 degrees at a point (past it a mitre runs 3.9 times the section's width), and when the +section folds: the path turns tighter than the section reaches on the inside of the turn. One `up` serves the +whole path, so a path that bends in two planes needs an `up` that crosses every segment and every corner's +bisector; a portal in the xz plane takes `up` +y, which stands an I section's web across the frame's plane. +`smooth` is not a field of an extrude: a section's faces are flat, and its corners take the part's `bevel`. + **`bevel`** is the width of a Bevel modifier `place_part` adds (2 segments, edges sharper than 30 degrees). Keep it well under the part's thinnest feature at its smallest params. @@ -500,7 +526,7 @@ takes planes in the cage's own frame and makes, as one mesh object under the cag - longerons through the ribs: each `{origin, axis, toward}` is the half-plane from the line through `origin` along `axis`, on `toward`'s side. Where it crosses a plane's rib, at the rib's mid-depth, is a station; the longeron runs through the stations in the planes' order and 0.12 of the end gaps past the end ribs, a section - `longeron` (`I`, `C`, `T`, `L` or `box`; `longeron_w`, `longeron_h`, `longeron_t`) with its up toward the plate. + `longeron` (a section of the extrude shape's table: `I`, `C`, `T`, `L`, `box`, `wedge` or `gusset`; `longeron_w`, `longeron_h`, `longeron_t`) with its up toward the plate. A rib's outer edge is where its plane cuts the offset surface (`core.inset` makes it: each vertex of the inner face stepped to where its faces, moved in by `standoff`, meet). Points `step` apart along the section each look @@ -693,6 +719,26 @@ the tank's axis. The bracket's `pivot` face lies on its plate's centre plane, so the same side, turned half (roll 180), pins on the same plane facing the first. An actuator on one and a strut on the other then lie in one plane and can meet at a pin: a braced leg. +## The frame kit + +`kits/frame.v0.json`: nine parts of chassis structure, every shell an extrude. Its socket types are `mount` (fits) +and `pivot` (equal), the same two lines as `mechanical`'s, so a frame part seats on a mechanical one and the other +way round (`place_part` and `describe` take `kit: "frame"`). + +| part | params | what it is | sockets | +| --- | --- | --- | --- | +| `beam_i`, `channel`, `tee`, `angle` | `length`, `w`, `h`, `t` | An I, C, T or L section along +z from 0 to `length`, `w` across x and `h` along y. `t` is held under 0.45 of the smaller of `w` and `h`. | `end_a` (z -z) and `end_b` (z +z), `mount`, size the smaller of `w` and `h`. On a channel and an angle they sit on the web at -x, where the end face is. | +| `box_beam` | `length`, `w`, `h` | A solid rectangular bar along +z. | `end_a`, `end_b`, as a beam's | +| `truss` | `length`, `height`, `pairs`, `chord`, `web` | A plane truss along +x in the xz plane: two square chords at z 0 and z `height`, `2*pairs + 1` verticals and `2*pairs` diagonals, rising then falling: `4*pairs + 3` shells. Bays come in pairs (1 to 16) because an expression has no floor: the diagonals are two repeats a double bay apart. | `end_a` (z -x) and `end_b` (z +x) on the end verticals at mid-height, `mount`, size `height` | +| `portal` | `width`, `height`, `w`, `h`, `t` | One I section up a leg, across and down the other in the xz plane, mitred at both corners; its flanges face +y and -y. | `foot_a`, `foot_b` (z -z), `mount` | +| `gusset` | `w`, `h`, `t`, `thickness` | A corner plate in the xy plane with its right angle at the origin, legs along +x and +y, `thickness` along +z. | `leg_a` on the x leg's edge (z -y) and `leg_b` on the y leg's (z -x), `mount`, size `thickness` | +| `wedge` | `length`, `w`, `h`, `t` | A toe cap, ramp or chock along +x: base on z 0, back `h` tall at -y, sloping to a front `t` tall at +y (`t` held under 0.9 of `h`). | `base` (z -z) and `back` (z -y), `mount` | + +No frame part has a bevel. `core.build` costs, as medians of 21 interleaved builds on the workstation beside the +mechanical actuator's 2.3 ms: a beam, the portal, the gusset or the wedge 0.7 to 0.9 ms; the truss 2.8 ms at +`pairs` 4 (19 shells) and 3.8 ms at `pairs` 16 (67 shells). A repeat sweeps its one shape once and copies it, so +a truss costs four sweeps whatever its bays; the same 19 and 67 shells swept one by one measured 5.9 ms and 20.7 ms. + ## Adding a part or a kit Edit the kit's JSON (or add `kits/.v0.json`, whose `kit` field is ``), then run the tests: @@ -706,10 +752,13 @@ 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`. -`CuttersKitTests` holds `cutters` to the same, with each floor on its cutter's bottom, and `SurfaceFrameTests` the +`FrameKitTests` holds `frame` to the same (its seat check reads a section's cap, which is not convex, by the +face's own normal and outline), with the truss's shells, the portal's mitres and a beam seated on a mechanical +bracket. `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, `PoseTests` the closed-form rolls. The operators are exercised in a real Blender by -`tests/live/kitbash.py` (placing and re-parameterising), `tests/live/kitbash_assembly.py` (attach, detach, +`tests/live/kitbash.py` (placing and re-parameterising, and the frame kit: its nine parts placed, the truss +re-parameterised, a beam seated on a bracket), `tests/live/kitbash_assembly.py` (attach, detach, `set_params` on assemblies, a braced leg closed by `close`, boolean and apply), `tests/live/kitbash_shell.py` (`cut` and `cut_many` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no collection) and `tests/live/kitbash_pose.py` (roll, aim and reach). From 2f374cc4dedaa3e15f24a8cdd5a631d8188cdcab Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 17:42:06 +0100 Subject: [PATCH 113/223] brokkr.kit.v0 extrude: up is one vector or one per path point; the portal's web stands in its plane core.sweep already took an up for each point; the extrude shape now passes them through, and refuses an array that is not one per path point. The frame kit's portal gives each point the in-plane direction toward the inside of the frame, so its I section's web lies in the xz plane and its flanges run across y. Tests: the portal's web, extents and feet (kills S9, foot_b on foot_a), each beam's w across x and h along y (kills S14, box_beam's w and h swapped), the truss's chord ends, per-point ups at the shape. socket_seat reads a face by Newell's normal and a crossing count, so FrameKitTests' own seat check is gone. SEATED, VOLUME and PLACED sit at the geometric mean of shipped and least-mutant readings (lodur:ruling:deterministic-bound-margin). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/core.py | 15 +- .../blender/brokkr_kitbash/kits/frame.v0.json | 8 +- surfaces/blender/docs/kitbash.md | 19 +- surfaces/blender/tests/test_kitbash.py | 184 +++++++++++------- 4 files changed, 139 insertions(+), 87 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index e4b68ba..c298351 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -250,7 +250,13 @@ def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict: if not isinstance(path, list) or not least <= len(path) <= PATH: raise KitError(f"{where} path must be an array of {least} to {PATH} [x, y, z] points{' (it is a loop)' if made['loop'] else ''}") made["path"] = [_vector(point, names, f"{where} path[{i}]") for i, point in enumerate(path)] - made["up"] = _vector(shape["up"], names, f"{where} up") + ups = shape["up"] + if isinstance(ups, list) and ups and all(isinstance(up, list) for up in ups): # one up for each path point + if len(ups) != len(path): + raise KitError(f"{where} up lists {len(ups)} vectors for a path of {len(path)} points: give one [x, y, z] or one for each point") + made["up"] = [_vector(up, names, f"{where} up[{i}]") for i, up in enumerate(ups)] + else: + made["up"] = [_vector(ups, names, f"{where} up")] return made for key in ("loop", "smooth"): if not isinstance(shape.get(key, False), bool): @@ -572,12 +578,13 @@ def _box(shape: dict, env): def _extrude(shape: dict, env): """A PROFILES section swept along the path: profile and sweep own the geometry (the outline's x is up cross the path's tangent, its y is up taken off the tangent, the joints are mitred), and what either refuses is refused - here under the shape's name. Every face is flat.""" + here under the shape's name. `up` is one vector for the whole path or one for each point, as sweep takes them. + Every face is flat.""" size = [shape[key].value(env) for key in ("w", "h", "t")] path = [[e.value(env) for e in point] for point in shape["path"]] - up = [e.value(env) for e in shape["up"]] + ups = [[e.value(env) for e in up] for up in shape["up"]] try: - swept = sweep(path, profile(shape["section"], *size), up, shape["loop"]) + swept = sweep(path, profile(shape["section"], *size), ups[0] if len(ups) == 1 else ups, shape["loop"]) except KitError as error: raise KitError(f"{shape['where']}: {error}") from None return swept.V, swept.faces, swept.counts, swept.smooth, NO_SHARP diff --git a/surfaces/blender/brokkr_kitbash/kits/frame.v0.json b/surfaces/blender/brokkr_kitbash/kits/frame.v0.json index a61f3c7..e25c7fe 100644 --- a/surfaces/blender/brokkr_kitbash/kits/frame.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/frame.v0.json @@ -118,16 +118,16 @@ }, { "name": "portal", - "doc": "Portal frame in the xz plane: one I section up a leg, across and down the other, mitred at both corners. Its flanges face +y and -y.", + "doc": "Portal frame in the xz plane: one I section up a leg, across and down the other, mitred at both corners. Its web stands in the frame's plane; its flanges run across y on the inside and the outside of the frame.", "params": [ {"name": "width", "type": "number", "min": 0.5, "max": 4.0, "default": 1.2, "doc": "leg axis to leg axis (x)"}, {"name": "height", "type": "number", "min": 0.4, "max": 3.0, "default": 0.9, "doc": "feet to the beam's axis (z)"}, - {"name": "w", "type": "number", "min": 0.04, "max": 0.3, "default": 0.1, "doc": "section width, in the frame's plane"}, - {"name": "h", "type": "number", "min": 0.04, "max": 0.3, "default": 0.1, "doc": "section height (y)"}, + {"name": "w", "type": "number", "min": 0.04, "max": 0.3, "default": 0.1, "doc": "flange width, across the frame's plane (y)"}, + {"name": "h", "type": "number", "min": 0.04, "max": 0.3, "default": 0.1, "doc": "section height, flange to flange in the frame's plane"}, {"name": "t", "type": "number", "min": 0.004, "max": 0.04, "default": 0.01, "doc": "wall thickness; held under 0.45 of the smaller of w and h"} ], "shapes": [ - {"shape": "extrude", "section": "I", "w": "w", "h": "h", "t": "min(t,0.45*min(w,h))", "path": [["-width/2", 0, 0], ["-width/2", 0, "height"], ["width/2", 0, "height"], ["width/2", 0, 0]], "up": [0, 1, 0]} + {"shape": "extrude", "section": "I", "w": "w", "h": "h", "t": "min(t,0.45*min(w,h))", "path": [["-width/2", 0, 0], ["-width/2", 0, "height"], ["width/2", 0, "height"], ["width/2", 0, 0]], "up": [[1, 0, 0], [1, 0, -1], [-1, 0, -1], [-1, 0, 0]]} ], "sockets": [ {"name": "foot_a", "type": "mount", "size": "min(w,h)", "at": ["-width/2", 0, 0], "z": "-z", "y": "+y"}, diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 586b9ab..8cbd115 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -76,7 +76,7 @@ then y, then z, about the shape's own origin) place it, rotation first; both def | `tube` | `r0`, `r1`, `length`, `segments`, `inner0`?, `inner1`?, `smooth`? | A frustum on +z from radius `r0` at z=0 to `r1` at z=`length`, with n-gon caps. Inner radii above 0 make it hollow (an inner wall and two flat end rings); they are both above 0 or both 0, and below the outer radius. `segments` is 3 to 128. `smooth` shades the walls smooth; caps stay flat. | | `box` | `size` | A box centred on its origin; every size above 0. | | `lathe` | `profile`, `segments`, `loop`?, `smooth`? | A profile of `[r, z]` points revolved about +z into one shell, a ring of `segments` (3 to 128) vertices per point. An open profile's end on the axis (`r` exactly 0) is a pole; an end off the axis gets a flat n-gon cap. With `loop` true the last point joins the first and there are no caps (a ring: 3 points or more). `smooth` shades the walls smooth; a band between two points of one `z` (an annulus) and the caps stay flat. A point written `[r, z, "sharp"]` is a crease. | -| `extrude` | `section`, `w`, `h`, `t`, `path`, `up`, `loop`? | A section (`I`, `C`, `T`, `L`, `box`, `wedge` or `gusset`: a name, never an expression) of width `w`, height `h` and wall `t`, swept along `path`, 2 to 64 `[x, y, z]` points, into one shell with a flat cap at each end. `up` is one `[x, y, z]` vector the section's height stands along. With `loop` true the last point joins the first and there are no caps (3 points or more). Every face is flat. | +| `extrude` | `section`, `w`, `h`, `t`, `path`, `up`, `loop`? | A section (`I`, `C`, `T`, `L`, `box`, `wedge` or `gusset`: a name, never an expression) of width `w`, height `h` and wall `t`, swept along `path`, 2 to 64 `[x, y, z]` points, into one shell with a flat cap at each end. `up` is the direction the section's height stands along: one `[x, y, z]` vector for the whole path, or an array of one per path point. With `loop` true the last point joins the first and there are no caps (3 points or more). Every face is flat. | | `repeat` | `count`, `of`, and `step` or `around` with `center`? | `count` copies (1 to 256) of one tube, box, lathe or extrude: at `k * step`, k from 0, or turned `k * 360 / count` degrees, right-handed, about the axis `around` (one of `+x -x +y -y +z -z`) through `center` (default the origin). Exactly one of `step` and `around`. A repeat cannot hold a repeat. | A lathe's profile is listed out along the bottom and up the outside, as this flanged stub is: a cap of radius 0.1 @@ -130,9 +130,11 @@ place the whole shell as they place any shape. Every size is above 0. A build is refused, naming the kit, part and shape, when the section has no room for its wall, when `up` runs along the path at a point (or is zero), when two path points are closer than 1e-9, when the path turns more than 150 degrees at a point (past it a mitre runs 3.9 times the section's width), and when the -section folds: the path turns tighter than the section reaches on the inside of the turn. One `up` serves the -whole path, so a path that bends in two planes needs an `up` that crosses every segment and every corner's -bisector; a portal in the xz plane takes `up` +y, which stands an I section's web across the frame's plane. +section folds: the path turns tighter than the section reaches on the inside of the turn. One `up` must cross +every segment and every corner's bisector, so it can only stand a bent path's section across the plane of the +bend. To keep the section's height in that plane give one `up` per point, each in the plane and across the path +there (at a corner, across its bisector): the portal's four point toward the inside of the frame, which stands its +I section's web in the frame's plane. An array of ups that is not one per path point is refused. `smooth` is not a field of an extrude: a section's faces are flat, and its corners take the part's `bevel`. **`bevel`** is the width of a Bevel modifier `place_part` adds (2 segments, edges sharper than 30 degrees). Keep it @@ -730,7 +732,7 @@ way round (`place_part` and `describe` take `kit: "frame"`). | `beam_i`, `channel`, `tee`, `angle` | `length`, `w`, `h`, `t` | An I, C, T or L section along +z from 0 to `length`, `w` across x and `h` along y. `t` is held under 0.45 of the smaller of `w` and `h`. | `end_a` (z -z) and `end_b` (z +z), `mount`, size the smaller of `w` and `h`. On a channel and an angle they sit on the web at -x, where the end face is. | | `box_beam` | `length`, `w`, `h` | A solid rectangular bar along +z. | `end_a`, `end_b`, as a beam's | | `truss` | `length`, `height`, `pairs`, `chord`, `web` | A plane truss along +x in the xz plane: two square chords at z 0 and z `height`, `2*pairs + 1` verticals and `2*pairs` diagonals, rising then falling: `4*pairs + 3` shells. Bays come in pairs (1 to 16) because an expression has no floor: the diagonals are two repeats a double bay apart. | `end_a` (z -x) and `end_b` (z +x) on the end verticals at mid-height, `mount`, size `height` | -| `portal` | `width`, `height`, `w`, `h`, `t` | One I section up a leg, across and down the other in the xz plane, mitred at both corners; its flanges face +y and -y. | `foot_a`, `foot_b` (z -z), `mount` | +| `portal` | `width`, `height`, `w`, `h`, `t` | One I section up a leg, across and down the other in the xz plane, mitred at both corners. Its web stands in the frame's plane: `h` is the section's height in that plane, flange to flange, and `w` the flanges' width across y. | `foot_a`, `foot_b` (z -z), `mount` | | `gusset` | `w`, `h`, `t`, `thickness` | A corner plate in the xy plane with its right angle at the origin, legs along +x and +y, `thickness` along +z. | `leg_a` on the x leg's edge (z -y) and `leg_b` on the y leg's (z -x), `mount`, size `thickness` | | `wedge` | `length`, `w`, `h`, `t` | A toe cap, ramp or chock along +x: base on z 0, back `h` tall at -y, sloping to a front `t` tall at +y (`t` held under 0.9 of `h`). | `base` (z -z) and `back` (z -y), `mount` | @@ -752,9 +754,10 @@ 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`. -`FrameKitTests` holds `frame` to the same (its seat check reads a section's cap, which is not convex, by the -face's own normal and outline), with the truss's shells, the portal's mitres and a beam seated on a mechanical -bracket. `CuttersKitTests` holds `cutters` to the same, with each floor on its cutter's bottom, and `SurfaceFrameTests` the +`FrameKitTests` holds `frame` to the same (the seat check reads a cap that is not convex, an I section's, as it +reads a convex one), with the truss's shells and chords, the portal's mitres, its web in the frame's plane and its +feet apart, each beam's `w` across x and `h` along y, and a beam seated on a mechanical +bracket. Its bounds `SEATED`, `VOLUME` and `PLACED` carry their shipped and mutant readings in `tests/test_kitbash.py`. `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, `PoseTests` the closed-form rolls. The operators are exercised in a real Blender by `tests/live/kitbash.py` (placing and re-parameterising, and the frame kit: its nine parts placed, the truss diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index a00e264..55c0723 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -5,8 +5,8 @@ Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; The operators are exercised in a real Blender by tests/live/kitbash.py, tests/live/kitbash_assembly.py and tests/live/kitbash_pose.py. -Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is -the built value, and each names the mutant it kills. +Bounds follow lodur:ruling:deterministic-bound-margin: SEATED, VOLUME and PLACED, below, carry their shipped and +mutant readings; a reading that is exact is asserted equal. Each check names the mutant it kills. """ from __future__ import annotations @@ -85,44 +85,52 @@ def frustum(r0, r1, h, n) -> float: return h / 3.0 * (a0 + a1 + math.sqrt(a0 * a1)) -def point_triangle(p, a, b, c) -> float: - """Distance from p to triangle abc (Ericson, Real-Time Collision Detection 5.1.5).""" - ab, ac, ap = b - a, c - a, p - a - d1, d2 = ab @ ap, ac @ ap - if d1 <= 0 and d2 <= 0: - return float(np.linalg.norm(ap)) - bp = p - b - d3, d4 = ab @ bp, ac @ bp - if d3 >= 0 and d4 <= d3: - return float(np.linalg.norm(bp)) - vc = d1 * d4 - d3 * d2 - if vc <= 0 and d1 >= 0 and d3 <= 0: - return float(np.linalg.norm(ap - ab * (d1 / (d1 - d3)))) - cp = p - c - d5, d6 = ab @ cp, ac @ cp - if d6 >= 0 and d5 <= d6: - return float(np.linalg.norm(cp)) - vb = d5 * d2 - d1 * d6 - if vb <= 0 and d2 >= 0 and d6 <= 0: - return float(np.linalg.norm(ap - ac * (d2 / (d2 - d6)))) - va = d3 * d6 - d5 * d4 - if va <= 0 and d4 - d3 >= 0 and d5 - d6 >= 0: - return float(np.linalg.norm(bp - (c - b) * ((d4 - d3) / ((d4 - d3) + (d5 - d6))))) - normal = np.cross(ab, ac) - return float(abs(ap @ normal) / np.linalg.norm(normal)) +# Bounds of the extrude shape's and the frame kit's checks (ShapeTests, FrameKitTests), by +# lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped worst reading and the least +# claimed mutant's. A mutant is one edit of core.py or kits/frame.v0.json; a reading is the worst of every check under +# the bound, over every draw. +# Metres from a frame part's socket origin to the face it sits on. Shipped worst 1.1e-15; least claimed mutant 0.04 +# (a portal foot one wall above its end cap); separation 6.0e6 each side. Also claimed: a truss end on its vertical's +# axis 0.05, a channel's end off its web 0.15, a tee built as an L 0.16, a wedge not lifted onto its base 0.25. +SEATED = 6.7e-9 +# Cubic metres between a swept shell's volume and its section's area times its path's length. Shipped worst 2.7e-15; +# least claimed mutant 0.02 (E7, loop ignored: the ring an open path); separation 2.7e6 each side. A sweep with no +# mitre reads 0.023. +VOLUME = 7.3e-9 +# Metres between a built point, extent or centre and where the part's doc puts it. Shipped worst 8.9e-16; least claimed +# mutant 0.01 (a portal foot one wall above its end cap, read against its cap's middle); separation 3.4e6 each side. +# Also claimed: a truss's chords a web short 0.015, a sweep with no mitre 0.044, S14 (box_beam's w and h swapped) +# 0.075, P1 (the portal on one up +y) 0.3, U1 (only the first of an extrude's ups used) 0.6, S9 (foot_b on foot_a) 1.2, +# a truss's falling diagonals a bay late 1.6, E1 (an extrude ignores at and rot) 3.0. +PLACED = 3.0e-9 def socket_seat(b, socket) -> float: - """Distance from the socket's origin to the nearest face whose normal is the socket's z (inf when none faces it).""" + """Distance from the socket's origin to the nearest face whose normal is the socket's z (inf when none faces it). + The face's normal is Newell's sum; the origin is over the face by crossing count, and beside it the distance is + to the nearest edge: so a cap that is not convex (an I section's) reads as a convex one does.""" origin, z = socket["matrix"][:3, 3], socket["matrix"][:3, 2] best = math.inf for face in faces_of(b): p = b.V[face] - normal = np.cross(p[1] - p[0], p[2] - p[0]) + normal = np.cross(p, np.roll(p, -1, axis=0)).sum(axis=0) normal /= np.linalg.norm(normal) if np.abs(normal - z).max() > 1e-6: continue - best = min([best] + [point_triangle(origin, p[0], p[i], p[i + 1]) for i in range(1, len(face) - 1)]) + u = np.cross(normal, [1.0, 0.0, 0.0] if abs(normal[0]) < 0.9 else [0.0, 1.0, 0.0]) + u /= np.linalg.norm(u) + v = np.cross(normal, u) + a, o = np.stack([p @ u, p @ v], axis=1), np.array([origin @ u, origin @ v]) + c = np.roll(a, -1, axis=0) + straddles = (a[:, 1] > o[1]) != (c[:, 1] > o[1]) + with np.errstate(divide="ignore", invalid="ignore"): + crossing = a[:, 0] + (o[1] - a[:, 1]) * (c[:, 0] - a[:, 0]) / (c[:, 1] - a[:, 1]) + off = float(abs((origin - p[0]) @ normal)) + if not int((straddles & (crossing > o[0])).sum()) % 2: # beside the face: to its nearest edge + edge = c - a + along = np.clip(np.einsum("ij,ij->i", o - a, edge) / np.einsum("ij,ij->i", edge, edge), 0.0, 1.0) + off = math.hypot(off, float(np.linalg.norm(a + along[:, None] * edge - o, axis=1).min())) + best = min(best, off) return best @@ -435,7 +443,7 @@ class ShapeTests(unittest.TestCase): area = float(0.5 * np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y)) b = built([{**self.BEAM, "section": section, "w": "a", "path": [[0, 0, 0], [0, 0, "5*a"]]}], [param("a", 0.01, 1, w)]) self.assertTrue(closed_and_oriented(b), section) - self.assertLess(abs(signed_volume(b) - area * 0.3), 1e-12, section) + self.assertLess(abs(signed_volume(b) - area * 0.3), VOLUME, section) self.assertEqual((b.shell_count, b.counts.tolist(), bool(b.smooth.any()), b.sharp.shape), (1, [4] * len(outline) + [len(outline)] * 2, False, (0, 2)), section) self.assertEqual(b.V[:len(outline)].tolist(), [[px, py, 0.0] for px, py in outline.tolist()], section) self.assertEqual(b.V[len(outline):, 2].tolist(), [0.06 * 5] * len(outline)) @@ -451,20 +459,20 @@ class ShapeTests(unittest.TestCase): swept = built([{**self.BEAM, "section": "box", "rot": rot, "at": at}]) box = built([{"shape": "box", "size": size, "rot": rot, "at": lifted}]) order = lambda V: V[np.lexsort(np.round(V, 9).T)] # noqa: E731 - self.assertLess(float(np.abs(order(swept.V) - order(box.V)).max()), 1e-12) - self.assertLess(abs(signed_volume(swept) - 0.06 * 0.1 * 0.3), 1e-12) + self.assertLess(float(np.abs(order(swept.V) - order(box.V)).max()), PLACED) + self.assertLess(abs(signed_volume(swept) - 0.06 * 0.1 * 0.3), VOLUME) area = 2 * 0.06 * 0.012 + (0.1 - 2 * 0.012) * 0.012 for change, centres in (({"step": [0.5, 0, "a"]}, [[0, 0, 0.15], [0.5, 0, 1.15], [1.0, 0, 2.15]]), ({"around": "+y", "center": [1, 0, 0]}, [[0, 0, 0.15], [1.5 + 0.15 * 0.75 ** 0.5, 0, 0.75 ** 0.5 - 0.075], [1.5 - 0.15 * 0.75 ** 0.5, 0, -0.75 ** 0.5 - 0.075]])): b = built([{"shape": "box", "size": [1, 1, 1]}, {"shape": "repeat", "count": 3, **change, "of": self.BEAM}], [param("a")]) self.assertEqual((b.shell_count, b.shape.tolist()), (4, [0] * 6 + [1] * 14 * 3)) self.assertTrue(closed_and_oriented(b)) - self.assertLess(abs(signed_volume(b) - 1.0 - 3 * area * 0.3), 1e-12) - self.assertTrue(np.allclose(b.V[8:].reshape(3, 24, 3).mean(axis=1), centres, atol=1e-12), change) + self.assertLess(abs(signed_volume(b) - 1.0 - 3 * area * 0.3), VOLUME) + self.assertLess(float(np.abs(b.V[8:].reshape(3, 24, 3).mean(axis=1) - centres).max()), PLACED, change) ring = built([{**self.BEAM, "section": "box", "w": 0.1, "h": 0.2, "loop": True, "path": [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], "up": [0, 0, 1]}]) self.assertEqual((ring.shell_count, ring.counts.tolist(), len(ring.V)), (1, [4] * 16, 16)) self.assertTrue(closed_and_oriented(ring)) - self.assertLess(abs(signed_volume(ring) - 0.1 * 0.2 * 4.0), 1e-12) # mitred: the area times the path's length + self.assertLess(abs(signed_volume(ring) - 0.1 * 0.2 * 4.0), VOLUME) # mitred: the area times the path's length def test_what_a_sweep_refuses_an_extrude_refuses_by_name(self): """extrude-refusals, at build. Mutant E8 (the where prefix dropped): each message starts at 'path point' or @@ -484,6 +492,33 @@ class ShapeTests(unittest.TestCase): built([{"shape": "box", "size": [1, 1, 1]}, {"shape": "repeat", "count": 2, "step": [1, 0, 0], "of": {**self.BEAM, "up": [0, 0, 1]}}]) self.assertEqual(len(built([{**self.BEAM, "t": "a"}], [param("a", 0, 1, 0.05)], {"a": 0.04}).counts), 14) + def test_an_extrude_takes_one_up_or_one_for_each_point(self): + """portal-web-across-plane, at its owner. An L of path in the xz plane: one up +y stands the I section's height + (0.1) across the plane; an up for each point, in the plane and across the path there, stands it in the plane, + at the same volume, mitred. The same up given three times is the one up, byte for byte. Mutants U1 (only the + first of the ups is used: the far leg's up runs along its path and the build is refused) and U2 (an array of + ups of another length than the path is admitted).""" + bent = {**self.BEAM, "path": [[0, 0, 0], [0, 0, 1], [1, 0, 1]]} + across, three, inplane = (built([{**bent, "up": up}]) for up in ([0, 1, 0], [[0, 1, 0]] * 3, [[1, 0, 0], [1, 0, -1], [0, 0, -1]])) + self.assertEqual((across.V.tobytes(), across.faces.tobytes()), (three.V.tobytes(), three.faces.tobytes())) + self.assertTrue(closed_and_oriented(inplane)) + self.assertLess(abs(signed_volume(inplane) - signed_volume(across)), VOLUME) + for b, extents in ((across, [1.03, 0.1, 1.03]), (inplane, [1.05, 0.06, 1.05])): # the path's 1 by 1 and half the section either end + self.assertLess(float(np.abs(np.ptp(b.V, axis=0) - extents).max()), PLACED) + ring = inplane.V.reshape(3, 12, 3) + self.assertLess(float(np.abs(ring[:, 1] - ring[:, 0] - [0.0, -0.06, 0.0]).max()), PLACED) # the flange runs across y at every point + expression = built([{**bent, "up": [["a", 0, 0], ["a", 0, "-a"], [0, 0, "-a"]]}], [param("a")]) + self.assertEqual(expression.V.tobytes(), inplane.V.tobytes()) + for up, message in (([[0, 1, 0]] * 2, r"part 'p' shape 0 \(extrude\) up lists 2 vectors for a path of 3 points: give one \[x, y, z\] or one for each point$"), + ([[0, 1, 0]], r"part 'p' shape 0 \(extrude\) up lists 1 vectors for a path of 3 points"), + ([[0, 1, 0], [0, 1, 0], [0, 1]], r"part 'p' shape 0 \(extrude\) up\[2\] must be an array of three"), + ([[0, 1, 0], [0, 1, 0], [0, "q", 0]], r"part 'p' shape 0 \(extrude\) up\[2\]\[1\]: 'q' names 'q'"), + ([], r"part 'p' shape 0 \(extrude\) up must be an array of three")): + with self.assertRaisesRegex(core.KitError, message): + core.check_kit(document([{**bent, "up": up}])) + with self.assertRaisesRegex(core.KitError, r"^kit 't' part 'p' shape 0 \(extrude\): path point 2: up \[1\.0, 0\.0, 0\.0\] runs along the path there"): + built([{**bent, "up": [[1, 0, 0], [1, 0, -1], [1, 0, 0]]}]) + def test_sockets_are_right_handed_frames(self): socket = {"name": "s", "type": "mount", "size": "2*a", "at": ["a", 2, 3], "z": "+x", "y": "+z"} kit = core.check_kit(document(params=[param("a")], sockets=[socket])) @@ -763,29 +798,6 @@ class FrameKitTests(unittest.TestCase): cls.kit = core.load_kit("frame") cls.mechanical = core.load_kit("mechanical") - @staticmethod - def seat(b, socket) -> float: - """How far the socket's origin stands off the nearest face that faces its z and holds it: the face's normal by - Newell's sum and the origin inside its outline by crossing count, since a section's cap is not convex (inf - when no face holds it).""" - origin, z = socket["matrix"][:3, 3], socket["matrix"][:3, 2] - best = math.inf - for face in faces_of(b): - p = b.V[face] - normal = np.cross(p, np.roll(p, -1, axis=0)).sum(axis=0) - normal /= np.linalg.norm(normal) - if np.abs(normal - z).max() > 1e-6: - continue - u = np.cross(normal, [1.0, 0.0, 0.0] if abs(normal[0]) < 0.9 else [0.0, 1.0, 0.0]) - q, o = np.stack([p @ u, p @ np.cross(normal, u)], axis=1), np.array([origin @ u, origin @ np.cross(normal, u)]) - a, c = q, np.roll(q, -1, axis=0) - straddles = (a[:, 1] > o[1]) != (c[:, 1] > o[1]) - with np.errstate(divide="ignore", invalid="ignore"): - crossing = a[:, 0] + (o[1] - a[:, 1]) * (c[:, 0] - a[:, 0]) / (c[:, 1] - a[:, 1]) - if int((straddles & (crossing > o[0])).sum()) % 2: - best = min(best, float(abs((origin - p[0]) @ normal))) - return best - def draws(self, name): part = self.kit["parts"][name] rng = random.Random(f"frame.{name}") @@ -824,9 +836,9 @@ class FrameKitTests(unittest.TestCase): self.assertEqual(len(b.sockets), 2) for socket in b.sockets: frame = socket["matrix"][:3, :3] - self.assertLess(np.abs(frame.T @ frame - np.eye(3)).max(), 1e-9) - self.assertLess(abs(np.linalg.det(frame) - 1.0), 1e-9) - self.assertLess(self.seat(b, socket), 1e-9, f"{name}.{socket['name']} {given}") + # exact: a frame part's socket axes are named axes, so its frame is a signed permutation + self.assertEqual((float(np.abs(frame.T @ frame - np.eye(3)).max()), float(np.linalg.det(frame))), (0.0, 1.0)) + self.assertLess(socket_seat(b, socket), SEATED, f"{name}.{socket['name']} {given}") self.assertGreater(socket["size"], 0.0) def test_a_truss_is_two_chords_a_vertical_a_bay_and_a_diagonal_a_bay(self): @@ -838,25 +850,55 @@ class FrameKitTests(unittest.TestCase): self.assertEqual((b.shell_count, len(b.counts)), (2 + (2 * pairs + 1) + 2 * pairs, 6 * (4 * pairs + 3))) bay = 3.2 / (2 * pairs) shells = b.V.reshape(-1, 8, 3) - self.assertTrue(np.allclose(shells[2:2 * pairs + 3].mean(axis=1), [[k * bay, 0, 0.2] for k in range(2 * pairs + 1)], atol=1e-12)) - self.assertTrue(np.allclose(shells[2 * pairs + 3:].mean(axis=1), [[(k + 0.5) * bay, 0, 0.2] for k in list(range(0, 2 * pairs, 2)) + list(range(1, 2 * pairs, 2))], atol=1e-12)) + self.assertLess(float(np.abs(np.array([shells[:2, :, 0].min(axis=1), shells[:2, :, 0].max(axis=1)]).T - [-0.015, 3.215]).max()), PLACED) # each chord runs to the end verticals' outer faces + self.assertLess(float(np.abs(shells[2:2 * pairs + 3].mean(axis=1) - [[k * bay, 0, 0.2] for k in range(2 * pairs + 1)]).max()), PLACED) + self.assertLess(float(np.abs(shells[2 * pairs + 3:].mean(axis=1) - [[(k + 0.5) * bay, 0, 0.2] for k in list(range(0, 2 * pairs, 2)) + list(range(1, 2 * pairs, 2))]).max()), PLACED) rising, falling = shells[2 * pairs + 3], shells[3 * pairs + 3] - self.assertTrue(np.allclose([rising[:4].mean(axis=0), rising[4:].mean(axis=0)], [[0, 0, 0], [bay, 0, 0.4]], atol=1e-12)) - self.assertTrue(np.allclose([falling[:4].mean(axis=0), falling[4:].mean(axis=0)], [[bay, 0, 0.4], [2 * bay, 0, 0]], atol=1e-12)) + self.assertLess(float(np.abs(np.array([rising[:4].mean(axis=0), rising[4:].mean(axis=0)]) - [[0, 0, 0], [bay, 0, 0.4]]).max()), PLACED) + self.assertLess(float(np.abs(np.array([falling[:4].mean(axis=0), falling[4:].mean(axis=0)]) - [[bay, 0, 0.4], [2 * bay, 0, 0]]).max()), PLACED) def test_the_portals_corners_are_mitred(self): """frame-kit-holds: at each corner every point of the section stands as far from the leg's axis as from the - beam's, which is its own distance across the section (unmitred, 0.707 of it from each).""" + beam's, which is its own height in the section (unmitred, 0.707 of it from each): the section's height lies in + the frame's plane. Mutant F1 (a sweep with no mitre).""" part, draws = self.draws("portal") for given in draws[:6]: b = core.build(part, given) env = b.params - across = np.abs(core.profile("I", env["w"], env["h"], min(env["t"], 0.45 * min(env["w"], env["h"])))[:, 0]) + across = np.abs(core.profile("I", env["w"], env["h"], min(env["t"], 0.45 * min(env["w"], env["h"])))[:, 1]) for ring, corner in ((1, [-env["width"] / 2, 0.0, env["height"]]), (2, [env["width"] / 2, 0.0, env["height"]])): off = np.abs(b.V[12 * ring:12 * ring + 12] - corner) - self.assertLess(float(np.abs(off[:, [0, 2]] - across[:, None]).max()), 1e-12, given) + self.assertLess(float(np.abs(off[:, [0, 2]] - across[:, None]).max()), PLACED, given) self.assertEqual((b.shell_count, b.counts.tolist()), (1, [4] * 36 + [12, 12])) + def test_the_portal_stands_its_web_in_plane_and_its_feet_apart(self): + """portal-web-across-plane, frame-layout-unpinned. The I section's height h lies in the xz plane and its flanges + run w across y, at every point of the path: the frame is width + h wide, w deep and height + h / 2 tall, and + its web is the plate on y 0. foot_a stands under the leg at -width / 2 and foot_b under the one at +width / 2, + each on its own end cap. Mutants P1 (one up +y: the web across the plane, the frame h deep) and S9 (foot_b at + -width / 2, on foot_a).""" + part = self.kit["parts"]["portal"] + for given in ({"width": 1.2, "height": 0.9, "w": 0.06, "h": 0.2, "t": 0.01}, {"width": 0.8, "height": 1.5, "w": 0.3, "h": 0.05, "t": 0.004}): + b = core.build(part, given) + width, height, w, h, t = (given[key] for key in ("width", "height", "w", "h", "t")) + self.assertLess(float(np.abs(np.ptp(b.V, axis=0) - [width + h, w, height + h / 2]).max()), PLACED, given) + ring = b.V.reshape(4, 12, 3) + self.assertLess(float(np.abs(ring[:, 1] - ring[:, 0] - [0.0, -w, 0.0]).max()), PLACED, given) # a flange's edge runs across y + self.assertLess(float(np.abs(np.abs(ring[:, [3, 4, 9, 10], 1]) - t / 2).max()), PLACED, given) # the web's four corners, t / 2 off the plane + feet = {s["name"]: s["matrix"] for s in b.sockets} + self.assertEqual(list(feet), ["foot_a", "foot_b"]) + for name, side, cap in (("foot_a", -1.0, ring[0]), ("foot_b", 1.0, ring[3])): + self.assertLess(float(np.abs(feet[name][:3, 3] - [side * width / 2, 0.0, 0.0]).max()), PLACED, name) + self.assertLess(float(np.abs(feet[name][:3, 3] - cap.mean(axis=0)).max()), PLACED, name) # at the middle of its own cap + self.assertEqual((feet[name][:3, 2].tolist(), feet[name][:3, 1].tolist()), ([0.0, 0.0, -1.0], [0.0, 1.0, 0.0])) + + def test_a_beam_is_w_across_x_and_h_along_y(self): + """frame-layout-unpinned. Each of the five beams runs length along +z from 0, w wide across x and h tall along + y, about its axis. Mutant S14 (box_beam's w and h swapped).""" + for name in ("beam_i", "channel", "tee", "angle", "box_beam"): + b = core.build(self.kit["parts"][name], {"length": 0.7, "w": 0.05, "h": 0.2}) + self.assertLess(float(np.abs(np.array([b.V.min(axis=0), b.V.max(axis=0)]) - [[-0.025, -0.1, 0.0], [0.025, 0.1, 0.7]]).max()), PLACED, name) + def test_builds_are_deterministic(self): for part in self.kit["parts"].values(): a, b = core.build(part), core.build(part) @@ -872,8 +914,8 @@ class FrameKitTests(unittest.TestCase): self.assertEqual((mount["size"], end["size"]), (0.09, 0.08)) self.assertIsNone(core.mate_refusal(self.mechanical["socketTypes"], mount, end, self.kit["socketTypes"], names)) seated = core.mate(mount, end) @ end["matrix"] - self.assertLess(float(np.abs(seated[:3, 3]).max()), 1e-12) - self.assertLess(float(np.abs(seated[:3, 2] - [0.0, 0.0, 1.0]).max()), 1e-12) # the beam's end faces the bracket's foot and the beam runs on along -z + self.assertLess(float(np.abs(seated[:3, 3]).max()), PLACED) + self.assertEqual(seated[:3, 2].tolist(), [0.0, 0.0, 1.0]) # the beam's end faces the bracket's foot and the beam runs on along -z wide = core.build(self.kit["parts"]["box_beam"], {"w": 0.2, "h": 0.2}) self.assertIn("it is larger", core.mate_refusal(self.mechanical["socketTypes"], mount, wide.sockets[0], self.kit["socketTypes"], names)) self.assertIn("are of different types", core.mate_refusal(self.mechanical["socketTypes"], bracket.sockets[1], end, self.kit["socketTypes"], names)) From 8513bd35e335199eef35dec9ed5544160c4e3adc Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 17:42:08 +0100 Subject: [PATCH 114/223] live kitbash_ribs: wedge and gusset longerons through the legs' ribs, each its section's area along the run Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/kitbash_ribs.py | 17 +++++++++++++++++ .../blender/tests/live/kitbash_ribs.result.json | 11 +++++++++++ 2 files changed, 28 insertions(+) diff --git a/surfaces/blender/tests/live/kitbash_ribs.py b/surfaces/blender/tests/live/kitbash_ribs.py index 4b8d756..d593fdf 100644 --- a/surfaces/blender/tests/live/kitbash_ribs.py +++ b/surfaces/blender/tests/live/kitbash_ribs.py @@ -106,6 +106,10 @@ CLEARED = 0.0058 # 5.2e-07; least claimed mutant 0.0021 (K1, a sweep with no mitre: the rib's mid-depth line stands in from where the # facets' offsets meet); separation 64 each side. K9 (the station at the chain's first point) reads 1.2. STATIONED = 3.3e-5 +# A wedge's or a gusset's longerons' volume less a T's, over the difference of the two sections' areas along both runs, +# less 1. Shipped 1.1e-06; least claimed mutant 0.235, computed, not run (a wedge built as a gusset; the section ignored +# and a T built reads 1); separation 460 each side. +SECTIONED = 5.1e-4 # What lightening holes removed from five crossing ribs, over the holes' faceted area times the thickness, less 1. # Shipped 2.7e-08; least claimed mutant 22 (K11, each plane's Manifold Boolean taken over all five ribs' webs, which # cross, with the action's own check of the cut off); separation 28000 each side. @@ -504,6 +508,19 @@ try: receipt["status"] == "accepted" and [s["chains"] for s in report["sections"]] == [2, 2, 2] and report["ribs"] == 6 and [(r["index"], len(r["stations"])) for r in report["longerons"]] == [(0, 3), (1, 3)] and R["readings"].get("stationed", 1.0) < STATIONED and (shape["shells"], shape["nonManifoldEdges"]) == (8, 0) and abs(float(points(ribs)[:, 2].max()) - (0.8 + 0.3 * 0.12)) < 1e-6 and abs(float(points(ribs)[:, 2].min()) - (0.2 - 0.3 * 0.12)) < 1e-6, [receipt["message"], report, R["readings"]]) + # the longeron enum's other sections: a wedge and a gusset through the same ribs. A straight longeron's shells are its + # section's area times its length, so against the T's ribs each differs by the two sections' areas over two legs. + t_volume, run = (shape or {}).get("volume", 0.0), LEVELS[-1] - LEVELS[0] + 2 * 0.3 * 0.12 + area = lambda kind: (lambda x, y: float(0.5 * np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y)))(*core.profile(kind, 0.05, 0.05, 0.008).T) # noqa: E731 + for kind in ("wedge", "gusset"): + receipt, report = send("brokkr_kitbash.ribs", object_name="Legs", ribs_name=f"LegRibs_{kind}", planes=flat(LEVELS), **SIZES, longerons=json.dumps(BEAMS), + longeron=kind, longeron_w=0.05, longeron_h=0.05, longeron_t=0.008) + made = bpy.data.objects.get(f"LegRibs_{kind}") + shape = measure(made.data) if made is not None else {} + check(f"a {kind} longeron through each leg's ribs: the stations a T's has, closed shells, and the {kind}'s area along the run", + receipt["status"] == "accepted" and [(r["index"], len(r["stations"])) for r in report["longerons"]] == [(0, 3), (1, 3)] + and (shape["shells"], shape["nonManifoldEdges"]) == (8, 0) + and reading("sectioned", abs((shape["volume"] - t_volume) / (2 * run * (area(kind) - area("T"))) - 1.0)) < SECTIONED, [receipt["message"], report, R["readings"]]) LEG = {"object_name": "Legs", "ribs_name": "Bad", "planes": flat(LEVELS), **SIZES} refused("a longeron whose half-plane meets no rib", {**LEG, "longerons": json.dumps([{"origin": [0.0, 0.0, 0.0], "axis": [0.0, 0.0, 1.0], "toward": [0.0, 1.0, 0.0]}])}, "longerons[0] does not meet the ribs of planes[0]") diff --git a/surfaces/blender/tests/live/kitbash_ribs.result.json b/surfaces/blender/tests/live/kitbash_ribs.result.json index 396fca8..40360ad 100644 --- a/surfaces/blender/tests/live/kitbash_ribs.result.json +++ b/surfaces/blender/tests/live/kitbash_ribs.result.json @@ -121,6 +121,16 @@ "ok": true, "detail": null }, + { + "name": "a wedge longeron through each leg's ribs: the stations a T's has, closed shells, and the wedge's area along the run", + "ok": true, + "detail": null + }, + { + "name": "a gusset longeron through each leg's ribs: the stations a T's has, closed shells, and the gusset's area along the run", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: a longeron whose half-plane meets no rib", "ok": true, @@ -256,6 +266,7 @@ "planar": 1.4e-07, "ring": 2.1e-06, "round": 9.7e-08, + "sectioned": 1.1e-06, "stationed": 5.2e-07, "stood": 6.4e-08, "sunk": 0.0047, From 13f60bbff136fda9e01ffbcb78b4d2c3bbe6a4db Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 16:18:21 +0100 Subject: [PATCH 115/223] brokkr_kitbash/route.py: a hose's path from waypoints and a distance oracle (cut kit-hose) grid, wavefront, pull and leg search a leg; fillet rounds the polyline by each corner's measured room; sag lowers a span by half its room (ruling hose-slack-and-skinned); passes turns the child's side through a pin's rolls; frames are rotation minimising. numpy only; tests/test_route.py. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/route.py | 398 +++++++++++++++++++++++ surfaces/blender/tests/test_route.py | 296 +++++++++++++++++ 2 files changed, 694 insertions(+) create mode 100644 surfaces/blender/brokkr_kitbash/route.py create mode 100644 surfaces/blender/tests/test_route.py diff --git a/surfaces/blender/brokkr_kitbash/route.py b/surfaces/blender/brokkr_kitbash/route.py new file mode 100644 index 0000000..2221cd7 --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/route.py @@ -0,0 +1,398 @@ +"""The path of a hose: from waypoints and a distance oracle to a curve with frames. numpy only, tested without +Blender (tests/test_route.py); brokkr_kitbash.hose is the bpy around it (docs/kitbash.md, Hoses between sockets). + +A `distance` is a callable over (N, 3) points that answers how far each stands from the nearest obstacle; the caller +owns what an obstacle is and may cap the answer. `need` is how far a hose's centre line must stay from every +obstacle: the bundle's half width plus its clearance. + +A leg between two waypoints is searched on a voxel grid of the box around them (grid, wavefront), then pulled taut +(pull). A voxel is free when it stands need plus half a voxel's diagonal from every obstacle: distance changes by at +most the distance moved, so every point of a step between two neighbouring free voxels keeps need. The legs joined are +one polyline; fillet rounds its corners, each by the largest arc its measured room allows, and verify measures the +curve. sag lowers the middle of a leg by what its room allows. passes turns the part of a polyline beyond a point on +a pin's axis through the pin's rolls and measures each. frames gives the rotation-minimising ups the tubes are swept +with (Wang, Juettler, Zheng and Liu, "Computation of rotation minimizing frames", ACM TOG 27(1), 2008: the double +reflection method). + +Every refusal is a RouteError that names the leg, corner, point or roll. +""" +from __future__ import annotations + +import math +from typing import NamedTuple + +import numpy as np + + +class RouteError(ValueError): + """A route that cannot be made, in words that name where.""" + + +NEIGHBOURS = [(i, j, k) for i in (-1, 0, 1) for j in (-1, 0, 1) for k in (-1, 0, 1) if (i, j, k) != (0, 0, 0)] +REACH = math.sqrt(3.0) / 2.0 # of a voxel: how far a point of a step between two neighbouring voxels can stand from the nearer one +STRAIGHT = 1e-9 # radians: a corner that turns less is no corner +HELD = 1e-9 # metres under need that a reading may stand and hold it +ARC = 24 # arc segments a radian of turn + + +def spot(point) -> str: + return "[" + ", ".join(f"{float(v):.4g}" for v in point) + "]" + + +def bundle(count: int, radius: float, spread: float, clearance: float, bend: float) -> dict: + """The sizes a bundle of `count` hoses of `radius` routes by. spread is centre to centre (0: 2.6 radii). width is + across the bundle; envelope its half; need is how far the centre line stays from obstacles; floor the least + radius of the centre line, bend outside diameters for the innermost hose, which runs half the bundle's spread + inside it; lead the straight a fitting keeps: a ferrule of 5 radii, then 1.5 outside diameters before any bend.""" + spread = spread if spread > 0.0 else 2.6 * radius + half = (count - 1) / 2.0 * spread + return {"spread": spread, "width": 2.0 * half + 2.0 * radius, "envelope": half + radius, "need": half + radius + clearance, + "floor": bend * 2.0 * radius + half, "lead": 5.0 * radius + 1.5 * 2.0 * radius} + + +class Grid(NamedTuple): + """Voxels of a box: free[i, j, k] is the voxel centred at lo + step * (i, j, k).""" + free: np.ndarray + lo: np.ndarray + step: float + + +def grid(lo, hi, step: float, distance, need: float, limit: int = 2 ** 19) -> Grid: + """The voxels of the box lo..hi at `step` that stand at least `need` from every obstacle. Refuses a box of more + than `limit` voxels, naming a step that fits.""" + lo, hi = np.asarray(lo, dtype=np.float64), np.asarray(hi, dtype=np.float64) + shape = lambda s: np.maximum(1, np.ceil((hi - lo) / s - 1e-9).astype(np.int64) + 1) # noqa: E731 + n = shape(step) + if int(n.prod()) > limit: + fits = step + while int(shape(fits).prod()) > limit: + fits *= 1.05 + raise RouteError(f"its search box of {spot(hi - lo)} m is {int(n.prod())} voxels at step {step:g}, over {limit}: a step of {math.ceil(fits * 1e4) / 1e4:g} fits") + axes = [lo[i] + step * np.arange(n[i]) for i in range(3)] + points = np.stack(np.meshgrid(*axes, indexing="ij"), axis=-1).reshape(-1, 3) + return Grid(free=(np.asarray(distance(points)) >= need).reshape(n), lo=lo, step=float(step)) + + +def wavefront(free: np.ndarray, start, goal) -> list: + """The voxels of a shortest 26-connected way from start to goal through free voxels, both ends included: a + wavefront grown from the goal by array shifts, then walked down from the start, at each step to the neighbour one + wave nearer that stands nearest the goal. Refuses an end that is not free, and a start no wave reaches.""" + start, goal, n = tuple(int(v) for v in start), tuple(int(v) for v in goal), free.shape + for name, voxel in (("start", start), ("end", goal)): + if not free[voxel]: + raise RouteError(f"its {name} voxel is not free") + unreached = np.iinfo(np.int32).max + waves = np.full(n, unreached, dtype=np.int32) + waves[goal] = 0 + front = np.zeros(n, dtype=bool) + front[goal] = True + wave = 0 + while waves[start] == unreached and front.any(): + wave += 1 + padded, grown = np.pad(front, 1), np.zeros(n, dtype=bool) + for i, j, k in NEIGHBOURS: + grown |= padded[1 + i:1 + i + n[0], 1 + j:1 + j + n[1], 1 + k:1 + k + n[2]] + front = grown & free & (waves == unreached) + waves[front] = wave + if waves[start] == unreached: + raise RouteError("no free way joins its ends: obstacles close every way through its search box") + way, at = [start], start + while waves[at] > 0: + nearer = [(math.dist(m, goal), m) for m in ((at[0] + i, at[1] + j, at[2] + k) for i, j, k in NEIGHBOURS) + if all(0 <= m[axis] < n[axis] for axis in range(3)) and waves[m] == waves[at] - 1] + at = min(nearer)[1] + way.append(at) + return way + + +def along(a, b, spacing: float) -> np.ndarray: + """Points from a to b, both included, no further apart than spacing.""" + a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64) + count = max(2, int(math.ceil(float(np.linalg.norm(b - a)) / spacing)) + 1) + return a[None] + (b - a)[None] * np.linspace(0.0, 1.0, count)[:, None] + + +def clear(a, b, distance, need: float, spacing: float) -> bool: + return bool((np.asarray(distance(along(a, b, spacing))) >= need - HELD).all()) + + +def pull(points, distance, need: float, spacing: float) -> np.ndarray: + """A polyline pulled taut: from each kept point, the farthest later point in clear sight (need kept at samples no + further apart than spacing); the next point when none is.""" + points = np.asarray(points, dtype=np.float64) + kept, i = [points[0]], 0 + while i < len(points) - 1: + j = len(points) - 1 + while j > i + 1 and not clear(points[i], points[j], distance, need, spacing): + j -= 1 + kept.append(points[j]) + i = j + return np.array(kept) + + +def leg(a, b, occupancy, distance, need: float, step: float, margin: float, limit: int, name: str): + """(the pulled polyline from a to b, the voxels searched): a grid over the two ends' box plus margin, free where + `occupancy` reads need plus REACH of a voxel, a wavefront between the free voxels beside the ends, pulled at need + against `distance`. Refuses, naming the leg: an end nearer an obstacle than need, an end with no free voxel in + sight beside it, a box over the limit, and no way through.""" + a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64) + for label, point in (("start", a), ("end", b)): + reads = float(np.asarray(distance(point[None]))[0]) + if reads < need - HELD: + raise RouteError(f"{name}: its {label} {spot(point)} stands {reads:.4g} m from an obstacle, under the {need:.4g} m the bundle needs") + try: + cells = grid(np.minimum(a, b) - margin, np.maximum(a, b) + margin, step, occupancy, need + REACH * step, limit) + except RouteError as error: + raise RouteError(f"{name}: {error}") from None + ends = [] + for label, point in (("start", a), ("end", b)): + middle = np.clip(np.round((point - cells.lo) / step).astype(int), 0, np.array(cells.free.shape) - 1) + beside = [tuple(int(v) for v in middle + np.array(d)) for d in [(0, 0, 0)] + NEIGHBOURS] + beside = [m for m in beside if all(0 <= m[axis] < cells.free.shape[axis] for axis in range(3)) and cells.free[m]] + beside.sort(key=lambda m: float(np.linalg.norm(cells.lo + step * np.array(m) - point))) + seen = [m for m in beside if clear(point, cells.lo + step * np.array(m), distance, need, step / 2.0)] + if not seen: + raise RouteError(f"{name}: no free voxel stands in sight of its {label} {spot(point)}: an obstacle is nearer it than {need + REACH * step:.4g} m on every side") + ends.append(seen[0]) + try: + way = wavefront(cells.free, ends[0], ends[1]) + except RouteError as error: + raise RouteError(f"{name}: {error}") from None + return pull(np.vstack([a[None], cells.lo + step * np.array(way, dtype=np.float64), b[None]]), distance, need, step / 2.0), int(cells.free.size) + + +def sag(points, depth: float, room, down=(0.0, 0.0, -1.0)): + """(the polyline, the metres it was lowered): the middle of a leg's longest segment lowered by `depth`, less where + the segment runs along `down` (a hanging span sags, a vertical one does not) and never by more than half the room + `room(a, b)` measures along that segment: both halves then stand within that much of the taut segment, so they keep + need with as much room again for the arc at the middle. A segment shorter than 8 times the drop is left taut.""" + points = np.asarray(points, dtype=np.float64) + lengths = np.linalg.norm(np.diff(points, axis=0), axis=1) + i = int(np.argmax(lengths)) + a, b = points[i], points[i + 1] + across = np.asarray(down, dtype=np.float64) - (b - a) / lengths[i] * float(np.asarray(down) @ (b - a) / lengths[i]) + hang = float(np.linalg.norm(across)) + if depth <= 0.0 or hang < 1e-6: + return points, 0.0 + drop = min(depth, 0.5 * (math.inf if room is None else float(room(a, b)))) * hang + if drop <= 1e-6 or lengths[i] < 8.0 * drop: + return points, 0.0 + return np.vstack([points[:i + 1], ((a + b) / 2.0 + across / hang * drop)[None], points[i + 1:]]), drop + + +def _turns(points): + steps = np.diff(points, axis=0) + lengths = np.linalg.norm(steps, axis=1) + if (lengths < 1e-9).any(): + raise RouteError(f"point {int(np.argmax(lengths < 1e-9))} {spot(points[int(np.argmax(lengths < 1e-9))])}: the segment from it is shorter than 1e-9") + unit = steps / lengths[:, None] + return lengths, unit, np.arccos(np.clip(np.einsum("ij,ij->i", unit[:-1], unit[1:]), -1.0, 1.0)) + + +def _kept(count: int, lead: float, keep) -> np.ndarray: + keep = np.zeros(count) if keep is None else np.array(keep, dtype=np.float64) + keep[0] += lead + keep[-1] += lead + return keep + + +def _radius(point, before, after, turn: float, cap: float, room) -> float: + """The largest radius of the arc at a corner whose tangent lengths stay within cap and whose room allows it: the + arc stands within radius x (1 - cos(turn / 2)) of its two tangent segments, so with that much room beyond need + measured along them it keeps need (the triangle inequality). The tangent segments grow with the radius, so the + room can only shrink: the largest radius is found by bisection.""" + most = max(cap, 0.0) / math.tan(turn / 2.0) + if room is None: + return most + depth = 1.0 - math.cos(turn / 2.0) + + def fits(radius: float) -> bool: + t = radius * math.tan(turn / 2.0) + return radius * depth <= min(room(point - before * t, point), room(point, point + after * t)) + + if fits(most): + return most + low, high = 0.0, most + for _ in range(24): + middle = (low + high) / 2.0 + low, high = (middle, high) if fits(middle) else (low, middle) + return low + + +def tangents(points, room, lead: float, keep=None, centred=None) -> np.ndarray: + """The tangent length of the arc at each interior point of a polyline (0 where it runs straight on). Each corner + first gets the largest radius its room allows (_radius) within the straight its two segments have to give: a + segment's length less what it keeps straight (`keep` for each segment, and `lead` more on the first and last), or + half of that at each end of a `centred` segment, whose kept straight stays in its middle. Where two corners' + tangents overlap on a segment both shrink in proportion until they share it.""" + points = np.asarray(points, dtype=np.float64) + lengths, unit, turn = _turns(points) + free = np.maximum(lengths - _kept(len(lengths), lead, keep), 0.0) + each = np.where(np.zeros(len(lengths), dtype=bool) if centred is None else np.asarray(centred, dtype=bool), free / 2.0, free) + t = np.zeros(len(turn)) + for c in np.flatnonzero(turn >= STRAIGHT): + t[c] = _radius(points[c + 1], unit[c], unit[c + 1], float(turn[c]), float(min(each[c], each[c + 1])), room) * math.tan(turn[c] / 2.0) + share = np.ones(len(lengths)) + both = t[:-1] + t[1:] # on segment s, between corners s - 1 and s + share[1:-1] = np.where(both > free[1:-1], free[1:-1] / np.maximum(both, 1e-300), 1.0) + return t * np.minimum(share[:-1], share[1:]) + + +def arcs(points, t): + """(curve, owner): the polyline with the arc of tangent length t[c] at each interior point c + 1, as points + ARC to the radian, and for each curve point the corner whose arc it is on (-1 on the straights' ends). Every arc + is tangent to both its segments.""" + points = np.asarray(points, dtype=np.float64) + _, unit, turn = _turns(points) + curve, owner = [points[0]], [-1] + for c in range(len(turn)): + corner, before, after = points[c + 1], unit[c], unit[c + 1] + if turn[c] < STRAIGHT or t[c] < 1e-9: + curve.append(corner) + owner.append(c) + continue + radius = t[c] / math.tan(turn[c] / 2.0) + inward = after - before * float(before @ after) + inward /= np.linalg.norm(inward) + centre = corner - before * t[c] + inward * radius + for angle in np.linspace(0.0, turn[c], max(2, int(math.ceil(turn[c] * ARC))) + 1): + curve.append(centre + radius * (before * math.sin(angle) - inward * math.cos(angle))) + owner.append(c) + curve.append(points[-1]) + owner.append(-1) + curve, owner = np.array(curve), np.array(owner) + keep = np.r_[True, np.linalg.norm(np.diff(curve, axis=0), axis=1) > 1e-9] + return curve[keep], owner[keep] + + +class Filleted(NamedTuple): + curve: np.ndarray # (N, 3) + owner: np.ndarray # (N,) the corner a curve point's arc belongs to, -1 off the arcs + t: np.ndarray # tangent length at each interior point of the polyline + radii: np.ndarray # radius at each interior point, inf where the polyline runs straight on + + +def fillet(polyline, room, floor: float, lead: float, keep=None, centred=None) -> Filleted: + """A polyline with its corners rounded (tangents, arcs). `room(a, b)` is the least obstacle distance along the + segment a..b less need, or None where nothing stands near. Refuses a corner whose radius is under `floor`, naming + the corner, its point, the radius it got and the floor.""" + polyline = np.asarray(polyline, dtype=np.float64) + if len(polyline) < 3: + return Filleted(polyline, np.full(len(polyline), -1), np.zeros(0), np.zeros(0)) + t = tangents(polyline, room, lead, keep, centred) + turn = _turns(polyline)[2] + radii = np.where(turn >= STRAIGHT, t / np.tan(np.maximum(turn, STRAIGHT) / 2.0), np.inf) + under = np.flatnonzero(radii < floor * (1.0 - 1e-9)) + if len(under): + c = int(under[np.argmin(radii[under])]) + raise RouteError(f"corner {c + 1} at {spot(polyline[c + 1])} turns {math.degrees(turn[c]):.1f} degrees and gets a bend of radius {radii[c]:.4g} m, under the floor {floor:.4g}: " + "its segments are too short or an obstacle stands too near it") + return Filleted(*arcs(polyline, t), t, radii) + + +def samples(curve, spacing: float): + """(points, arc length at each) along a polyline, its own points included, no further apart than spacing.""" + curve = np.asarray(curve, dtype=np.float64) + lengths = np.linalg.norm(np.diff(curve, axis=0), axis=1) + starts = np.r_[0.0, np.cumsum(lengths)] + points, s = [curve[:1]], [np.zeros(1)] + for i, length in enumerate(lengths): + count = max(1, int(math.ceil(length / spacing))) + f = np.arange(1, count + 1) / count + points.append(curve[i][None] + (curve[i + 1] - curve[i])[None] * f[:, None]) + s.append(starts[i] + length * f) + return np.vstack(points), np.concatenate(s) + + +def verify(curve, distance, need: float, lead: float, spacing: float, name: str = "the hose") -> float: + """The least distance the curve stands from an obstacle outside its two leads (the first and last `lead` of its + length, where it leaves its own ports). Refuses a reading under need, naming the point.""" + points, s = samples(curve, spacing) + inside = (s >= lead) & (s <= s[-1] - lead) + if not inside.any(): + return math.inf + reads = np.asarray(distance(points[inside])) + worst = int(np.argmin(reads)) + if reads[worst] < need - HELD: + raise RouteError(f"{name} stands {float(reads[worst]):.4g} m from an obstacle at {spot(points[inside][worst])}, under the {need:.4g} m the bundle needs") + return float(reads[worst]) + + +def frames(curve, up0) -> np.ndarray: + """An up for each point of a curve, rotation minimising: the first is up0 projected off the tangent, each next the + last reflected twice (Wang et al. 2008), so the ups do not twist about the curve. Tangents are the unit bisectors + core.sweep stands its sections on. Refuses an up0 along the first tangent.""" + curve, up = np.asarray(curve, dtype=np.float64), np.asarray(up0, dtype=np.float64) + steps = np.diff(curve, axis=0) + steps = steps / np.linalg.norm(steps, axis=1)[:, None] + tangent = np.vstack([steps[:1], steps[:-1] + steps[1:], steps[-1:]]) + tangent /= np.linalg.norm(tangent, axis=1)[:, None] + r = up - tangent[0] * float(up @ tangent[0]) + if not np.linalg.norm(r) > 1e-6 * np.linalg.norm(up): + raise RouteError(f"up {spot(up)} runs along the curve's first tangent (or is zero)") + r = r / np.linalg.norm(r) + ups = [r] + for i in range(len(curve) - 1): + v1 = curve[i + 1] - curve[i] + c1 = float(v1 @ v1) + r_left = r - (2.0 / c1) * float(v1 @ r) * v1 + t_left = tangent[i] - (2.0 / c1) * float(v1 @ tangent[i]) * v1 + v2 = tangent[i + 1] - t_left + c2 = float(v2 @ v2) + r = r_left - (2.0 / c2) * float(v2 @ r_left) * v2 if c2 > 1e-18 else r_left + ups.append(r) + return np.array(ups) + + +def turned(points, origin, axis, degrees: float) -> np.ndarray: + """Points turned `degrees` about the line through origin along axis, right-handed.""" + axis = np.asarray(axis, dtype=np.float64) / np.linalg.norm(axis) + p = np.asarray(points, dtype=np.float64) - origin + c, s = math.cos(math.radians(degrees)), math.sin(math.radians(degrees)) + return origin + p * c + np.cross(axis, p) * s + axis[None] * (p @ axis)[:, None] * (1.0 - c) + + +def rolls_of(low: float, high: float, step: float) -> list: + """low, then every step up to high, and high.""" + return [float(v) for v in np.arange(low, high - 1e-9, step)] + [float(high)] + + +def passes(polyline, t, j: int, origin, axis, rolls, current: float, parent, child, need: float, floor: float, lead: float, spacing: float, keep=None) -> dict: + """A hose through a pin's rolls. `polyline` runs from the parent's side through point j, which stands on the + pin's axis (origin, axis), to the child's side; `t` are its tangent lengths at the roll `current`. At each roll + the points beyond j are turned about the axis by roll - current, as the child's parts are: the straights on each + side move with their own part, and only the corner at j is rounded again, its neighbours' tangents as they were. + The parent's side is then measured against the child's obstacles turned (`child` reads the child's parts where + they stand at `current`, so the samples are turned back), the child's side against the parent's (`parent`), and the + arc at j against both, all outside the leads. Refuses a roll whose bend at the pin is under the floor or whose + reading is under need, naming the roll, the side and the reading. {rolls, worstRoll, least, lengthChange, radius}.""" + polyline, origin = np.asarray(polyline, dtype=np.float64), np.asarray(origin, dtype=np.float64) + c, least, lengths, radius = j - 1, (math.inf, None), [], math.inf + kept = _kept(len(polyline) - 1, lead, keep) + for roll in rolls: + posed = np.vstack([polyline[:j + 1], turned(polyline[j + 1:], origin, axis, roll - current)]) + back = lambda points, roll=roll: turned(points, origin, axis, current - roll) # noqa: E731 + both = lambda points, back=back: np.minimum(np.asarray(parent(points)), np.asarray(child(back(points)))) # noqa: E731 + lengths_, unit, turn = _turns(posed) + t_roll = np.array(t, dtype=np.float64) + t_roll[c] = 0.0 + if turn[c] >= STRAIGHT: + cap = min(lengths_[c] - kept[c] - (t_roll[c - 1] if c > 0 else 0.0), lengths_[c + 1] - kept[c + 1] - (t_roll[c + 1] if c + 1 < len(t_roll) else 0.0)) + bend = _radius(posed[j], unit[c], unit[c + 1], float(turn[c]), float(cap), lambda a, b, both=both: float(both(along(a, b, spacing)).min()) - need) + if bend < floor * (1.0 - 1e-9): + raise RouteError(f"roll {roll:g}: the bend at the pin turns {math.degrees(turn[c]):.1f} degrees and gets radius {bend:.4g} m, under the floor {floor:.4g}") + t_roll[c], radius = bend * math.tan(turn[c] / 2.0), min(radius, bend) + curve, owner = arcs(posed, t_roll) + points, s = samples(curve, spacing) + at = np.r_[0.0, np.cumsum(np.linalg.norm(np.diff(curve, axis=0), axis=1))][owner == c] + inside = (s >= lead) & (s <= s[-1] - lead) + for side, chosen, reads in (("parent's side", inside & (s < at[0]), lambda p, back=back: np.asarray(child(back(p)))), + ("child's side", inside & (s > at[-1]), parent), + ("bend at the pin", inside & (s >= at[0]) & (s <= at[-1]), both)): + if chosen.any(): + reading = float(np.asarray(reads(points[chosen])).min()) + if reading < need - HELD: + raise RouteError(f"roll {roll:g}: the hose's {side} stands {reading:.4g} m from the parts on the other side of the pin, under the {need:.4g} m the bundle needs") + least = min(least, (reading, float(roll))) + lengths.append(float(s[-1])) + return {"rolls": len(lengths), "worstRoll": least[1], "least": least[0], "lengthChange": max(lengths) - min(lengths), "radius": radius} diff --git a/surfaces/blender/tests/test_route.py b/surfaces/blender/tests/test_route.py new file mode 100644 index 0000000..09db333 --- /dev/null +++ b/surfaces/blender/tests/test_route.py @@ -0,0 +1,296 @@ +"""Route tests. No Blender: brokkr_kitbash/route.py against analytic distance fields. + +Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) +The hose action is exercised in a real Blender by tests/live/kitbash_hose.py. + +Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is the +rule itself, and each names the mutant it kills (cut kit-hose's H list). +""" +from __future__ import annotations + +import importlib.util +import math +import unittest +from pathlib import Path + +SURFACE = Path(__file__).resolve().parents[1] + +try: + import numpy as np +except ImportError: # pragma: no cover + np = None + +if np is not None: + spec = importlib.util.spec_from_file_location("brokkr_kitbash_route", SURFACE / "brokkr_kitbash" / "route.py") + route = importlib.util.module_from_spec(spec) + spec.loader.exec_module(route) + +NEED = 0.04 + + +def wall(hole: float): + """A wall 0.04 thick across x = 1 with a round hole of radius `hole` about the line y = z = 0.2.""" + def distance(points): + points = np.asarray(points, dtype=np.float64) + out = np.maximum(np.abs(points[:, 0] - 1.0) - 0.02, 0.0) + inside = hole - np.hypot(points[:, 1] - 0.2, points[:, 2] - 0.2) + return np.where(inside > 0.0, np.hypot(out, inside), out) + return distance + + +def ball(centre, radius: float): + return lambda points: np.linalg.norm(np.asarray(points, dtype=np.float64) - np.asarray(centre), axis=1) - radius + + +def nothing(points): + return np.full(len(points), 10.0) + + +def room_of(distance, need: float, spacing: float = 0.002): + return lambda a, b: float(np.asarray(distance(route.along(a, b, spacing))).min()) - need + + +def length(points) -> float: + return float(np.linalg.norm(np.diff(np.asarray(points), axis=0), axis=1).sum()) + + +@unittest.skipIf(np is None, "numpy is not installed") +class SearchTests(unittest.TestCase): + def test_a_leg_passes_the_hole_and_every_sight_line_keeps_need(self): + """wavefront-and-pull. Mutant H12 (occupancy at need less a voxel): a kept point stands under need.""" + distance = wall(0.12) + a, b = np.array([0.0, 0.0, 0.0]), np.array([2.0, 0.0, 0.0]) + pulled, voxels = route.leg(a, b, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1") + self.assertEqual(voxels, 131 * 31 * 31) + self.assertTrue(np.allclose(pulled[0], a) and np.allclose(pulled[-1], b)) + dense = np.vstack([route.along(p, q, 0.0025) for p, q in zip(pulled[:-1], pulled[1:])]) # a quarter of the spacing pull samples at + self.assertGreaterEqual(float(distance(dense).min()), NEED - 1e-9) + through = dense[np.abs(dense[:, 0] - 1.0) < 0.02] + self.assertTrue(len(through) and (np.hypot(through[:, 1] - 0.2, through[:, 2] - 0.2) < 0.12 - NEED + 1e-9).all()) + self.assertLess(length(pulled), 2.0 * math.hypot(1.0, 0.2 * math.sqrt(2.0)) + 0.05) # taut: near the two straights through the hole's middle + + def test_two_neighbouring_free_voxels_keep_need_between_them(self): + """The half diagonal a free voxel stands beyond need is what a step between two of them can lose: beside an + edge (a thin rod) every step between neighbouring free voxels keeps need, and without it some do not.""" + rod = lambda points: np.hypot(np.asarray(points)[:, 0], np.asarray(points)[:, 1]) # noqa: E731 + for reach, holds in ((route.REACH, True), (0.0, False)): + cells = route.grid([-0.1, -0.1, 0.0], [0.1, 0.1, 0.0], 0.02, rod, 0.043 + reach * 0.02) + free = [np.array(m) for m in zip(*np.nonzero(cells.free))] + least = min(float(rod(route.along(cells.lo + 0.02 * p, cells.lo + 0.02 * q, 0.001)).min()) + for p in free for q in free if 0 < np.abs(p - q).max() <= 1) + self.assertEqual(least >= 0.043, holds, least) + + def test_a_closed_way_a_buried_end_and_a_box_too_fine_are_refused_by_name(self): + distance = wall(0.03) # a hole narrower than the bundle + ends = (np.array([0.0, 0.0, 0.0]), np.array([2.0, 0.0, 0.0])) + with self.assertRaisesRegex(route.RouteError, r"^leg 2: no free way joins its ends"): + route.leg(*ends, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 2") + with self.assertRaisesRegex(route.RouteError, r"^leg 3: its end \[1, 0, 0\] stands 0 m from an obstacle, under the 0\.04 m"): + route.leg(ends[0], np.array([1.0, 0.0, 0.0]), distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 3") + with self.assertRaisesRegex(route.RouteError, r"^leg 4: its search box of \[2\.6, 0\.6, 0\.6\] m is \d+ voxels at step 0\.005, over 524288: a step of 0\.0\d+ fits"): + route.leg(*ends, distance, distance, NEED, 0.005, 0.3, 2 ** 19, "leg 4") + try: + route.leg(*ends, distance, distance, NEED, 0.005, 0.3, 2 ** 19, "leg 4") + except route.RouteError as error: + fits = float(str(error).split("a step of ")[1].split(" ")[0]) + self.assertLessEqual(int(np.prod(np.ceil(np.array([2.6, 0.6, 0.6]) / fits - 1e-9) + 1)), 2 ** 19) + with self.assertRaisesRegex(route.RouteError, "its start voxel is not free"): + route.wavefront(np.zeros((2, 2, 2), dtype=bool), (0, 0, 0), (1, 1, 1)) + + def test_a_wavefront_way_is_a_shortest_one(self): + free = np.ones((9, 9, 1), dtype=bool) + free[4, 1:, 0] = False # a wall with a gap at j = 0 + way = route.wavefront(free, (0, 8, 0), (8, 8, 0)) + self.assertEqual((way[0], way[-1], len(way)), ((0, 8, 0), (8, 8, 0), 17)) + self.assertIn((4, 0, 0), way) + self.assertTrue(all(max(abs(p[i] - q[i]) for i in range(3)) == 1 for p, q in zip(way[:-1], way[1:]))) + + +@unittest.skipIf(np is None, "numpy is not installed") +class FilletTests(unittest.TestCase): + ZIGZAG = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.3, 0.0], [2.0, 0.3, 0.4], [2.0, 1.5, 0.4]]) + + def test_every_arc_is_tangent_and_two_corners_share_a_segment(self): + """fillet-rule. Mutant H2 (arcs not tangent): the first chord of an arc leaves its segment at more than half a + step of the arc. Two corners on the 0.3 segment shrink until their tangents share it.""" + made = route.fillet(self.ZIGZAG, None, 0.01, 0.2) + lengths, unit, turn = route._turns(self.ZIGZAG) + self.assertTrue((made.t[:-1] + made.t[1:] <= lengths[1:-1] + 1e-12).all()) + self.assertAlmostEqual(float(made.t[0] + made.t[1]), 0.3, places=12) + self.assertAlmostEqual(float(made.t[0] / made.t[1]), min(0.8, 0.3) / min(0.3, float(lengths[2])), places=12) # in proportion to what each had alone + for c in range(3): + arc = made.curve[made.owner == c] + steps = max(2, math.ceil(turn[c] * route.ARC)) + self.assertEqual(len(arc), steps + (c != 1)) # arcs 0 and 1 meet on the shared segment: the point where they meet is listed once, as arc 0's + for chord, tangent in ((arc[1] - arc[0], unit[c]), (arc[-1] - arc[-2], unit[c + 1]))[c == 1:]: + self.assertAlmostEqual(math.acos(min(1.0, float(chord @ tangent) / float(np.linalg.norm(chord)))), turn[c] / steps / 2.0, places=9) + self.assertAlmostEqual(float(np.linalg.norm(arc[-1] - self.ZIGZAG[c + 1])), float(made.t[c]), places=12) + self.assertAlmostEqual(float(made.radii[c]), float(made.t[c] / math.tan(turn[c] / 2.0)), places=12) + + def test_the_leads_stay_straight(self): + """Mutant H1 (lead ignored): the first corner's tangent takes the whole first segment and the bend starts at + the ferrule.""" + made = route.fillet(np.array([[0.0, 0.0, 0.0], [0.3, 0.0, 0.0], [0.3, 2.0, 0.0], [0.3, 2.0, 0.5]]), None, 0.01, 0.2) + self.assertAlmostEqual(float(made.t[0]), 0.1, places=12) + self.assertAlmostEqual(float(made.t[1]), 0.3, places=12) + self.assertAlmostEqual(float(np.linalg.norm(made.curve[1] - made.curve[0])), 0.2, places=12) + self.assertAlmostEqual(float(np.linalg.norm(made.curve[-1] - made.curve[-2])), 0.2, places=12) + + def test_a_kept_straight_stays_in_the_middle_of_a_centred_segment(self): + points = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.5, 0.0], [3.0, 0.5, 1.0]]) + made = route.fillet(points, None, 0.01, 0.0, keep=[0.0, 0.1, 0.0], centred=[False, True, False]) + self.assertAlmostEqual(float(made.t[0]), 0.2, places=12) + self.assertAlmostEqual(float(made.t[1]), 0.2, places=12) + + def test_a_corner_that_wraps_an_obstacle_gets_the_radius_its_room_allows(self): + """Mutant H3 (the room cap off: radius by segments only): the arc cuts through the ball.""" + distance = ball([-0.25, 0.25, 0.0], 0.17) + points = np.array([[-1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]]) + room = room_of(distance, 0.05) + made = route.fillet(points, room, 0.05, 0.0) + radius, t = float(made.radii[0]), float(made.t[0]) + depth = 1.0 - math.cos(math.pi / 4.0) + measured = min(room(points[1] - np.array([1.0, 0.0, 0.0]) * t, points[1]), room(points[1], points[1] + np.array([0.0, 1.0, 0.0]) * t)) + self.assertLessEqual(radius * depth, measured + 1e-12) + self.assertGreater(radius, 0.03 / depth) # more than the room at the segments' nearest points allows: the room is measured along the tangent segments only + self.assertLess(radius, 0.25) + arc = made.curve[made.owner == 0] + self.assertGreaterEqual(float(distance(np.vstack([route.along(p, q, 0.001) for p, q in zip(arc[:-1], arc[1:])])).min()), 0.05) + grown = route.arcs(points, np.array([t * 1.05]))[0] # the largest: 5 percent more breaks the rule + t2 = t * 1.05 + self.assertGreater(t2 / math.tan(math.pi / 4.0) * depth, min(room(points[1] - np.array([1.0, 0.0, 0.0]) * t2, points[1]), room(points[1], points[1] + np.array([0.0, 1.0, 0.0]) * t2))) + self.assertEqual(len(grown), len(made.curve)) + free = route.fillet(points, None, 0.05, 0.0) + self.assertAlmostEqual(float(free.radii[0]), 1.0, places=12) + self.assertLess(float(distance(free.curve).min()), 0.0) + self.assertGreaterEqual(route.verify(made.curve, distance, 0.05, 0.0, 0.002), 0.05) + with self.assertRaisesRegex(route.RouteError, r"^the hose stands -0\.\d+ m from an obstacle at \[-0\.\d+, 0\.\d+, 0\], under the 0\.05 m"): + route.verify(free.curve, distance, 0.05, 0.0, 0.002) + + def test_a_corner_under_the_floor_is_refused_by_name(self): + with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[1, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.15 m, under the floor 0\.5"): + route.fillet(self.ZIGZAG, None, 0.5, 0.2) + with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[0, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.00\d+ m, under the floor 0\.05"): + route.fillet(np.array([[-1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]]), room_of(ball([-0.05, 0.05, 0.0], 0.02), 0.05), 0.05, 0.0) # a ball in the corner + + def test_the_floor_is_the_innermost_hose_s(self): + """Mutant H8 (the floor taken at the centre line): the innermost of three hoses bends tighter than bend + outside diameters.""" + sizes = route.bundle(3, 0.014, 0.0, 0.01, 4.0) + self.assertAlmostEqual(sizes["spread"], 0.0364, places=12) + self.assertAlmostEqual(sizes["floor"] - sizes["spread"], 4.0 * 0.028, places=12) + self.assertAlmostEqual(sizes["need"], 0.0364 + 0.014 + 0.01, places=12) + self.assertAlmostEqual(sizes["width"], 2 * 0.0364 + 0.028, places=12) + self.assertAlmostEqual(sizes["lead"], 5 * 0.014 + 1.5 * 0.028, places=12) + self.assertEqual(route.bundle(1, 0.01, 0.0, 0.0, 4.0)["floor"], 0.08) + + def test_a_span_sags_by_no_more_than_half_its_room(self): + """ruling hose-slack-and-skinned. Mutant S1 (the sag not bounded by the room): the span hangs into the floor + under it.""" + ground = lambda points: np.asarray(points, dtype=np.float64)[:, 2] # noqa: E731 + span = np.array([[0.0, 0.0, 0.1], [1.0, 0.0, 0.1]]) + hung, drop = route.sag(span, 0.1, room_of(ground, 0.05)) + self.assertAlmostEqual(drop, 0.025, places=12) + self.assertTrue(np.allclose(hung[1], [0.5, 0.0, 0.075])) + made = route.fillet(np.vstack([[[0.0, 0.0, 0.5]], hung, [[1.0, 0.0, 0.5]]]), room_of(ground, 0.05), 0.01, 0.1) + self.assertGreaterEqual(route.verify(made.curve, ground, 0.05, 0.1, 0.002), 0.05) + self.assertGreater(float(made.radii[1]), 1.0) # a gentle arc, not a kink + high, drop = route.sag(span + [0.0, 0.0, 1.0], 0.1, room_of(ground, 0.05)) + self.assertEqual((drop, len(high)), (0.1, 3)) + self.assertEqual(route.sag(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]), 0.1, None)[1], 0.0) # a vertical span does not sag + self.assertEqual(route.sag(span, 0.0, None)[1], 0.0) + leaning, drop = route.sag(np.array([[0.0, 0.0, 1.0], [1.0, 0.0, 2.0]]), 0.1, None) # across the span, by how far it runs from vertical + self.assertAlmostEqual(drop, 0.1 * math.sqrt(0.5), places=12) + self.assertAlmostEqual(float((leaning[1] - [0.5, 0.0, 1.5]) @ [1.0, 0.0, 1.0]), 0.0, places=12) + self.assertEqual(route.sag(np.array([[0.0, 0.0, 1.0], [0.5, 0.0, 1.0]]), 0.1, None)[1], 0.0) # too short for the drop + + +@unittest.skipIf(np is None, "numpy is not installed") +class FrameTests(unittest.TestCase): + @staticmethod + def reference(curve, tangent, up): + """The double reflection method as Wang et al. 2008 state it, a point at a time.""" + ups = [up] + for i in range(len(curve) - 1): + v1 = [curve[i + 1][k] - curve[i][k] for k in range(3)] + c1 = sum(v * v for v in v1) + dot = lambda a, b: sum(x * y for x, y in zip(a, b)) # noqa: E731 + r_left = [ups[-1][k] - 2.0 / c1 * dot(v1, ups[-1]) * v1[k] for k in range(3)] + t_left = [tangent[i][k] - 2.0 / c1 * dot(v1, tangent[i]) * v1[k] for k in range(3)] + v2 = [tangent[i + 1][k] - t_left[k] for k in range(3)] + c2 = dot(v2, v2) + ups.append([r_left[k] - 2.0 / c2 * dot(v2, r_left) * v2[k] for k in range(3)]) + return np.array(ups) + + @staticmethod + def tangents(curve): + steps = np.diff(curve, axis=0) + steps /= np.linalg.norm(steps, axis=1)[:, None] + tangent = np.vstack([steps[:1], steps[:-1] + steps[1:], steps[-1:]]) + return tangent / np.linalg.norm(tangent, axis=1)[:, None] + + def test_ups_are_rotation_minimising(self): + """frames-rmf. Mutant H7 (Frenet frames for ups): on a planar S the up leaves the plane's normal.""" + s = np.linspace(0.0, 2.0 * math.pi, 200) + planar = np.stack([s, np.sin(s), np.zeros_like(s)], axis=1) + ups = route.frames(planar, [0.0, 0.0, 1.0]) + self.assertLess(float(np.abs(ups - [0.0, 0.0, 1.0]).max()), 1e-12) + helix = np.stack([np.cos(s * 2.0), np.sin(s * 2.0), 0.3 * s], axis=1) + ups, tangent = route.frames(helix, [0.0, 0.0, 1.0]), self.tangents(helix) + self.assertLess(float(np.abs(np.einsum("ij,ij->i", ups, tangent)).max()), 1e-12) + self.assertLess(float(np.abs(np.linalg.norm(ups, axis=1) - 1.0).max()), 1e-12) + first = np.array([0.0, 0.0, 1.0]) - tangent[0] * tangent[0][2] + self.assertLess(float(np.abs(ups - self.reference(helix.tolist(), tangent.tolist(), (first / np.linalg.norm(first)).tolist())).max()), 1e-9) + with self.assertRaisesRegex(route.RouteError, "runs along the curve's first tangent"): + route.frames(planar, planar[1] - planar[0]) + + +@unittest.skipIf(np is None, "numpy is not installed") +class JointTests(unittest.TestCase): + P = np.array([[0.5, 0.0, 1.0], [0.2, 0.0, 0.0], [0.5, 0.0, -1.0]]) # through a point on the x axis + AXIS = (np.zeros(3), np.array([1.0, 0.0, 0.0])) + SIZES = {"need": 0.05, "floor": 0.05, "lead": 0.1, "spacing": 0.01} + + def test_a_polyline_through_the_axis_keeps_its_length_at_every_roll(self): + """joint-passage.""" + rolls = route.rolls_of(-120.0, 10.0, 5.0) + self.assertEqual((len(rolls), rolls[0], rolls[-2], rolls[-1]), (27, -120.0, 5.0, 10.0)) + self.assertEqual(route.rolls_of(0.0, 12.0, 5.0), [0.0, 5.0, 10.0, 12.0]) + for roll in rolls: + posed = np.vstack([self.P[:2], route.turned(self.P[2:], *self.AXIS, roll)]) + self.assertAlmostEqual(length(posed), length(self.P), places=12) + self.assertTrue(np.allclose(route.turned(np.array([[0.3, 1.0, 0.0]]), *self.AXIS, 90.0), [[0.3, 0.0, 1.0]])) # right-handed about +x + t = route.fillet(self.P, None, 0.05, 0.1).t + found = route.passes(self.P, t, 1, *self.AXIS, rolls, 0.0, nothing, nothing, **self.SIZES) + self.assertEqual((found["rolls"], found["least"]), (27, 10.0)) + self.assertGreater(found["lengthChange"], 0.01) # the bend at the pin is what changes: each roll's is the largest arc its segments give + self.assertLess(found["lengthChange"], length(self.P) * (1.0 - math.pi / 4.0) * 2.0) # no more than every corner's shortcut + + def test_a_hairpin_roll_is_refused_by_name(self): + t = route.fillet(self.P, None, 0.05, 0.1).t + with self.assertRaisesRegex(route.RouteError, r"^roll 180: the bend at the pin turns 180\.0 degrees and gets radius \S+e-\d+ m, under the floor 0\.05"): + route.passes(self.P, t, 1, *self.AXIS, [0.0, 90.0, 180.0], 0.0, nothing, nothing, **self.SIZES) + + def test_each_side_is_measured_against_the_other_where_the_roll_puts_it(self): + """Mutants H5 (the child's obstacles not turned with the roll) and H6 (the range checked at its ends only): a + part of the child that the roll carries into the parent's side of the hose, between the ends of the range.""" + middle = (self.P[0] + self.P[1]) / 2.0 + child = ball(route.turned(middle[None], *self.AXIS, -45.0)[0], 0.05) # where it stands at roll 0 + t = route.fillet(self.P, None, 0.05, 0.1).t + for ends in ([-90.0, 90.0], [0.0]): + self.assertEqual(route.passes(self.P, t, 1, *self.AXIS, ends, 0.0, nothing, child, **self.SIZES)["rolls"], len(ends)) + with self.assertRaisesRegex(route.RouteError, r"^roll 35: the hose's parent's side stands 0\.0\d+ m from the parts on the other side of the pin, under the 0\.05 m"): + route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-90.0, 90.0, 5.0), 0.0, nothing, child, **self.SIZES) + seen = [] + route.passes(self.P, t, 1, *self.AXIS, [30.0], 10.0, nothing, lambda points: seen.append(np.array(points)) or nothing(points), **self.SIZES) + line = (self.P[1] - self.P[0]) / np.linalg.norm(self.P[1] - self.P[0]) + on = [points for points in seen if len(points) > 3 and np.abs(np.cross(route.turned(points, *self.AXIS, 20.0) - self.P[0], line)).max() < 1e-12] + self.assertTrue(on) # the parent's side was read turned back by roll - current: turned forward again it lies on its own segment + self.assertTrue(all(np.abs(np.cross(points - self.P[0], line)).max() > 0.01 for points in on)) + parent = ball(route.turned(((self.P[1] + self.P[2]) / 2.0)[None], *self.AXIS, 45.0)[0], 0.05) # a part of the parent the child's side swings into + with self.assertRaisesRegex(route.RouteError, r"^roll 35: the hose's child's side stands"): + route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-90.0, 90.0, 5.0), 0.0, parent, nothing, **self.SIZES) + + +if __name__ == "__main__": + unittest.main() From 305efd541f5d973d73b53bfe8ac8cccbe531747b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 16:21:10 +0100 Subject: [PATCH 116/223] mechanical kit: socket type hose, and port_cap and port_rod on the actuator's port bosses (cut kit-hose) Co-Authored-By: Claude Fable 5.2 --- .../blender/brokkr_kitbash/kits/mechanical.v0.json | 7 +++++-- surfaces/blender/tests/test_kitbash.py | 10 ++++------ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json index 1da5a7b..027e85a 100644 --- a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json @@ -5,7 +5,8 @@ "socketTypes": { "flange": {"match": "equal", "doc": "bolted pipe or duct face; size is the bore diameter"}, "mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"}, - "pivot": {"match": "equal", "doc": "pin joint; size is the pin diameter"} + "pivot": {"match": "equal", "doc": "pin joint; size is the pin diameter"}, + "hose": {"match": "fits", "doc": "hose port; size is the widest bundle it takes"} }, "parts": [ { @@ -173,7 +174,9 @@ {"name": "base", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "0.8*body_r"], "z": "+y", "y": "+z"}, {"name": "base_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "0.8*body_r"], "z": "-y", "y": "+z"}, {"name": "rod_end", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "3.8*body_r+body_len+extension"], "z": "+y", "y": "+z"}, - {"name": "rod_end_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "3.8*body_r+body_len+extension"], "z": "-y", "y": "+z"} + {"name": "rod_end_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "3.8*body_r+body_len+extension"], "z": "-y", "y": "+z"}, + {"name": "port_cap", "type": "hose", "size": "0.4*body_r", "at": ["1.45*body_r", 0, "1.75*body_r"], "z": "+x", "y": "+z"}, + {"name": "port_rod", "type": "hose", "size": "0.4*body_r", "at": ["1.45*body_r", 0, "2.25*body_r+body_len"], "z": "+x", "y": "+z"} ] }, { diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 55c0723..1a099d4 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -565,15 +565,15 @@ class MechanicalKitTests(unittest.TestCase): def setUpClass(cls): cls.kit = core.load_kit("mechanical") - def test_the_kit_is_the_eleven_parts_and_three_socket_types(self): + def test_the_kit_is_the_eleven_parts_and_four_socket_types(self): self.assertEqual(list(self.kit["parts"]), self.PARTS) - self.assertEqual({k: v["match"] for k, v in self.kit["socketTypes"].items()}, {"flange": "equal", "mount": "fits", "pivot": "equal"}) + self.assertEqual({k: v["match"] for k, v in self.kit["socketTypes"].items()}, {"flange": "equal", "mount": "fits", "pivot": "equal", "hose": "fits"}) self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, { "nozzle": [("mount", "flange")], "tank": [("port_a", "flange"), ("port_b", "flange"), ("saddle", "mount"), ("lug_a", "mount"), ("lug_b", "mount"), ("lug_a_back", "mount"), ("lug_b_back", "mount")], "ribbed_cylinder": [("end_a", "flange"), ("end_b", "flange")], "strut": [("end_a", "pivot"), ("end_a_back", "pivot"), ("end_b", "pivot"), ("end_b_back", "pivot")], - "actuator": [("base", "pivot"), ("base_back", "pivot"), ("rod_end", "pivot"), ("rod_end_back", "pivot")], + "actuator": [("base", "pivot"), ("base_back", "pivot"), ("rod_end", "pivot"), ("rod_end_back", "pivot"), ("port_cap", "hose"), ("port_rod", "hose")], "pipe_fitting": [("a", "flange"), ("b", "flange"), ("c", "flange")], "radiator_stack": [("base", "mount")], "vent": [("back", "mount")], "plate": [("back", "mount"), ("front", "mount")], "reducer": [("big", "flange"), ("small", "flange")], "bracket": [("mount", "mount"), ("pivot", "pivot"), ("pivot_back", "pivot")]}) @@ -811,8 +811,6 @@ class FrameKitTests(unittest.TestCase): """frame-kit-holds. Mutant E10 (frame's mount declared 'equal'): the types differ from mechanical's.""" self.assertEqual(list(self.kit["parts"]), self.PARTS) self.assertEqual(self.kit["socketTypes"], {name: self.mechanical["socketTypes"][name] for name in ("mount", "pivot")}) - lines = lambda name: [line for line in (core.KITS / f"{name}.v0.json").read_text(encoding="utf-8").split("\n") if line.startswith((' "mount"', ' "pivot"'))] # noqa: E731 - self.assertEqual((lines("frame"), len(lines("frame"))), (lines("mechanical"), 2)) # byte for byte ends = [("end_a", "mount"), ("end_b", "mount")] self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, { "beam_i": ends, "channel": ends, "tee": ends, "angle": ends, "box_beam": ends, "truss": ends, @@ -1943,7 +1941,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", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json"]) + self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json", "route.py"]) for pattern in self.PACKAGE: for name, text in self.sources().items(): if pattern is self.PACKAGE[2] and name == "__init__.py": From ee45731e001bf32d3587a8830c3b0a8443949777 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 16:43:06 +0100 Subject: [PATCH 117/223] brokkr_kitbash.hose: a hose bundle routed between two sockets, clamped, through a pin's axis across its roll range (cut kit-hose) The action is the bpy around route.py: ends and clamps from kit sockets, the crossed pin from the parent chain, obstacles from every evaluated mesh as two trees split at the pin, one mesh object swept by core.sweep. Each free span sags a little, bounded by its measured room, and a hose stays one object across a pin (ruling hose-slack-and-skinned). Row in brokkr_actions.json; tests/live/kitbash_hose.py and its result. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 319 ++++++++++++++- .../brokkr_kitbash/brokkr_actions.json | 105 +++++ surfaces/blender/brokkr_kitbash/route.py | 14 + surfaces/blender/tests/live/kitbash_hose.py | 364 ++++++++++++++++++ .../tests/live/kitbash_hose.result.json | 340 ++++++++++++++++ surfaces/blender/tests/test_kitbash.py | 47 ++- surfaces/blender/tests/test_route.py | 7 + 7 files changed, 1191 insertions(+), 5 deletions(-) create mode 100644 surfaces/blender/tests/live/kitbash_hose.py create mode 100644 surfaces/blender/tests/live/kitbash_hose.result.json diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 076453a..57c6f17 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -49,6 +49,13 @@ shell is the one writer of the mesh, its crease attributes and those two modifie object rewrites the mesh in place, leaving the object, its cutters, ribs, Booleans and material slots. shell evaluates nothing: Blender's own update after the action evaluates the plate once. +hose routes a bundle of hoses between two sockets. route.py owns the path (legs searched on a voxel grid of the +scene's clearance, pulled taut, sagged a little, filleted, verified, and turned through the rolls of the one pin it may +cross) and core.sweep owns every tube, ferrule and clamp. A hose is a bake of the scene at the call: posing or moving a +part leaves it stale until hose runs again on its name. It is one object: where it crosses a pin it is meant to be +skinned between the bones on either side, and this package writes no weights. kit_hose on it is the request, kept as +a record: nothing reads it to decide geometry, and hose is its one writer. + 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 @@ -73,7 +80,7 @@ try: except ImportError as error: # register() says so; the classes below only need something to subclass RESULT, PolishOperator, Refused, mesh_object, MISSING = "brokkr_mesh_polish_result", bpy.types.Operator, RuntimeError, None, error -from . import core +from . import core, route KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" SOCKET, PARENT_SOCKET, ROLL, BAKED = "kit_socket", "kit_parent_socket", "kit_roll", "kit_baked" @@ -89,6 +96,12 @@ LONGERONS_LIMIT = 16 # longerons in one ribs SHELL = "kit_shell" # on a shell: the request its cage is derived from, as JSON; its presence admits a rebuild, and nothing reads it to decide geometry SUBSURF, SOLIDIFY = "Kit Subsurf", "Kit Solidify" # a shell's own modifiers, in that order, before any of its Booleans and the Kit Bevel SHELL_FACES_LIMIT = 262144 # faces of a shell's subdivided surface: cage quads times 4 to the levels +HOSE = "kit_hose" # on a hose: the request it was routed from, as JSON; its presence admits a rebuild, and nothing reads it to decide geometry +HOSE_CLAMPS = 8 # clamps in one hose: each is one more leg to search +HOSE_VOXELS = 2 ** 19 # voxels of one leg's search box: 1.8 s of capped nearest-face queries at 3.4 us each +HOSE_MARGIN = 0.25 # metres a leg's search box reaches beyond its two ends: the room a way around an obstacle between them has +HOSE_SEGMENTS = 12 # sides of a hose, a ferrule and a clamp's pad +ROLL_STEP = 5.0 # degrees between the rolls of a joint's range that hose measures: the step an assembly's clearance is read at def kit_work(work): @@ -1405,6 +1418,308 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): evaluated.to_mesh_clear() +class BROKKR_KITBASH_OT_hose(PolishOperator): + """Route a bundle of hoses between two sockets around every mesh in the scene, through clamps on mount sockets and + through a point on a pin's axis across the pin's roll range; on an object that is already a hose, rebuild it in + place""" + bl_idname = "brokkr_kitbash.hose" + bl_label = "Route A Hose" + object_name: bpy.props.StringProperty(name="Object", description="The hose's name: a new object, or a hose to rebuild") + start: bpy.props.StringProperty(name="Start", description="'Object:socket', a hose or flange socket of a kit part; or 'Object', an empty whose z the hose leaves along") + end: bpy.props.StringProperty(name="End", description="As start") + count: bpy.props.IntProperty(name="Count", default=1, min=1, max=8, description="Hoses in the bundle, side by side") + radius: bpy.props.FloatProperty(name="Radius", default=0.01, min=0.0029, max=0.1, description="A hose's outside radius") + spread: bpy.props.FloatProperty(name="Spread", default=0.0, min=0.0, max=0.5, description="Centre to centre between hoses; 0: 2.6 radii") + clearance: bpy.props.FloatProperty(name="Clearance", default=0.01, min=0.0, max=0.5, description="Free space kept between the bundle and every other mesh") + bend: bpy.props.FloatProperty(name="Bend", default=4.0, min=1.0, max=20.0, description="Least bend radius of the innermost hose, in outside diameters") + step: bpy.props.FloatProperty(name="Step", default=0.02, min=0.0049, max=0.2, description="Voxel size of the search") + sag: bpy.props.FloatProperty(name="Sag", default=1.0, min=0.0, max=8.0, description="How far the middle of each free span hangs, in outside diameters; 0: taut") + clamps: bpy.props.StringProperty(name="Clamps", default="[]", description="A JSON array of up to 8 {socket: 'Object:socket'}, mount sockets, in order along the hose") + joint: bpy.props.StringProperty(name="Joint", default="", description="Empty, or a JSON object {socket, standoff, range: [lo, hi]}: the pin the hose crosses") + + # the action table states radius from 0.003 and step from 0.005: a float property rounds those up, so its bounds stand just under + @kit_work + def work(self, context): + if not 1 <= len(self.object_name) <= 63: + raise Refused(f"object_name {self.object_name!r} must be 1 to 63 characters; nothing changed.") + hose = bpy.data.objects.get(self.object_name) + if hose is not None: + if hose.type != "MESH" or HOSE not in hose: + raise Refused(f"An object named {hose.name!r} exists and is no hose (it carries no {HOSE}): hose rebuilds only what hose made; nothing changed.") + own_mesh(hose, "rebuilding") + sizes = route.bundle(self.count, self.radius, self.spread, self.clearance, self.bend) + r, need, floor, lead, half_width = self.radius, sizes["need"], sizes["floor"], sizes["lead"], sizes["envelope"] - self.radius + kits = {} + start, end = (self.frame(context, text, what, ("hose", "flange"), kits, True) for text, what in ((self.start, "start"), (self.end, "end"))) + for what, port in (("start", start), ("end", end)): + if port["size"] is not None and sizes["width"] > port["size"] * (1.0 + core.SLACK): + raise Refused(f"{what}: a bundle of {self.count} hoses is {sizes['width']:.6g} m wide, over socket {port['name']!r} ({port['type']}, size {port['size']:.6g}): " + "use fewer or thinner hoses, a smaller spread, or a larger port; nothing changed.") + clamp_rows, joint = self.rows() + clamps = [self.frame(context, row, f"clamps[{index}]", ("mount",), kits) for index, row in enumerate(clamp_rows)] + pins, pin = self.crossed(start["object"], end["object"], kits), None + if joint is None and pins: + raise Refused(f"The hose crosses the pin of {pins[0][0].name!r} on {pins[0][0].parent.name!r} (socket {pins[0][1]['name']!r}): give joint, a socket on that pin's axis, " + "a standoff and the roll range; nothing changed.") + if joint is not None and len(pins) != 1: + raise Refused(("joint is given and the hose crosses no pin: its ends are on parts no pivot connection stands between" if not pins else + f"The hose crosses {len(pins)} pins ({', '.join(repr(child.name) + ' on ' + repr(child.parent.name) for child, _, _ in pins)}): a hose crosses one; " + "end it on a part between them and route the next from there") + "; nothing changed.") + if pins: + child, socket, current = pins[0] + if current is None: + raise Refused(f"{child.name!r} on {child.parent.name!r}: its {ROLL} is not a number: detach it and attach it again; nothing changed.") + on = self.frame(context, joint["socket"], "joint.socket", None, kits) + axis = np.array(child.parent.matrix_world) @ socket["matrix"] + off = float(np.linalg.norm(np.cross(on["matrix"][:3, 3] - axis[:3, 3], axis[:3, 2]))) + lean = float(np.linalg.norm(np.cross(on["matrix"][:3, 2], axis[:3, 2]))) + if off > 1e-6 or lean > 1e-6: + raise Refused(f"joint.socket {on['name']!r} is not on the axis of the pin the hose crosses ({child.name!r} on {child.parent.name!r}, socket {socket['name']!r}): " + f"its origin stands {off:.6g} m off the axis and its z leans {math.degrees(math.asin(min(1.0, lean))):.6g} degrees from it; nothing changed.") + if not joint["range"][0] - 1e-9 <= current <= joint["range"][1] + 1e-9: + raise Refused(f"{child.name!r} stands at roll {current:.6g}, outside joint.range {joint['range']}: the range holds the pose the hose is routed at; nothing changed.") + sides = [child in self.chain(stop["object"]) for stop in (start, *clamps, end)] + changes = [index for index in range(len(sides) - 1) if sides[index] != sides[index + 1]] + if len(changes) != 1: + raise Refused(f"clamps cross the pin of {child.name!r} {len(changes)} times: list them in order along the hose, those on the start's side of the pin first; nothing changed.") + pin = {"origin": axis[:3, 3], "axis": axis[:3, 2], "current": current, "before": changes[0], "child": child, "child_first": sides[0], + "point": on["matrix"][:3, 3] + on["matrix"][:3, 2] * joint["standoff"]} + rest, moved = self.trees(start["depsgraph"], hose, pin and pin["child"]) + reach = need + 2.0 * floor + self.step + occupied = self.reader((rest, moved), need + route.REACH * self.step) + far, far_rest, far_moved = self.reader((rest, moved), reach), self.reader((rest,), reach), self.reader((moved,), reach) + room = lambda a, b: float(far(route.along(a, b, self.step / 2.0)).min()) - need # noqa: E731 + exempt = max(lead, need) # a bundle wider than its lead stands on its own port's face that far + stand = sizes["envelope"] + self.clearance + r # a clamped bundle's centre line above the socket's face: its pad is one radius thick + held = 2.0 * 2.0 * r + floor + try: + ends = [port["matrix"][:3, 3] + port["matrix"][:3, 2] * (lead + floor) for port in (start, end)] # a leg starts where the first bend has its floor's length of straight behind it + stops = [("clamp", f"clamps[{index}]", clamp["matrix"][:3, 3] + clamp["matrix"][:3, 2] * stand, clamp["matrix"][:3, 1]) for index, clamp in enumerate(clamps)] + if pin is not None: + stops.insert(pin["before"], ("pin", "the pin", pin["point"], None)) + legs, at, came = [], ends[0], "start" + for kind, label, point, y in stops + [("end", "end", ends[1], None)]: + into, out = point, point + if kind == "clamp": + into, out = sorted((point - y * held, point + y * held), key=lambda p: float(np.linalg.norm(p - at))) + pulled, voxels = route.leg(at, into, occupied, far, need, self.step, HOSE_MARGIN, HOSE_VOXELS, f"leg {len(legs) + 1} ({came} to {label})") + legs.append((pulled, voxels, kind, out)) + at, came = out, label + shaped, refusal = None, None + for depth in dict.fromkeys((self.sag * 2.0 * r, 0.0)): # slack yields to clearance: a route the sag breaks is made taut + try: + shaped = self.shaped(legs, start, end, depth, room, far, far_rest, far_moved, pin, joint, need, floor, lead, exempt, 4.0 * 2.0 * r) # a clamp keeps 2 outside diameters of straight each side of its point + break + except route.RouteError as error: + refusal = refusal or error + if shaped is None: + raise refusal + curve, made, sagged, least, swing = shaped + built = self.built(curve, start, clamps, stand, r, sizes["spread"], half_width) + except route.RouteError as error: + raise Refused(f"{error}; nothing changed.") from None + world = np.array(start["object"].matrix_world) + built = built._replace(V=(built.V - world[:3, 3]) @ world[:3, :3]) # into the start's object's frame: the hose is its child + rebuilt = hose is not None + if rebuilt: + mesh = hose.data + mesh.clear_geometry() + else: + mesh = bpy.data.meshes.new(self.object_name) + write_mesh(mesh, built) + if not rebuilt: + hose = bpy.data.objects.new(self.object_name, mesh) + context.scene.collection.objects.link(hose) + hose.parent = start["object"] + hose.matrix_world = start["object"].matrix_world.copy() # read by a report; no depsgraph update here + seat(hose, np.eye(4)) + hose[HOSE] = json.dumps({"object_name": self.object_name, "start": self.start, "end": self.end, "count": self.count, "radius": self.radius, "spread": self.spread, + "clearance": self.clearance, "bend": self.bend, "step": self.step, "sag": self.sag, "clamps": json.loads(self.clamps), + "joint": json.loads(self.joint) if self.joint else None}) + radii = made.radii[np.isfinite(made.radii)] + report = {"object": hose.name, "rebuilt": rebuilt, "hoses": self.count, "length": round(float(np.linalg.norm(np.diff(curve, axis=0), axis=1).sum()), 6), + "lengthChange": None if swing is None else round(swing["lengthChange"], 6), "floor": round(floor, 6), + "clearance": None if not math.isfinite(least) else round(least - sizes["envelope"], 6), "capped": round(reach - sizes["envelope"], 6), + "voxels": [voxels for _, voxels, _, _ in legs], "sag": [round(drop, 6) for drop in sagged], + "rolls": None if swing is None else swing["rolls"], "worstRoll": None if swing is None else swing["worstRoll"], + "worstClearance": None if swing is None or not math.isfinite(swing["least"]) else round(swing["least"] - sizes["envelope"], 6), **measured(mesh)} + report["radii"] = {"least": round(float(radii.min()), 6) if len(radii) else None} + report["radii"]["corners"] = fitted(report, "corners", [round(float(v), 6) for v in radii]) + return report + + @staticmethod + def chain(obj) -> list: + """An object and its parents, nearest first.""" + found = [] + while obj is not None: + found.append(obj) + obj = obj.parent + return found + + @staticmethod + def frame(context, text: str, what: str, kinds, kits, loose: bool = False) -> dict: + """What a hose reads at 'Object:socket': {object, matrix (the socket's world frame), size, type, name, depsgraph}. + The socket is a kit part's, of one of `kinds` (any when None); with `loose`, 'Object' alone names an empty and + its own frame. Refuses a name with no object, a part that is scaled (rigid), a socket the part does not have or + of another type, and an object Blender does not evaluate.""" + name, socket = (text, "") if text in bpy.data.objects or ":" not in text else text.rsplit(":", 1) + obj = bpy.data.objects.get(name) + if obj is None: + raise Refused(f"{what}: no object named {name!r}; nothing changed.") + if not socket: + if not loose or obj.type != "EMPTY": + raise Refused(f"{what} {text!r} names no socket: give 'Object:socket'" + (", or an empty whose z the hose leaves along" if loose else "") + "; nothing changed.") + rigid(obj) + return {"object": obj, "matrix": np.array(obj.matrix_world), "size": None, "type": "empty", "name": text, "depsgraph": evaluable(context, obj)[0]} + part, built = built_part(obj, kits) + found = [s for s in built.sockets if s["name"] == socket] + if not found: + raise Refused(f"{what}: {obj.name!r} (a {part['name']}) has no socket {socket!r}; its sockets: {', '.join(s['name'] for s in built.sockets) or 'none'}; nothing changed.") + if kinds is not None and found[0]["type"] not in kinds: + raise Refused(f"{what}: socket {socket!r} of {obj.name!r} is a {found[0]['type']} socket; this takes a {' or '.join(kinds)} socket; nothing changed.") + return {"object": obj, "matrix": np.array(obj.matrix_world) @ found[0]["matrix"], "size": found[0]["size"], "type": found[0]["type"], "name": text, + "depsgraph": evaluable(context, obj)[0]} + + def rows(self): + """(the clamps' 'Object:socket' texts, the joint as {socket, standoff, range} or None), each refused by shape.""" + try: + clamps, joint = json.loads(self.clamps or "[]"), json.loads(self.joint) if self.joint else None + except ValueError as error: + raise Refused(f"clamps and joint must be JSON ({error}); nothing changed.") from None + if not isinstance(clamps, list) or len(clamps) > HOSE_CLAMPS: + raise Refused(f"clamps must be a JSON array of 0 to {HOSE_CLAMPS} objects; nothing changed.") + for index, row in enumerate(clamps): + if not isinstance(row, dict) or set(row) != {"socket"} or not isinstance(row["socket"], str): + raise Refused(f"clamps[{index}] must be an object of socket, an 'Object:socket' text; nothing changed.") + if joint is not None: + span = joint.get("range") if isinstance(joint, dict) else None + if (not isinstance(joint, dict) or set(joint) != {"socket", "standoff", "range"} or not isinstance(joint["socket"], str) + or not (core.finite(joint["standoff"]) and 0.0 <= joint["standoff"] <= 10.0) + or not (isinstance(span, list) and len(span) == 2 and all(core.finite(v) and -360.0 <= v <= 360.0 for v in span) and 0.0 <= span[1] - span[0] <= 360.0)): + raise Refused("joint must be an object of socket (an 'Object:socket' text), standoff (0 to 10) and range ([lo, hi] in degrees, lo to hi at most 360, each within 360 of 0); nothing changed.") + return [row["socket"] for row in clamps], joint + + def crossed(self, start, end, kits) -> list: + """The pins between two objects, [(child, the parent's pivot socket, roll)]: a connection is a child's parent + pointer and its kit_parent_socket (link), and it is a pin when that socket is a pivot. Read along both parent + chains up to the first object they share; with none shared, along both whole chains.""" + up, down = self.chain(start), self.chain(end) + shared = [obj for obj in up if obj in down] + between = up[:up.index(shared[0])] + down[:down.index(shared[0])] if shared else up + down + pins = [] + for child in between: + stated = link(child) + if stated is None or child.parent is None or PART not in child.parent: + continue + socket = [s for s in built_part(child.parent, kits)[1].sockets if s["name"] == stated[1] and s["type"] == "pivot"] + if socket: + pins.append((child, socket[0], stated[2])) + return pins + + def trees(self, depsgraph, hose, child): + """(a tree of every mesh the depsgraph evaluates but this hose and the pin's child side, a tree of the child + side: the objects whose parent chain passes `child`), in world space; None for a side with no face. Membership + of the depsgraph is what makes a mesh an obstacle: no flag or name is read. Only evaluated meshes are read: no + datablock is made or freed.""" + sides = ([], []) + for evaluated in depsgraph.objects: + source = evaluated.original + if evaluated.type != "MESH" or source == hose or not len(evaluated.data.polygons): + continue + mesh, world = evaluated.data, np.array(evaluated.matrix_world) + points = np.zeros(3 * len(mesh.vertices)) + mesh.vertices.foreach_get("co", points) + mesh.calc_loop_triangles() + corners = np.zeros(3 * len(mesh.loop_triangles), dtype=np.int32) + mesh.loop_triangles.foreach_get("vertices", corners) + sides[child is not None and child in self.chain(source)].append((points.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3], corners.reshape(-1, 3))) + made = [] + for side in sides: + offsets = np.cumsum([0] + [len(points) for points, _ in side[:-1]]) + made.append(BVHTree.FromPolygons(np.vstack([points for points, _ in side]).tolist(), np.vstack([corners + offset for (_, corners), offset in zip(side, offsets)]).tolist()) + if side else None) + return made + + @staticmethod + def reader(trees, cap: float): + """A route distance over trees: how far each point stands from the nearest face, no further than cap (a capped + find_nearest costs 3.4 us on 82,000 faces where an uncapped one costs 100).""" + def distance(points): + out = np.full(len(points), cap) + for tree in trees: + if tree is not None: + for index, point in enumerate(np.asarray(points, dtype=np.float64).tolist()): + found = tree.find_nearest(point, cap)[3] + if found is not None and found < out[index]: + out[index] = found + return out + return distance + + def shaped(self, legs, start, end, depth, room, far, far_rest, far_moved, pin, joint, need, floor, lead, exempt, kept): + """(curve, its fillet, the metres each leg sagged, the least distance outside the leads, the joint's passes or + None) of the legs joined at one sag depth: one polyline from port to port, one fillet, one verification, and + with a pin every roll of its range from the range's low to its high every ROLL_STEP degrees.""" + points, keep, centred, sagged, j, last = [start["matrix"][:3, 3]], [], [], [], None, None + for pulled, _, kind, _ in legs: + hung, drop = route.sag(pulled, depth, room) + sagged.append(drop) + hung = hung[1:] if last == "pin" else hung # a leg from the pin point starts on the point the last one ended on + points += list(hung) + keep += [kept if last == "clamp" else 0.0] + [0.0] * (len(hung) - 1) # a leg from a clamp starts at the far end of the clamp's straight + centred += [last == "clamp"] + [False] * (len(hung) - 1) + if kind == "pin": + j = len(points) - 1 + last = kind + points.append(end["matrix"][:3, 3]) + keep.append(0.0) + centred.append(False) + points = np.array(points) + made = route.fillet(points, room, floor, lead, keep, centred) + least = route.verify(made.curve, far, need, exempt, self.step / 2.0) + swing = None + if pin is not None: + order = slice(None, None, -1) if pin["child_first"] else slice(None) # passes reads a polyline from the parent's side + swing = route.passes(points[order], made.t[order], (len(points) - 1 - j) if pin["child_first"] else j, pin["origin"], pin["axis"], + route.rolls_of(joint["range"][0], joint["range"][1], ROLL_STEP), pin["current"], far_rest, far_moved, need, floor, exempt, self.step / 2.0, + keep=np.array(keep)[order]) + return made.curve, made, sagged, least, swing + + def built(self, curve, start, clamps, stand, r, spread, half_width): + """The mesh, in world space: each hose swept along the curve offset across the bundle, two ferrule collars at + each of its ends, and at each clamp a pad on the socket's face and a strap around the bundle. The ups are + route.frames', turned so the bundle lies flat on the first clamp.""" + curve = route.thinned(curve, 0.05 * r) # an arc's chord is at least a twelfth of a radius at the least bend + steps = np.diff(curve, axis=0) + steps /= np.linalg.norm(steps, axis=1)[:, None] + tangent = np.vstack([steps[:1], steps[:-1] + steps[1:], steps[-1:]]) + tangent /= np.linalg.norm(tangent, axis=1)[:, None] + ups = route.frames(curve, start["matrix"][:3, 1]) + seats = [int(np.argmin(np.linalg.norm(curve - (clamp["matrix"][:3, 3] + clamp["matrix"][:3, 2] * stand), axis=1))) for clamp in clamps] + if clamps: # rotation-minimising ups keep their angle to each other: turning the first turns every one as much + k, z = seats[0], clamps[0]["matrix"][:3, 2] + turn = math.atan2(float(tangent[k] @ np.cross(ups[k], z)), float(ups[k] @ z)) + ups = route.frames(curve, ups[0] * math.cos(turn) + np.cross(tangent[0], ups[0]) * math.sin(turn)) + side = np.cross(ups, tangent) + shells, section = [], core.circle(r, HOSE_SEGMENTS) + for index in range(self.count): + path = curve + side * ((index - (self.count - 1) / 2.0) * spread) + shells.append(core.sweep(path, section, ups)) + for at, along_, up in ((path[0], tangent[0], ups[0]), (path[-1], -tangent[-1], ups[-1])): + shells.append(core.sweep([at, at + along_ * 4.5 * r], core.circle(1.45 * r, HOSE_SEGMENTS), up)) + shells.append(core.sweep([at + along_ * 4.5 * r, at + along_ * 6.0 * r], core.circle(1.2 * r, HOSE_SEGMENTS), up)) + band, reach = 0.5 * r, 1.25 * r + 1e-4 # a strap's thickness, and its mid-line's distance from a hose's centre + for clamp, k in zip(clamps, seats): + centre, across, up = curve[k], side[k], ups[k] + turns = np.radians(np.arange(-90.0, 90.0 + 1e-9, 30.0)) + loop = ([centre + across * (half_width + reach * math.cos(a)) + up * (reach * math.sin(a)) for a in turns] + + [centre - across * (half_width + reach * math.cos(a)) - up * (reach * math.sin(a)) for a in turns]) + loop = np.array(loop if half_width > 1e-9 else loop[:6] + loop[7:13]) + shells.append(core.sweep(loop, core.profile("box", band, 2.0 * r, band), tangent[k], closed=True)) + face, out = clamp["matrix"][:3, 3], clamp["matrix"][:3, 2] + shells.append(core.sweep([face, face + out * (float(((loop - face) @ out).min()) + 0.25 * band)], core.circle(1.5 * r + 0.5 * half_width, HOSE_SEGMENTS), clamp["matrix"][:3, 1])) + return core.joined(shells) + + class BROKKR_KITBASH_OT_describe(PolishOperator): """List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame at default params""" @@ -1437,7 +1752,7 @@ class BROKKR_KITBASH_OT_report(PolishOperator): classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report, BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach, BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply, BROKKR_KITBASH_OT_ribs, - BROKKR_KITBASH_OT_shell) + BROKKR_KITBASH_OT_shell, BROKKR_KITBASH_OT_hose) def register(): diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 2f5db7d..2988f00 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -781,6 +781,111 @@ "doc": "evaluate the wall (Kit Subsurf and Kit Solidify alone) and report folded, the number of its inner faces that fold over" } ] + }, + { + "name": "brokkr_kitbash.hose", + "doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut, and the whole polyline is rounded, each corner by the largest arc its measured room allows; the innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a pivot connection between its ends' parts): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres, \"range\": [lo, hi]}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. Every roll from lo to hi in steps of 5 degrees is measured, each side against the other side's parts where the roll puts them, without posing anything. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, sag per leg in metres, rolls, worstRoll, worstClearance, faces, volume, nonManifoldEdges and radii {least, corners}.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the hose's name: no object's name, or a hose's, which is then rebuilt" + }, + { + "name": "start", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 96, + "doc": "'Object:socket' (a hose or flange socket of a kit part), or 'Object' (an empty: the hose leaves along its z)" + }, + { + "name": "end", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 96, + "doc": "as start" + }, + { + "name": "count", + "type": "integer", + "minimum": 1, + "maximum": 8, + "default": 1, + "doc": "hoses in the bundle, side by side" + }, + { + "name": "radius", + "type": "number", + "minimum": 0.003, + "maximum": 0.1, + "default": 0.01, + "doc": "a hose's outside radius" + }, + { + "name": "spread", + "type": "number", + "minimum": 0, + "maximum": 0.5, + "default": 0, + "doc": "centre to centre between hoses; 0: 2.6 radii" + }, + { + "name": "clearance", + "type": "number", + "minimum": 0, + "maximum": 0.5, + "default": 0.01, + "doc": "free space kept between the bundle and every other mesh" + }, + { + "name": "bend", + "type": "number", + "minimum": 1, + "maximum": 20, + "default": 4, + "doc": "least bend radius of the innermost hose, in outside diameters" + }, + { + "name": "step", + "type": "number", + "minimum": 0.005, + "maximum": 0.2, + "default": 0.02, + "doc": "voxel size of the search; a way narrower than the bundle plus two voxels is not found" + }, + { + "name": "sag", + "type": "number", + "minimum": 0, + "maximum": 8, + "default": 1, + "doc": "how far the middle of each free span hangs, in outside diameters; 0: taut" + }, + { + "name": "clamps", + "type": "string", + "minLength": 2, + "maxLength": 4000, + "doc": "a JSON array of 0 to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose", + "default": "[]" + }, + { + "name": "joint", + "type": "string", + "minLength": 0, + "maxLength": 4000, + "doc": "empty, or a JSON object {\"socket\": \"Object:socket\", \"standoff\": 0 to 10, \"range\": [lo, hi]}: the pin the hose crosses", + "default": "" + } + ] } ] } diff --git a/surfaces/blender/brokkr_kitbash/route.py b/surfaces/blender/brokkr_kitbash/route.py index 2221cd7..d2eaaf7 100644 --- a/surfaces/blender/brokkr_kitbash/route.py +++ b/surfaces/blender/brokkr_kitbash/route.py @@ -318,6 +318,20 @@ def verify(curve, distance, need: float, lead: float, spacing: float, name: str return float(reads[worst]) +def thinned(curve, gap: float) -> np.ndarray: + """A curve without the points that stand within `gap` of the point kept before them; its two ends stay. Where two + arcs meet tangent to tangent they can leave a straight far shorter than a tube is wide between them, and a + section swept over it would fold; with the short straight gone the two arcs meet at one point.""" + curve = np.asarray(curve, dtype=np.float64) + kept = [0] + for index in range(1, len(curve)): + if np.linalg.norm(curve[index] - curve[kept[-1]]) > gap: + kept.append(index) + if kept[-1] != len(curve) - 1: + kept[-1 if len(kept) > 1 else len(kept):] = [len(curve) - 1] + return curve[kept] + + def frames(curve, up0) -> np.ndarray: """An up for each point of a curve, rotation minimising: the first is up0 projected off the tangent, each next the last reflected twice (Wang et al. 2008), so the ups do not twist about the curve. Tangents are the unit bisectors diff --git a/surfaces/blender/tests/live/kitbash_hose.py b/surfaces/blender/tests/live/kitbash_hose.py new file mode 100644 index 0000000..0355a38 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_hose.py @@ -0,0 +1,364 @@ +"""Live proof, in a background Blender, of brokkr_kitbash.hose through run_intent: a bundle of three hoses from an actuator +on one strut to an actuator on the next, around an armour plate and through a point on the knee pin's axis; the pin's +roll range measured without posing anything, and a range that swings the hose into the plate refused by roll; a second +hose that keeps clear of the first; a rebuild in place; a hose from a tank's flange over two clamps to an actuator's +port; and the refusals. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_hose.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. With , an +absolute path, the scene is saved there at the end. + +Bounds follow lodur:ruling:deterministic-bound-margin; each is written beside its constant with the shipped reading +and the least claimed mutant's (cut kit-hose's H list). The checks run inside one try: an uncaught error is a failed +check that names its section, and the result file is always written. +""" +import importlib.util +import json +import math +import os +import sys +import tempfile +import traceback +import types +from pathlib import Path + +import bpy +import numpy as np +from mathutils import Vector +from mathutils.bvhtree import BVHTree + +SURFACE = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(SURFACE / "tools")) +import private_dirs # noqa: E402 + +_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) +if _refused: + raise SystemExit(_refused) +OUT = sys.argv[sys.argv.index("--") + 1] +if not Path(OUT).is_absolute(): + raise SystemExit(f"{OUT!r} is not an absolute path") +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules["brokkr_bridge"] = package +from brokkr_bridge import blender_target as bt # noqa: E402 + +import addon_utils # noqa: E402 + +spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_reference", SURFACE / "brokkr_kitbash" / "core.py") +core = importlib.util.module_from_spec(spec) # core as the unit tests load it +spec.loader.exec_module(core) + +sys.path.append(str(SURFACE)) +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_kitbash"): + addon_utils.enable(module, default_set=True) +target = bt.BrokkrBlenderTarget(bpy) +WORK = Path(tempfile.mkdtemp(prefix="brokkr-kitbash-hose-")) +target.configure_action_dirs("", str(WORK)) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}, "reports": {}, "seconds": {}} +COUNT, SECTION = [0], ["setup"] +kit = core.load_kit("mechanical") +RADIUS, CLEARANCE, COUNT_HOSES = 0.006, 0.005, 3 +SPREAD = 2.6 * RADIUS +ENVELOPE = SPREAD + RADIUS # half the bundle's width +LEAD = 8.0 * RADIUS +FLOOR = 4.0 * 2.0 * RADIUS + SPREAD # of the centre line: the innermost hose keeps 4 outside diameters +BUNDLE = {"count": COUNT_HOSES, "radius": RADIUS, "clearance": CLEARANCE} +# Metres between a hose's surface and the nearest other mesh, read on the hose's own vertices further than the lead +# from both its ports (the least is the worst). The action promises the clearance asked for, 0.005, beyond the +# bundle's envelope, and a vertex of a 12-sided tube swept over chords of a 24th of a radian stands inside its circle +# by under 0.0002: the bound is that promise less the faceting. Shipped worst 0.030 (the second hose beside the +# first). No mutant of the cut's list lowers this reading: H10 (other hoses no obstacles) dies where a third hose is +# refused at a port a hose already holds, H4 (no verification) at tests/test_kitbash.py's count of route.verify, and +# H3 and H12 at tests/test_route.py; the reading is claimed by none of them and stands as the action's own promise. +CLEAR = 0.0048 +# Metres a clamped hose's ring vertices stand off the radius about its own line over a clamp (the line through the +# clamp point along the socket's y, offset across the bundle), over the 24 nearest; 1 when a hose has no 24 vertices +# there. Shipped worst 4.6e-08 (float32 meshes); least claimed mutant 1 (C2, the straight laid along the socket's x: +# the route is refused, or no ring stands on the line); the geometric mean, separation 4700 each side. C1 (no +# straight kept at a clamp) reads 0.013 on `kept`, the least distance along the line from a clamp point to a ring, +# where shipped reads 0.028 and the promise is 0.024, two outside diameters. +CLAMPED = 2.1e-4 + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) + + +def reading(name, value, least=False): + """The worst of a metric: the largest, or with `least` the smallest.""" + R["readings"][name] = (min if least else max)(R["readings"].get(name, float(value)), float(value)) + return float(value) + + +def section(name): + SECTION[0] = name + + +def send(action, **fields): + COUNT[0] += 1 + receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "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"])[:400], flush=True) + return receipt, result + + +def scene_state(): + return {o.name: (o.parent and o.parent.name, np.round(np.array(o.matrix_basis), 6).tolist(), {k: repr(o[k]) for k in sorted(o.keys()) if k.startswith("kit_")}, + [(m.name, m.type, m.show_viewport) for m in o.modifiers], o.data.name if o.type == "MESH" else None, len(o.data.polygons) if o.type == "MESH" else None, + np.round(np.array([v.co for v in o.data.vertices[:8]]), 6).tolist() if o.type == "MESH" else None) + for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes), sorted(c.name for c in bpy.data.collections) + + +def refused(label, fields, expected): + state = scene_state() + receipt, _ = send("brokkr_kitbash.hose", **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 place(name, part, params="", location=None, rotation=None, parent=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]) + made = bpy.data.objects[name] + if parent is not None: # carried rigidly: a plain parent, which states no connection + bpy.context.view_layer.update() + made.parent = parent + made.matrix_parent_inverse = parent.matrix_world.inverted() + return made + + +def box(name, low, high, parent=None): + (x0, y0, z0), (x1, y1, z1) = low, high + made = bpy.data.objects.new(name, bpy.data.meshes.new(name)) + made.data.from_pydata([(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0), (x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1)], [], + [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]) + bpy.context.scene.collection.objects.link(made) + if parent is not None: + bpy.context.view_layer.update() + made.parent = parent + made.matrix_parent_inverse = parent.matrix_world.inverted() + return made + + +def frame(obj, name): + """A socket's world frame, from the object's matrix_world and core's build of its stored params.""" + built = core.build(core.part(kit, obj["kit_part"]), json.loads(obj["kit_params"])) + return np.array(obj.matrix_world, dtype=np.float64) @ next(s for s in built.sockets if s["name"] == name)["matrix"] + + +def world_points(obj): + points = np.zeros(3 * len(obj.data.vertices)) + obj.data.vertices.foreach_get("co", points) + world = np.array(obj.matrix_world) + return points.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3] + + +def others(hose): + """A tree of every other mesh object's evaluated mesh in the world: this test's own reading of the obstacles.""" + depsgraph, points, faces = bpy.context.evaluated_depsgraph_get(), [], [] + for obj in bpy.context.scene.objects: + if obj.type != "MESH" or obj == hose: + continue + evaluated = obj.evaluated_get(depsgraph) + mesh, start = evaluated.to_mesh(), sum(len(p) for p in points) + points.append(np.array([evaluated.matrix_world @ v.co for v in mesh.vertices]).reshape(-1, 3)) + faces += [[start + i for i in polygon.vertices] for polygon in mesh.polygons] + evaluated.to_mesh_clear() + return BVHTree.FromPolygons(np.vstack(points).tolist(), faces) + + +def surface_clearance(hose, ports): + """The least distance from the hose's vertices to any other mesh, over the vertices further than the lead and the + bundle's half width from both ports.""" + bpy.context.view_layer.update() + tree, points = others(hose), world_points(hose) + far = np.all([np.linalg.norm(points - port, axis=1) > LEAD + ENVELOPE + CLEARANCE for port in ports], axis=0) + return min(tree.find_nearest(Vector(p))[3] for p in points[far]) + + +def shells(obj): + """(closed shells, edges that do not join two faces) of a mesh object.""" + edges = {} + for polygon in obj.data.polygons: + for a, b in polygon.edge_keys: + edges[(a, b)] = edges.get((a, b), 0) + 1 + root = list(range(len(obj.data.vertices))) + + def find(i): + while root[i] != i: + root[i] = root[root[i]] + i = root[i] + return i + for a, b in edges: + root[find(a)] = find(b) + return len({find(i) for i in range(len(root))}), sum(1 for n in edges.values() if n != 2) + + +def timed(fields): + """Median wall seconds of three rebuilds of a hose, each after one report action.""" + import time + taken = [] + for _ in range(3): + send("brokkr_kitbash.report", object_name="Thigh") + started = time.perf_counter() + send("brokkr_kitbash.hose", **fields) + taken.append(time.perf_counter() - started) + return sorted(taken)[1] + + +try: + section("knee") + STRUT = "length=0.8;width=0.08;thickness=0.05" + RAM = "body_r=0.12;body_len=0.2;extension=0" + thigh = place("Thigh", "strut", STRUT) + place("Shin", "strut", STRUT) + send("brokkr_kitbash.attach", object_name="Shin", socket="end_a", parent_name="Thigh", parent_socket="end_b_back", roll=0.0) + shin = bpy.data.objects["Shin"] + upper = place("ActT", "actuator", RAM, [-0.674, -0.2, -0.2], parent=thigh) + lower = place("ActS", "actuator", RAM, [-0.674, -0.2, 0.89], parent=shin) + plate = box("Armour", (-0.21, -0.45, 0.15), (-0.19, 0.05, 0.7), parent=thigh) + bpy.context.view_layer.update() + ports = [frame(upper, "port_cap")[:3, 3], frame(lower, "port_cap")[:3, 3]] + check("the actuator's ports sit on its boss faces, facing out", np.allclose(ports[0], [-0.5, -0.2, 0.01], atol=1e-6) and np.allclose(frame(upper, "port_cap")[:3, 2], [1, 0, 0], atol=1e-6) + and others(None).find_nearest(Vector(ports[0]))[3] < 1e-6 and np.allclose(frame(upper, "port_rod")[:3, 3], [-0.5, -0.2, 0.27], atol=1e-6), ports[0].tolist()) + JOINT = {"socket": "Shin:end_a_back", "standoff": 0.08, "range": [-20, 20]} + FEED = {"object_name": "Feed", "start": "ActT:port_cap", "end": "ActS:port_cap", **BUNDLE, "joint": json.dumps(JOINT)} + state = scene_state() + receipt, report = send("brokkr_kitbash.hose", **FEED) + R["reports"]["feed"] = report + check("hose-behind-armour: three hoses route from the thigh's ram to the shin's, round the plate and through the pin point", + receipt["status"] == "accepted" and report["hoses"] == 3 and not report["rebuilt"] and report["nonManifoldEdges"] == 0 and report["rolls"] == 9 + and report["clearance"] >= CLEARANCE and report["worstClearance"] >= CLEARANCE and report["radii"]["least"] >= FLOOR * (1 - 1e-6) and len(report["voxels"]) == 2, + [receipt["status"], receipt["message"], report]) + feed = bpy.data.objects["Feed"] + check("the hose is one object, the start's child under an identity parent inverse, and carries its request", + feed.parent == upper and np.allclose(np.array(feed.matrix_parent_inverse), np.eye(4)) and np.allclose(np.array(feed.matrix_basis), np.eye(4)) + and json.loads(feed["kit_hose"])["joint"] == JOINT and len(feed.data.materials) == 0 and len(feed.vertex_groups) == 0, feed.get("kit_hose")) + check("every hose and collar is a closed shell", shells(feed) == (3 + 3 * 4, 0), shells(feed)) + points = world_points(feed) + check("each hose starts on the port's face, side by side across it", + min(np.linalg.norm(points - ports[0], axis=1)) < RADIUS * 1.5 and abs(float(((points - ports[0]) @ [1.0, 0, 0]).min())) < 1e-5, None) + line_blocked = others(feed).ray_cast(Vector(ports[0] + [0.12, 0, 0]), Vector((np.array([0, -0.2075, 0.764]) - ports[0] - [0.12, 0, 0])))[0] is not None + check("the straight way from the port to the pin point is through the plate", line_blocked, None) + check("hose-behind-armour: the hose's surface keeps the clearance from every other mesh outside its leads", + reading("clear", surface_clearance(feed, ports), least=True) >= CLEAR, R["readings"]) + check("the hose passes the pin's axis: its vertices come within the bundle of the point 0.08 beyond the shin's pin face", + float(np.linalg.norm(points - [0.0, -0.2075, 0.764], axis=1).min()) < 0.08, float(np.linalg.norm(points - [0.0, -0.2075, 0.764], axis=1).min())) + check("the report states sag for both legs, no more than the sag asked for", len(report["sag"]) == 2 and all(0.0 <= s <= 2 * RADIUS + 1e-9 for s in report["sag"]) and any(s > 0 for s in report["sag"]), report["sag"]) + _, taut = send("brokkr_kitbash.hose", **{**FEED, "sag": 0.0}) + check("sag 0 routes taut and no longer than the sagged hose", taut["sag"] == [0.0, 0.0] and taut["rebuilt"] and taut["length"] < report["length"], [taut["length"], report["length"]]) + reading("slack", report["length"] - taut["length"]) + section("range") + _, again = send("brokkr_kitbash.hose", **FEED) + check("a rebuild at the same pose reports what the first call did", {**again, "rebuilt": False} == report and len(bpy.data.meshes) == len(state[1]) + 1, again) + check("hose-through-range: the range passes and reports the length's change", report["lengthChange"] is not None and report["lengthChange"] >= 0 and report["worstRoll"] is not None, report) + refused("a range that swings the shin's hose into the thigh's parts", {**FEED, "joint": json.dumps({**JOINT, "range": [-20, 90]})}, + "roll 50: the hose's child's side stands 0.02384 m from the parts on the other side of the pin, under the 0.0266 m the bundle needs") + send("brokkr_kitbash.roll", object_name="Shin", roll=10.0) + bpy.context.view_layer.update() + receipt, rolled = send("brokkr_kitbash.hose", **FEED) + check("after a roll the hose rebuilds in place on its name", receipt["status"] == "accepted" and rolled["rebuilt"] and bpy.data.objects["Feed"] == feed and rolled["rolls"] == 9, receipt["message"]) + check("the rebuilt hose keeps the clearance at the new pose", reading("clear", surface_clearance(feed, [frame(upper, "port_cap")[:3, 3], frame(lower, "port_cap")[:3, 3]]), least=True) >= CLEAR, R["readings"]) + mesh = feed.data + bpy.data.objects.remove(feed) + bpy.data.meshes.remove(mesh) + bpy.context.view_layer.update() + receipt, fresh = send("brokkr_kitbash.hose", **FEED) + feed = bpy.data.objects["Feed"] + check("hose-through-range: roll then rebuild gives the same report as a fresh hose", receipt["status"] == "accepted" and {**rolled, "rebuilt": False} == fresh, [rolled, fresh]) + R["seconds"]["hose on the knee, median of 3"] = round(timed(FEED), 3) + section("second hose") + RETURN = {"object_name": "Return", "start": "ActT:port_rod", "end": "ActS:port_rod", **BUNDLE, "step": 0.03, "joint": json.dumps({**JOINT, "standoff": 0.24})} # round the plate's edge a voxel of 0.02 leaves a bend under the floor + receipt, back = send("brokkr_kitbash.hose", **RETURN) + R["reports"]["return"] = back + check("a second hose routes through the same knee", receipt["status"] == "accepted" and back["nonManifoldEdges"] == 0, [receipt["status"], receipt["message"]]) + rod_ports = [frame(upper, "port_rod")[:3, 3], frame(lower, "port_rod")[:3, 3]] + check("hose-behind-armour: the second hose keeps the clearance from the first", reading("clear", surface_clearance(bpy.data.objects["Return"], rod_ports), least=True) >= CLEAR, R["readings"]) + refused("a pin point another hose already passes", {**RETURN, "object_name": "Third"}, "from an obstacle") + section("clamps") + tank = place("Tank", "tank", "radius=0.22;length=0.9", [3.0, 0.0, 0.0]) + seats = [place(name, "plate", "width=0.1;height=0.1", [x, 0.0, 1.25], [0.0, 0.0, math.pi / 2]) for name, x in (("SeatA", 3.45), ("SeatB", 4.05))] + ram = place("Ram", "actuator", RAM, [5.074, 0.0, 1.07], [0.0, 0.0, math.pi]) + bpy.context.view_layer.update() + LINE = {"object_name": "Line", "start": "Tank:port_b", "end": "Ram:port_cap", **BUNDLE, "clamps": json.dumps([{"socket": "SeatA:front"}, {"socket": "SeatB:front"}])} + receipt, line = send("brokkr_kitbash.hose", **LINE) + R["reports"]["line"] = line + check("hose-clamps-ports: a hose runs from the tank's flange over two clamps to the ram's port", receipt["status"] == "accepted" and line["nonManifoldEdges"] == 0 and len(line["voxels"]) == 3 + and line["rolls"] is None and line["lengthChange"] is None, [receipt["status"], receipt["message"]]) + hose = bpy.data.objects["Line"] + check("three hoses with four collars each, two straps and two pads", shells(hose) == (3 + 12 + 4, 0), shells(hose)) + points = world_points(hose) + stand, held = ENVELOPE + CLEARANCE + RADIUS, 4.0 * RADIUS + FLOOR + for seat in seats: + at = frame(seat, "front") + centre, y, x = at[:3, 3] + at[:3, 2] * stand, at[:3, 1], at[:3, 0] + for k in range(COUNT_HOSES): + origin = centre + x * (k - 1) * SPREAD + rel = points - origin + along = rel @ y + off = np.abs(np.linalg.norm(rel - np.outer(along, y), axis=1) - RADIUS) + near = np.sort(off[np.abs(along) <= held + 1e-6])[:24] # the two rings where the kept straight ends, twelve vertices each + reading("clamped", near.max() if len(near) == 24 else 1.0) + reading("kept", np.abs(along[off < 1e-5]).min() if (off < 1e-5).any() else 0.0, least=True) + check("hose-clamps-ports: each hose passes each clamp point straight along the socket's y", R["readings"]["clamped"] <= CLAMPED, R["readings"]) + check("the bundle runs straight for two outside diameters each side of a clamp point: no ring of a bend stands nearer", R["readings"]["kept"] >= 4.0 * RADIUS * (1 - 1e-6), R["readings"]) + check("the clamped hose reports the clearance it keeps (its pads stand on their seats)", line["clearance"] >= CLEARANCE and surface_clearance(hose, [frame(tank, "port_b")[:3, 3], frame(ram, "port_cap")[:3, 3]]) < 1e-6, + line["clearance"]) + refused("a bundle wider than the port", {**LINE, "object_name": "Wide", "count": 5}, "a bundle of 5 hoses is 0.0744 m wide, over socket 'Ram:port_cap' (hose, size 0.048)") + tip = bpy.data.objects.new("Tip", None) + bpy.context.scene.collection.objects.link(tip) + tip.location, tip.rotation_euler = (3.5, 0.0, -1.3), (0.0, -math.pi / 6, 0.0) # under the tank's lower port, its z up toward it + bpy.context.view_layer.update() + receipt, loose = send("brokkr_kitbash.hose", object_name="Loose", start="Tank:port_a", end="Tip", radius=0.02) + check("a hose runs from a flange to an empty", receipt["status"] == "accepted" and loose["hoses"] == 1 and shells(bpy.data.objects["Loose"]) == (5, 0), [receipt["status"], receipt["message"]]) + section("refusals") + refused("a name taken by a mesh that is no hose", {**FEED, "object_name": "Thigh"}, "An object named 'Thigh' exists and is no hose") + refused("a socket the part does not have", {**FEED, "start": "ActT:nope"}, "start: 'ActT' (a actuator) has no socket 'nope'; its sockets: base, base_back, rod_end, rod_end_back, port_cap, port_rod") + refused("an object that does not exist", {**FEED, "end": "Nobody:port_cap"}, "end: no object named 'Nobody'") + refused("a pivot as an end", {**FEED, "start": "Thigh:end_a"}, "start: socket 'end_a' of 'Thigh' is a pivot socket; this takes a hose or flange socket") + refused("a mesh that is no empty as an end", {**FEED, "end": "Armour"}, "end 'Armour' names no socket") + refused("a clamp on a pivot", {**FEED, "clamps": json.dumps([{"socket": "Thigh:end_a"}])}, "clamps[0]: socket 'end_a' of 'Thigh' is a pivot socket; this takes a mount socket") + refused("clamps that are not rows of socket", {**FEED, "clamps": json.dumps([{"at": [0, 0, 0]}])}, "clamps[0] must be an object of socket") + refused("nine clamps", {**FEED, "clamps": json.dumps([{"socket": "SeatA:front"}] * 9)}, "clamps must be a JSON array of 0 to 8 objects") + refused("a pin crossed with no joint", {k: v for k, v in FEED.items() if k != "joint"}, "The hose crosses the pin of 'Shin' on 'Thigh' (socket 'end_b_back'): give joint") + refused("a joint where no pin is crossed", {**LINE, "object_name": "New", "joint": json.dumps(JOINT)}, "joint is given and the hose crosses no pin") + place("Jack", "actuator", "body_r=0.0534;body_len=0.2;extension=0") + send("brokkr_kitbash.attach", object_name="Jack", socket="base", parent_name="Shin", parent_socket="end_b", roll=90.0) + bpy.context.view_layer.update() + refused("two pins crossed", {**FEED, "object_name": "New", "end": "Jack:port_cap", "count": 1, "radius": 0.004}, "The hose crosses 2 pins ('Jack' on 'Shin', 'Shin' on 'Thigh'): a hose crosses one") + refused("a joint socket off the crossed pin's axis", {**FEED, "joint": json.dumps({**JOINT, "socket": "Shin:end_b_back"})}, "joint.socket 'Shin:end_b_back' is not on the axis of the pin the hose crosses ('Shin' on 'Thigh', socket 'end_b_back')") + refused("the current roll outside the range", {**FEED, "joint": json.dumps({**JOINT, "range": [30, 60]})}, "'Shin' stands at roll 10, outside joint.range [30, 60]") + refused("a range over a full turn", {**FEED, "joint": json.dumps({**JOINT, "range": [-200, 200]})}, "joint must be an object of socket") + refused("a grid past the voxel limit", {**FEED, "step": 0.005}, "voxels at step 0.005, over 524288: a step of ") + lower.scale = (1.0, 1.0, 1.01) + bpy.context.view_layer.update() + refused("a scaled part", FEED, "'ActS' is scaled, mirrored or sheared in the world") + lower.scale = (1.0, 1.0, 1.0) + tip.hide_viewport = True + bpy.context.view_layer.update() + refused("a hidden end", {"object_name": "Loose", "start": "Tank:port_a", "end": "Tip", "radius": 0.02}, "Blender does not evaluate 'Tip' in this view layer") + tip.hide_viewport = False + bpy.context.view_layer.update() + if len(sys.argv) > sys.argv.index("--") + 2: + bpy.ops.wm.save_as_mainfile(filepath=sys.argv[sys.argv.index("--") + 2]) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file + check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:]) +finally: + R["ok"] = all(c["ok"] for c in R["checks"]) + R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} + seconds = R.pop("seconds") # wall time is this machine's: printed, and kept out of the result file + 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) + print("SECONDS", seconds, flush=True) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_hose.result.json b/surfaces/blender/tests/live/kitbash_hose.result.json new file mode 100644 index 0000000..a42ebae --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_hose.result.json @@ -0,0 +1,340 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "the actuator's ports sit on its boss faces, facing out", + "ok": true, + "detail": null + }, + { + "name": "hose-behind-armour: three hoses route from the thigh's ram to the shin's, round the plate and through the pin point", + "ok": true, + "detail": null + }, + { + "name": "the hose is one object, the start's child under an identity parent inverse, and carries its request", + "ok": true, + "detail": null + }, + { + "name": "every hose and collar is a closed shell", + "ok": true, + "detail": null + }, + { + "name": "each hose starts on the port's face, side by side across it", + "ok": true, + "detail": null + }, + { + "name": "the straight way from the port to the pin point is through the plate", + "ok": true, + "detail": null + }, + { + "name": "hose-behind-armour: the hose's surface keeps the clearance from every other mesh outside its leads", + "ok": true, + "detail": null + }, + { + "name": "the hose passes the pin's axis: its vertices come within the bundle of the point 0.08 beyond the shin's pin face", + "ok": true, + "detail": null + }, + { + "name": "the report states sag for both legs, no more than the sag asked for", + "ok": true, + "detail": null + }, + { + "name": "sag 0 routes taut and no longer than the sagged hose", + "ok": true, + "detail": null + }, + { + "name": "a rebuild at the same pose reports what the first call did", + "ok": true, + "detail": null + }, + { + "name": "hose-through-range: the range passes and reports the length's change", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a range that swings the shin's hose into the thigh's parts", + "ok": true, + "detail": null + }, + { + "name": "after a roll the hose rebuilds in place on its name", + "ok": true, + "detail": null + }, + { + "name": "the rebuilt hose keeps the clearance at the new pose", + "ok": true, + "detail": null + }, + { + "name": "hose-through-range: roll then rebuild gives the same report as a fresh hose", + "ok": true, + "detail": null + }, + { + "name": "a second hose routes through the same knee", + "ok": true, + "detail": null + }, + { + "name": "hose-behind-armour: the second hose keeps the clearance from the first", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a pin point another hose already passes", + "ok": true, + "detail": null + }, + { + "name": "hose-clamps-ports: a hose runs from the tank's flange over two clamps to the ram's port", + "ok": true, + "detail": null + }, + { + "name": "three hoses with four collars each, two straps and two pads", + "ok": true, + "detail": null + }, + { + "name": "hose-clamps-ports: each hose passes each clamp point straight along the socket's y", + "ok": true, + "detail": null + }, + { + "name": "the bundle runs straight for two outside diameters each side of a clamp point: no ring of a bend stands nearer", + "ok": true, + "detail": null + }, + { + "name": "the clamped hose reports the clearance it keeps (its pads stand on their seats)", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a bundle wider than the port", + "ok": true, + "detail": null + }, + { + "name": "a hose runs from a flange to an empty", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a name taken by a mesh that is no hose", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a socket the part does not have", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an object that does not exist", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a pivot as an end", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a mesh that is no empty as an end", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a clamp on a pivot", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: clamps that are not rows of socket", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: nine clamps", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a pin crossed with no joint", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a joint where no pin is crossed", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: two pins crossed", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a joint socket off the crossed pin's axis", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: the current roll outside the range", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a range over a full turn", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a grid past the voxel limit", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a scaled part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a hidden end", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "readings": { + "clamped": 4.6e-08, + "clear": 0.03, + "kept": 0.028, + "slack": 0.021 + }, + "reports": { + "feed": { + "object": "Feed", + "rebuilt": false, + "hoses": 3, + "length": 1.64165, + "lengthChange": 0.030219, + "floor": 0.0636, + "clearance": 0.005763, + "capped": 0.1522, + "voxels": [ + 79488, + 53406 + ], + "sag": [ + 0.001609, + 0.009076 + ], + "rolls": 9, + "worstRoll": -20.0, + "worstClearance": 0.057408, + "faces": 3378, + "volume": 0.000577078, + "nonManifoldEdges": 0, + "radii": { + "least": 0.123768, + "corners": [ + 0.248224, + 0.123768, + 30.12343, + 0.218148, + 3.812707, + 0.129781 + ] + } + }, + "return": { + "object": "Return", + "rebuilt": false, + "hoses": 3, + "length": 1.678891, + "lengthChange": 0.034002, + "floor": 0.0636, + "clearance": 0.021671, + "capped": 0.1622, + "voxels": [ + 26040, + 28560 + ], + "sag": [ + 0.006276, + 0.00844 + ], + "rolls": 9, + "worstRoll": 20.0, + "worstClearance": 0.034016, + "faces": 4926, + "volume": 0.000589144, + "nonManifoldEdges": 0, + "radii": { + "least": 0.071383, + "corners": [ + 0.073199, + 7.398753, + 0.071383, + 0.118904, + 10.830696, + 0.095513 + ] + } + }, + "line": { + "object": "Line", + "rebuilt": false, + "hoses": 3, + "length": 2.10108, + "lengthChange": null, + "floor": 0.0636, + "clearance": 0.011, + "capped": 0.1522, + "voxels": [ + 49815, + 34992, + 43011 + ], + "sag": [ + 0.00942, + 0.012, + 0.011996 + ], + "rolls": null, + "worstRoll": null, + "worstClearance": null, + "faces": 2510, + "volume": 0.000777433, + "nonManifoldEdges": 0, + "radii": { + "least": 0.09689, + "corners": [ + 0.097757, + 4.439012, + 0.09689, + 1.734649, + 2.898844, + 1.734649, + 1.665625, + 7.39548, + 10.86245 + ] + } + } + }, + "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 1a099d4..6f50fc9 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1813,7 +1813,7 @@ class SheetTests(unittest.TestCase): ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs", - "brokkr_kitbash.shell"] + "brokkr_kitbash.shell", "brokkr_kitbash.hose"] class HostFileTests(unittest.TestCase): @@ -1883,7 +1883,7 @@ class HostFileTests(unittest.TestCase): self.assertEqual([(row["name"], field["name"], field["default"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "boolean"], [("brokkr_kitbash.shell", "count_folds", False)]) # the one evaluation shell makes is asked for, never the default self.assertEqual([(row["name"], field["name"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "integer"], - [("brokkr_kitbash.shell", "levels")]) + [("brokkr_kitbash.shell", "levels"), ("brokkr_kitbash.hose", "count")]) sheet = json.dumps({"rings": [[[0, 0, 0], [1, 0, 0]], [[0, 0, 1], [1, 0, 1]]]}) shell = {**envelope, "action": "brokkr_kitbash.shell", "object_name": "Plate", "sheet": sheet} self.assertEqual([at.validate(shell, host)[k] for k in ("thickness", "offset", "levels", "bevel", "count_folds")], [0.05, -1, 3, 0, False]) @@ -1976,7 +1976,7 @@ class OwnershipTests(unittest.TestCase): for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["apply"], "bpy.data.meshes.new_from_object("), (bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()")): self.assertLess(body.index("evaluable("), body.index(first_write)) - self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs", "shell"]) + self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs", "shell", "hose"]) ribs = bodies["ribs"] # every refusal before the ribs object is written, and the cage's modifiers shown again whatever happened self.assertLess(ribs.rindex("raise Refused("), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)")) self.assertLess(ribs.index("finally:"), ribs.index("modifier.show_viewport = True")) @@ -2024,6 +2024,47 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(len(re.findall(rf"(? Date: Wed, 2 Dec 2026 16:50:34 +0100 Subject: [PATCH 118/223] docs/kitbash.md: hoses between sockets; kitbash live result with the hose row and the actuator's ports (cut kit-hose) Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 94 ++++++++++++++++++- .../blender/tests/live/kitbash.result.json | 7 +- 2 files changed, 96 insertions(+), 5 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 8cbd115..4e6f012 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -604,6 +604,93 @@ evaluate, but deleting the copy costs the same whole evaluation (1.44 to 1.54 s included, and the hole cut's temporary objects must be deleted too. So a hull with twenty cutters pays their evaluation once for every `ribs` call; iterate planes on the cage before it is cut, or with its Booleans off. +## Hoses between sockets + +`brokkr_kitbash.hose` routes a bundle of hoses from one socket to another around everything in the scene: + +```json +{"action": "brokkr_kitbash.hose", "object_name": "Feed", "start": "ThighRam:port_cap", "end": "ShinRam:port_cap", + "count": 3, "radius": 0.006, "clearance": 0.005, + "joint": "{\"socket\": \"Shin:end_a_back\", \"standoff\": 0.08, \"range\": [-120, 20]}"} +``` + +**Ends.** `start` and `end` are `Object:socket` on a kit part, a `hose` socket (an actuator's `port_cap` and +`port_rod`) or a `flange`, no narrower than the bundle; or `Object` alone, an empty whose z the hose leaves along. +A fitting keeps a straight lead of 8 radii (a ferrule of 5, then 1.5 outside diameters before any bend), and the +bundle's clearance is not asked of that lead: it stands on its own port. + +**The path.** `route.py` (numpy, no Blender) owns it. Waypoints are each fitting's lead end, each clamp and the +pin point. A leg between two waypoints is searched on a voxel grid of their box plus 0.25 m: a voxel is free when it +stands the bundle's half width, the clearance and half a voxel's diagonal from every other mesh, so every step +between neighbouring free voxels keeps the clearance; a 26-connected wavefront finds a shortest way and it is +pulled taut. The legs joined are one polyline, and each corner is rounded by the largest arc its measured room +allows: the arc stands within `radius * (1 - cos(turn / 2))` of its two tangent segments, so with that much room +beyond the clearance measured along them it keeps the clearance. Where two arcs would overlap on a segment both +shrink in proportion. The floor is `bend` outside diameters for the innermost hose (the centre line's is half the +bundle's spread more); a corner that gets less is refused, naming its point, the radius it got and the floor. The +finished curve is measured once more against every mesh before anything is written. + +A corner that wraps an edge stands about 0.87 of a voxel beyond the clearance, and that is its room: the radius it +can get is `0.87 * step / (1 - cos(turn / 2))`. When a bend round an edge is refused under the floor, raise `step` +(the hose then swings wider), lower `clearance` or `bend`, or give the hose a clamp to steer it. A 90 degree bend +straight out of a fitting needs `0.29 * floor` of room at the lead's end, which a bundle of three at the default +clearance of 0.01 does not have: 0.005 does. + +**Slack.** `sag` (outside diameters, default 1) lowers the middle of each free span's longest segment along world +-z, by less where the span runs steeply, and never by more than half the room measured along it: both halves then +keep the clearance with as much room again for the arc at the middle. A route that the sag would break is made +taut instead; the report's `sag` lists the metres each leg hangs. 0 routes taut. + +**Clamps.** `clamps` is a JSON array of up to 8 `{"socket": "Object:socket"}`, `mount` sockets in order along the +hose. The bundle runs straight along the socket's y through the point its half width, the clearance and one hose +radius above the face, for 2 outside diameters each side, and gets a pad on the face and a strap around it. The +bundle lies flat on the first clamp; its ups are rotation minimising (Wang et al. 2008), so it does not twist +between clamps, and a later clamp's strap follows the bundle as it arrives. + +**A pin.** A hose may cross one pin: a pivot connection between its ends' parts, found from their parent chains. +`joint` names a socket on that pin's axis whose z runs along it (the free end face of the pin: a strut's +`end_a_back`), a `standoff` and the pin's roll `range`. The hose passes through the point `standoff` beyond that +socket, on the axis, as a robot's dress pack does: the straights on each side then move with their own part and +only the bend at that point changes with the roll. Every roll from `lo` to `hi` in steps of 5 degrees is measured +without posing anything: the child's side of the polyline is turned about the axis, the corner at the pin point is +rounded again, and each side is measured against the other side's parts where that roll puts them. A roll that +fails is refused by name (`roll 50: the hose's child's side stands 0.02384 m from the parts on the other side of +the pin`). `lengthChange` is the centre line's longest less its shortest over the range, as each roll rounds the +bend. Two pins between the ends are refused: end the hose on a part between them. + +**What it writes.** One mesh object, a child of the start's object under identity matrices, with no modifier and +no material: each hose, two ferrule collars at each of its ends, and the clamps, all swept by `core.sweep`. +`kit_hose` on it is the request as JSON, a record nothing reads back. Other hoses are obstacles like any mesh, so +route the stiffest first. The hose is a bake of the scene at the call: after a part moves or rolls, run `hose` +again with the same `object_name` and it is rebuilt in place. + +A hose that crosses a pin stays one object. In the exported mesh it is skinned geometry, meant to be weighted +between the bones on either side of the pin, blending near the pin point; the posed shape then comes from the +skin, and the rebuild is for stills and for checking the range. This package writes no weights or vertex groups: +skin weights are `brokkr_rig`'s. + +**Refusals**, each before anything is written: a name taken by an object that is no hose; an end or clamp that +names no object, no such socket, or a socket of the wrong type; a bundle wider than a port, naming both sizes; a +part that is scaled or that Blender does not evaluate; a pin crossed with no `joint`, a `joint` with no pin, two +pins, a `joint` socket off the pin's axis, the current roll outside `range`; a search box over 524288 voxels, +naming a step that fits; an end nearer an obstacle than the bundle needs; no way through; a corner under the +floor; a roll that fails. + +**Cost.** Probes in Blender 5.3 on Starfire, medians of 3 interleaved repetitions: a nearest-face query on a tree of +81,920 faces takes 100 to 123 us uncapped and 3.4 us capped at 0.06 m, so every query is capped; on a grid of +97,061 voxels with a wall and a hole a heap A* took 8.47 s (56,824 pops) and the wavefront 0.26 s (100 waves); on +a knee of five boxes (96,565 voxels at 0.02 m) the occupancy took 0.46 s uncapped, the search 0.19 s, the pull, the +fillet and the verification under 2 ms together, 27 rolls 0.056 s and the sweep of three hoses 4 ms. The live +knee of `tests/live/kitbash_hose.py` (two struts, two actuators and a plate; two legs of 79,488 and 53,406 +voxels at roll 0, timed at roll 10; three hoses of 3,378 faces, 9 rolls) took 0.50 s a call, median of 3 each after one report action: 0.28 s of it +the occupancy (55 percent), 0.05 s the wavefront, 0.04 s the rolls, 0.02 s the fillet and its room, 0.01 s the +pull and the verification, and the rest the trees, the sweep and the write. The same call read 0.47 to 1.1 s +across runs while other Blenders were rendering on the machine. + +`tests/test_route.py` proves the path without Blender (the half-diagonal rule, the fillet's tangency, sharing, room +and floor, the sag's bound, the frames against the double reflection method, the rolls), and +`tests/live/kitbash_hose.py` the action in Blender. + ## Expressions Every numeric field of a shape or socket, and `bevel`, is a number or a string over the part's params: @@ -638,6 +725,7 @@ vertices overflow. | `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | | `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | +| `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff, range}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. | `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. @@ -683,8 +771,8 @@ file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the ## The mechanical kit -`kits/mechanical.v0.json`: eleven parts, each along +z, with socket types `flange` (equal), `mount` (fits) and -`pivot` (equal). +`kits/mechanical.v0.json`: eleven parts, each along +z, with socket types `flange` (equal), `mount` (fits), +`pivot` (equal) and `hose` (fits: a port takes a bundle no wider than its size). | part | params | sockets | | --- | --- | --- | @@ -692,7 +780,7 @@ file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the | `tank` | `radius`, `length`, `segments` | `port_a`, `port_b` (flange), `saddle` (mount), `lug_a`, `lug_b`, `lug_a_back`, `lug_b_back` (mount): a lug on each side (+x, and -x for `_back`) of each strap | | `ribbed_cylinder` | `radius`, `length`, `ribs`, `rib_depth`, `rib_width`, `segments` | `end_a`, `end_b` (flange) | | `strut` | `length`, `width`, `thickness`, `segments` | `end_a`, `end_a_back`, `end_b`, `end_b_back` (pivot): the two end faces of the pin at each end | -| `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `base_back`, `rod_end`, `rod_end_back` (pivot); the rod end's two move with `extension` | +| `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `base_back`, `rod_end`, `rod_end_back` (pivot); the rod end's two move with `extension`; `port_cap`, `port_rod` (hose, `0.4*body_r` wide) on the end faces of its two port bosses | | `pipe_fitting` | `pipe_r`, `run`, `branch`, `flange_r`, `flange_t`, `segments` | `a`, `b`, `c` (flange) | | `radiator_stack` | `fins`, `fin_w`, `fin_h`, `fin_t`, `pitch`, `segments` | `base` (mount) | | `vent` | `width`, `height`, `depth`, `slats`, `slat_t`, `tilt` | `back` (mount) | diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index bacf88b..9a852d1 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -481,7 +481,8 @@ "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs", - "brokkr_kitbash.shell" + "brokkr_kitbash.shell", + "brokkr_kitbash.hose" ], "frame": { "beam_i": { @@ -608,7 +609,9 @@ "base", "base_back", "rod_end", - "rod_end_back" + "rod_end_back", + "port_cap", + "port_rod" ] }, "pipe_fitting": { From b21e745d2e8e49a67edeca9cd4a52c3e77574514 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 17:47:40 +0100 Subject: [PATCH 119/223] brokkr_kitbash.hose: clearance measured between readings, the roll range swept by bins, legs searched with room for their bends (cut kit-hose, h2) route.measure replaces sampling at half a voxel: a reading answers for its piece less half the piece's length, pieces are halved to 1 mm, so no plate stands unseen between two readings and no measurement depends on step. route.passes measures a range, not a list of rolls: each roll answers for a bin by what a point can move within it (rho x half width), the bend at the pin has one radius through a bin with its dip added to the need, and a bin that falls short is halved down to 0.3 degrees. A leg is searched and pulled with 0.29 of the floor beyond need where a way has it: a line pulled at need grazed what it wrapped and left its corner an accidental room that changed with step. A corner under the floor says what limits it; a refusal names the sagged and the taut attempt; another hose through the same pin is an obstacle where it stands and is not measured across the rolls as if rigid. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 67 +++-- .../brokkr_kitbash/brokkr_actions.json | 2 +- surfaces/blender/brokkr_kitbash/route.py | 271 ++++++++++++------ surfaces/blender/tests/test_route.py | 157 ++++++++-- 4 files changed, 364 insertions(+), 133 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 57c6f17..a635370 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -54,7 +54,8 @@ scene's clearance, pulled taut, sagged a little, filleted, verified, and turned cross) and core.sweep owns every tube, ferrule and clamp. A hose is a bake of the scene at the call: posing or moving a part leaves it stale until hose runs again on its name. It is one object: where it crosses a pin it is meant to be skinned between the bones on either side, and this package writes no weights. kit_hose on it is the request, kept as -a record: nothing reads it to decide geometry, and hose is its one writer. +a record: hose is its one writer, and the one thing read back from it is which two parts a hose joins, by a later hose +that crosses the same pin (it bends with the pin, so it is measured as an obstacle where it stands and not across the rolls). 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 @@ -96,12 +97,13 @@ LONGERONS_LIMIT = 16 # longerons in one ribs SHELL = "kit_shell" # on a shell: the request its cage is derived from, as JSON; its presence admits a rebuild, and nothing reads it to decide geometry SUBSURF, SOLIDIFY = "Kit Subsurf", "Kit Solidify" # a shell's own modifiers, in that order, before any of its Booleans and the Kit Bevel SHELL_FACES_LIMIT = 262144 # faces of a shell's subdivided surface: cage quads times 4 to the levels -HOSE = "kit_hose" # on a hose: the request it was routed from, as JSON; its presence admits a rebuild, and nothing reads it to decide geometry +HOSE = "kit_hose" # on a hose: the request it was routed from, as JSON; its presence admits a rebuild, and another hose reads its two ends to know that it crosses the same pin HOSE_CLAMPS = 8 # clamps in one hose: each is one more leg to search HOSE_VOXELS = 2 ** 19 # voxels of one leg's search box: 1.8 s of capped nearest-face queries at 3.4 us each HOSE_MARGIN = 0.25 # metres a leg's search box reaches beyond its two ends: the room a way around an obstacle between them has HOSE_SEGMENTS = 12 # sides of a hose, a ferrule and a clamp's pad -ROLL_STEP = 5.0 # degrees between the rolls of a joint's range that hose measures: the step an assembly's clearance is read at +ROLL_STEP = 5.0 # degrees between the rolls of a joint's range that hose measures first: the step an assembly's clearance is read at +ROLL_FINEST = 0.3 # degrees: the half width under which a bin of rolls that falls short is refused instead of halved (5 degrees halved 4 times) def kit_work(work): @@ -1484,11 +1486,12 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): raise Refused(f"clamps cross the pin of {child.name!r} {len(changes)} times: list them in order along the hose, those on the start's side of the pin first; nothing changed.") pin = {"origin": axis[:3, 3], "axis": axis[:3, 2], "current": current, "before": changes[0], "child": child, "child_first": sides[0], "point": on["matrix"][:3, 3] + on["matrix"][:3, 2] * joint["standoff"]} - rest, moved = self.trees(start["depsgraph"], hose, pin and pin["child"]) + rest, moved, through = self.trees(start["depsgraph"], hose, pin and pin["child"], kits) reach = need + 2.0 * floor + self.step - occupied = self.reader((rest, moved), need + route.REACH * self.step) - far, far_rest, far_moved = self.reader((rest, moved), reach), self.reader((rest,), reach), self.reader((moved,), reach) - room = lambda a, b: float(far(route.along(a, b, self.step / 2.0)).min()) - need # noqa: E731 + roomy = route.BEND * floor # room beyond need a leg is searched with: what the arc of a quarter turn at the floor takes + occupied = self.reader((rest, moved, through), need + roomy + route.REACH * self.step) + far, far_rest, far_moved = self.reader((rest, moved, through), reach), self.reader((rest,), reach), self.reader((moved,), reach) + room = lambda a, b: route.room(a, b, far, need) # noqa: E731 exempt = max(lead, need) # a bundle wider than its lead stands on its own port's face that far stand = sizes["envelope"] + self.clearance + r # a clamped bundle's centre line above the socket's face: its pad is one radius thick held = 2.0 * 2.0 * r + floor @@ -1502,18 +1505,25 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): into, out = point, point if kind == "clamp": into, out = sorted((point - y * held, point + y * held), key=lambda p: float(np.linalg.norm(p - at))) - pulled, voxels = route.leg(at, into, occupied, far, need, self.step, HOSE_MARGIN, HOSE_VOXELS, f"leg {len(legs) + 1} ({came} to {label})") + name = f"leg {len(legs) + 1} ({came} to {label})" + for pad in (roomy, 0.0): # with room for its bends where a way with that room exists; a clamp stands nearer its seat than that + try: + pulled, voxels = route.leg(at, into, occupied, far, need, self.step, HOSE_MARGIN, HOSE_VOXELS, name, pad) + break + except route.RouteError: + if pad <= 0.0: + raise legs.append((pulled, voxels, kind, out)) at, came = out, label - shaped, refusal = None, None + shaped, refusals = None, [] for depth in dict.fromkeys((self.sag * 2.0 * r, 0.0)): # slack yields to clearance: a route the sag breaks is made taut try: shaped = self.shaped(legs, start, end, depth, room, far, far_rest, far_moved, pin, joint, need, floor, lead, exempt, 4.0 * 2.0 * r) # a clamp keeps 2 outside diameters of straight each side of its point break except route.RouteError as error: - refusal = refusal or error - if shaped is None: - raise refusal + refusals.append(("sagged" if depth > 0.0 else "taut", str(error))) + if shaped is None: # both attempts are named: the taut one is the one sag 0 would make + raise route.RouteError(refusals[0][1] if len({text for _, text in refusals}) == 1 else "; ".join(f"{how}: {text}" for how, text in refusals)) curve, made, sagged, least, swing = shaped built = self.built(curve, start, clamps, stand, r, sizes["spread"], half_width) except route.RouteError as error: @@ -1616,12 +1626,15 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): pins.append((child, socket[0], stated[2])) return pins - def trees(self, depsgraph, hose, child): - """(a tree of every mesh the depsgraph evaluates but this hose and the pin's child side, a tree of the child - side: the objects whose parent chain passes `child`), in world space; None for a side with no face. Membership - of the depsgraph is what makes a mesh an obstacle: no flag or name is read. Only evaluated meshes are read: no - datablock is made or freed.""" - sides = ([], []) + def trees(self, depsgraph, hose, child, kits): + """(a tree of every mesh the depsgraph evaluates but this hose, the pin's child side and the hoses through + the pin; a tree of the child side: the objects whose parent chain passes `child`; a tree of the other hoses + that cross the pin of `child`), in world space; None for a side with no face. Membership of the depsgraph is + what makes a mesh an obstacle: no flag or name is read for that. A hose through the same pin bends with it and + belongs to neither side: it is an obstacle where it stands (the first two trees and it are what a route keeps + clear of), and across the rolls each hose is measured against the parts of the two sides, not against where + the other hose stood. Only evaluated meshes are read: no datablock is made or freed.""" + sides = ([], [], []) for evaluated in depsgraph.objects: source = evaluated.original if evaluated.type != "MESH" or source == hose or not len(evaluated.data.polygons): @@ -1632,7 +1645,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): mesh.calc_loop_triangles() corners = np.zeros(3 * len(mesh.loop_triangles), dtype=np.int32) mesh.loop_triangles.foreach_get("vertices", corners) - sides[child is not None and child in self.chain(source)].append((points.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3], corners.reshape(-1, 3))) + sides[2 if child is not None and self.through(source, child, kits) else int(child is not None and child in self.chain(source))].append((points.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3], corners.reshape(-1, 3))) made = [] for side in sides: offsets = np.cumsum([0] + [len(points) for points, _ in side[:-1]]) @@ -1640,6 +1653,15 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): if side else None) return made + def through(self, source, child, kits) -> bool: + """Whether an object is a hose whose two stated ends stand on the two sides of the pin of `child`.""" + try: + stated = json.loads(source.get(HOSE, "null")) + ends = [bpy.data.objects.get(text if text in bpy.data.objects else text.rsplit(":", 1)[0]) for text in (stated["start"], stated["end"])] + except (ValueError, TypeError, KeyError, AttributeError): + return False + return None not in ends and any(found[0] == child for found in self.crossed(ends[0], ends[1], kits)) + @staticmethod def reader(trees, cap: float): """A route distance over trees: how far each point stands from the nearest face, no further than cap (a capped @@ -1658,7 +1680,8 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): def shaped(self, legs, start, end, depth, room, far, far_rest, far_moved, pin, joint, need, floor, lead, exempt, kept): """(curve, its fillet, the metres each leg sagged, the least distance outside the leads, the joint's passes or None) of the legs joined at one sag depth: one polyline from port to port, one fillet, one verification, and - with a pin every roll of its range from the range's low to its high every ROLL_STEP degrees.""" + with a pin its whole range: the rolls from the range's low to its high every ROLL_STEP degrees, each answering + for the rolls about it, and more between them where one falls short (route.passes).""" points, keep, centred, sagged, j, last = [start["matrix"][:3, 3]], [], [], [], None, None for pulled, _, kind, _ in legs: hung, drop = route.sag(pulled, depth, room) @@ -1675,12 +1698,12 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): centred.append(False) points = np.array(points) made = route.fillet(points, room, floor, lead, keep, centred) - least = route.verify(made.curve, far, need, exempt, self.step / 2.0) + least = route.verify(made.curve, far, need, exempt) swing = None if pin is not None: order = slice(None, None, -1) if pin["child_first"] else slice(None) # passes reads a polyline from the parent's side swing = route.passes(points[order], made.t[order], (len(points) - 1 - j) if pin["child_first"] else j, pin["origin"], pin["axis"], - route.rolls_of(joint["range"][0], joint["range"][1], ROLL_STEP), pin["current"], far_rest, far_moved, need, floor, exempt, self.step / 2.0, + route.rolls_of(joint["range"][0], joint["range"][1], ROLL_STEP), ROLL_FINEST, pin["current"], far_rest, far_moved, need, floor, exempt, keep=np.array(keep)[order]) return made.curve, made, sagged, least, swing diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 2988f00..5483183 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -784,7 +784,7 @@ }, { "name": "brokkr_kitbash.hose", - "doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut, and the whole polyline is rounded, each corner by the largest arc its measured room allows; the innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a pivot connection between its ends' parts): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres, \"range\": [lo, hi]}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. Every roll from lo to hi in steps of 5 degrees is measured, each side against the other side's parts where the roll puts them, without posing anything. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, sag per leg in metres, rolls, worstRoll, worstClearance, faces, volume, nonManifoldEdges and radii {least, corners}.", + "doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut with room for its bends where a way has it, and the whole polyline is rounded, each corner by the largest arc its measured room allows; the innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a pivot connection between its ends' parts): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres, \"range\": [lo, hi]}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. The whole range from lo to hi is measured without posing anything, each side against the other side's parts: a roll every 5 degrees answers for the rolls about it by what a point can move within them, and more are measured between where that falls short; another hose through the same pin is kept clear of where it stands, not across the rolls. Every line is measured so that nothing thinner than a spacing can stand between two readings, whatever the step. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, sag per leg in metres, rolls (how many were measured), worstRoll, worstClearance (least over the range, each reading less what its point can move within its roll's bin), faces, volume, nonManifoldEdges and radii {least, corners}.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/brokkr_kitbash/route.py b/surfaces/blender/brokkr_kitbash/route.py index d2eaaf7..75987e3 100644 --- a/surfaces/blender/brokkr_kitbash/route.py +++ b/surfaces/blender/brokkr_kitbash/route.py @@ -7,10 +7,13 @@ obstacle: the bundle's half width plus its clearance. A leg between two waypoints is searched on a voxel grid of the box around them (grid, wavefront), then pulled taut (pull). A voxel is free when it stands need plus half a voxel's diagonal from every obstacle: distance changes by at -most the distance moved, so every point of a step between two neighbouring free voxels keeps need. The legs joined are -one polyline; fillet rounds its corners, each by the largest arc its measured room allows, and verify measures the -curve. sag lowers the middle of a leg by what its room allows. passes turns the part of a polyline beyond a point on -a pin's axis through the pin's rolls and measures each. frames gives the rotation-minimising ups the tubes are swept +most the distance moved, so every point of a step between two neighbouring free voxels keeps need. The same bound is +what every measurement of a line rests on (measure): a reading answers for the piece around it, less half the piece's +length, and pieces are halved until that proves need, so nothing thinner than the spacing of some samples can stand +unseen between them; no measurement depends on the search's step. The legs joined are one polyline; fillet rounds its +corners, each by the largest arc its measured room allows, and verify measures the curve. sag lowers the middle of a leg +by what its room allows. passes turns the part of a polyline beyond a point on a pin's axis through the pin's rolls, +each roll answering for the rolls about it by what a point can move within them. frames gives the rotation-minimising ups the tubes are swept with (Wang, Juettler, Zheng and Liu, "Computation of rotation minimizing frames", ACM TOG 27(1), 2008: the double reflection method). @@ -32,6 +35,8 @@ NEIGHBOURS = [(i, j, k) for i in (-1, 0, 1) for j in (-1, 0, 1) for k in (-1, 0, REACH = math.sqrt(3.0) / 2.0 # of a voxel: how far a point of a step between two neighbouring voxels can stand from the nearer one STRAIGHT = 1e-9 # radians: a corner that turns less is no corner HELD = 1e-9 # metres under need that a reading may stand and hold it +FINE = 1e-3 # metres: the shortest piece measure halves to; a line must keep need by half of this to be proven +BEND = 1.0 - math.cos(math.pi / 4.0) # of a radius: how far the arc of a quarter turn stands from its tangent segments ARC = 24 # arc segments a radian of turn @@ -105,43 +110,95 @@ def wavefront(free: np.ndarray, start, goal) -> list: return way -def along(a, b, spacing: float) -> np.ndarray: - """Points from a to b, both included, no further apart than spacing.""" - a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64) - count = max(2, int(math.ceil(float(np.linalg.norm(b - a)) / spacing)) + 1) - return a[None] + (b - a)[None] * np.linspace(0.0, 1.0, count)[:, None] +class Measured(NamedTuple): + least: float # the least reading taken; of a measure that fell short, the reading that fell short + where: np.ndarray # the point it was taken at + short: bool # a piece is not proven to keep need -def clear(a, b, distance, need: float, spacing: float) -> bool: - return bool((np.asarray(distance(along(a, b, spacing))) >= need - HELD).all()) +def measure(a, b, distance, need: float, rate: float = 1.0, within: float | None = None) -> Measured: + """The segments a[i]..b[i] measured so that what stands between two readings is bounded, not sampled. A piece's + middle reads d, and a reading changes by at most `rate` times the distance moved (1 for a distance to obstacles), + so every point of a piece of length L reads at least d - rate x L / 2. A piece whose bound holds need is proven; + one whose middle reads under need falls short; any other is halved, down to FINE, where a piece still unproven + falls short too: a measure that is not short has proven need of every point, and a line that keeps need by under + rate x FINE / 2 is refused with the ones that do not keep it. With `within`, pieces are halved further until each + one's bound is within that much of the least reading (or the piece is FINE long): least less `within` then bounds + every point from below.""" + a, b = np.atleast_2d(np.asarray(a, dtype=np.float64)), np.atleast_2d(np.asarray(b, dtype=np.float64)) + least, where = math.inf, None + while len(a): + middle, length = (a + b) / 2.0, np.linalg.norm(b - a, axis=1) + reads = np.asarray(distance(middle), dtype=np.float64) + bound = reads - rate * length / 2.0 + unproven = bound < need - HELD + short = np.flatnonzero(unproven & ((reads < need - HELD) | (length <= FINE))) + if len(short): + worst = int(short[np.argmin(reads[short])]) + return Measured(float(reads[worst]), middle[worst], True) + if reads.min() < least: + least, where = float(reads.min()), middle[int(np.argmin(reads))] + again = unproven if within is None else unproven | ((bound < least - within) & (length > FINE)) + a, b = np.concatenate([a[again], middle[again]]), np.concatenate([middle[again], b[again]]) + return Measured(least, where, False) -def pull(points, distance, need: float, spacing: float) -> np.ndarray: - """A polyline pulled taut: from each kept point, the farthest later point in clear sight (need kept at samples no - further apart than spacing); the next point when none is.""" +def falls(reading: float, need: float) -> str: + """How a reading that fell short of need reads in a refusal.""" + return (f"under the {need:.4g} m the bundle needs" if reading < need - HELD else + f"too near the {need:.4g} m the bundle needs to prove it of what stands between two readings") + + +def clear(a, b, distance, need: float, rate: float = 1.0) -> bool: + return not measure(a, b, distance, need, rate).short + + +def room(a, b, distance, need: float) -> float: + """What every point of the segment a..b stands beyond need, less what verify needs to prove an arc that uses it + all: the least reading of a measure within FINE, less FINE for its bound and half of FINE more.""" + return measure(a, b, distance, -math.inf, within=FINE).least - need - 1.5 * FINE + + +def span(curve, low: float, high: float) -> np.ndarray: + """The part of a polyline between two lengths along it; no point when low is not under high.""" + curve = np.asarray(curve, dtype=np.float64) + s = np.r_[0.0, np.cumsum(np.linalg.norm(np.diff(curve, axis=0), axis=1))] + low, high = max(low, 0.0), min(high, float(s[-1])) + if not low < high: + return curve[:0] + ends = np.stack([np.interp((low, high), s, curve[:, axis]) for axis in range(3)], axis=1) + return np.vstack([ends[:1], curve[(s > low) & (s < high)], ends[1:]]) + + +def pull(points, distance, need: float, rate: float = 1.0) -> np.ndarray: + """A polyline pulled taut: from each kept point, the farthest later point in clear sight (the line between them + swept at need); the next point when none is.""" points = np.asarray(points, dtype=np.float64) kept, i = [points[0]], 0 while i < len(points) - 1: j = len(points) - 1 - while j > i + 1 and not clear(points[i], points[j], distance, need, spacing): + while j > i + 1 and not clear(points[i], points[j], distance, need, rate): j -= 1 kept.append(points[j]) i = j return np.array(kept) -def leg(a, b, occupancy, distance, need: float, step: float, margin: float, limit: int, name: str): +def leg(a, b, occupancy, distance, need: float, step: float, margin: float, limit: int, name: str, pad: float = 0.0): """(the pulled polyline from a to b, the voxels searched): a grid over the two ends' box plus margin, free where - `occupancy` reads need plus REACH of a voxel, a wavefront between the free voxels beside the ends, pulled at need - against `distance`. Refuses, naming the leg: an end nearer an obstacle than need, an end with no free voxel in - sight beside it, a box over the limit, and no way through.""" + `occupancy` reads need plus pad plus REACH of a voxel, a wavefront between the free voxels beside the ends, pulled + against `distance`. `pad` is room kept beyond need for the bends the leg's corners will get: a line pulled at + need alone grazes what it wraps, and the corner there has no room for an arc. Within twice pad of an end the pull + asks for half the distance from that end instead, since an end stands where it is given. Refuses, naming the + leg: an end nearer an obstacle than need, an end with no free voxel in sight beside it, a box over the limit, and + no way through.""" a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64) for label, point in (("start", a), ("end", b)): reads = float(np.asarray(distance(point[None]))[0]) if reads < need - HELD: raise RouteError(f"{name}: its {label} {spot(point)} stands {reads:.4g} m from an obstacle, under the {need:.4g} m the bundle needs") try: - cells = grid(np.minimum(a, b) - margin, np.maximum(a, b) + margin, step, occupancy, need + REACH * step, limit) + cells = grid(np.minimum(a, b) - margin, np.maximum(a, b) + margin, step, occupancy, need + pad + REACH * step, limit) except RouteError as error: raise RouteError(f"{name}: {error}") from None ends = [] @@ -150,15 +207,16 @@ def leg(a, b, occupancy, distance, need: float, step: float, margin: float, limi beside = [tuple(int(v) for v in middle + np.array(d)) for d in [(0, 0, 0)] + NEIGHBOURS] beside = [m for m in beside if all(0 <= m[axis] < cells.free.shape[axis] for axis in range(3)) and cells.free[m]] beside.sort(key=lambda m: float(np.linalg.norm(cells.lo + step * np.array(m) - point))) - seen = [m for m in beside if clear(point, cells.lo + step * np.array(m), distance, need, step / 2.0)] + seen = [m for m in beside if clear(point, cells.lo + step * np.array(m), distance, need)] if not seen: - raise RouteError(f"{name}: no free voxel stands in sight of its {label} {spot(point)}: an obstacle is nearer it than {need + REACH * step:.4g} m on every side") + raise RouteError(f"{name}: no free voxel stands in sight of its {label} {spot(point)}: an obstacle is nearer it than {need + pad + REACH * step:.4g} m on every side") ends.append(seen[0]) try: way = wavefront(cells.free, ends[0], ends[1]) except RouteError as error: raise RouteError(f"{name}: {error}") from None - return pull(np.vstack([a[None], cells.lo + step * np.array(way, dtype=np.float64), b[None]]), distance, need, step / 2.0), int(cells.free.size) + padded = distance if pad <= 0.0 else lambda p: np.asarray(distance(p)) - np.minimum(pad, 0.5 * np.minimum(np.linalg.norm(p - a, axis=1), np.linalg.norm(p - b, axis=1))) + return pull(np.vstack([a[None], cells.lo + step * np.array(way, dtype=np.float64), b[None]]), padded, need, 1.0 if pad <= 0.0 else 1.5), int(cells.free.size) def sag(points, depth: float, room, down=(0.0, 0.0, -1.0)): @@ -285,37 +343,35 @@ def fillet(polyline, room, floor: float, lead: float, keep=None, centred=None) - under = np.flatnonzero(radii < floor * (1.0 - 1e-9)) if len(under): c = int(under[np.argmin(radii[under])]) - raise RouteError(f"corner {c + 1} at {spot(polyline[c + 1])} turns {math.degrees(turn[c]):.1f} degrees and gets a bend of radius {radii[c]:.4g} m, under the floor {floor:.4g}: " - "its segments are too short or an obstacle stands too near it") + lengths, unit, _ = _turns(polyline) + free = np.maximum(lengths - _kept(len(lengths), lead, keep), 0.0) + each = np.where(np.zeros(len(lengths), dtype=bool) if centred is None else np.asarray(centred, dtype=bool), free / 2.0, free) + straight, tangent, depth = float(min(each[c], each[c + 1])), floor * math.tan(turn[c] / 2.0), floor * (1.0 - math.cos(turn[c] / 2.0)) + if straight < tangent: + why = (f"the bundle is too stiff for this route: the corner's segments leave {straight:.4g} m of straight for the {tangent:.4g} m its tangent takes at the floor " + "(a lower bend, thinner hoses, or ends, clamps and the pin point further apart)") + elif room is not None and _radius(polyline[c + 1], unit[c], unit[c + 1], float(turn[c]), straight, room) < floor * (1.0 - 1e-9): + stands = min(room(polyline[c + 1] - unit[c] * tangent, polyline[c + 1]), room(polyline[c + 1], polyline[c + 1] + unit[c + 1] * tangent)) + why = (f"the route passes too near an obstacle to bend here: its segments stand {max(stands, 0.0):.4g} m clear beyond what the bundle needs and the arc at the floor takes {depth:.4g} " + "(a lower bend, more room about the obstacle, or a clamp that leads the hose wide of it)") + else: + why = "it shares a segment with the corner beside it and their tangents do not both fit on it (a lower bend, or the two further apart)" + raise RouteError(f"corner {c + 1} at {spot(polyline[c + 1])} turns {math.degrees(turn[c]):.1f} degrees and gets a bend of radius {radii[c]:.4g} m, under the floor {floor:.4g}: {why}") return Filleted(*arcs(polyline, t), t, radii) -def samples(curve, spacing: float): - """(points, arc length at each) along a polyline, its own points included, no further apart than spacing.""" - curve = np.asarray(curve, dtype=np.float64) - lengths = np.linalg.norm(np.diff(curve, axis=0), axis=1) - starts = np.r_[0.0, np.cumsum(lengths)] - points, s = [curve[:1]], [np.zeros(1)] - for i, length in enumerate(lengths): - count = max(1, int(math.ceil(length / spacing))) - f = np.arange(1, count + 1) / count - points.append(curve[i][None] + (curve[i + 1] - curve[i])[None] * f[:, None]) - s.append(starts[i] + length * f) - return np.vstack(points), np.concatenate(s) - - -def verify(curve, distance, need: float, lead: float, spacing: float, name: str = "the hose") -> float: +def verify(curve, distance, need: float, lead: float, name: str = "the hose") -> float: """The least distance the curve stands from an obstacle outside its two leads (the first and last `lead` of its - length, where it leaves its own ports). Refuses a reading under need, naming the point.""" - points, s = samples(curve, spacing) - inside = (s >= lead) & (s <= s[-1] - lead) - if not inside.any(): + length, where it leaves its own ports), within half of FINE (measure). Refuses a curve not proven to keep need at + every point, naming the point.""" + curve = np.asarray(curve, dtype=np.float64) + inside = span(curve, lead, float(np.linalg.norm(np.diff(curve, axis=0), axis=1).sum()) - lead) + if len(inside) < 2: return math.inf - reads = np.asarray(distance(points[inside])) - worst = int(np.argmin(reads)) - if reads[worst] < need - HELD: - raise RouteError(f"{name} stands {float(reads[worst]):.4g} m from an obstacle at {spot(points[inside][worst])}, under the {need:.4g} m the bundle needs") - return float(reads[worst]) + swept = measure(inside[:-1], inside[1:], distance, need, within=FINE / 2.0) + if swept.short: + raise RouteError(f"{name} stands {swept.least:.4g} m from an obstacle at {spot(swept.where)}, {falls(swept.least, need)}") + return swept.least def thinned(curve, gap: float) -> np.ndarray: @@ -371,42 +427,93 @@ def rolls_of(low: float, high: float, step: float) -> list: return [float(v) for v in np.arange(low, high - 1e-9, step)] + [float(high)] -def passes(polyline, t, j: int, origin, axis, rolls, current: float, parent, child, need: float, floor: float, lead: float, spacing: float, keep=None) -> dict: - """A hose through a pin's rolls. `polyline` runs from the parent's side through point j, which stands on the - pin's axis (origin, axis), to the child's side; `t` are its tangent lengths at the roll `current`. At each roll - the points beyond j are turned about the axis by roll - current, as the child's parts are: the straights on each - side move with their own part, and only the corner at j is rounded again, its neighbours' tangents as they were. - The parent's side is then measured against the child's obstacles turned (`child` reads the child's parts where - they stand at `current`, so the samples are turned back), the child's side against the parent's (`parent`), and the - arc at j against both, all outside the leads. Refuses a roll whose bend at the pin is under the floor or whose - reading is under need, naming the roll, the side and the reading. {rolls, worstRoll, least, lengthChange, radius}.""" +def passes(polyline, t, j: int, origin, axis, rolls, finest: float, current: float, parent, child, need: float, floor: float, lead: float, keep=None) -> dict: + """A hose through a pin's rolls, every roll between the first and last of `rolls` and not those alone. `polyline` + runs from the parent's side through point j, which stands on the pin's axis (origin, axis), to the child's side; + `t` are its tangent lengths at the roll `current`. The points beyond j turn about the axis with the child's parts + and the straights and bends on each side move with their own part; only the corner at j is rounded again. + + Each roll of `rolls` answers for a bin: the rolls nearer it than any other. Within a bin of half width w a point + that stands rho from the axis moves at most rho x w against the other side's parts, so its reading against them + counts for that much less (`parent` and `child` read each side's parts where they stand at `current`; samples are + turned back for the child's). The bend at the pin has one radius through a bin, the largest that fits at the bin's + sharpest turn: its arc then stands within radius x (1 - cos(turn / 2)) of its two tangent segments, which are swept + for need and that much more. Everything else outside the leads is swept for need (measure). A bin that falls short + is halved and measured at each half's middle, down to `finest` degrees of half width, where it is refused, naming + the roll, the side, the point and the reading; so is a bin whose bend at the pin has no room for the floor. + {rolls: how many were measured, worstRoll, least: the least reading, each less what its point moves within its + bin, lengthChange, radius}.""" polyline, origin = np.asarray(polyline, dtype=np.float64), np.asarray(origin, dtype=np.float64) + axis = np.asarray(axis, dtype=np.float64) / np.linalg.norm(axis) c, least, lengths, radius = j - 1, (math.inf, None), [], math.inf - kept = _kept(len(polyline) - 1, lead, keep) - for roll in rolls: + off = float(np.linalg.norm(np.cross(polyline[j] - origin, axis))) + if off > 1e-6: # a point counted wrong (a sag's point before it, say) would turn the hose about a point it does not pass + raise RouteError(f"point {j} {spot(polyline[j])} of the hose stands {off:.4g} m off the pin's axis: the hose passes the pin at a point on it") + kept, sharp = _kept(len(polyline) - 1, lead, keep), np.array(t, dtype=np.float64) + sharp[c] = 0.0 + rolls = [float(v) for v in rolls] + edges = [rolls[0]] + [(u + v) / 2.0 for u, v in zip(rolls, rolls[1:])] + [rolls[-1]] + bins = [(edges[k + 1], edges[k], roll) for k, roll in reversed(list(enumerate(rolls)))] # a stack: the lowest roll is measured first + while bins: + high, low, roll = bins.pop() + half = max(high - roll, roll - low) + width = math.radians(half) posed = np.vstack([polyline[:j + 1], turned(polyline[j + 1:], origin, axis, roll - current)]) back = lambda points, roll=roll: turned(points, origin, axis, current - roll) # noqa: E731 - both = lambda points, back=back: np.minimum(np.asarray(parent(points)), np.asarray(child(back(points)))) # noqa: E731 + moves = lambda points: np.linalg.norm(np.cross(points - origin, axis), axis=1) * width # noqa: E731 + sides = {"parent's side": lambda p: np.minimum(np.asarray(parent(p)), np.asarray(child(back(p))) - moves(p)), + "child's side": lambda p: np.minimum(np.asarray(child(back(p))), np.asarray(parent(p)) - moves(p))} lengths_, unit, turn = _turns(posed) - t_roll = np.array(t, dtype=np.float64) - t_roll[c] = 0.0 - if turn[c] >= STRAIGHT: - cap = min(lengths_[c] - kept[c] - (t_roll[c - 1] if c > 0 else 0.0), lengths_[c + 1] - kept[c + 1] - (t_roll[c + 1] if c + 1 < len(t_roll) else 0.0)) - bend = _radius(posed[j], unit[c], unit[c + 1], float(turn[c]), float(cap), lambda a, b, both=both: float(both(along(a, b, spacing)).min()) - need) - if bend < floor * (1.0 - 1e-9): - raise RouteError(f"roll {roll:g}: the bend at the pin turns {math.degrees(turn[c]):.1f} degrees and gets radius {bend:.4g} m, under the floor {floor:.4g}") - t_roll[c], radius = bend * math.tan(turn[c] / 2.0), min(radius, bend) - curve, owner = arcs(posed, t_roll) - points, s = samples(curve, spacing) - at = np.r_[0.0, np.cumsum(np.linalg.norm(np.diff(curve, axis=0), axis=1))][owner == c] - inside = (s >= lead) & (s <= s[-1] - lead) - for side, chosen, reads in (("parent's side", inside & (s < at[0]), lambda p, back=back: np.asarray(child(back(p)))), - ("child's side", inside & (s > at[-1]), parent), - ("bend at the pin", inside & (s >= at[0]) & (s <= at[-1]), both)): - if chosen.any(): - reading = float(np.asarray(reads(points[chosen])).min()) - if reading < need - HELD: - raise RouteError(f"roll {roll:g}: the hose's {side} stands {reading:.4g} m from the parts on the other side of the pin, under the {need:.4g} m the bundle needs") - least = min(least, (reading, float(roll))) - lengths.append(float(s[-1])) + corner, sharpest = posed[j], min(float(turn[c]) + width, math.pi - 1e-6) + cap = min(lengths_[c] - kept[c] - (sharp[c - 1] if c > 0 else 0.0), lengths_[c + 1] - kept[c + 1] - (sharp[c + 1] if c + 1 < len(sharp) else 0.0)) + + def fits(bend: float): + """None, or (side, the measure that fell short, the dip) of the bend's two tangent segments at the bin's sharpest turn.""" + reach, depth = bend * math.tan(sharpest / 2.0), bend * (1.0 - math.cos(sharpest / 2.0)) + for side, a, b in (("parent's side", corner - unit[c] * reach, corner), ("child's side", corner, corner + unit[c + 1] * reach)): + swept = measure(a, b, sides[side], need + depth, 1.0 + width) + if swept.short: + return side, swept, depth + return None + + failed, bend, reach = None, math.inf, 0.0 + if sharpest >= STRAIGHT: + most = max(cap, 0.0) / math.tan(sharpest / 2.0) + if most < floor * (1.0 - 1e-9): + failed = (f"the bend at the pin turns up to {math.degrees(sharpest):.1f} degrees and its segments leave room for a radius of {most:.4g} m, under the floor {floor:.4g}", None) + else: + short = fits(floor) + if short is not None: + failed = (f"the bend at the pin turns up to {math.degrees(sharpest):.1f} degrees and at the floor radius {floor:.4g} its arc can dip {short[2]:.4g} m; " + f"the hose's {short[0]} beside it", short[1], need + short[2]) + else: + bend, high_ = floor, most + for _ in range(12 if fits(most) is not None else 0): + middle = (bend + high_) / 2.0 + bend, high_ = (middle, high_) if fits(middle) is None else (bend, middle) + bend = bend if high_ < most else most + reach = bend * math.tan(sharpest / 2.0) + curve, owner = arcs(posed, sharp) + s = np.r_[0.0, np.cumsum(np.linalg.norm(np.diff(curve, axis=0), axis=1))] + at = float(s[np.flatnonzero(owner == c)[0]]) + for side, part in (("parent's side", span(curve, lead, at - reach)), ("child's side", span(curve, at + reach, float(s[-1]) - lead))): + if failed is None and len(part) >= 2: + swept = measure(part[:-1], part[1:], sides[side], need, 1.0 + width) + if swept.short: + failed = (f"the hose's {side}", swept, need) + else: + least = min(least, (swept.least, float(roll))) + if failed is None: + radius = min(radius, bend) + lengths.append(float(s[-1]) + (0.0 if not math.isfinite(bend) else bend * (float(turn[c]) - 2.0 * math.tan(float(turn[c]) / 2.0)))) + continue + if half > finest and high > low: + bins += [(high, (low + high) / 2.0, (low + 3.0 * high) / 4.0), ((low + high) / 2.0, low, (3.0 * low + high) / 4.0)] + continue + through = f" through the {half:.3g} degrees either side of it" if half > 0.0 else "" + if failed[1] is None: + raise RouteError(f"roll {roll:.4g}: {failed[0]}{through}") + swept, bar = failed[1], failed[2] + raise RouteError(f"roll {roll:.4g}: {failed[0]} reads {swept.least:.4g} m from the parts about the pin at {spot(swept.where)}, counting the {float(moves(swept.where[None])[0]):.4g} m it can move against the other side's{through}: " + f"{falls(swept.least, bar)}") return {"rolls": len(lengths), "worstRoll": least[1], "least": least[0], "lengthChange": max(lengths) - min(lengths), "radius": radius} diff --git a/surfaces/blender/tests/test_route.py b/surfaces/blender/tests/test_route.py index 27a2932..973be7a 100644 --- a/surfaces/blender/tests/test_route.py +++ b/surfaces/blender/tests/test_route.py @@ -46,8 +46,19 @@ def nothing(points): return np.full(len(points), 10.0) -def room_of(distance, need: float, spacing: float = 0.002): - return lambda a, b: float(np.asarray(distance(route.along(a, b, spacing))).min()) - need +def room_of(distance, need: float): + return lambda a, b: route.room(a, b, distance, need) + + +def dense(a, b, spacing: float): + """This test's own reading of a segment: points no further apart than spacing.""" + a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64) + return a[None] + (b - a)[None] * np.linspace(0.0, 1.0, max(2, math.ceil(float(np.linalg.norm(b - a)) / spacing) + 1))[:, None] + + +def slab(x: float, half: float): + """A plate across x, `half` thick each side of it.""" + return lambda points: np.maximum(np.abs(np.asarray(points, dtype=np.float64)[:, 0] - x) - half, 0.0) def length(points) -> float: @@ -63,9 +74,9 @@ class SearchTests(unittest.TestCase): pulled, voxels = route.leg(a, b, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1") self.assertEqual(voxels, 131 * 31 * 31) self.assertTrue(np.allclose(pulled[0], a) and np.allclose(pulled[-1], b)) - dense = np.vstack([route.along(p, q, 0.0025) for p, q in zip(pulled[:-1], pulled[1:])]) # a quarter of the spacing pull samples at - self.assertGreaterEqual(float(distance(dense).min()), NEED - 1e-9) - through = dense[np.abs(dense[:, 0] - 1.0) < 0.02] + read = np.vstack([dense(p, q, 0.0025) for p, q in zip(pulled[:-1], pulled[1:])]) + self.assertGreaterEqual(float(distance(read).min()), NEED - 1e-9) + through = read[np.abs(read[:, 0] - 1.0) < 0.02] self.assertTrue(len(through) and (np.hypot(through[:, 1] - 0.2, through[:, 2] - 0.2) < 0.12 - NEED + 1e-9).all()) self.assertLess(length(pulled), 2.0 * math.hypot(1.0, 0.2 * math.sqrt(2.0)) + 0.05) # taut: near the two straights through the hole's middle @@ -76,10 +87,55 @@ class SearchTests(unittest.TestCase): for reach, holds in ((route.REACH, True), (0.0, False)): cells = route.grid([-0.1, -0.1, 0.0], [0.1, 0.1, 0.0], 0.02, rod, 0.043 + reach * 0.02) free = [np.array(m) for m in zip(*np.nonzero(cells.free))] - least = min(float(rod(route.along(cells.lo + 0.02 * p, cells.lo + 0.02 * q, 0.001)).min()) + least = min(float(rod(dense(cells.lo + 0.02 * p, cells.lo + 0.02 * q, 0.001)).min()) for p in free for q in free if 0 < np.abs(p - q).max() <= 1) self.assertEqual(least >= 0.043, holds, least) + def test_a_measure_proves_what_stands_between_its_readings(self): + """clearance-kept. Mutants M3 and M3b (verify and pull read at a spacing): a plate 1 mm thick stands between + two readings 0.1 apart, each of which keeps need, and the line through it is refused by measure, by pull and by + verify. The bound is a piece's reading less half its length: with the half length left out the first reading + of the whole segment would prove it.""" + plate, a, b = slab(1.0, 0.0005), np.array([0.05, 0.0, 0.0]), np.array([1.85, 0.0, 0.0]) + self.assertGreaterEqual(float(plate(dense(a, b, 0.1)).min()), 0.04) # readings 0.1 apart straddle it: the nearest stands 0.0495 off + swept = route.measure(a, b, plate, 0.01) + self.assertTrue(swept.short and swept.least < 0.01 and abs(float(swept.where[0]) - 1.0) < 0.0105, swept) + self.assertFalse(route.clear(a, b, plate, 0.01)) + self.assertTrue(route.clear(a, [0.98, 0.0, 0.0], plate, 0.01)) + over = np.array([a, [1.0, 0.0, 5.0], b]) # the plate ends nowhere: a pulled line keeps the point that leads round nothing, and is not shortened through it + self.assertEqual(len(route.pull(over, lambda points: np.where(np.asarray(points)[:, 2] > 4.0, 10.0, plate(points)), 0.01)), 3) + with self.assertRaisesRegex(route.RouteError, r"^the hose stands 0\.00\d+ m from an obstacle at \[(1|0\.99\d*|1\.00\d*), 0, 0\], under the 0\.01 m the bundle needs"): + route.verify(np.array([a, b]), plate, 0.01, 0.0) + ground = lambda points: np.asarray(points, dtype=np.float64)[:, 2] # noqa: E731 + along_ = lambda z: (np.array([0.0, 0.0, z]), np.array([1.0, 0.0, z])) # noqa: E731 + self.assertFalse(route.measure(*along_(0.01 + route.FINE), ground, 0.01).short) # a line that keeps need by FINE is proven + grazing = route.measure(*along_(0.01 + route.FINE / 4.0), ground, 0.01) # one that keeps it by less than half of FINE is not, and is refused as that + self.assertTrue(grazing.short and grazing.least >= 0.01) + self.assertIn("too near the 0.01 m the bundle needs to prove it", route.falls(grazing.least, 0.01)) + slope = lambda points: 0.3 + np.abs(np.asarray(points, dtype=np.float64)[:, 0] - 0.7137) # noqa: E731 + self.assertLess(route.measure([0.0, 0, 0], [1.0, 0, 0], slope, 0.01).least - 0.3, 0.3) # proven at need by a few readings + self.assertLess(route.measure([0.0, 0, 0], [1.0, 0, 0], slope, 0.01, within=route.FINE).least - 0.3, route.FINE) # the least itself, within the bound asked + self.assertTrue(np.allclose(route.span(np.array([[0.0, 0, 0], [1.0, 0, 0], [1.0, 1.0, 0]]), 0.5, 1.5), [[0.5, 0, 0], [1.0, 0, 0], [1.0, 0.5, 0]])) + self.assertEqual(len(route.span(np.array([[0.0, 0, 0], [1.0, 0, 0]]), 0.6, 0.4)), 0) + + def test_a_leg_searched_with_room_keeps_it_where_it_wraps(self): + """A line pulled at need grazes what it wraps, and the corner there has no room for an arc: with pad the + pulled line keeps need and pad of every point further than twice pad from its ends, and a corner's room is + the pad instead of what the pull happened to leave.""" + distance, pad = ball([1.0, 0.0, 0.0], 0.3), 0.03 + a, b = np.array([0.0, 0.0, 0.0]), np.array([2.0, 0.0, 0.0]) + tight = route.leg(a, b, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1")[0] + roomy = route.leg(a, b, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1", pad)[0] + least = lambda line: float(distance(np.vstack([dense(p, q, 0.002) for p, q in zip(line[:-1], line[1:])])).min()) # noqa: E731 + self.assertLess(least(tight), NEED + 0.2 * pad) + self.assertGreaterEqual(least(tight), NEED) + self.assertGreaterEqual(least(roomy), NEED + pad) + self.assertGreater(length(roomy), length(tight)) + near = np.array([0.66, 0.0, 0.0]) # an end that stands need from the ball has no voxel with that room beside it: the caller searches such a leg without + with self.assertRaisesRegex(route.RouteError, r"^leg 1: no free voxel stands in sight of its start \[0\.66, 0, 0\]: an obstacle is nearer it than 0\.08732 m on every side"): + route.leg(near, [0.0, 0.0, 0.0], distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1", pad) + self.assertEqual(len(route.leg(near, [0.0, 0.0, 0.0], distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1")[0]), 2) + def test_a_closed_way_a_buried_end_and_a_box_too_fine_are_refused_by_name(self): distance = wall(0.03) # a hole narrower than the bundle ends = (np.array([0.0, 0.0, 0.0]), np.array([2.0, 0.0, 0.0])) @@ -155,7 +211,7 @@ class FilletTests(unittest.TestCase): self.assertGreater(radius, 0.03 / depth) # more than the room at the segments' nearest points allows: the room is measured along the tangent segments only self.assertLess(radius, 0.25) arc = made.curve[made.owner == 0] - self.assertGreaterEqual(float(distance(np.vstack([route.along(p, q, 0.001) for p, q in zip(arc[:-1], arc[1:])])).min()), 0.05) + self.assertGreaterEqual(float(distance(np.vstack([dense(p, q, 0.001) for p, q in zip(arc[:-1], arc[1:])])).min()), 0.05) grown = route.arcs(points, np.array([t * 1.05]))[0] # the largest: 5 percent more breaks the rule t2 = t * 1.05 self.assertGreater(t2 / math.tan(math.pi / 4.0) * depth, min(room(points[1] - np.array([1.0, 0.0, 0.0]) * t2, points[1]), room(points[1], points[1] + np.array([0.0, 1.0, 0.0]) * t2))) @@ -163,14 +219,16 @@ class FilletTests(unittest.TestCase): free = route.fillet(points, None, 0.05, 0.0) self.assertAlmostEqual(float(free.radii[0]), 1.0, places=12) self.assertLess(float(distance(free.curve).min()), 0.0) - self.assertGreaterEqual(route.verify(made.curve, distance, 0.05, 0.0, 0.002), 0.05) + self.assertGreaterEqual(route.verify(made.curve, distance, 0.05, 0.0), 0.05) with self.assertRaisesRegex(route.RouteError, r"^the hose stands -0\.\d+ m from an obstacle at \[-0\.\d+, 0\.\d+, 0\], under the 0\.05 m"): - route.verify(free.curve, distance, 0.05, 0.0, 0.002) + route.verify(free.curve, distance, 0.05, 0.0) def test_a_corner_under_the_floor_is_refused_by_name(self): - with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[1, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.15 m, under the floor 0\.5"): + with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[1, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.15 m, under the floor 0\.5: the bundle is too stiff for this route: " + r"the corner's segments leave 0\.3 m of straight for the 0\.5 m its tangent takes at the floor"): route.fillet(self.ZIGZAG, None, 0.5, 0.2) - with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[0, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.00\d+ m, under the floor 0\.05"): + with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[0, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0(\.00\d+)? m, under the floor 0\.05: the route passes too near an obstacle to bend here: " + r"its segments stand 0(\.00\d+)? m clear beyond what the bundle needs and the arc at the floor takes 0\.01464 "): route.fillet(np.array([[-1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]]), room_of(ball([-0.05, 0.05, 0.0], 0.02), 0.05), 0.05, 0.0) # a ball in the corner def test_the_floor_is_the_innermost_hose_s(self): @@ -190,10 +248,10 @@ class FilletTests(unittest.TestCase): ground = lambda points: np.asarray(points, dtype=np.float64)[:, 2] # noqa: E731 span = np.array([[0.0, 0.0, 0.1], [1.0, 0.0, 0.1]]) hung, drop = route.sag(span, 0.1, room_of(ground, 0.05)) - self.assertAlmostEqual(drop, 0.025, places=12) - self.assertTrue(np.allclose(hung[1], [0.5, 0.0, 0.075])) + self.assertAlmostEqual(drop, 0.025 - 0.75 * route.FINE, places=12) # half the room: what the span stands beyond need, less what a measure cannot tell apart + self.assertTrue(np.allclose(hung[1], [0.5, 0.0, 0.1 - drop])) made = route.fillet(np.vstack([[[0.0, 0.0, 0.5]], hung, [[1.0, 0.0, 0.5]]]), room_of(ground, 0.05), 0.01, 0.1) - self.assertGreaterEqual(route.verify(made.curve, ground, 0.05, 0.1, 0.002), 0.05) + self.assertGreaterEqual(route.verify(made.curve, ground, 0.05, 0.1), 0.05) self.assertGreater(float(made.radii[1]), 1.0) # a gentle arc, not a kink high, drop = route.sag(span + [0.0, 0.0, 1.0], 0.1, room_of(ground, 0.05)) self.assertEqual((drop, len(high)), (0.1, 3)) @@ -256,7 +314,8 @@ class FrameTests(unittest.TestCase): class JointTests(unittest.TestCase): P = np.array([[0.5, 0.0, 1.0], [0.2, 0.0, 0.0], [0.5, 0.0, -1.0]]) # through a point on the x axis AXIS = (np.zeros(3), np.array([1.0, 0.0, 0.0])) - SIZES = {"need": 0.05, "floor": 0.05, "lead": 0.1, "spacing": 0.01} + SIZES = {"need": 0.05, "floor": 0.05, "lead": 0.1} + FINEST = 0.3 def test_a_polyline_through_the_axis_keeps_its_length_at_every_roll(self): """joint-passage.""" @@ -268,15 +327,24 @@ class JointTests(unittest.TestCase): self.assertAlmostEqual(length(posed), length(self.P), places=12) self.assertTrue(np.allclose(route.turned(np.array([[0.3, 1.0, 0.0]]), *self.AXIS, 90.0), [[0.3, 0.0, 1.0]])) # right-handed about +x t = route.fillet(self.P, None, 0.05, 0.1).t - found = route.passes(self.P, t, 1, *self.AXIS, rolls, 0.0, nothing, nothing, **self.SIZES) - self.assertEqual((found["rolls"], found["least"]), (27, 10.0)) + found = route.passes(self.P, t, 1, *self.AXIS, rolls, self.FINEST, 0.0, nothing, nothing, **self.SIZES) + self.assertEqual(found["rolls"], 27) + self.assertTrue(10.0 - 1.2 * math.radians(2.5) < found["least"] < 10.0, found) # a reading counts for less by what its point moves in half a step of the rolls + hung = np.vstack([route.sag(self.P[:2], 0.05, None)[0], route.sag(self.P[1:], 0.05, None)[0][1:]]) # sag-with-joint: each side hangs, and the pin point is still the one turned about + self.assertEqual(len(hung), 5) + sagged = route.passes(hung, route.fillet(hung, None, 0.05, 0.1).t, 2, *self.AXIS, rolls, self.FINEST, 0.0, nothing, nothing, **self.SIZES) + self.assertEqual(sagged["rolls"], 27) + self.assertLess(sagged["lengthChange"], found["lengthChange"]) # the hanging spans turn with their sides: only the bend at the pin changes, and its segments are shorter + with self.assertRaisesRegex(route.RouteError, r"^point 1 \[\S+, 0, \S+\] of the hose stands 0\.\d+ m off the pin's axis"): + route.passes(hung, route.fillet(hung, None, 0.05, 0.1).t, 1, *self.AXIS, rolls, self.FINEST, 0.0, nothing, nothing, **self.SIZES) self.assertGreater(found["lengthChange"], 0.01) # the bend at the pin is what changes: each roll's is the largest arc its segments give self.assertLess(found["lengthChange"], length(self.P) * (1.0 - math.pi / 4.0) * 2.0) # no more than every corner's shortcut def test_a_hairpin_roll_is_refused_by_name(self): t = route.fillet(self.P, None, 0.05, 0.1).t - with self.assertRaisesRegex(route.RouteError, r"^roll 180: the bend at the pin turns 180\.0 degrees and gets radius \S+e-\d+ m, under the floor 0\.05"): - route.passes(self.P, t, 1, *self.AXIS, [0.0, 90.0, 180.0], 0.0, nothing, nothing, **self.SIZES) + with self.assertRaisesRegex(route.RouteError, r"^roll 1[67]\d(\.\d+)?: the bend at the pin turns up to 1\d\d\.\d degrees and its segments leave room for a radius of \S+ m, under the floor 0\.05 " + r"through the 0\.\d+ degrees either side of it$"): + route.passes(self.P, t, 1, *self.AXIS, [0.0, 90.0, 180.0], self.FINEST, 0.0, nothing, nothing, **self.SIZES) def test_each_side_is_measured_against_the_other_where_the_roll_puts_it(self): """Mutants H5 (the child's obstacles not turned with the roll) and H6 (the range checked at its ends only): a @@ -284,19 +352,52 @@ class JointTests(unittest.TestCase): middle = (self.P[0] + self.P[1]) / 2.0 child = ball(route.turned(middle[None], *self.AXIS, -45.0)[0], 0.05) # where it stands at roll 0 t = route.fillet(self.P, None, 0.05, 0.1).t - for ends in ([-90.0, 90.0], [0.0]): - self.assertEqual(route.passes(self.P, t, 1, *self.AXIS, ends, 0.0, nothing, child, **self.SIZES)["rolls"], len(ends)) - with self.assertRaisesRegex(route.RouteError, r"^roll 35: the hose's parent's side stands 0\.0\d+ m from the parts on the other side of the pin, under the 0\.05 m"): - route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-90.0, 90.0, 5.0), 0.0, nothing, child, **self.SIZES) + self.assertEqual(route.passes(self.P, t, 1, *self.AXIS, [0.0], self.FINEST, 0.0, nothing, child, **self.SIZES)["rolls"], 1) + for rolls in ([-90.0, 90.0], route.rolls_of(-90.0, 90.0, 5.0)): # the rolls given are where measuring starts, not all that is measured: the two ends find it as the 5 degree steps do + with self.assertRaisesRegex(route.RouteError, r"^roll 3[34](\.\d+)?: the hose's parent's side reads 0\.0\d+ m from the parts about the pin at \[\S+, \S+, \S+\], counting the 0\.00\d+ m it can move " + r"against the other side's through the 0\.\d+ degrees either side of it: "): + route.passes(self.P, t, 1, *self.AXIS, rolls, self.FINEST, 0.0, nothing, child, **self.SIZES) seen = [] - route.passes(self.P, t, 1, *self.AXIS, [30.0], 10.0, nothing, lambda points: seen.append(np.array(points)) or nothing(points), **self.SIZES) + route.passes(self.P, t, 1, *self.AXIS, [30.0], self.FINEST, 10.0, nothing, lambda points: seen.append(np.array(points)) or nothing(points), **self.SIZES) line = (self.P[1] - self.P[0]) / np.linalg.norm(self.P[1] - self.P[0]) - on = [points for points in seen if len(points) > 3 and np.abs(np.cross(route.turned(points, *self.AXIS, 20.0) - self.P[0], line)).max() < 1e-12] + on = [points for points in seen if np.abs(np.cross(route.turned(points, *self.AXIS, 20.0) - self.P[0], line)).max() < 1e-12] self.assertTrue(on) # the parent's side was read turned back by roll - current: turned forward again it lies on its own segment - self.assertTrue(all(np.abs(np.cross(points - self.P[0], line)).max() > 0.01 for points in on)) + self.assertTrue(any(np.linalg.norm(np.cross(points - self.P[0], line), axis=1).min() > 0.01 for points in on)) # and as read it lay off it parent = ball(route.turned(((self.P[1] + self.P[2]) / 2.0)[None], *self.AXIS, 45.0)[0], 0.05) # a part of the parent the child's side swings into - with self.assertRaisesRegex(route.RouteError, r"^roll 35: the hose's child's side stands"): - route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-90.0, 90.0, 5.0), 0.0, parent, nothing, **self.SIZES) + with self.assertRaisesRegex(route.RouteError, r"^roll 3[34](\.\d+)?: the hose's child's side reads"): + route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-90.0, 90.0, 5.0), self.FINEST, 0.0, parent, nothing, **self.SIZES) + + def test_the_bend_at_the_pin_is_no_larger_than_its_room(self): + """A ball inside the bend at the pin that both of the corner's segments clear: the arc there takes the radius + whose dip the segments' room allows, not the largest its segments give. Mutant R3 (the bend's tangent segments + measured for need alone) rounds the corner under need of the ball.""" + inside = ball([0.28, 0.0, 0.0], 0.01) + t = route.fillet(self.P, None, 0.05, 0.1).t + self.assertGreater(float(inside(np.vstack([dense(self.P[0], self.P[1], 0.001), dense(self.P[1], self.P[2], 0.001)])).min()), 0.06) + free = route.passes(self.P, t, 1, *self.AXIS, [0.0], self.FINEST, 0.0, nothing, nothing, **self.SIZES)["radius"] + found = route.passes(self.P, t, 1, *self.AXIS, [0.0], self.FINEST, 0.0, inside, nothing, **self.SIZES)["radius"] + self.assertGreater(free, 2.0) + self.assertTrue(0.05 <= found < 0.5, found) + turn = float(route._turns(self.P)[2][0]) + arc = route.arcs(self.P, np.array([found * math.tan(turn / 2.0)]))[0] + self.assertGreaterEqual(float(inside(np.vstack([dense(p, q, 0.001) for p, q in zip(arc[:-1], arc[1:])])).min()), 0.05) + self.assertLess(float(inside(route.arcs(self.P, np.array([free * math.tan(turn / 2.0)]))[0]).min()), 0.05) # the largest arc its segments give stands under need of the ball + + def test_a_plate_between_two_rolls_is_found(self): + """range-sampled-not-swept. A part of the child 2 mm across that crosses the parent's side of the hose at roll + 17.5, half way between two rolls 5 degrees apart: at 15 and at 20 the hose reads 0.02 from it and keeps its + need of 0.01, and the range is refused at a roll between them. Mutant R1 (a reading not lessened by what its + point moves within its bin) accepts the range.""" + middle = (self.P[0] + self.P[1]) / 2.0 + child = ball(route.turned(middle[None], *self.AXIS, -17.5)[0], 0.001) + t, sizes = route.fillet(self.P, None, 0.05, 0.1).t, {**self.SIZES, "need": 0.01} + for roll in (15.0, 20.0): + self.assertGreater(float(child(route.turned(dense(self.P[0], self.P[1], 0.0005), *self.AXIS, -roll)).min()), 0.02) + self.assertEqual(route.passes(self.P, t, 1, *self.AXIS, [15.0], self.FINEST, 0.0, nothing, child, **sizes)["rolls"], 1) # one roll answers for itself alone + with self.assertRaisesRegex(route.RouteError, r"^roll 1[5-9]\.\d+: the hose's parent's side reads"): + route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-20.0, 20.0, 5.0), self.FINEST, 0.0, nothing, child, **sizes) + clear_of = route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-20.0, 10.0, 5.0), self.FINEST, 0.0, nothing, child, **sizes) + self.assertGreaterEqual(clear_of["rolls"], 7) # short of the plate the same range passes, with more rolls measured where the 5 degree bins fell short if __name__ == "__main__": From d3650ce6699a07a897a51cdd5ad598a28a09c275 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 17:47:42 +0100 Subject: [PATCH 120/223] live kitbash_hose: a 1 mm plate between two rolls, the coarsest step, a second bundle at the default step, a straight only verify measures; CLEAR and KEPT by the margin rule; docs (cut kit-hose, h2) CLEAR 0.017: shipped worst 0.032, mutant H4b (verify refuses nothing) 0.0089. KEPT 0.019: shipped 0.028, C1 0.013. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 68 +++++--- surfaces/blender/tests/live/kitbash_hose.py | 114 ++++++++++++-- .../tests/live/kitbash_hose.result.json | 145 +++++++++++++----- 3 files changed, 252 insertions(+), 75 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 4e6f012..3b8ed49 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -627,14 +627,27 @@ pulled taut. The legs joined are one polyline, and each corner is rounded by the allows: the arc stands within `radius * (1 - cos(turn / 2))` of its two tangent segments, so with that much room beyond the clearance measured along them it keeps the clearance. Where two arcs would overlap on a segment both shrink in proportion. The floor is `bend` outside diameters for the innermost hose (the centre line's is half the -bundle's spread more); a corner that gets less is refused, naming its point, the radius it got and the floor. The -finished curve is measured once more against every mesh before anything is written. +bundle's spread more). The finished curve is measured once more against every mesh before anything is written. -A corner that wraps an edge stands about 0.87 of a voxel beyond the clearance, and that is its room: the radius it -can get is `0.87 * step / (1 - cos(turn / 2))`. When a bend round an edge is refused under the floor, raise `step` -(the hose then swings wider), lower `clearance` or `bend`, or give the hose a clamp to steer it. A 90 degree bend -straight out of a fitting needs `0.29 * floor` of room at the lead's end, which a bundle of three at the default -clearance of 0.01 does not have: 0.005 does. +**Measured, not sampled.** Every line the route trusts (a sight line of the pull, a tangent segment's room, the +finished curve, each side at each roll) is measured by `route.measure`: a reading answers for the piece of line +around it, less half the piece's length, because a distance to obstacles changes by no more than the distance +moved. A piece that this proves clear is done, one that reads under the need is refused, and any other is halved, +down to 1 mm. So a plate thinner than any spacing cannot stand unseen between two readings, and no measurement +depends on `step`: `step` sets only how fine the search for a way is. The price is half a millimetre: a line that +keeps the clearance by less than that cannot be proven and is refused as too near. + +**Room for the bends.** A line pulled taut at the clearance alone grazes whatever it wraps, and the corner there +has no room for an arc; how much it happened to keep changed with `step`, so a bundle could route at 0.02 and at +0.03 and be refused at 0.0125. Each leg is therefore searched and pulled with room for its bends first: 0.29 of the +floor beyond the clearance, what the arc of a quarter turn at the floor takes (within twice that of a leg's end +the pull asks half the distance from the end instead, since an end stands where it is given). A leg with no way +that roomy (a clamp stands nearer its seat than that, and so does a gap the bundle only just passes) is searched +again without, and the hose is longer where the roomy way goes round. A corner under the floor is refused by what +limits it: the bundle too stiff for the route (the corner's segments are shorter than its tangent at the floor), +an obstacle too near the corner's segments for the arc (both distances named), or two corners that cannot share +the segment between them. The remedies are a lower `bend`, thinner or fewer hoses, waypoints further apart (a +larger `standoff`), or a clamp that leads the hose wide; a different `step` is not one. **Slack.** `sag` (outside diameters, default 1) lowers the middle of each free span's longest segment along world -z, by less where the span runs steeply, and never by more than half the room measured along it: both halves then @@ -651,17 +664,30 @@ between clamps, and a later clamp's strap follows the bundle as it arrives. `joint` names a socket on that pin's axis whose z runs along it (the free end face of the pin: a strut's `end_a_back`), a `standoff` and the pin's roll `range`. The hose passes through the point `standoff` beyond that socket, on the axis, as a robot's dress pack does: the straights on each side then move with their own part and -only the bend at that point changes with the roll. Every roll from `lo` to `hi` in steps of 5 degrees is measured -without posing anything: the child's side of the polyline is turned about the axis, the corner at the pin point is -rounded again, and each side is measured against the other side's parts where that roll puts them. A roll that -fails is refused by name (`roll 50: the hose's child's side stands 0.02384 m from the parts on the other side of -the pin`). `lengthChange` is the centre line's longest less its shortest over the range, as each roll rounds the +only the bend at that point changes with the roll. The whole range is measured without posing anything, not a +list of rolls in it. Each roll from `lo` to `hi` in steps of 5 degrees answers for the rolls nearer it than any +other: within such a bin of half width w a point that stands rho from the pin's axis moves at most `rho * w` +against the other side's parts, so its reading against them counts for that much less. The bend at the pin has one +radius through a bin, the largest that fits at the bin's sharpest turn, and its two tangent segments are measured +for the clearance and the arc's dip more. A bin that falls short is halved and measured again at each half's +middle, down to 0.3 degrees of half width, so a range that is clear costs 9 rolls for 40 degrees and one that +passes near a part costs more only there (`rolls` reports how many were measured). A range that fails is refused +by roll, side and point (`roll 49.22: the hose's child's side reads 0.02653 m from the parts about the pin at +[-0.2107, -0.2043, 0.7271], counting the 0.0005832 m it can move against the other side's through the 0.156 degrees +either side of it: under the 0.0266 m the bundle needs`); when the sagged route and the taut one both fail the +refusal names both. `worstClearance` is the least reading over the range, each less what its point can move within +its bin. `lengthChange` is the centre line's longest less its shortest over the rolls measured, as each rounds the bend. Two pins between the ends are refused: end the hose on a part between them. +Another hose through the same pin bends with it and belongs to neither side. A route keeps clear of it where it +stands, and across the rolls each hose is measured against the parts of the two sides, not against where the other +hose stood: give two hoses through one pin different standoffs, and their clearance from each other holds at the +pose they were routed at. + **What it writes.** One mesh object, a child of the start's object under identity matrices, with no modifier and no material: each hose, two ferrule collars at each of its ends, and the clamps, all swept by `core.sweep`. -`kit_hose` on it is the request as JSON, a record nothing reads back. Other hoses are obstacles like any mesh, so -route the stiffest first. The hose is a bake of the scene at the call: after a part moves or rolls, run `hose` +`kit_hose` on it is the request as JSON; the one thing read back from it is which two parts a hose joins, by a +later hose that crosses the same pin. Other hoses are obstacles like any mesh, so route the stiffest first. The hose is a bake of the scene at the call: after a part moves or rolls, run `hose` again with the same `object_name` and it is rebuilt in place. A hose that crosses a pin stays one object. In the exported mesh it is skinned geometry, meant to be weighted @@ -674,7 +700,7 @@ names no object, no such socket, or a socket of the wrong type; a bundle wider t part that is scaled or that Blender does not evaluate; a pin crossed with no `joint`, a `joint` with no pin, two pins, a `joint` socket off the pin's axis, the current roll outside `range`; a search box over 524288 voxels, naming a step that fits; an end nearer an obstacle than the bundle needs; no way through; a corner under the -floor; a roll that fails. +floor, by what limits it; a curve not proven to keep the clearance, naming the point; a roll that fails. **Cost.** Probes in Blender 5.3 on Starfire, medians of 3 interleaved repetitions: a nearest-face query on a tree of 81,920 faces takes 100 to 123 us uncapped and 3.4 us capped at 0.06 m, so every query is capped; on a grid of @@ -682,13 +708,13 @@ floor; a roll that fails. a knee of five boxes (96,565 voxels at 0.02 m) the occupancy took 0.46 s uncapped, the search 0.19 s, the pull, the fillet and the verification under 2 ms together, 27 rolls 0.056 s and the sweep of three hoses 4 ms. The live knee of `tests/live/kitbash_hose.py` (two struts, two actuators and a plate; two legs of 79,488 and 53,406 -voxels at roll 0, timed at roll 10; three hoses of 3,378 faces, 9 rolls) took 0.50 s a call, median of 3 each after one report action: 0.28 s of it -the occupancy (55 percent), 0.05 s the wavefront, 0.04 s the rolls, 0.02 s the fillet and its room, 0.01 s the -pull and the verification, and the rest the trees, the sweep and the write. The same call read 0.47 to 1.1 s -across runs while other Blenders were rendering on the machine. +voxels at roll 0, timed at roll 10; three hoses, 9 rolls) took 0.80 s a call, median of 3 each after one report +action, where it took 0.50 s when lines were sampled at half a voxel and each leg was searched once: the occupancy +is read to a larger cap and the room, the curve and the rolls are measured to 1 mm near what they pass. -`tests/test_route.py` proves the path without Blender (the half-diagonal rule, the fillet's tangency, sharing, room -and floor, the sag's bound, the frames against the double reflection method, the rolls), and +`tests/test_route.py` proves the path without Blender (the half-diagonal rule, a plate between two readings, a leg's +room where it wraps, the fillet's tangency, sharing, room and floor, the sag's bound, the frames against the double +reflection method, the rolls and a plate between two of them, the bend at the pin's room), and `tests/live/kitbash_hose.py` the action in Blender. ## Expressions diff --git a/surfaces/blender/tests/live/kitbash_hose.py b/surfaces/blender/tests/live/kitbash_hose.py index 0355a38..b9a74ca 100644 --- a/surfaces/blender/tests/live/kitbash_hose.py +++ b/surfaces/blender/tests/live/kitbash_hose.py @@ -68,20 +68,19 @@ LEAD = 8.0 * RADIUS FLOOR = 4.0 * 2.0 * RADIUS + SPREAD # of the centre line: the innermost hose keeps 4 outside diameters BUNDLE = {"count": COUNT_HOSES, "radius": RADIUS, "clearance": CLEARANCE} # Metres between a hose's surface and the nearest other mesh, read on the hose's own vertices further than the lead -# from both its ports (the least is the worst). The action promises the clearance asked for, 0.005, beyond the -# bundle's envelope, and a vertex of a 12-sided tube swept over chords of a 24th of a radian stands inside its circle -# by under 0.0002: the bound is that promise less the faceting. Shipped worst 0.030 (the second hose beside the -# first). No mutant of the cut's list lowers this reading: H10 (other hoses no obstacles) dies where a third hose is -# refused at a port a hose already holds, H4 (no verification) at tests/test_kitbash.py's count of route.verify, and -# H3 and H12 at tests/test_route.py; the reading is claimed by none of them and stands as the action's own promise. -CLEAR = 0.0048 +# from both its ports (the least is the worst), over every hose this suite makes. Shipped worst 0.032. Least claimed +# mutant 0.0089: H4b (route.verify measures and refuses nothing) accepts the hose past the plate beside a port's +# straight, section "verify", and the ring of it nearest the plate reads that; shipped refuses it and makes no hose. +# The geometric mean, separation 1.9 each side. +CLEAR = 0.017 # Metres a clamped hose's ring vertices stand off the radius about its own line over a clamp (the line through the # clamp point along the socket's y, offset across the bundle), over the 24 nearest; 1 when a hose has no 24 vertices # there. Shipped worst 4.6e-08 (float32 meshes); least claimed mutant 1 (C2, the straight laid along the socket's x: -# the route is refused, or no ring stands on the line); the geometric mean, separation 4700 each side. C1 (no -# straight kept at a clamp) reads 0.013 on `kept`, the least distance along the line from a clamp point to a ring, -# where shipped reads 0.028 and the promise is 0.024, two outside diameters. +# the route is refused, or no ring stands on the line); the geometric mean, separation 4700 each side. CLAMPED = 2.1e-4 +# Metres along a clamped hose's line from a clamp point to the nearest ring of a bend. Shipped 0.028; least claimed +# mutant 0.013 (C1, no straight kept at a clamp); the geometric mean, separation 1.47 each side. +KEPT = 0.019 def check(name, ok, detail=None): R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) @@ -236,7 +235,7 @@ try: receipt, report = send("brokkr_kitbash.hose", **FEED) R["reports"]["feed"] = report check("hose-behind-armour: three hoses route from the thigh's ram to the shin's, round the plate and through the pin point", - receipt["status"] == "accepted" and report["hoses"] == 3 and not report["rebuilt"] and report["nonManifoldEdges"] == 0 and report["rolls"] == 9 + receipt["status"] == "accepted" and report["hoses"] == 3 and not report["rebuilt"] and report["nonManifoldEdges"] == 0 and report["rolls"] >= 9 and report["clearance"] >= CLEARANCE and report["worstClearance"] >= CLEARANCE and report["radii"]["least"] >= FLOOR * (1 - 1e-6) and len(report["voxels"]) == 2, [receipt["status"], receipt["message"], report]) feed = bpy.data.objects["Feed"] @@ -261,12 +260,61 @@ try: _, again = send("brokkr_kitbash.hose", **FEED) check("a rebuild at the same pose reports what the first call did", {**again, "rebuilt": False} == report and len(bpy.data.meshes) == len(state[1]) + 1, again) check("hose-through-range: the range passes and reports the length's change", report["lengthChange"] is not None and report["lengthChange"] >= 0 and report["worstRoll"] is not None, report) - refused("a range that swings the shin's hose into the thigh's parts", {**FEED, "joint": json.dumps({**JOINT, "range": [-20, 90]})}, - "roll 50: the hose's child's side stands 0.02384 m from the parts on the other side of the pin, under the 0.0266 m the bundle needs") + refused("a range that swings the shin's hose into the thigh's parts, naming the sagged attempt and the taut one", {**FEED, "joint": json.dumps({**JOINT, "range": [-20, 90]})}, + "sagged: roll 49.22: the hose's child's side reads 0.02653 m from the parts about the pin at [-0.2107, -0.2043, 0.7271], counting the 0.0005832 m it can move against the other side's " + "through the 0.156 degrees either side of it: under the 0.0266 m the bundle needs; taut: roll 50.78: the hose's child's side reads 0.0264 m") + receipt, _ = send("brokkr_kitbash.hose", **{**FEED, "joint": json.dumps({**JOINT, "range": [-20, 90]})}) + check("the refusal names both attempts, each by its roll and its side", "sagged: roll " in str(receipt["message"]) and "; taut: roll " in str(receipt["message"]) + and str(receipt["message"]).count("the hose's child's side reads") == 2, receipt["message"]) + section("thin plate") + # A plate 1 mm thick, 4 cm square, on the thigh, where a point of the shin's side of a single hose stands at roll + # -17.5: between two of the rolls 5 degrees apart. At -20 and at -15 the hose keeps its need from it. + SINGLE = {**FEED, "object_name": "Single", "start": "ActT:port_rod", "end": "ActS:port_rod", "count": 1, "joint": json.dumps({**JOINT, "standoff": 0.24})} + _, single = send("brokkr_kitbash.hose", **SINGLE) + line = world_points(bpy.data.objects["Single"]) + pivot = frame(shin, "end_a_back") + origin, axis = pivot[:3, 3], pivot[:3, 2] + beyond = line[(line[:, 2] > origin[2] + 0.1) & (np.linalg.norm(line - frame(lower, "port_rod")[:3, 3], axis=1) > 0.15)] + far_point = beyond[np.argmax(np.linalg.norm(np.cross(beyond - origin, axis), axis=1))] + turn = math.radians(-17.5) + rel = far_point - origin + at = origin + rel * math.cos(turn) + np.cross(axis, rel) * math.sin(turn) + axis * float(rel @ axis) * (1.0 - math.cos(turn)) + way = np.cross(axis, at - origin) + way /= np.linalg.norm(way) + out = np.cross(way, axis) + corners = [at + axis * a * 0.02 + out * b * 0.02 + way * c * 0.0005 for c in (-1, 1) for a in (-1, 1) for b in (-1, 1)] + thin = bpy.data.objects.new("Thin", bpy.data.meshes.new("Thin")) + thin.data.from_pydata([tuple(v) for v in corners], [], [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (1, 5, 7, 3), (3, 7, 6, 2), (2, 6, 4, 0)]) + bpy.context.scene.collection.objects.link(thin) + bpy.context.view_layer.update() + thin.parent = thigh + thin.matrix_parent_inverse = thigh.matrix_world.inverted() + bpy.context.view_layer.update() + check("the plate stands in the single hose's swing, over 0.03 from where it stands now", single is not None and float(np.linalg.norm(line - at, axis=1).min()) > 0.03, float(np.linalg.norm(line - at, axis=1).min())) + refused("range-sampled-not-swept: a 1 mm plate the hose crosses between two rolls 5 degrees apart", SINGLE, "roll -1") + receipt, _ = send("brokkr_kitbash.hose", **SINGLE) + named = [float(part.split(":")[0]) for part in str(receipt["message"]).split("roll ")[1:]] + check("the refusal names a roll between -20 and -15 for each attempt", len(named) >= 1 and all(-20.0 < roll < -15.0 for roll in named), receipt["message"]) + receipt, narrow = send("brokkr_kitbash.hose", **{**SINGLE, "joint": json.dumps({**JOINT, "standoff": 0.24, "range": [-10, 20]})}) + check("short of the plate the same hose passes its range", receipt["status"] == "accepted" and narrow["rolls"] >= 7, receipt["message"]) + for name in ("Thin", "Single"): + gone = bpy.data.objects[name] + mesh = gone.data + bpy.data.objects.remove(gone) + bpy.data.meshes.remove(mesh) + bpy.context.view_layer.update() + section("coarse step") + # coarse-step-cuts-thin-plate: no measurement of a hose depends on the search's step. At the coarsest step the + # single taut hose of the finding and the bundle both keep the clearance from the 2 cm armour plate. + for label, extra in (("one taut hose", {"count": 1, "sag": 0.0}), ("the bundle", {})): + receipt, coarse = send("brokkr_kitbash.hose", **{**FEED, "step": 0.2, **extra}) + check(f"at step 0.2 {label} routes and keeps the clearance from every other mesh", receipt["status"] == "accepted" and coarse["rebuilt"] and coarse["clearance"] >= CLEARANCE + and reading("clear", surface_clearance(feed, ports), least=True) >= CLEAR, [receipt["message"], R["readings"]]) + section("range") send("brokkr_kitbash.roll", object_name="Shin", roll=10.0) bpy.context.view_layer.update() receipt, rolled = send("brokkr_kitbash.hose", **FEED) - check("after a roll the hose rebuilds in place on its name", receipt["status"] == "accepted" and rolled["rebuilt"] and bpy.data.objects["Feed"] == feed and rolled["rolls"] == 9, receipt["message"]) + check("after a roll the hose rebuilds in place on its name", receipt["status"] == "accepted" and rolled["rebuilt"] and bpy.data.objects["Feed"] == feed and rolled["rolls"] >= 9, receipt["message"]) check("the rebuilt hose keeps the clearance at the new pose", reading("clear", surface_clearance(feed, [frame(upper, "port_cap")[:3, 3], frame(lower, "port_cap")[:3, 3]]), least=True) >= CLEAR, R["readings"]) mesh = feed.data bpy.data.objects.remove(feed) @@ -277,10 +325,16 @@ try: check("hose-through-range: roll then rebuild gives the same report as a fresh hose", receipt["status"] == "accepted" and {**rolled, "rebuilt": False} == fresh, [rolled, fresh]) R["seconds"]["hose on the knee, median of 3"] = round(timed(FEED), 3) section("second hose") - RETURN = {"object_name": "Return", "start": "ActT:port_rod", "end": "ActS:port_rod", **BUNDLE, "step": 0.03, "joint": json.dumps({**JOINT, "standoff": 0.24})} # round the plate's edge a voxel of 0.02 leaves a bend under the floor + RETURN = {"object_name": "Return", "start": "ActT:port_rod", "end": "ActS:port_rod", **BUNDLE, "joint": json.dumps({**JOINT, "standoff": 0.24})} # the pin point further out than the first hose's, at the default step receipt, back = send("brokkr_kitbash.hose", **RETURN) R["reports"]["return"] = back - check("a second hose routes through the same knee", receipt["status"] == "accepted" and back["nonManifoldEdges"] == 0, [receipt["status"], receipt["message"]]) + check("second-bundle: a second hose routes through the same knee at the default step, its range measured against the parts and not against where the first hose stood", + receipt["status"] == "accepted" and back["nonManifoldEdges"] == 0 and back["rolls"] >= 9 and abs(json.loads(bpy.data.objects["Return"]["kit_hose"])["step"] - 0.02) < 1e-6, [receipt["status"], receipt["message"]]) + for step in (0.0125, 0.03, 0.04): # feasibility does not turn on the step: a leg is searched with room for its bends + receipt, _ = send("brokkr_kitbash.hose", **{**FEED, "step": step}) + check(f"the first hose's route also stands at step {step}, beside the second", receipt["status"] == "accepted", receipt["message"]) + send("brokkr_kitbash.hose", **FEED) + refused("a bundle too stiff for the knee, by what limits its bend", {**FEED, "bend": 16.0}, "under the floor 0.2076: ") rod_ports = [frame(upper, "port_rod")[:3, 3], frame(lower, "port_rod")[:3, 3]] check("hose-behind-armour: the second hose keeps the clearance from the first", reading("clear", surface_clearance(bpy.data.objects["Return"], rod_ports), least=True) >= CLEAR, R["readings"]) refused("a pin point another hose already passes", {**RETURN, "object_name": "Third"}, "from an obstacle") @@ -310,7 +364,7 @@ try: reading("clamped", near.max() if len(near) == 24 else 1.0) reading("kept", np.abs(along[off < 1e-5]).min() if (off < 1e-5).any() else 0.0, least=True) check("hose-clamps-ports: each hose passes each clamp point straight along the socket's y", R["readings"]["clamped"] <= CLAMPED, R["readings"]) - check("the bundle runs straight for two outside diameters each side of a clamp point: no ring of a bend stands nearer", R["readings"]["kept"] >= 4.0 * RADIUS * (1 - 1e-6), R["readings"]) + check("the bundle runs straight for two outside diameters each side of a clamp point: no ring of a bend stands nearer", R["readings"]["kept"] >= KEPT, R["readings"]) check("the clamped hose reports the clearance it keeps (its pads stand on their seats)", line["clearance"] >= CLEARANCE and surface_clearance(hose, [frame(tank, "port_b")[:3, 3], frame(ram, "port_cap")[:3, 3]]) < 1e-6, line["clearance"]) refused("a bundle wider than the port", {**LINE, "object_name": "Wide", "count": 5}, "a bundle of 5 hoses is 0.0744 m wide, over socket 'Ram:port_cap' (hose, size 0.048)") @@ -320,6 +374,32 @@ try: bpy.context.view_layer.update() receipt, loose = send("brokkr_kitbash.hose", object_name="Loose", start="Tank:port_a", end="Tip", radius=0.02) check("a hose runs from a flange to an empty", receipt["status"] == "accepted" and loose["hoses"] == 1 and shells(bpy.data.objects["Loose"]) == (5, 0), [receipt["status"], receipt["message"]]) + section("verify") + # h4-claimable-live: a straight hose from a ram's port to an empty in line with it has no corner and no pin, and + # its leg starts beyond the plate that stands 0.008 under its first straight: route.verify is the only thing that + # measures that straight, and refuses it. With verify refusing nothing (H4b) the hose is made and reads under CLEAR. + solo = place("Solo", "actuator", RAM, [10.0, 0.0, 0.0]) + bpy.context.view_layer.update() + mouth = frame(solo, "port_cap")[:3, 3] + stub = bpy.data.objects.new("Stub", None) + bpy.context.scene.collection.objects.link(stub) + stub.location, stub.rotation_euler = (float(mouth[0]) + 0.5, float(mouth[1]), float(mouth[2])), (0.0, -math.pi / 2, 0.0) # its z back along the line toward the port + box("Beside", (mouth[0] + 0.06, mouth[1] - 0.05, mouth[2] - 0.06), (mouth[0] + 0.08, mouth[1] + 0.05, mouth[2] - 0.008)) + bpy.context.view_layer.update() + PAST = {"object_name": "Past", "start": "Solo:port_cap", "end": "Stub", "radius": RADIUS, "clearance": CLEARANCE, "sag": 0.0} + state = scene_state() + receipt, _ = send("brokkr_kitbash.hose", **PAST) + past = bpy.data.objects.get("Past") + if past is not None: + reading("clear", surface_clearance(past, [mouth, np.array(stub.location)]), least=True) + check("h4: the straight past the plate is refused by route.verify, naming the point; nothing changed", + receipt["status"] != "accepted" and "the hose stands 0.008 m from an obstacle at [" in str(receipt["message"]) and "under the 0.011 m the bundle needs" in str(receipt["message"]) + and scene_state() == state, [receipt["status"], receipt["message"]]) + check("h4: no hose this suite made stands nearer another mesh than CLEAR", R["readings"]["clear"] >= CLEAR, R["readings"]) + bpy.data.objects["Beside"].location = (0.0, 0.0, -0.01) # 0.018 under the straight: the same call routes + bpy.context.view_layer.update() + receipt, past = send("brokkr_kitbash.hose", **PAST) + check("with the plate 0.018 under it the same straight is made", receipt["status"] == "accepted" and (past["radii"]["least"] is None or past["radii"]["least"] > 1e3) and abs(past["clearance"] - 0.012) < 1e-4, [receipt["message"], past]) section("refusals") refused("a name taken by a mesh that is no hose", {**FEED, "object_name": "Thigh"}, "An object named 'Thigh' exists and is no hose") refused("a socket the part does not have", {**FEED, "start": "ActT:nope"}, "start: 'ActT' (a actuator) has no socket 'nope'; its sockets: base, base_back, rod_end, rod_end_back, port_cap, port_rod") diff --git a/surfaces/blender/tests/live/kitbash_hose.result.json b/surfaces/blender/tests/live/kitbash_hose.result.json index a42ebae..5f50176 100644 --- a/surfaces/blender/tests/live/kitbash_hose.result.json +++ b/surfaces/blender/tests/live/kitbash_hose.result.json @@ -62,7 +62,42 @@ "detail": null }, { - "name": "refused, scene unchanged: a range that swings the shin's hose into the thigh's parts", + "name": "refused, scene unchanged: a range that swings the shin's hose into the thigh's parts, naming the sagged attempt and the taut one", + "ok": true, + "detail": null + }, + { + "name": "the refusal names both attempts, each by its roll and its side", + "ok": true, + "detail": null + }, + { + "name": "the plate stands in the single hose's swing, over 0.03 from where it stands now", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: range-sampled-not-swept: a 1 mm plate the hose crosses between two rolls 5 degrees apart", + "ok": true, + "detail": null + }, + { + "name": "the refusal names a roll between -20 and -15 for each attempt", + "ok": true, + "detail": null + }, + { + "name": "short of the plate the same hose passes its range", + "ok": true, + "detail": null + }, + { + "name": "at step 0.2 one taut hose routes and keeps the clearance from every other mesh", + "ok": true, + "detail": null + }, + { + "name": "at step 0.2 the bundle routes and keeps the clearance from every other mesh", "ok": true, "detail": null }, @@ -82,7 +117,27 @@ "detail": null }, { - "name": "a second hose routes through the same knee", + "name": "second-bundle: a second hose routes through the same knee at the default step, its range measured against the parts and not against where the first hose stood", + "ok": true, + "detail": null + }, + { + "name": "the first hose's route also stands at step 0.0125, beside the second", + "ok": true, + "detail": null + }, + { + "name": "the first hose's route also stands at step 0.03, beside the second", + "ok": true, + "detail": null + }, + { + "name": "the first hose's route also stands at step 0.04, beside the second", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a bundle too stiff for the knee, by what limits its bend", "ok": true, "detail": null }, @@ -131,6 +186,21 @@ "ok": true, "detail": null }, + { + "name": "h4: the straight past the plate is refused by route.verify, naming the point; nothing changed", + "ok": true, + "detail": null + }, + { + "name": "h4: no hose this suite made stands nearer another mesh than CLEAR", + "ok": true, + "detail": null + }, + { + "name": "with the plate 0.018 under it the same straight is made", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: a name taken by a mesh that is no hose", "ok": true, @@ -220,7 +290,7 @@ "hostErrors": [], "readings": { "clamped": 4.6e-08, - "clear": 0.03, + "clear": 0.032, "kept": 0.028, "slack": 0.021 }, @@ -229,33 +299,33 @@ "object": "Feed", "rebuilt": false, "hoses": 3, - "length": 1.64165, - "lengthChange": 0.030219, + "length": 1.646929, + "lengthChange": 0.029095, "floor": 0.0636, - "clearance": 0.005763, + "clearance": 0.024995, "capped": 0.1522, "voxels": [ 79488, 53406 ], "sag": [ - 0.001609, + 0.001879, 0.009076 ], "rolls": 9, "worstRoll": -20.0, - "worstClearance": 0.057408, + "worstClearance": 0.025029, "faces": 3378, - "volume": 0.000577078, + "volume": 0.000578788, "nonManifoldEdges": 0, "radii": { - "least": 0.123768, + "least": 0.122563, "corners": [ - 0.248224, - 0.123768, - 30.12343, - 0.218148, - 3.812707, + 0.297307, + 0.122563, + 31.156603, + 0.207446, + 3.895369, 0.129781 ] } @@ -264,33 +334,34 @@ "object": "Return", "rebuilt": false, "hoses": 3, - "length": 1.678891, - "lengthChange": 0.034002, + "length": 1.691847, + "lengthChange": 0.024737, "floor": 0.0636, - "clearance": 0.021671, - "capped": 0.1622, + "clearance": 0.026695, + "capped": 0.1522, "voxels": [ - 26040, - 28560 + 82110, + 92820 ], "sag": [ - 0.006276, + 0.008745, 0.00844 ], "rolls": 9, - "worstRoll": 20.0, - "worstClearance": 0.034016, - "faces": 4926, - "volume": 0.000589144, + "worstRoll": -20.0, + "worstClearance": 0.027636, + "faces": 5430, + "volume": 0.000593342, "nonManifoldEdges": 0, "radii": { - "least": 0.071383, + "least": 0.070247, "corners": [ - 0.073199, - 7.398753, - 0.071383, - 0.118904, - 10.830696, + 0.070247, + 4.795067, + 0.124489, + 0.24111, + 0.07885, + 10.851944, 0.095513 ] } @@ -299,10 +370,10 @@ "object": "Line", "rebuilt": false, "hoses": 3, - "length": 2.10108, + "length": 2.10125, "lengthChange": null, "floor": 0.0636, - "clearance": 0.011, + "clearance": 0.010962, "capped": 0.1522, "voxels": [ 49815, @@ -318,14 +389,14 @@ "worstRoll": null, "worstClearance": null, "faces": 2510, - "volume": 0.000777433, + "volume": 0.000777488, "nonManifoldEdges": 0, "radii": { - "least": 0.09689, + "least": 0.091455, "corners": [ 0.097757, 4.439012, - 0.09689, + 0.091455, 1.734649, 2.898844, 1.734649, From ef806e57771ca9a86b76f20c5a5920bf2f77119e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:14:45 +0100 Subject: [PATCH 121/223] brokkr_reference.core: a reference view's camera solved from marked points Ported from round 9's experiments/mechs/camsolve.py (3f45b67). The focal length is held to 4-4000 mm at the box's width; the record carries lens_band (an equal-error band, walked to the first miss or the bound) and lens_at_bound; square snaps the yaw to a quarter turn; solve refuses by ReferenceError naming the cause; camera_of reads blender() back. Place is solved as a dolly-zoom offset so log f alone is the distance-lens trade, and a parameter held at a bound sits out of the LM step. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/core.py | 333 ++++++++++++++++++++++ surfaces/blender/tests/test_reference.py | 250 ++++++++++++++++ 2 files changed, 583 insertions(+) create mode 100644 surfaces/blender/brokkr_reference/core.py create mode 100644 surfaces/blender/tests/test_reference.py diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py new file mode 100644 index 0000000..f9f4bf9 --- /dev/null +++ b/surfaces/blender/brokkr_reference/core.py @@ -0,0 +1,333 @@ +"""The camera of a reference view, solved from marked points. numpy and the standard library; no Blender. + +A reference image (a concept sheet, a render, a photograph) draws a view through some camera nobody wrote down. +Given points whose place in the world is known (a build's joints, sockets or vertices) and the pixel where the +image draws each, solve() finds the pinhole camera that draws them there: where it stands, how it is turned and +its focal length, all at once (PnP with the focal length unknown), by Levenberg-Marquardt from a grid of starts +round the points. docs/reference.md says what the answer is worth; in short, six or more points not all in one +plane decide the camera, and a long or square-on view decides everything but how far off it stands: distance and +focal length trade against each other (a dolly zoom), and "lens_band" says how far. + + world x right, y forward, z up, metres + pixels the image's, in whatever unit the points were marked in; v down + camera looks down its own -z, y up (Blender's); "R" turns world to camera; "f" is in pixels; "c" is the + principal point, at the middle of the view's box unless the model solves it (MODELS) + misses are weighed by a pseudo-Huber loss (SOFT pixels): a build poses some points elsewhere than the image + draws them, and those should not turn the camera + lens millimetres on a SENSOR mm sensor across the box's width, held inside LENS_MM + + solve(world, pixels, box, model="auto") the camera record, a dict that goes to JSON + project(cam, points) pixels of world points + ray(cam, pixel) (origin, unit direction) of a pixel's line of sight, in the world + lift(cam, pixel, plane_point, plane_normal) where that line of sight meets a plane: a traced 2D point made 3D + blender(cam, width) what a Blender camera takes to be this one, the frame being the box + camera_of(params, box) the record of a Blender camera: blender() read back + in_frame(cam, pixels, width) image pixels as pixels of the frame blender() renders + points(text, size), numbers(text, count) the action's string fields +""" +from __future__ import annotations + +import math + +import numpy as np + +SOFT = 10.0 # pixels: about the error of a point marked by hand; a point the build poses elsewhere misses by several times that +SENSOR = 36.0 # mm, fitted to the box's width +LENS_MM = (4.0, 4000.0) # the focal length never leaves this: past 4000 mm a view is orthographic to any marking, and an unbounded solve runs off (docs/reference.md) +BAND = 1.1 # lens_band: the lenses whose refitted rms is within this multiple of the best +STEP = 0.1 # the band is walked in steps of this in log f +MODELS = {"upright": (), "rolled": ("roll",), "free": ("roll", "centre"), "square": ("square",)} # what a model solves beyond place, yaw, pitch and focal length; "square" holds the yaw at a quarter turn instead +QUARTER = math.pi / 2 + + +class ReferenceError(ValueError): # noqa: A001 the package's refusal; the builtin of the same name (weakref) is not used here + """solve() or a field parser cannot take what it was given; the message names which.""" + + +def _rotation(yaw, pitch, roll): + """World to camera for a camera whose line of sight is turned `yaw` about the world's z from looking along +y, + pitched up by `pitch`, and rolled about its line of sight.""" + cy, sy, cp, sp, cr, sr = math.cos(yaw), math.sin(yaw), math.cos(pitch), math.sin(pitch), math.cos(roll), math.sin(roll) + look = np.array([-sy * cp, cy * cp, sp]) + right = np.array([cy, sy, 0.0]) + up = np.array([sy * sp, -cy * sp, cp]) # right x look + r, u = cr * right + sr * up, -sr * right + cr * up + return np.stack([r, u, -look]) + + +def project(cam, points): + """Pixels (n, 2) of world points (n, 3). A point behind the camera comes back far off the frame.""" + q = (np.asarray(points, float) - np.asarray(cam["C"], float)) @ np.asarray(cam["R"], float).T + z = np.where(q[:, 2] < -1e-6, -q[:, 2], 1e-6) + return np.stack([cam["c"][0] + cam["f"] * q[:, 0] / z, cam["c"][1] - cam["f"] * q[:, 1] / z], 1) + + +def ray(cam, pixel): + d = np.array([(pixel[0] - cam["c"][0]) / cam["f"], -(pixel[1] - cam["c"][1]) / cam["f"], -1.0]) @ np.asarray(cam["R"], float) + return np.asarray(cam["C"], float), d / np.linalg.norm(d) + + +def lift(cam, pixel, plane_point, plane_normal): + o, d = ray(cam, pixel) + n = np.asarray(plane_normal, float) + return o + d * (((np.asarray(plane_point, float) - o) @ n) / (d @ n)) + + +def lm(residual, p, low=None, high=None, rounds=80): + """Levenberg-Marquardt on a residual function, its Jacobian by differences. `low` and `high` (per parameter, + infinite where free) are bounds: a step is clipped to them, a difference that would cross one is taken the + other way, and a parameter held against one is left out of the step. Returns (p, residual).""" + p = np.array(p, float) + low = np.full(len(p), -np.inf) if low is None else np.asarray(low, float) + high = np.full(len(p), np.inf) if high is None else np.asarray(high, float) + p = np.clip(p, low, high) + r = residual(p) + lam = 1e-3 + for _ in range(rounds): + J = np.empty((len(r), len(p))) + for k in range(len(p)): + h = 1e-6 * max(1.0, abs(p[k])) + if p[k] + h > high[k]: + h = -h + q = p.copy() + q[k] += h + J[:, k] = (residual(q) - r) / h + J[:, ((p <= low) & (J.T @ r > 0)) | ((p >= high) & (J.T @ r < 0))] = 0.0 # a parameter at its bound and pulled past it sits this round out, so the others take their own step + A, g = J.T @ J, J.T @ r + for _ in range(12): + try: + step = np.linalg.solve(A + lam * np.diag(np.diag(A) + 1e-12), -g) + except np.linalg.LinAlgError: + lam *= 10 + continue + q = np.clip(p + step, low, high) + r2 = residual(q) + if r2 @ r2 < r @ r: + gain = (r @ r - r2 @ r2) / max(r @ r, 1e-30) + p, r, lam = q, r2, lam / 3 + break + lam *= 4 + else: + break + if gain < 1e-12: + break + return p, r + + +def _turned(W, turned, angle, pivot): + """W with its `turned` rows turned by `angle` about the vertical through `pivot`.""" + X = W.copy() + if turned.any(): + c, s = math.cos(angle), math.sin(angle) + d = W[turned, :2] - np.asarray(pivot, float) + X[turned, 0], X[turned, 1] = pivot[0] + c * d[:, 0] - s * d[:, 1], pivot[1] + s * d[:, 0] + c * d[:, 1] + return X + + +def _fit(W, P, c0, model, logf, f_fixed=None, near=None, turned=None, pivot=(0.0, 0.0), frame=None): + """The best camera of a model over a grid of starts, or from the one start `near` (the parameter vector of a + solve of nearly the same points): (rms pixels, parameter vector, camera, the points as solved, the turn). + `logf` is (low, high), the bounds of log f. `turned` marks the points that turn together about the vertical + through `pivot` (x, y) by one more unknown angle. The vector is place (3), yaw, pitch, then roll, log f, centre + (2) and the turn, each only when solved. Place is the camera's offset from the points' middle divided by f over + the marks' extent in pixels, so that log f alone is a dolly zoom: the camera backs off as the lens grows and + the picture keeps its size. A long view decides its lens loosely, and with place in metres the solve crawled + along that trade and stopped short of where the error was least. `frame` is the (middle, extent) a `near` + vector was solved in, when its points were not quite these.""" + extra = MODELS[model] + turned = np.zeros(len(W), bool) if turned is None else np.asarray(turned, bool) + twist = bool(turned.any()) + size = np.ptp(W, axis=0).max() + centre, px = (W.mean(0), np.ptp(P, axis=0).max()) if frame is None else frame + at = 5 + ("roll" in extra) # where log f sits when it is solved + + def split(p): + p = list(p) + off, yaw, pitch = np.array(p[:3]), p[3], p[4] + del p[:5] + if "square" in extra: + yaw = QUARTER * round(yaw / QUARTER) # held: a difference of 1e-6 never crosses to the next quarter, so the yaw's column is zero and it stays at its start + roll = p.pop(0) if "roll" in extra else 0.0 + f = f_fixed if f_fixed is not None else math.exp(min(max(p.pop(0), logf[0]), logf[1])) + c = [p.pop(0), p.pop(0)] if "centre" in extra else c0 + return {"C": centre + off * (f / px), "R": _rotation(yaw, pitch, roll), "f": f, "c": np.array(c, float)}, (p.pop(0) if twist else 0.0) + + def residual(p): + cam, angle = split(p) + r = project(cam, _turned(W, turned, angle, pivot)) - P + n = np.maximum(np.hypot(r[:, 0], r[:, 1]), 1e-9) # pseudo-Huber: a miss far past SOFT pixels pulls as its distance, not its square + return (r * (np.sqrt(2 * SOFT * SOFT * (np.sqrt(1 + (n / SOFT) ** 2) - 1)) / n)[:, None]).ravel() + + starts = [] + if near is not None: + starts.append(near) + else: + for az in (range(0, 360, 90) if "square" in extra else range(-180, 180, 45)): + for dist in (1.5, 6.0): + a = math.radians(az) + d = dist * size + starts.append([-size * math.sin(a), size * math.cos(a), 0.0, a + math.pi, 0.0] + [0.0] * ("roll" in extra) + + ([] if f_fixed is not None else [math.log(px * d / size)]) + (list(c0) if "centre" in extra else []) + [0.0] * twist) + low, high = np.full(len(starts[0]), -np.inf), np.full(len(starts[0]), np.inf) + if f_fixed is None: + low[at], high[at] = logf + best = None + for start in starts: + p, r = lm(residual, start, low, high) + if best is None or r @ r < best[0] - 1e-9: + best = (float(r @ r), p) + cam, angle = split(best[1]) + X = _turned(W, turned, angle, pivot) + miss = project(cam, X) - P + return math.sqrt((miss * miss).sum() / len(W)), best[1], cam, X, angle + + +def _left_out(W, P, c0, model, logf, f_fixed, near, turned, pivot): + """Leave-one-out: each point predicted by the camera solved without it; the rms of those misses, pixels.""" + miss, frame = [], (W.mean(0), np.ptp(P, axis=0).max()) + for k in range(len(W)): + keep = np.arange(len(W)) != k + start = near if turned[keep].any() or not turned.any() else near[:-1] + _, _, cam, _, angle = _fit(W[keep], P[keep], c0, model, logf, f_fixed=f_fixed, near=start, turned=turned[keep], pivot=pivot, frame=frame) + one = _turned(W[k:k + 1], turned[k:k + 1], angle, pivot) + miss.append(np.linalg.norm(project(cam, one)[0] - P[k])) + return float(np.sqrt(np.mean(np.square(miss)))) + + +def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.0)): + """world {name: [x, y, z]}, pixels {name: [u, v]}: the camera that draws the names both hold. `box` is the + view's box on the image [u0, v0, u1, v1]. `model` is one of MODELS: "upright" holds the camera level and its + centre at the middle of the box, "rolled" lets it roll, "free" solves the centre too (a view cropped off-axis); + "auto" takes whichever of those predicts left-out points best, since a freer model always fits the marked ones + closer. "square" is for a view drawn square-on from far off (a rear or side elevation): there the points lie + nearly in one plane across the line of sight, a turn of the camera and a narrower figure draw the same picture, + and the solve would spend the turn on the build's error in width; so the camera looks straight along a world + axis, whichever quarter turn fits best. `lens` (mm) holds the focal length instead of solving it: for a view + that must agree with another. `turned` names points that turn as one about the vertical through `pivot` (a + torso on its waist ring): the angle is solved with the camera, and "twist" is how far they turn from where + they were given. + + Returns the camera record: {"C", "R", "f", "c", "box", "lens" (mm), "lens_band" [low, high] (the lenses that + refit within BAND of the best rms, walked out from the best: an equal-error band, not a confidence interval), + "lens_at_bound" (None, or "short" or "long" when the solve stopped at an end of LENS_MM), "rms", "median" + (pixels), "worst" [name, pixels], "left_out" (the leave-one-out rms), "model", "tried" {model: rms, left_out, + lens}, "azimuth", "elevation" (degrees: where the camera stands round the points' middle), "distance", "roll", + "twist" (degrees), "residuals" {name: [du, dv]}}. Refuses with ReferenceError.""" + if model != "auto" and model not in MODELS: + raise ReferenceError(f"unknown model {model!r}: one of auto, {', '.join(MODELS)}") + box = [float(v) for v in box] + if len(box) != 4 or not all(math.isfinite(v) for v in box) or box[2] - box[0] <= 0 or box[3] - box[1] <= 0: + raise ReferenceError(f"box {box} has no {'width' if len(box) != 4 or not box[2] - box[0] > 0 else 'height'}: it is u0, v0, u1, v1 with u1 past u0 and v1 past v0") + width = box[2] - box[0] + if lens is not None and not LENS_MM[0] <= lens <= LENS_MM[1]: + raise ReferenceError(f"lens {lens} mm is outside {LENS_MM[0]:g} to {LENS_MM[1]:g} mm") + names = [k for k in pixels if k in world] + if len(names) < 6: + raise ReferenceError(f"{len(names)} points are named in both world and pixels; six are needed") + for k in names: + if len(world[k]) != 3 or len(pixels[k]) != 2 or not all(math.isfinite(v) for v in (*world[k], *pixels[k])): + raise ReferenceError(f"point {k!r} is not three finite world numbers and two finite pixel numbers: {list(world[k])}, {list(pixels[k])}") + W, P = np.array([world[k] for k in names], float), np.array([pixels[k] for k in names], float) + T = np.array([k in turned for k in names]) + c0 = [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2] + logf = (math.log(LENS_MM[0] * width / SENSOR), math.log(LENS_MM[1] * width / SENSOR)) + fixed = None if lens is None else lens * width / SENSOR + tried = {} + for m in (("upright", "rolled", "free") if model == "auto" else (model,)): + rms, p, cam, X, angle = _fit(W, P, c0, m, logf, f_fixed=fixed, turned=T, pivot=pivot) + tried[m] = (rms, p, cam, X, angle, _left_out(W, P, c0, m, logf, fixed, p, T, pivot)) + kind = min(tried, key=lambda k: tried[k][5]) + rms, p, cam, X, angle, left = tried[kind] + mm = lambda f: min(max(f * SENSOR / width, LENS_MM[0]), LENS_MM[1]) # noqa: E731 an end of the range reads as exactly that end + span, best = [cam["f"]], math.log(cam["f"]) + for way in ((-1, 1) if fixed is None else ()): # walk the lens out each way from the best, each solve started at the last, to the first that misses or to the bound + q, step = np.delete(p, 5 + ("roll" in MODELS[kind])), 1 + while True: + at = best + STEP * way * step + f = math.exp(min(max(at, logf[0]), logf[1])) + r_f, q = _fit(W, P, c0, kind, logf, f_fixed=f, near=q, turned=T, pivot=pivot)[:2] + if r_f > BAND * rms + 1e-9: + break + span.append(f) + if not logf[0] < at < logf[1]: + break + step += 1 + off = cam["C"] - X.mean(0) + res = project(cam, X) - P + worst = int(np.argmax(np.linalg.norm(res, axis=1))) + edge = None if fixed is not None else "short" if best <= logf[0] + 1e-9 else "long" if best >= logf[1] - 1e-9 else None + return {"C": [float(v) for v in cam["C"]], "R": [[float(v) for v in row] for row in cam["R"]], "f": float(cam["f"]), "c": [float(v) for v in cam["c"]], + "box": box, "lens": float(mm(cam["f"])), "lens_band": [float(mm(min(span))), float(mm(max(span)))], "lens_at_bound": edge, + "rms": float(rms), "median": float(np.median(np.linalg.norm(res, axis=1))), "worst": [names[worst], float(np.linalg.norm(res[worst]))], + "left_out": left, "model": kind, "tried": {k: {"rms": float(v[0]), "left_out": v[5], "lens": float(mm(v[2]["f"]))} for k, v in tried.items()}, + "azimuth": float(math.degrees(math.atan2(-off[0], off[1]))), "elevation": float(math.degrees(math.atan2(off[2], math.hypot(off[0], off[1])))), + "distance": float(np.linalg.norm(off)), "roll": float(math.degrees(p[5])) if "roll" in MODELS[kind] else 0.0, "twist": float(math.degrees(angle)), + "residuals": {k: [float(v) for v in r] for k, r in zip(names, res)}} + + +def blender(cam, width): + """What a Blender camera takes to be this one, the frame being the view's box at `width` pixels across: + {"matrix_world" (rows), "lens" (mm), "shift_x", "shift_y", "sensor_width", "sensor_fit", "resolution" [w, h]}. + The sensor is SENSOR mm, fitted HORIZONTAL, so both shifts are in widths of the frame.""" + R, C = np.asarray(cam["R"], float), np.asarray(cam["C"], float) + M = np.eye(4) + M[:3, :3], M[:3, 3] = R.T, C + u0, v0, u1, v1 = cam["box"] + w, h = u1 - u0, v1 - v0 + return {"matrix_world": [[float(v) for v in row] for row in M], "lens": float(cam["f"] * SENSOR / w), "shift_x": float(((u0 + u1) / 2 - cam["c"][0]) / w), + "shift_y": float((cam["c"][1] - (v0 + v1) / 2) / w), "sensor_width": SENSOR, "sensor_fit": "HORIZONTAL", "resolution": [int(width), int(round(width * h / w))]} + + +def camera_of(params, box=None, width=None): + """The camera record of a Blender camera, blender() read back: {"C", "R", "f", "c", "box", "lens"}. `params` is + what blender() returns (a scene camera's matrix_world rows, lens, shifts, sensor_width and the render's + resolution; the sensor fit must be HORIZONTAL, which is what AUTO means on a frame wider than tall). `box` is + the frame in the image's pixels; without one it is the frame itself from (0, 0), `width` pixels across (the + render's own width when that is not given either).""" + if params.get("sensor_fit", "HORIZONTAL") != "HORIZONTAL": + raise ReferenceError(f"sensor fit {params['sensor_fit']!r}: camera_of reads a HORIZONTAL fit only") + M = np.asarray(params["matrix_world"], float) + if box is None: + rx, ry = params["resolution"] + width = rx if width is None else width + box = [0.0, 0.0, float(width), float(width) * ry / rx] + u0, v0, u1, v1 = (float(v) for v in box) + w = u1 - u0 + return {"C": [float(v) for v in M[:3, 3]], "R": [[float(v) for v in row] for row in M[:3, :3].T], "f": float(params["lens"] * w / params.get("sensor_width", SENSOR)), + "c": [float((u0 + u1) / 2 - params["shift_x"] * w), float((v0 + v1) / 2 + params["shift_y"] * w)], "box": [u0, v0, u1, v1], "lens": float(params["lens"] * SENSOR / params.get("sensor_width", SENSOR))} + + +def in_frame(cam, pixels, width): + """Image pixels as pixels of the frame blender() renders at `width`. The frame's height is a whole number of + pixels, so it stands up to half a pixel taller or shorter than the box about the same middle.""" + u0, v0, u1, v1 = cam["box"] + k = width / (u1 - u0) + return (np.asarray(pixels, float) - np.array([u0, v0], float)) * k + np.array([0.0, (round(k * (v1 - v0)) - k * (v1 - v0)) / 2]) + + +def numbers(text, count, what): + """'1, 2.5, 3' as `count` finite floats; ReferenceError names `what`.""" + try: + values = [float(v) for v in text.split(",")] + except ValueError: + values = [] + if len(values) != count or not all(math.isfinite(v) for v in values): + raise ReferenceError(f"{what} {text.strip()!r} is not {count} finite numbers with commas between") + return values + + +def points(text, size, what): + """'a=1,2,3; b=4,5,6' as {name: [numbers]}, each of `size` numbers; ReferenceError names `what` and the entry. + A name given twice is refused: which of the two was meant is not this parser's to choose.""" + out = {} + for entry in (piece.strip() for piece in text.split(";")): + if not entry: + continue + name, _, values = entry.partition("=") + name = name.strip() + if not name: + raise ReferenceError(f"{what} entry {entry!r} has no name") + if name in out: + raise ReferenceError(f"{what} names {name!r} twice") + out[name] = numbers(values, size, f"{what} point {name!r}:") + return out diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py new file mode 100644 index 0000000..3462bb2 --- /dev/null +++ b/surfaces/blender/tests/test_reference.py @@ -0,0 +1,250 @@ +"""Reference camera tests. No Blender: brokkr_reference/core.py on seeded points drawn through known cameras, and +the host action file against Brokkr's own checker. + +Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) +The operator and a camera stood in a scene are exercised in a real Blender by tests/live/reference.py. + +Bounds follow lodur:ruling:deterministic-bound-margin: a reading here is the same on every run, so a bound a mutant +claims sits at the geometric mean of the shipped reading and that mutant's, and says both. The other numbers are +tolerances round a known truth that no mutant claims. The mutants, each run once on a scratch copy: + M1 plain squares for the pseudo-Huber loss test_one_point_60_px_off_does_not_turn_the_camera + M2 auto chooses by in-sample rms test_auto_takes_the_model_that_predicts_left_out_points + M3 the lens walk restarts from the grid test_the_band_is_walked_from_the_last_solve + M4 no bound on the focal length test_long_lenses_stay_finite_and_inside_the_range + M5 shift_y's sign flipped in blender() test_blender_params_draw_the_same_pixels + M6 the turned group is not turned test_a_turned_torso_is_recovered_as_twist + M7 square holds the yaw along y only test_square_solves_elevations_along_both_axes +""" +from __future__ import annotations + +import importlib.util +import json +import math +import sys +import types +import unittest +from pathlib import Path + +SURFACE = Path(__file__).resolve().parents[1] +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules.setdefault("brokkr_bridge", package) +from brokkr_bridge import action_table as at # noqa: E402 + +try: + import numpy as np +except ImportError: # pragma: no cover + np = None + +if np is not None: + spec = importlib.util.spec_from_file_location("brokkr_reference_core", SURFACE / "brokkr_reference" / "core.py") + core = importlib.util.module_from_spec(spec) + spec.loader.exec_module(core) + +BOX = [100.0, 50.0, 1100.0, 800.0] +NAMES = [f"p{i}" for i in range(13)] + + +def cloud(): + """Thirteen points in a box 3 m wide, 5 m long and 2 m tall.""" + return np.random.default_rng(3).uniform([-1.5, -2.5, 0.0], [1.5, 2.5, 2.0], (13, 3)) + + +def camera(points, azimuth, elevation, lens, centre=None): + """A camera `lens` mm long looking at the points' middle from far enough off that they fill most of the box.""" + f = lens * (BOX[2] - BOX[0]) / 36.0 + a, e = math.radians(azimuth), math.radians(elevation) + off = 1.3 * np.ptp(points, axis=0).max() * f / (BOX[2] - BOX[0]) + C = points.mean(0) + off * np.array([-math.sin(a) * math.cos(e), math.cos(a) * math.cos(e), math.sin(e)]) + return {"C": C, "R": core._rotation(a + math.pi, -e, 0.0), "f": f, "c": centre or [(BOX[0] + BOX[2]) / 2, (BOX[1] + BOX[3]) / 2], "box": BOX} + + +def marks(cam, points, noise=1.0, build=0.0, drawn=None): + """(world, pixels): the points as a build has them (`build` metres of error) and as the image draws them.""" + r = np.random.default_rng(5) + P = core.project(cam, points if drawn is None else drawn) + r.normal(0, noise, (len(points), 2)) + W = points + r.normal(0, build, points.shape) if build else points + return dict(zip(NAMES, W.tolist())), dict(zip(NAMES, P.tolist())) + + +def place_error(solved, cam): + return float(np.linalg.norm(np.array(solved["C"]) - cam["C"])) + + +@unittest.skipIf(np is None, "numpy") +class SolveTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.points = cloud() + cls.oblique = camera(cls.points, 35, 20, 50) + cls.world, cls.pixels = marks(cls.oblique, cls.points) + cls.auto = core.solve(cls.world, cls.pixels, BOX) + + def test_an_oblique_50_mm_view_is_recovered(self): + """recovers-oblique: 1 px of marking noise on 13 points. Read 50.22 mm, 0.031 m, 34.99 and 20.08 degrees, rms 1.17.""" + s = self.auto + self.assertAlmostEqual(s["lens"], 50.0, delta=1.0) + self.assertLess(place_error(s, self.oblique), 0.1) + self.assertAlmostEqual(s["azimuth"], 35.0, delta=0.3) + self.assertAlmostEqual(s["elevation"], 20.0, delta=0.3) + self.assertTrue(0.8 < s["rms"] < 1.6, s["rms"]) + self.assertEqual(s["lens_at_bound"], None) + self.assertEqual(sorted(s["residuals"]), sorted(NAMES)) + self.assertEqual(json.loads(json.dumps(s)), s) + + def test_one_point_60_px_off_does_not_turn_the_camera(self): + """M1. Azimuth off by 0.262 degrees shipped, 1.186 with plain squares: bound 0.557. Place off by 0.0411 m + shipped, 0.1401: bound 0.0759. Median miss 1.43 px shipped, 2.82: bound 2.01.""" + pixels = dict(self.pixels, p4=[self.pixels["p4"][0] + 60, self.pixels["p4"][1]]) + s = core.solve(self.world, pixels, BOX, model="upright") + self.assertLess(abs(s["azimuth"] - 35.0), 0.557) + self.assertLess(place_error(s, self.oblique), 0.0759) + self.assertLess(s["median"], 2.01) + self.assertEqual(s["worst"][0], "p4") + + def test_auto_takes_the_model_that_predicts_left_out_points(self): + """M2: on a centred view the free model fits the marks closest (rms 1.10 against upright's 1.17) and predicts + a left-out one worst (1.95 against 1.49); on a view cropped off-centre it is the only one that predicts.""" + self.assertEqual(self.auto["model"], "upright") + tried = self.auto["tried"] + self.assertLess(tried["free"]["rms"], tried["upright"]["rms"]) + self.assertLess(tried["upright"]["left_out"], tried["free"]["left_out"]) + cropped = camera(self.points, 35, 20, 50, centre=[640.0, 400.0]) + s = core.solve(*marks(cropped, self.points), BOX) + self.assertEqual(s["model"], "free") + self.assertAlmostEqual(s["c"][0], 640.0, delta=5.0) + + def test_the_band_is_an_equal_error_band(self): + """band-is-equal-error: a build 4 cm off. Every lens in the band refits within BAND of the best rms, and one + step past each end does not.""" + world, pixels = marks(self.oblique, self.points, build=0.04) + s = core.solve(world, pixels, BOX, model="upright") + low, high = s["lens_band"] + self.assertLess(low, s["lens"] * 0.95) + self.assertGreater(high, s["lens"] * 1.05) + for lens in (low, math.sqrt(low * s["lens"]), math.sqrt(high * s["lens"]), high): + self.assertLessEqual(core.solve(world, pixels, BOX, model="upright", lens=lens)["rms"], core.BAND * s["rms"] + 1e-6, lens) + for lens in (low * math.exp(-core.STEP), high * math.exp(core.STEP)): + self.assertGreater(core.solve(world, pixels, BOX, model="upright", lens=lens)["rms"], core.BAND * s["rms"], lens) + held = core.solve(world, pixels, BOX, model="upright", lens=low) + self.assertEqual((held["lens"], held["lens_band"], held["lens_at_bound"]), (low, [low, low], None)) + + def test_the_band_is_walked_from_the_last_solve(self): + """M3: each step of the walk is one solve started at the one before. Counted: 16 starts, 13 left-out solves, + one per lens inside the band and one past each end; restarting from the grid costs 16 per step.""" + world, pixels = marks(self.oblique, self.points, build=0.04) + calls, lm = [0], core.lm + + def counted(*args, **kwargs): + calls[0] += 1 + return lm(*args, **kwargs) + core.lm = counted + try: + s = core.solve(world, pixels, BOX, model="upright") + finally: + core.lm = lm + inside = round(math.log(s["lens_band"][1] / s["lens_band"][0]) / core.STEP) + self.assertGreater(inside, 2) + self.assertEqual(calls[0], 16 + 13 + inside + 2) + + def test_long_lenses_stay_finite_and_inside_the_range(self): + """long-lens-bounded, M4: with no bound the 400 mm view on a build 4 cm off runs log f to OverflowError and + the orthographic one reads 20208 mm.""" + for lens in (135, 400): + cam = camera(self.points, 35, 20, lens) + for build in (0.0, 0.04): + s = core.solve(*marks(cam, self.points, build=build), BOX, model="upright") + low, high = s["lens_band"] + self.assertTrue(core.LENS_MM[0] <= low <= s["lens"] <= high <= core.LENS_MM[1], (lens, build, s["lens"], s["lens_band"])) + self.assertTrue(low <= lens <= high or build == 0.0, (lens, build, s["lens_band"])) + self.assertTrue(all(math.isfinite(v) for v in s["C"])) + self.assertEqual(s["lens_at_bound"], "long" if s["lens"] == core.LENS_MM[1] else None) + far = camera(self.points, 35, 20, 1e5) # orthographic to any marking + s = core.solve(*marks(far, self.points, noise=0.0), BOX, model="upright") + self.assertEqual((s["lens"], s["lens_at_bound"], s["lens_band"][1]), (core.LENS_MM[1], "long", core.LENS_MM[1])) + self.assertLess(s["rms"], 1.0) + self.assertAlmostEqual(s["azimuth"], 35.0, delta=0.3) + + def test_a_turned_torso_is_recovered_as_twist(self): + """torso-turn, M6: five points drawn turned 12 degrees about a pivot. Twist off by 0.05 degrees shipped and + by 12 untwisted: bound 0.77. rms 1.16 px shipped, 23.5: bound 5.2.""" + turned, pivot = NAMES[:5], (0.2, -0.3) + drawn = core._turned(self.points, np.array([n in turned for n in NAMES]), math.radians(12), pivot) + world, pixels = marks(self.oblique, self.points, drawn=drawn) + s = core.solve(world, pixels, BOX, model="upright", turned=turned, pivot=pivot) + self.assertLess(abs(s["twist"] - 12.0), 0.77) + self.assertLess(s["rms"], 5.2) + + def test_square_solves_elevations_along_both_axes(self): + """square-quarter-turns, M7: a rear elevation (the camera behind, looking along +y) and a side elevation + (looking along x) at 300 mm. rms 1.17 and 1.19 px shipped; a yaw held to y only cannot draw the side view.""" + for azimuth in (180, 90): + cam = camera(self.points, azimuth, 0, 300) + s = core.solve(*marks(cam, self.points), BOX, model="square") + self.assertLess(s["rms"], 2.0, azimuth) + self.assertAlmostEqual(abs(s["azimuth"]), azimuth, delta=0.05) + look = -np.array(s["R"][2]) + self.assertLess(min(abs(look[0]), abs(look[1])), 1e-9) # straight along a world axis + + def test_refusals_name_their_cause(self): + """refusals""" + few = {k: self.pixels[k] for k in NAMES[:5]} + cases = (((self.world, few, BOX), {}, "5 points"), ((dict(self.world, p3=[0.0, float("nan"), 1.0]), self.pixels, BOX), {}, "'p3'"), + ((self.world, self.pixels, [100, 50, 100, 800]), {}, "no width"), ((self.world, self.pixels, [100, 50, 1100, 50]), {}, "no height"), + ((self.world, self.pixels, BOX), {"model": "x"}, "unknown model 'x'"), ((self.world, self.pixels, BOX), {"lens": 5000.0}, "5000")) + for args, kwargs, said in cases: + with self.assertRaises(core.ReferenceError) as caught: + core.solve(*args, **kwargs) + self.assertIn(said, str(caught.exception)) + self.assertTrue(issubclass(core.ReferenceError, ValueError)) + + +@unittest.skipIf(np is None, "numpy") +class CameraTests(unittest.TestCase): + CAM = {"C": [3.0, -7.0, 2.5], "f": 1400.0, "c": [640.0, 395.0], "box": BOX} + + def setUp(self): + self.cam = dict(self.CAM, R=core._rotation(0.4, -0.2, 0.05).tolist()) + self.points = cloud() + + def blender_pixels(self, params, points): + """Where Blender's camera draws world points, from its own definitions: the sensor spans the frame's width, + shifts are in frame widths, and the frame's middle is the optical axis moved by the shift.""" + M = np.array(params["matrix_world"]) + q = (points - M[:3, 3]) @ M[:3, :3] + w, h = params["resolution"] + x = q[:, 0] / -q[:, 2] * params["lens"] / params["sensor_width"] - params["shift_x"] + y = q[:, 1] / -q[:, 2] * params["lens"] / params["sensor_width"] - params["shift_y"] + return np.stack([(x + 0.5) * w, h / 2 - y * w], 1) + + def test_blender_params_draw_the_same_pixels(self): + """blender-round-trip, M5: the centre is 30 px below the box's middle, so a flipped shift_y moves every + point 72 px at this width.""" + for width in (1200, 777): + params = core.blender(self.cam, width) + self.assertEqual(params["resolution"], [width, round(width * 0.75)]) + ours = core.in_frame(self.cam, core.project(self.cam, self.points), width) + self.assertLess(np.abs(self.blender_pixels(params, self.points) - ours).max(), 1e-6) + + def test_camera_of_reads_blender_back(self): + back = core.camera_of(core.blender(self.cam, 1200), BOX) + for key in ("C", "R", "f", "c", "box"): + self.assertLess(np.abs(np.array(back[key]) - np.array(self.cam[key])).max(), 1e-9, key) + framed = core.camera_of(core.blender(self.cam, 1200)) # no box: the frame itself, in its own pixels + self.assertEqual(framed["box"], [0.0, 0.0, 1200.0, 900.0]) + self.assertLess(np.abs(core.project(framed, self.points) - core.in_frame(self.cam, core.project(self.cam, self.points), 1200)).max(), 1e-6) + with self.assertRaises(core.ReferenceError): + core.camera_of(dict(core.blender(self.cam, 1200), sensor_fit="VERTICAL")) + + def test_a_lifted_pixel_lies_on_its_plane_and_draws_back(self): + point = core.lift(self.cam, [500.0, 300.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]) + self.assertAlmostEqual(point[2], 1.0, places=9) + self.assertLess(np.abs(core.project(self.cam, point[None])[0] - [500.0, 300.0]).max(), 1e-6) + + def test_field_parsers(self): + self.assertEqual(core.points("a=1,2,3; b = 4, 5.5 ,6;", 3, "world"), {"a": [1.0, 2.0, 3.0], "b": [4.0, 5.5, 6.0]}) + self.assertEqual(core.numbers("100, 50,1100,800", 4, "box"), BOX) + for text, size, said in (("a=1,2", 3, "'a'"), ("a=1,2,3; a=4,5,6", 3, "twice"), ("=1,2", 2, "no name"), ("a=1,nan", 2, "'a'"), ("a=1,x", 2, "'a'")): + with self.assertRaises(core.ReferenceError) as caught: + core.points(text, size, "world") + self.assertIn(said, str(caught.exception)) From d6b8896e003032d1871ec2974853dbe1f7805aad Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:18:38 +0100 Subject: [PATCH 122/223] brokkr_reference.solve_camera: the host action, its row and its table tests Points go in as text (world, pixels, box, turned, pivot); with camera_name the camera is created or updated at the record and the render size set to the box. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/__init__.py | 90 +++++++++++++++++++ .../brokkr_reference/brokkr_actions.json | 85 ++++++++++++++++++ surfaces/blender/tests/test_reference.py | 57 +++++++++++- 3 files changed, 230 insertions(+), 2 deletions(-) create mode 100644 surfaces/blender/brokkr_reference/__init__.py create mode 100644 surfaces/blender/brokkr_reference/brokkr_actions.json diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py new file mode 100644 index 0000000..5a96b7f --- /dev/null +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -0,0 +1,90 @@ +"""Fit a scene to a reference image: the camera a reference view was drawn through, solved from marked points. + +A host add-on for Brokkr beside brokkr_mesh_polish (it imports that package's operator base, and nothing from +Brokkr): brokkr_actions.json beside this file lists the operators agents may run (docs/reference.md). The +arithmetic is core.py (numpy, tested without Blender); this file is the bpy around it. Every operator writes a +JSON report to WindowManager.brokkr_mesh_polish_result, as the polish operators do. + +The camera record core.solve returns is the truth; a Blender camera stood at it is derived by core.blender, and +core.camera_of reads one back. The images, traces and masks a view is marked on stay with whoever marked them: +this package takes points and gives cameras. +""" +bl_info = {"name": "Brokkr Reference", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), + "category": "Camera", "description": "Solve a reference view's camera from marked points; agent-callable through Brokkr."} + +import bpy +from mathutils import Matrix + +try: + from brokkr_mesh_polish import RESULT, PolishOperator, Refused + MISSING = None +except ImportError as error: # register() says so; the class below only needs something to subclass + RESULT, PolishOperator, Refused, MISSING = "brokkr_mesh_polish_result", bpy.types.Operator, RuntimeError, error + +from . import core + + +def stand(scene, name, cam, width): + """Create or update the camera object `name` at a camera record, the frame being the record's box at `width` + pixels across, and set the scene's render size to that frame: a pixel of the render is then the image's pixel + less the box's corner, times width over the box's width (core.in_frame). Returns core.blender's params.""" + params = core.blender(cam, width) + obj = bpy.data.objects.get(name) + if obj is None: + obj = bpy.data.objects.new(name, bpy.data.cameras.new(name)) + scene.collection.objects.link(obj) + data = obj.data + data.type, data.sensor_fit, data.sensor_width = "PERSP", params["sensor_fit"], params["sensor_width"] + data.lens, data.shift_x, data.shift_y = params["lens"], params["shift_x"], params["shift_y"] + data.clip_end = max(data.clip_end, 4 * cam["distance"]) + obj.matrix_world = Matrix(params["matrix_world"]) + scene.render.resolution_x, scene.render.resolution_y = params["resolution"] + return params + + +class BROKKR_REFERENCE_OT_solve_camera(PolishOperator): + """Solve the camera a reference view was drawn through from points known in the world and marked on the + image, and optionally stand a scene camera there""" + bl_idname = "brokkr_reference.solve_camera" + bl_label = "Solve Reference Camera" + world: bpy.props.StringProperty(name="World", maxlen=4000, description="name=x,y,z; name=x,y,z ... points in the world, metres") + pixels: bpy.props.StringProperty(name="Pixels", maxlen=4000, description="name=u,v; name=u,v ... where the image draws each, v down; six or more names shared with World") + box: bpy.props.StringProperty(name="Box", maxlen=120, description="u0,v0,u1,v1: the view's box on the image, in the pixels the points were marked in") + model: bpy.props.EnumProperty(name="Model", default="auto", description="What the camera may do beyond standing, turning and zooming", + items=[("auto", "Auto", "Upright, rolled or free, whichever predicts left-out points best"), + ("upright", "Upright", "Level, its centre at the middle of the box"), ("rolled", "Rolled", "May roll about its line of sight"), + ("free", "Free", "May roll, and its centre is solved (a view cropped off-axis)"), + ("square", "Square", "Looks straight along a world axis: an elevation drawn from far off")]) + lens: bpy.props.FloatProperty(name="Lens", default=0.0, min=0.0, max=4000.0, description="mm on a 36 mm sensor across the box; 0 solves it. Hold it for a view that must agree with another") + turned: bpy.props.StringProperty(name="Turned", maxlen=2000, description="Names, spaces between, of points that turn as one about the vertical through Pivot; the angle is solved") + pivot: bpy.props.StringProperty(name="Pivot", maxlen=80, description="x,y of that vertical; empty is 0,0") + camera_name: bpy.props.StringProperty(name="Camera", maxlen=63, description="A camera object to create or update at the solved camera, with the scene's render size; empty only computes") + width: bpy.props.IntProperty(name="Width", default=1000, min=16, max=16384, description="Pixels across the frame the box becomes") + + def work(self, context): + if self.camera_name and getattr(bpy.data.objects.get(self.camera_name), "type", "CAMERA") != "CAMERA": + raise Refused(f"{self.camera_name!r} is an object that is not a camera.") + try: + cam = core.solve(core.points(self.world, 3, "world"), core.points(self.pixels, 2, "pixels"), core.numbers(self.box, 4, "box"), model=self.model, + lens=self.lens or None, turned=tuple(self.turned.split()), pivot=core.numbers(self.pivot, 2, "pivot") if self.pivot.strip() else (0.0, 0.0)) + except core.ReferenceError as refusal: + raise Refused(str(refusal)) from None + report = {**cam, "residuals": {k: [round(v, 2) for v in r] for k, r in cam["residuals"].items()}, "camera": None} # hundredths of a pixel: 280 points still fit a receipt + if self.camera_name: + report.update(camera=self.camera_name, blender=stand(context.scene, self.camera_name, cam, self.width)) + return report + + +classes = (BROKKR_REFERENCE_OT_solve_camera,) + + +def register(): + if MISSING is not None or not hasattr(bpy.types.WindowManager, RESULT): + raise RuntimeError(f"brokkr_reference needs brokkr_mesh_polish enabled first ({MISSING or 'its result property is not registered'}).") + for cls in classes: + bpy.utils.register_class(cls) + + +def unregister(): + for cls in reversed(classes): + bpy.utils.unregister_class(cls) diff --git a/surfaces/blender/brokkr_reference/brokkr_actions.json b/surfaces/blender/brokkr_reference/brokkr_actions.json new file mode 100644 index 0000000..759504c --- /dev/null +++ b/surfaces/blender/brokkr_reference/brokkr_actions.json @@ -0,0 +1,85 @@ +{ + "schema": "brokkr.blender.host_actions.v0", + "actions": [ + { + "name": "brokkr_reference.solve_camera", + "doc": "Solve the camera a reference view was drawn through from six or more points known in the world and marked on the image; with camera_name, stand a camera there and set the render size to the view's box. The result is the camera record (docs/reference.md).", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "world", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 4000, + "doc": "name=x,y,z; name=x,y,z ... points in the world: x right, y forward, z up, metres" + }, + { + "name": "pixels", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 4000, + "doc": "name=u,v; name=u,v ... where the image draws each, v down; six or more names shared with world" + }, + { + "name": "box", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 120, + "doc": "u0,v0,u1,v1: the view's box on the image, in the pixels the points were marked in" + }, + { + "name": "model", + "type": "string", + "enum": [ + "auto", + "upright", + "rolled", + "free", + "square" + ], + "default": "auto", + "doc": "auto takes upright, rolled or free by leave-one-out error; square looks straight along a world axis (an elevation)" + }, + { + "name": "lens", + "type": "number", + "minimum": 0, + "maximum": 4000, + "default": 0, + "doc": "mm on a 36 mm sensor across the box; 0 solves it, 4 to 4000 holds it (a view that must agree with another)" + }, + { + "name": "turned", + "type": "string", + "maxLength": 2000, + "doc": "names, spaces between, of points that turn as one about the vertical through pivot; the angle is solved as twist" + }, + { + "name": "pivot", + "type": "string", + "maxLength": 80, + "doc": "x,y of that vertical; absent is 0,0" + }, + { + "name": "camera_name", + "type": "string", + "maxLength": 63, + "doc": "a camera object to create or update at the solved camera; absent only computes" + }, + { + "name": "width", + "type": "integer", + "minimum": 16, + "maximum": 16384, + "default": 1000, + "doc": "pixels across the frame the box becomes when camera_name is given" + } + ] + } + ] +} diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index 3462bb2..f2f0c2f 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -20,6 +20,7 @@ from __future__ import annotations import importlib.util import json import math +import re import sys import types import unittest @@ -177,11 +178,12 @@ class SolveTests(unittest.TestCase): def test_square_solves_elevations_along_both_axes(self): """square-quarter-turns, M7: a rear elevation (the camera behind, looking along +y) and a side elevation - (looking along x) at 300 mm. rms 1.17 and 1.19 px shipped; a yaw held to y only cannot draw the side view.""" + (looking along x) at 300 mm. The side view's rms is 1.19 px shipped and 193.9 with the yaw held to y only: + bound 15.2.""" for azimuth in (180, 90): cam = camera(self.points, azimuth, 0, 300) s = core.solve(*marks(cam, self.points), BOX, model="square") - self.assertLess(s["rms"], 2.0, azimuth) + self.assertLess(s["rms"], 15.2, azimuth) self.assertAlmostEqual(abs(s["azimuth"]), azimuth, delta=0.05) look = -np.array(s["R"][2]) self.assertLess(min(abs(look[0]), abs(look[1])), 1e-9) # straight along a world axis @@ -248,3 +250,54 @@ class CameraTests(unittest.TestCase): with self.assertRaises(core.ReferenceError) as caught: core.points(text, size, "world") self.assertIn(said, str(caught.exception)) + + +class HostFileTests(unittest.TestCase): + def setUp(self): + self.document = json.loads((SURFACE / "brokkr_reference" / "brokkr_actions.json").read_text(encoding="utf-8")) + self.host = [{**row, "host": "brokkr_reference"} for row in self.document["actions"]] + self.envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver", "action": "brokkr_reference.solve_camera"} + + def test_brokkr_admits_the_file(self): + """rows-check: Brokkr's own host-file checker.""" + at.check_host(self.document, at.table()["charsets"]) + + def test_the_row_names_the_operator_and_properties_the_add_on_defines(self): + source = (SURFACE / "brokkr_reference" / "__init__.py").read_text(encoding="utf-8") + (row,) = self.document["actions"] + self.assertIn(f'bl_idname = "{row["name"]}"', source) + self.assertEqual(row.get("result"), "brokkr_mesh_polish_result") + body = source.split(f'bl_idname = "{row["name"]}"')[1].split("def work")[0] + for field in row["fields"]: + self.assertIn(f" {field['name']}: bpy.props.", body, field["name"]) + self.assertEqual(body.count(": bpy.props."), len(row["fields"])) + + def test_a_valid_intent_is_admitted_and_a_bound_miss_is_refused(self): + fields = {"world": "a=0,0,0", "pixels": "a=1,2", "box": "0,0,10,10"} + admitted = at.validate({**self.envelope, **fields}, self.host) + self.assertEqual((admitted["model"], admitted["lens"], admitted["width"]), ("auto", 0, 1000)) + for bad in ({"lens": 4001}, {"model": "fisheye"}, {"width": 8}, {"world": ""}): + with self.assertRaises(at.IntentInvalid): + at.validate({**self.envelope, **fields, **bad}, self.host) + + +class OwnershipTests(unittest.TestCase): + """The negative patterns of the cut: the arithmetic needs no Blender, the images and sheets stay with whoever + marked them, and no other package reaches into this one.""" + + def test_core_does_not_import_blender(self): + self.assertIsNone(re.search(r"import bpy|mathutils", (SURFACE / "brokkr_reference" / "core.py").read_text(encoding="utf-8"))) + + def test_the_package_reads_no_image_or_sheet(self): + for path in (SURFACE / "brokkr_reference").glob("*"): + if path.is_file(): + self.assertIsNone(re.search(r"concepts\.json|PIL|Image\.open", path.read_text(encoding="utf-8")), path.name) + + def test_no_other_package_names_this_one(self): + for package in ("brokkr_kitbash", "brokkr_rig", "brokkr_bridge", "brokkr_mesh_polish"): + for path in (SURFACE / package).rglob("*.py"): + self.assertNotIn("brokkr_reference", path.read_text(encoding="utf-8"), str(path)) + + +if __name__ == "__main__": + unittest.main() From 3cf4234edb2b5966c954bca234b75de76d3afc50 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:18:38 +0100 Subject: [PATCH 123/223] tests/live/reference.py: a known scene rendered, solved through the action, rendered again 1 - IoU of the two silhouettes 0.000168 (0.6489 with shift_y flipped); Blender 5.3.0. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/reference.py | 183 ++++++++++++++++++ .../blender/tests/live/reference.result.json | 146 ++++++++++++++ 2 files changed, 329 insertions(+) create mode 100644 surfaces/blender/tests/live/reference.py create mode 100644 surfaces/blender/tests/live/reference.result.json diff --git a/surfaces/blender/tests/live/reference.py b/surfaces/blender/tests/live/reference.py new file mode 100644 index 0000000..87d186f --- /dev/null +++ b/surfaces/blender/tests/live/reference.py @@ -0,0 +1,183 @@ +"""Live proof, in a background Blender, that the brokkr_reference row is admitted by Brokkr as a host action and +that solve_camera, through run_intent, finds the camera a known scene was rendered through: three boxes rendered +at a 50 mm camera cropped off-axis, their corners marked where Blender's own projection draws them (to a tenth of +a pixel), the camera solved and stood as a second camera object, and the scene rendered again through it. The two +silhouettes must agree. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). is an absolute path: it writes .result.json, .truth.png and .solved.png, and +exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names the +check before it, and the result file is written whatever happened. +""" +import json +import os +import sys +import tempfile +import time +import traceback +import types +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from bpy_extras.object_utils import world_to_camera_view +from mathutils import Euler, Matrix, Vector + +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 os.path.isabs(OUT): + raise SystemExit(f" must be an absolute path, not {OUT!r}: a relative one lands in Blender's start directory") +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 + +sys.path.append(str(SURFACE)) +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_reference"): + addon_utils.enable(module, default_set=True) +from brokkr_reference import core # noqa: E402 + +target = bt.BrokkrBlenderTarget(bpy) +target.configure_action_dirs("", tempfile.mkdtemp(prefix="brokkr-reference-live-")) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], + "hostRows": [row["name"] for row in target.host_actions()[0]]} +COUNT = [0] +T0 = time.time() +WIDTH, HEIGHT = 800, 600 + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +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 = json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None + print("SEND", f"{time.time() - T0:.1f}s", action, receipt["status"], str(receipt["message"])[:300], flush=True) + return receipt, result + + +def silhouette(camera, path): + """Render through `camera` with a transparent film and return where the scene covers the frame.""" + scene = bpy.context.scene + scene.camera = camera + scene.render.filepath = path + bpy.ops.render.render(write_still=True) + image = bpy.data.images.load(path) + alpha = np.array(image.pixels[:], dtype=np.float32).reshape(image.size[1], image.size[0], 4)[:, :, 3] + bpy.data.images.remove(image) + return alpha > 0.5 + + +def drawn(camera, point): + """The frame pixel (u, v down) Blender's own projection gives a world point.""" + x, y, _ = world_to_camera_view(bpy.context.scene, camera, Vector(point)) + return x * WIDTH, (1.0 - y) * HEIGHT + + +def params_of(camera): + data, render = camera.data, bpy.context.scene.render + return {"matrix_world": [list(row) for row in camera.matrix_world], "lens": data.lens, "shift_x": data.shift_x, "shift_y": data.shift_y, + "sensor_width": data.sensor_width, "sensor_fit": data.sensor_fit, "resolution": [render.resolution_x, render.resolution_y]} + + +try: + check("host file admitted", not R["hostErrors"] and "brokkr_reference.solve_camera" in R["hostRows"], R["hostRows"]) + scene = bpy.context.scene + scene.render.engine = "BLENDER_WORKBENCH" + scene.render.film_transparent = True + scene.render.image_settings.file_format = "PNG" + scene.render.image_settings.color_mode = "RGBA" + scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage = WIDTH, HEIGHT, 100 + + # --- the known scene: a hull, a tower off its middle and a wing, none mirrored, so no camera but one draws it -------- + bm = bmesh.new() + for size, place in (((1.6, 4.0, 0.8), (0.0, 0.0, 0.4)), ((0.6, 0.8, 1.2), (0.3, -1.0, 1.4)), ((1.8, 1.0, 0.2), (1.7, 0.6, 0.5))): + bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Translation(place) @ Matrix.Diagonal((*size, 1.0))) + mesh = bpy.data.meshes.new("Known") + bm.to_mesh(mesh) + bm.free() + scene.collection.objects.link(bpy.data.objects.new("Known", mesh)) + truth = bpy.data.objects.new("Truth", bpy.data.cameras.new("Truth")) + scene.collection.objects.link(truth) + truth.data.lens, truth.data.sensor_width, truth.data.sensor_fit, truth.data.shift_x, truth.data.shift_y = 50.0, 36.0, "HORIZONTAL", 0.08, -0.05 + truth.matrix_world = Matrix.Translation((-6.5, -8.0, 4.6)) @ Euler((1.2, 0.03, -0.72), "XYZ").to_matrix().to_4x4() + bpy.context.view_layer.update() + first = silhouette(truth, OUT + ".truth.png") + check("fixture: the scene covers part of the frame and touches no edge", 0.05 < first.mean() < 0.6 and not (first[0].any() or first[-1].any() or first[:, 0].any() or first[:, -1].any()), float(first.mean())) + + corners = {f"v{v.index}": tuple(v.co) for v in mesh.vertices} + marks = {k: drawn(truth, p) for k, p in corners.items()} + world = "; ".join(f"{k}={p[0]:.4f},{p[1]:.4f},{p[2]:.4f}" for k, p in corners.items()) + pixels = "; ".join(f"{k}={u:.1f},{v:.1f}" for k, (u, v) in marks.items()) + box = f"0,0,{WIDTH},{HEIGHT}" + + # --- camera_of reads the scene's own camera: the record draws what Blender draws ------------------------------------ + record = core.camera_of(params_of(truth)) + off = float(np.abs(core.project(record, list(corners.values())) - np.array(list(marks.values()))).max()) + check("camera_of(the truth camera) draws each corner where Blender does, within 0.01 px", off < 0.01, off) + + # --- compute only ---------------------------------------------------------------------------------------------------- + before = sorted(o.name for o in bpy.data.objects) + receipt, only = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box=box) + check("compute only: accepted, the record in the receipt, no object made", receipt["status"] == "accepted" and only and only["camera"] is None + and sorted(o.name for o in bpy.data.objects) == before and len(only["residuals"]) == 24, [receipt["message"], only and only["model"]]) + check("auto takes the free model on a view cropped off-axis", only and only["model"] == "free", only and only["tried"]) + + # --- stood as a camera, and the scene rendered again through it --------------------------------------------------- + scene.render.resolution_x, scene.render.resolution_y = 320, 200 # the action sets the frame, not the caller + receipt, solved = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box=box, model="free", camera_name="Solved", width=WIDTH) + stood = bpy.data.objects.get("Solved") + check("solve_camera with camera_name: accepted, a camera object, the render size set to the box", receipt["status"] == "accepted" and stood is not None + and stood.type == "CAMERA" and (scene.render.resolution_x, scene.render.resolution_y) == (WIDTH, HEIGHT), receipt["message"]) + R["record"] = {k: solved[k] for k in ("lens", "lens_band", "lens_at_bound", "rms", "median", "left_out", "model", "c", "azimuth", "elevation", "distance", "roll")} + place = float((stood.matrix_world.translation - truth.matrix_world.translation).length) + check("the record: lens within 1 mm of 50, place within 0.1 m, rms under 0.2 px, lens not at a bound", + abs(solved["lens"] - 50.0) < 1.0 and place < 0.1 and solved["rms"] < 0.2 and solved["lens_at_bound"] is None, [solved["lens"], place, solved["rms"]]) + check("the centre is solved: the truth's shifts within 0.005 of a frame width", abs(stood.data.shift_x - 0.08) < 0.005 and abs(stood.data.shift_y + 0.05) < 0.005, + [stood.data.shift_x, stood.data.shift_y]) + worst = max(float(np.hypot(*np.subtract(drawn(stood, p), marks[k]))) for k, p in corners.items()) + check("Blender's projection through the stood camera draws each corner within 0.5 px of its mark", worst < 0.5, worst) + second = silhouette(stood, OUT + ".solved.png") + miss = 1.0 - float((first & second).sum() / (first | second).sum()) + R["iouMiss"] = miss + # 1 - IoU of the two silhouettes. Shipped 0.000168; with shift_y's sign flipped in core.blender (M5) 0.6489: the bound is their geometric mean. + check("the re-render's silhouette matches the first: 1 - IoU under 0.0105", miss < 0.0105, miss) + + # --- again under the same name updates the one camera; a held lens is held ------------------------------------------ + receipt, held = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box=box, model="free", lens=85, camera_name="Solved", width=400) + check("a second run updates the same camera: one object, the lens held at 85, the frame 400 by 300", receipt["status"] == "accepted" + and [o.name for o in bpy.data.objects if o.type == "CAMERA"] == ["Solved", "Truth"] and abs(stood.data.lens - 85.0) < 1e-4 + and held["lens_band"] == [85.0, 85.0] and (scene.render.resolution_x, scene.render.resolution_y) == (400, 300), [receipt["message"], held and held["lens"]]) + + # --- refusals are failed receipts that name the cause ---------------------------------------------------------------- + five = "; ".join(pixels.split("; ")[:5]) + receipt, _ = send("brokkr_reference.solve_camera", world=world, pixels=five, box=box) + check("five points: failed, naming the count", receipt["status"] == "failed" and "5 points" in receipt["message"], receipt["message"]) + receipt, _ = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box=box, camera_name="Known") + check("camera_name of a mesh object: failed, nothing changed", receipt["status"] == "failed" and "not a camera" in receipt["message"] + and bpy.data.objects["Known"].type == "MESH", receipt["message"]) + receipt, _ = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box="0,0,0,600") + check("a box of no width: failed, naming it", receipt["status"] == "failed" and "no width" in receipt["message"], receipt["message"]) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) + +R["ok"] = all(c["ok"] for c in R["checks"]) +for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/reference.result.json b/surfaces/blender/tests/live/reference.result.json new file mode 100644 index 0000000..55664b6 --- /dev/null +++ b/surfaces/blender/tests/live/reference.result.json @@ -0,0 +1,146 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "host file admitted", + "ok": true, + "detail": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick", + "brokkr_reference.solve_camera" + ] + }, + { + "name": "fixture: the scene covers part of the frame and touches no edge", + "ok": true, + "detail": 0.1361375 + }, + { + "name": "camera_of(the truth camera) draws each corner where Blender does, within 0.01 px", + "ok": true, + "detail": 6.941722509168358e-05 + }, + { + "name": "compute only: accepted, the record in the receipt, no object made", + "ok": true, + "detail": [ + "Operator brokkr_reference.solve_camera finished.", + "free" + ] + }, + { + "name": "auto takes the free model on a view cropped off-axis", + "ok": true, + "detail": { + "upright": { + "rms": 1.380259942769221, + "left_out": 1.5572430492976839, + "lens": 48.08928208959338 + }, + "rolled": { + "rms": 0.6797349192884168, + "left_out": 0.8350092431422779, + "lens": 48.499059377417225 + }, + "free": { + "rms": 0.03555833513434369, + "left_out": 0.04252972975472319, + "lens": 50.02266319807241 + } + } + }, + { + "name": "solve_camera with camera_name: accepted, a camera object, the render size set to the box", + "ok": true, + "detail": "Operator brokkr_reference.solve_camera finished." + }, + { + "name": "the record: lens within 1 mm of 50, place within 0.1 m, rms under 0.2 px, lens not at a bound", + "ok": true, + "detail": [ + 50.02266319807241, + 0.004567543465755453, + 0.03555833513434369 + ] + }, + { + "name": "the centre is solved: the truth's shifts within 0.005 of a frame width", + "ok": true, + "detail": [ + 0.079900361597538, + -0.051553647965192795 + ] + }, + { + "name": "Blender's projection through the stood camera draws each corner within 0.5 px of its mark", + "ok": true, + "detail": 0.03400179965902824 + }, + { + "name": "the re-render's silhouette matches the first: 1 - IoU under 0.0105", + "ok": true, + "detail": 0.00016831152933971527 + }, + { + "name": "a second run updates the same camera: one object, the lens held at 85, the frame 400 by 300", + "ok": true, + "detail": [ + "Operator brokkr_reference.solve_camera finished.", + 85.0 + ] + }, + { + "name": "five points: failed, naming the count", + "ok": true, + "detail": "Error: 5 points are named in both world and pixels; six are needed" + }, + { + "name": "camera_name of a mesh object: failed, nothing changed", + "ok": true, + "detail": "Error: 'Known' is an object that is not a camera." + }, + { + "name": "a box of no width: failed, naming it", + "ok": true, + "detail": "Error: box [0.0, 0.0, 0.0, 600.0] has no width: it is u0, v0, u1, v1 with u1 past u0 and v1 past v0" + } + ], + "hostErrors": [], + "hostRows": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick", + "brokkr_reference.solve_camera" + ], + "record": { + "lens": 50.02266319807241, + "lens_band": [ + 50.02266319807241, + 50.02266319807241 + ], + "lens_at_bound": null, + "rms": 0.03555833513434369, + "median": 0.036713200453055594, + "left_out": 0.04252972975472319, + "model": "free", + "c": [ + 336.07971210679585, + 258.7570824524072 + ], + "azimuth": 137.66552423487752, + "elevation": 19.81349852084873, + "distance": 11.315569478894277, + "roll": -1.8445361216036547 + }, + "iouMiss": 0.00016831152933971527, + "ok": true +} \ No newline at end of file From ae42cf9d8c15487d1c537c6581d6d8b97edebd16 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:18:39 +0100 Subject: [PATCH 124/223] docs/reference.md: conventions, the action, and what the lens band means Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/reference.md | 123 +++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 surfaces/blender/docs/reference.md diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md new file mode 100644 index 0000000..70edc4b --- /dev/null +++ b/surfaces/blender/docs/reference.md @@ -0,0 +1,123 @@ +# Reference views: the camera a picture was drawn through + +`surfaces/blender/brokkr_reference` is a Blender add-on that fits a scene to a reference image. A concept sheet, +a render or a photograph draws its subject through a camera nobody wrote down; given points whose place in the +world is known and the pixel where the image draws each, `solve_camera` finds that camera, so that a render through +it lays over the image pixel for pixel and a line traced on the image can be lifted into the scene. + +It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish`: it +imports that package's operator base and `Refused`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish` +first; `brokkr_reference` refuses to register without it. `brokkr_actions.json` beside its `__init__.py` lists the +one operator agents may run; the arithmetic is `core.py` (numpy only, tested without Blender), which a script may +import directly. The action writes its JSON report to `brokkr_mesh_polish_result`, returned in the receipt's +`hostResult`. + +The package takes points and gives cameras. The images, the marks on them, traces and masks belong to whoever +made them; nothing here opens an image. + +## Conventions + +- World: x right, y forward, z up, metres. +- Pixels: the image's, in whatever unit the points were marked in, u right and v down. `box` is the view's + rectangle on the image, `u0,v0,u1,v1`; for an image that is one view it is `0,0,width,height`. +- Camera record: `C` is where the camera stands, `R` turns world to camera (rows), the camera looks down its own + -z with y up (Blender's), `f` is the focal length in pixels, `c` the principal point in pixels. `lens` is `f` + in millimetres on a 36 mm sensor across the box's width. +- Misses are weighed by a pseudo-Huber loss of 10 px: a build poses some points elsewhere than the image draws + them, and one such point pulls the camera as its distance, not its square. + +The record is the truth. A Blender camera stood at it (`core.blender`) is derived, and `core.camera_of` reads one +back into a record. + +## The action + +`brokkr_reference.solve_camera`. Host action fields are scalar, so points go in as text: + +| field | | +| --- | --- | +| `world` | `name=x,y,z; name=x,y,z ...` | +| `pixels` | `name=u,v; name=u,v ...`; six or more names shared with `world`, the rest ignored | +| `box` | `u0,v0,u1,v1` | +| `model` | `auto` (default), `upright`, `rolled`, `free`, `square` | +| `lens` | mm; 0 (default) solves it, 4 to 4000 holds it | +| `turned` | names, spaces between, of points that turn as one about the vertical through `pivot` | +| `pivot` | `x,y`; absent is `0,0` | +| `camera_name` | a camera object to create or update at the solved camera; absent only computes | +| `width` | pixels across the frame the box becomes (default 1000) | + +The models differ in what the camera may do beyond standing somewhere, turning and zooming. `upright` holds it +level with its centre at the middle of the box. `rolled` lets it roll about its line of sight. `free` also solves +the centre: a view cropped off-axis. `auto` solves all three and takes the one that predicts left-out points best +(each point predicted by the camera solved without it), since a freer model always fits the marked points closer. +`square` is for an elevation drawn square-on from far off: the points lie nearly in one plane across the line of +sight, where a small turn of the camera and a narrower subject draw the same picture, so the camera is held looking +straight along a world axis, whichever of the four fits best. + +`turned` is for one articulated group (a torso on its waist ring): its turn about the vertical through `pivot` is +solved with the camera and reported as `twist`, in degrees from where the points were given. + +With `camera_name` the action creates that camera, or updates it if it exists (an object of that name that is not +a camera is refused): its matrix, lens, shifts, a 36 mm sensor fitted horizontally, `clip_end` raised to four +times the camera's distance if it was nearer, and the scene's render resolution set to `width` by the box's +proportion. It does not make it the scene's active camera and does not touch `resolution_percentage`. A pixel of a +render through it at 100% is then the image's pixel less the box's corner, times `width` over the box's width +(`core.in_frame`; the frame's height is a whole number of pixels, so it can stand half a pixel off the box's). + +The report is the camera record: `C`, `R`, `f`, `c`, `box`, `lens`, `lens_band`, `lens_at_bound`, `rms`, `median` +and `worst` (`[name, pixels]`), `left_out` (the leave-one-out rms), `model`, `tried` (each model's `rms`, +`left_out` and `lens`), `azimuth`, `elevation` and `distance` (where the camera stands round the points' middle), +`roll`, `twist`, and `residuals` (`{name: [du, dv]}`, to a hundredth of a pixel in a receipt); plus `camera` (the +object's name or null) and, when a camera was stood, `blender` (what `core.blender` gave it). + +Refusals name their cause: fewer than six shared names, a point that is not finite numbers, a name given twice, a +box of no width or height, a lens outside 4 to 4000 mm. + +## How far to trust the lens + +Six or more points that are not all in one plane decide a camera. What they decide well is the picture: where each +point is drawn. What a long or square-on view decides badly is how far off the camera stands, because distance +and focal length trade against each other (a dolly zoom) and the picture barely changes. So: + +- The focal length is held inside 4 to 4000 mm. Without a bound the solve ran the focal length to overflow on long + views; past 4000 mm a view is orthographic to any marking. `lens_at_bound` is `"long"` or `"short"` when the + answer sits at an end: read that as "at least this long", not as a lens. +- `lens_band` is `[low, high]`: the lenses that, held and refitted, come within 1.1 times the best rms, walked out + from the best in steps of a tenth in log f until one misses or the bound is reached. It is an **equal-error + band, not a confidence interval**: it says which lenses the marks cannot tell apart, not where the true lens + lies, and on a probe one such band excluded the true lens. A band that ends at 4000 was stopped by the bound. +- There is no prior. Where the data cannot decide, the answer is a wide band rather than a plausible-looking 50 mm. +- Hold `lens` only when views must agree: two views of one subject solved alone may each sit anywhere in their + bands, and a fit rendered from elsewhere than the reference view depends on the lens the band does not fix. + +What this buys and costs, measured on a generated hull rendered at known cameras with 10 to 16 marked points +(Blender 5.3 on Starfire): a 50 mm oblique view with 1 px of marking noise came back at 49.9 mm; a 135 mm view on a +build 2% of its length out came back anywhere from 94 mm to the bound, with the camera's place off by eleven hull +lengths, and a crease lifted through that camera onto the hull's mirror plane was still within 1.4% of the hull's +length of the truth, moving at most 0.6% between the band's ends. A wide band is a warning about the camera's +place, not about a lift made in the view's own frame. + +`rms` is the plain root mean square of the misses, in pixels at the marking unit, though the solve minimises the +pseudo-Huber loss; `median` beside it shows when a few points carry the error. A solve with `auto` on 13 points +takes several seconds (three models, each from 16 starts, plus a left-out solve per point per model). + +## What it cannot do + +It solves one pinhole camera for one view: no lens distortion, no two views solved together, one turned group and +no other pose. It does not find the points; marking them is the caller's. Points on posed joints fit worse than +points on rigid features of one body, because the build's pose is not the drawing's. It does not say whether the +subject is the right size: a build twice too large is the same picture from twice as far. + +## From a script + +```python +from brokkr_reference import core +cam = core.solve(world, pixels, box, model="auto") # dicts by name; the record +u_v = core.project(cam, points) # where it draws world points +origin, direction = core.ray(cam, (u, v)) # a pixel's line of sight +point = core.lift(cam, (u, v), plane_point, plane_normal) # a traced pixel on a plane +params = core.blender(cam, 1000) # matrix_world, lens, shifts, resolution +cam2 = core.camera_of(params, box) # and back +``` + +The tests are `tests/test_reference.py` (no Blender) and `tests/live/reference.py` (a known scene rendered, +solved through the action and rendered again; `reference.result.json` is its last run). From 263236ba4d784b0d3fa9ca5217fde9d361439b39 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:21:12 +0100 Subject: [PATCH 125/223] test_reference: say where the unbounded-focal mutant died Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/test_reference.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index f2f0c2f..9b11ba6 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -10,7 +10,7 @@ tolerances round a known truth that no mutant claims. The mutants, each run once M1 plain squares for the pseudo-Huber loss test_one_point_60_px_off_does_not_turn_the_camera M2 auto chooses by in-sample rms test_auto_takes_the_model_that_predicts_left_out_points M3 the lens walk restarts from the grid test_the_band_is_walked_from_the_last_solve - M4 no bound on the focal length test_long_lenses_stay_finite_and_inside_the_range + M4 no bound on the focal length SolveTests.setUpClass (OverflowError), before test_long_lenses_stay_finite_and_inside_the_range M5 shift_y's sign flipped in blender() test_blender_params_draw_the_same_pixels M6 the turned group is not turned test_a_turned_torso_is_recovered_as_twist M7 square holds the yaw along y only test_square_solves_elevations_along_both_axes @@ -150,7 +150,8 @@ class SolveTests(unittest.TestCase): def test_long_lenses_stay_finite_and_inside_the_range(self): """long-lens-bounded, M4: with no bound the 400 mm view on a build 4 cm off runs log f to OverflowError and - the orthographic one reads 20208 mm.""" + the orthographic one reads 20208 mm; so does one start of the oblique solve in setUpClass, which is where + the mutant run died (every test of this class with it).""" for lens in (135, 400): cam = camera(self.points, 35, 20, lens) for build in (0.0, 0.04): From edbd04f1efbdfeb9d3b0434cf07c6905c566042b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:21:33 +0100 Subject: [PATCH 126/223] brokkr_kitbash.hose: a search's polyline is a seed, refined in continuous space; other grid origins and half the step before a refusal; too stiff only where proven (cut kit-hose, h3) route.tangents gives each corner its floor's tangent before a neighbour gets more, and the pin's corner the tangent of its sharpest roll (sharpest_turn, exact over a range; passes sizes a bin's bend by it). route.relax drops, moves and adds a seed's free vertices until every segment has the straight its corners take (strain), each change proven clear by the oracle. hose searches each leg on three grid origins and then at half the step, names what it tried when it refuses, and says too stiff only where route.leaves proves no curve of the floor radius leaves a port. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 190 +++++++++++++------ surfaces/blender/brokkr_kitbash/route.py | 199 +++++++++++++++++--- surfaces/blender/tests/test_kitbash.py | 6 +- surfaces/blender/tests/test_route.py | 69 ++++++- 4 files changed, 373 insertions(+), 91 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index a635370..299d1e6 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -50,12 +50,14 @@ object rewrites the mesh in place, leaving the object, its cutters, ribs, Boolea evaluates nothing: Blender's own update after the action evaluates the plate once. hose routes a bundle of hoses between two sockets. route.py owns the path (legs searched on a voxel grid of the -scene's clearance, pulled taut, sagged a little, filleted, verified, and turned through the rolls of the one pin it may -cross) and core.sweep owns every tube, ferrule and clamp. A hose is a bake of the scene at the call: posing or moving a +scene's clearance and pulled taut, which is a seed; refined in continuous space where its corners lack straight, sagged a +little, filleted, verified, and turned through the rolls of the one pin it may cross; other grid origins and half the +step are searched before a route is refused) and core.sweep owns every tube, ferrule and clamp. A hose is a bake of the scene at the call: posing or moving a part leaves it stale until hose runs again on its name. It is one object: where it crosses a pin it is meant to be skinned between the bones on either side, and this package writes no weights. kit_hose on it is the request, kept as a record: hose is its one writer, and the one thing read back from it is which two parts a hose joins, by a later hose -that crosses the same pin (it bends with the pin, so it is measured as an obstacle where it stands and not across the rolls). +that crosses the same pin (it bends with the pin, so it is measured as an obstacle where it stands and not across the rolls: +follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes that check). 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 @@ -101,6 +103,8 @@ HOSE = "kit_hose" # on a hose: the request it was routed from, as JSON; its pre HOSE_CLAMPS = 8 # clamps in one hose: each is one more leg to search HOSE_VOXELS = 2 ** 19 # voxels of one leg's search box: 1.8 s of capped nearest-face queries at 3.4 us each HOSE_MARGIN = 0.25 # metres a leg's search box reaches beyond its two ends: the room a way around an obstacle between them has +HOSE_OFFSETS = ((0.0, 0.0, 0.0), (0.5, 0.5, 0.5), (0.31, 0.67, 0.13)) # of a step: the grid origins a leg's seed is searched on before a route is refused +HOSE_FINEST = 0.005 # metres: the least step, and the least a refused step is halved to for one more round of seeds HOSE_SEGMENTS = 12 # sides of a hose, a ferrule and a clamp's pad ROLL_STEP = 5.0 # degrees between the rolls of a joint's range that hose measures first: the step an assembly's clearance is read at ROLL_FINEST = 0.3 # degrees: the half width under which a bin of rolls that falls short is refused instead of halved (5 degrees halved 4 times) @@ -1489,42 +1493,45 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): rest, moved, through = self.trees(start["depsgraph"], hose, pin and pin["child"], kits) reach = need + 2.0 * floor + self.step roomy = route.BEND * floor # room beyond need a leg is searched with: what the arc of a quarter turn at the floor takes - occupied = self.reader((rest, moved, through), need + roomy + route.REACH * self.step) far, far_rest, far_moved = self.reader((rest, moved, through), reach), self.reader((rest,), reach), self.reader((moved,), reach) - room = lambda a, b: route.room(a, b, far, need) # noqa: E731 exempt = max(lead, need) # a bundle wider than its lead stands on its own port's face that far stand = sizes["envelope"] + self.clearance + r # a clamped bundle's centre line above the socket's face: its pad is one radius thick - held = 2.0 * 2.0 * r + floor + ends = [port["matrix"][:3, 3] + port["matrix"][:3, 2] * (lead + floor) for port in (start, end)] # a leg starts where the first bend has its floor's length of straight behind it + stops = [("clamp", f"clamps[{index}]", clamp["matrix"][:3, 3] + clamp["matrix"][:3, 2] * stand, clamp["matrix"][:3, 1]) for index, clamp in enumerate(clamps)] + if pin is not None: + stops.insert(pin["before"], ("pin", "the pin", pin["point"], None)) + sized = {"need": need, "floor": floor, "lead": lead, "exempt": exempt, "roomy": roomy, "held": 2.0 * 2.0 * r + floor, "kept": 4.0 * 2.0 * r, # a clamp keeps 2 outside diameters of straight each side of its point + "far": far, "far_rest": far_rest, "far_moved": far_moved, "room": lambda a, b: route.room(a, b, far, need), "pin": pin, "joint": joint} + steps = [self.step] + [self.step / 2.0] * (self.step / 2.0 >= HOSE_FINEST) + shaped, tried, blocked = None, [], None try: - ends = [port["matrix"][:3, 3] + port["matrix"][:3, 2] * (lead + floor) for port in (start, end)] # a leg starts where the first bend has its floor's length of straight behind it - stops = [("clamp", f"clamps[{index}]", clamp["matrix"][:3, 3] + clamp["matrix"][:3, 2] * stand, clamp["matrix"][:3, 1]) for index, clamp in enumerate(clamps)] - if pin is not None: - stops.insert(pin["before"], ("pin", "the pin", pin["point"], None)) - legs, at, came = [], ends[0], "start" - for kind, label, point, y in stops + [("end", "end", ends[1], None)]: - into, out = point, point - if kind == "clamp": - into, out = sorted((point - y * held, point + y * held), key=lambda p: float(np.linalg.norm(p - at))) - name = f"leg {len(legs) + 1} ({came} to {label})" - for pad in (roomy, 0.0): # with room for its bends where a way with that room exists; a clamp stands nearer its seat than that + for step in steps: # a seed's vertices follow its lattice: a route is refused only after other lattices gave their seeds + occupied = self.reader((rest, moved, through), need + roomy + route.REACH * step) + for offset in HOSE_OFFSETS: try: - pulled, voxels = route.leg(at, into, occupied, far, need, self.step, HOSE_MARGIN, HOSE_VOXELS, name, pad) + points, kinds, voxels = self.seed(start, end, ends, stops, occupied, step, offset, sized) + shaped = (*self.routed(points, kinds, sized), voxels, {"step": round(step, 6), "offset": list(offset)}) break - except route.RouteError: - if pad <= 0.0: - raise - legs.append((pulled, voxels, kind, out)) - at, came = out, label - shaped, refusals = None, [] - for depth in dict.fromkeys((self.sag * 2.0 * r, 0.0)): # slack yields to clearance: a route the sag breaks is made taut - try: - shaped = self.shaped(legs, start, end, depth, room, far, far_rest, far_moved, pin, joint, need, floor, lead, exempt, 4.0 * 2.0 * r) # a clamp keeps 2 outside diameters of straight each side of its point + except route.Blocked as error: # where a waypoint stands: no other seed lifts it + blocked = str(error) + break + except route.RouteError as error: + tried.append(str(error)) + if shaped is not None or blocked is not None: break - except route.RouteError as error: - refusals.append(("sagged" if depth > 0.0 else "taut", str(error))) - if shaped is None: # both attempts are named: the taut one is the one sag 0 would make - raise route.RouteError(refusals[0][1] if len({text for _, text in refusals}) == 1 else "; ".join(f"{how}: {text}" for how, text in refusals)) - curve, made, sagged, least, swing = shaped + if shaped is None: + for what, port, towards in (("start", start, stops[0][2] if stops else ends[1]), ("end", end, stops[-1][2] if stops else ends[0])): + tip, out = port["matrix"][:3, 3] + port["matrix"][:3, 2] * lead, port["matrix"][:3, 2] + if (lead >= need and np.linalg.norm(towards - tip) > 2.0 * floor and float(far(tip[None])[0]) >= need - route.HELD + and not route.leaves(tip, out, floor, far, need)): + raise route.RouteError(f"the bundle is too stiff to leave its {what}: from the end of its lead at {route.spot(tip)} no curve that bends at the floor radius {floor:.4g} m or wider " + f"keeps {need:.4g} m from what stands within {2.0 * floor:.4g} m of it (a lower bend, thinner hoses, or more room before the port)") + if blocked is not None: + raise route.RouteError(blocked) + origins = ", ".join("(" + ", ".join(f"{v:g}" for v in offset) + ")" for offset in HOSE_OFFSETS) + raise route.RouteError(f"the search found no route: it tried step{'s' if len(steps) > 1 else ''} {' and '.join(f'{step:g}' for step in steps)}, each on grid origins {origins} of a step, " + f"and refined each seed in continuous space; this does not show that no route exists. The first refusal: {tried[0]}") + curve, made, sagged, least, swing, refined, voxels, seeded = shaped built = self.built(curve, start, clamps, stand, r, sizes["spread"], half_width) except route.RouteError as error: raise Refused(f"{error}; nothing changed.") from None @@ -1550,7 +1557,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): report = {"object": hose.name, "rebuilt": rebuilt, "hoses": self.count, "length": round(float(np.linalg.norm(np.diff(curve, axis=0), axis=1).sum()), 6), "lengthChange": None if swing is None else round(swing["lengthChange"], 6), "floor": round(floor, 6), "clearance": None if not math.isfinite(least) else round(least - sizes["envelope"], 6), "capped": round(reach - sizes["envelope"], 6), - "voxels": [voxels for _, voxels, _, _ in legs], "sag": [round(drop, 6) for drop in sagged], + "voxels": voxels, "seed": {**seeded, "refined": refined}, "sag": [round(drop, 6) for drop in sagged], "rolls": None if swing is None else swing["rolls"], "worstRoll": None if swing is None else swing["worstRoll"], "worstClearance": None if swing is None or not math.isfinite(swing["least"]) else round(swing["least"] - sizes["envelope"], 6), **measured(mesh)} report["radii"] = {"least": round(float(radii.min()), 6) if len(radii) else None} @@ -1677,35 +1684,102 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): return out return distance - def shaped(self, legs, start, end, depth, room, far, far_rest, far_moved, pin, joint, need, floor, lead, exempt, kept): + @staticmethod + def seed(start, end, ends, stops, occupied, step, offset, sized): + """(points, kinds, the voxels each leg searched) of one seed: every leg searched on the grid of `step` at + `offset` and pulled (route.leg), joined port to port. A point's kind says what holds it: "P" a port, "E" the + end of a fitting's straight, "I" and "O" where the hose comes onto and leaves a clamp's straight, "J" the + pin point; None is a vertex the search put there, which a refinement may move.""" + points, kinds, voxels, at, came = [start["matrix"][:3, 3]], ["P"], [], ends[0], "start" + for kind, label, point, y in stops + [("end", "end", ends[1], None)]: + into, out = point, point + if kind == "clamp": + into, out = sorted((point - y * sized["held"], point + y * sized["held"]), key=lambda p: float(np.linalg.norm(p - at))) + name = f"leg {len(voxels) + 1} ({came} to {label})" + for pad in (sized["roomy"], 0.0): # with room for its bends where a way with that room exists; a clamp stands nearer its seat than that + try: + pulled, searched = route.leg(at, into, occupied, sized["far"], sized["need"], step, HOSE_MARGIN, HOSE_VOXELS, name, pad, offset) + break + except route.Blocked: + raise + except route.RouteError: + if pad <= 0.0: + raise + if kinds[-1] != "J": # a leg from the pin point starts on the point the last one ended on + points.append(pulled[0]) + kinds.append("E" if came == "start" else "O") + points += list(pulled[1:]) + kinds += [None] * (len(pulled) - 2) + [{"pin": "J", "clamp": "I", "end": "E"}[kind]] + voxels.append(searched) + at, came = out, label + return np.array(points + [end["matrix"][:3, 3]]), kinds + ["P"], voxels + + @staticmethod + def straights(points, kinds, sized): + """(keep, centred, least) for route's fillet and strain: a clamp's straight keeps its length in its middle, + and the corner at the pin holds the tangent its sharpest turn of the joint's range takes at the floor.""" + clamped = np.array([a == "I" and b == "O" for a, b in zip(kinds, kinds[1:])]) + least, pin = np.zeros(len(points) - 2), sized["pin"] + if pin is not None: + j = kinds.index("J") + before, after = points[j] - points[j - 1], points[j + 1] - points[j] + if min(np.linalg.norm(before), np.linalg.norm(after)) > 1e-9: + before, after = before / np.linalg.norm(before), after / np.linalg.norm(after) + if pin["child_first"]: # read from the parent's side, as route.passes turns it + before, after = -after, -before + low, high = (v - pin["current"] for v in sized["joint"]["range"]) + least[j - 1] = sized["floor"] * math.tan(min(route.sharpest_turn(before, after, pin["axis"], low, high), route.STIFF) / 2.0) + return np.where(clamped, sized["kept"], 0.0), clamped, least + + def routed(self, points, kinds, sized): + """(curve, its fillet, sags, least distance, passes, whether the seed was refined) of one seed: shaped as it + is, sagged and then taut (slack yields to clearance); and where that is refused, refined in continuous space + (route.relax: until every segment has the straight its corners' tangents take at the floor, each moved + segment proven clear with the room a leg is pulled with) and shaped again. Refuses with what each shaping + was refused for, by name.""" + fixed = np.array([point for point, kind in zip(points, kinds) if kind is not None]) + padded = lambda p: np.asarray(sized["far"](p)) - np.minimum(sized["roomy"], 0.5 * np.linalg.norm(np.asarray(p)[:, None] - fixed[None], axis=2).min(axis=1)) # noqa: E731 + refusals = [] + for refined in (False, True): + if refined: + moved, tags = route.relax(points, kinds, lambda p, g: route.strain(p, sized["floor"], sized["lead"], *self.straights(p, g, sized)), + lambda a, b: route.clear(a, b, padded, sized["need"], 1.5), sized["floor"]) + if len(moved) == len(points) and np.allclose(moved, points, atol=1e-12): + break + points, kinds = moved, tags + for depth in dict.fromkeys((self.sag * 2.0 * self.radius, 0.0)): + try: + return (*self.shaped(points, kinds, depth, sized), refined) + except route.RouteError as error: + refusals.append((("sagged" if depth > 0.0 else "taut") + (", refined" if refined else ""), str(error))) + raise route.RouteError(refusals[0][1] if len({text for _, text in refusals}) == 1 else "; ".join(f"{how}: {text}" for how, text in refusals)) + + def shaped(self, points, kinds, depth, sized): """(curve, its fillet, the metres each leg sagged, the least distance outside the leads, the joint's passes or - None) of the legs joined at one sag depth: one polyline from port to port, one fillet, one verification, and - with a pin its whole range: the rolls from the range's low to its high every ROLL_STEP degrees, each answering - for the rolls about it, and more between them where one falls short (route.passes).""" - points, keep, centred, sagged, j, last = [start["matrix"][:3, 3]], [], [], [], None, None - for pulled, _, kind, _ in legs: - hung, drop = route.sag(pulled, depth, room) - sagged.append(drop) - hung = hung[1:] if last == "pin" else hung # a leg from the pin point starts on the point the last one ended on - points += list(hung) - keep += [kept if last == "clamp" else 0.0] + [0.0] * (len(hung) - 1) # a leg from a clamp starts at the far end of the clamp's straight - centred += [last == "clamp"] + [False] * (len(hung) - 1) - if kind == "pin": - j = len(points) - 1 - last = kind - points.append(end["matrix"][:3, 3]) - keep.append(0.0) - centred.append(False) - points = np.array(points) - made = route.fillet(points, room, floor, lead, keep, centred) - least = route.verify(made.curve, far, need, exempt) + None) of a polyline at one sag depth: each leg sagged (the runs between held points, but a fitting's straight + and a clamp's), one fillet, one verification, and with a pin its whole range: the rolls from the range's low + to its high every ROLL_STEP degrees, each answering for the rolls about it, and more between them where one + falls short (route.passes).""" + hung, tags, sagged = [points[0]], [kinds[0]], [] + held = [index for index, kind in enumerate(kinds) if kind is not None] + for a, b in zip(held, held[1:]): + run = points[a:b + 1] + if (kinds[a], kinds[b]) not in (("P", "E"), ("E", "P"), ("I", "O")): + run, drop = route.sag(run, depth, sized["room"]) + sagged.append(drop) + hung += list(run[1:]) + tags += [None] * (len(run) - 2) + [kinds[b]] + points, pin = np.array(hung), sized["pin"] + keep, centred, least = self.straights(points, tags, sized) + made = route.fillet(points, sized["room"], sized["floor"], sized["lead"], keep, centred, least) + clearance = route.verify(made.curve, sized["far"], sized["need"], sized["exempt"]) swing = None if pin is not None: - order = slice(None, None, -1) if pin["child_first"] else slice(None) # passes reads a polyline from the parent's side + j, order = tags.index("J"), slice(None, None, -1) if pin["child_first"] else slice(None) # passes reads a polyline from the parent's side swing = route.passes(points[order], made.t[order], (len(points) - 1 - j) if pin["child_first"] else j, pin["origin"], pin["axis"], - route.rolls_of(joint["range"][0], joint["range"][1], ROLL_STEP), ROLL_FINEST, pin["current"], far_rest, far_moved, need, floor, exempt, - keep=np.array(keep)[order]) - return made.curve, made, sagged, least, swing + route.rolls_of(sized["joint"]["range"][0], sized["joint"]["range"][1], ROLL_STEP), ROLL_FINEST, pin["current"], sized["far_rest"], sized["far_moved"], + sized["need"], sized["floor"], sized["exempt"], keep=keep[order]) + return made.curve, made, sagged, clearance, swing def built(self, curve, start, clamps, stand, r, spread, half_width): """The mesh, in world space: each hose swept along the curve offset across the bundle, two ferrule collars at diff --git a/surfaces/blender/brokkr_kitbash/route.py b/surfaces/blender/brokkr_kitbash/route.py index 75987e3..5b60d45 100644 --- a/surfaces/blender/brokkr_kitbash/route.py +++ b/surfaces/blender/brokkr_kitbash/route.py @@ -6,7 +6,12 @@ owns what an obstacle is and may cap the answer. `need` is how far a hose's cent obstacle: the bundle's half width plus its clearance. A leg between two waypoints is searched on a voxel grid of the box around them (grid, wavefront), then pulled taut -(pull). A voxel is free when it stands need plus half a voxel's diagonal from every obstacle: distance changes by at +(pull). That polyline is a seed and no more: where its vertices stand follows the grid's lattice, so whether its +corners have straight enough for their bends does too. relax then moves, drops and adds vertices in continuous +space until every segment has the straight its corners' tangents take at the floor radius (strain), each move kept +only if the oracle proves its segments clear; tangents gives every corner its floor's tangent before any corner gets +more. leaves is the one proof of a bundle too stiff: a curve that bends no tighter than the floor cannot get out of +what stands about the end of a fitting's lead. A voxel is free when it stands need plus half a voxel's diagonal from every obstacle: distance changes by at most the distance moved, so every point of a step between two neighbouring free voxels keeps need. The same bound is what every measurement of a line rests on (measure): a reading answers for the piece around it, less half the piece's length, and pieces are halved until that proves need, so nothing thinner than the spacing of some samples can stand @@ -31,6 +36,10 @@ class RouteError(ValueError): """A route that cannot be made, in words that name where.""" +class Blocked(RouteError): + """A refusal that rests on where a waypoint stands, not on a search: no other grid lifts it.""" + + NEIGHBOURS = [(i, j, k) for i in (-1, 0, 1) for j in (-1, 0, 1) for k in (-1, 0, 1) if (i, j, k) != (0, 0, 0)] REACH = math.sqrt(3.0) / 2.0 # of a voxel: how far a point of a step between two neighbouring voxels can stand from the nearer one STRAIGHT = 1e-9 # radians: a corner that turns less is no corner @@ -38,6 +47,8 @@ HELD = 1e-9 # metres under need that a reading may stand and hold it FINE = 1e-3 # metres: the shortest piece measure halves to; a line must keep need by half of this to be proven BEND = 1.0 - math.cos(math.pi / 4.0) # of a radius: how far the arc of a quarter turn stands from its tangent segments ARC = 24 # arc segments a radian of turn +STIFF = math.radians(170.0) # a turn past this is priced as this one: its tangent at the floor is already 11 floors long +AXES = [np.array(v, dtype=np.float64) for v in ((1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1))] def spot(point) -> str: @@ -78,6 +89,14 @@ def grid(lo, hi, step: float, distance, need: float, limit: int = 2 ** 19) -> Gr return Grid(free=(np.asarray(distance(points)) >= need).reshape(n), lo=lo, step=float(step)) +def _grow(front: np.ndarray) -> np.ndarray: + """The 26 neighbours of a front's voxels, by array shifts.""" + n, padded, grown = front.shape, np.pad(front, 1), np.zeros(front.shape, dtype=bool) + for i, j, k in NEIGHBOURS: + grown |= padded[1 + i:1 + i + n[0], 1 + j:1 + j + n[1], 1 + k:1 + k + n[2]] + return grown + + def wavefront(free: np.ndarray, start, goal) -> list: """The voxels of a shortest 26-connected way from start to goal through free voxels, both ends included: a wavefront grown from the goal by array shifts, then walked down from the start, at each step to the neighbour one @@ -94,10 +113,7 @@ def wavefront(free: np.ndarray, start, goal) -> list: wave = 0 while waves[start] == unreached and front.any(): wave += 1 - padded, grown = np.pad(front, 1), np.zeros(n, dtype=bool) - for i, j, k in NEIGHBOURS: - grown |= padded[1 + i:1 + i + n[0], 1 + j:1 + j + n[1], 1 + k:1 + k + n[2]] - front = grown & free & (waves == unreached) + front = _grow(front) & free & (waves == unreached) waves[front] = wave if waves[start] == unreached: raise RouteError("no free way joins its ends: obstacles close every way through its search box") @@ -184,21 +200,22 @@ def pull(points, distance, need: float, rate: float = 1.0) -> np.ndarray: return np.array(kept) -def leg(a, b, occupancy, distance, need: float, step: float, margin: float, limit: int, name: str, pad: float = 0.0): +def leg(a, b, occupancy, distance, need: float, step: float, margin: float, limit: int, name: str, pad: float = 0.0, offset=(0.0, 0.0, 0.0)): """(the pulled polyline from a to b, the voxels searched): a grid over the two ends' box plus margin, free where `occupancy` reads need plus pad plus REACH of a voxel, a wavefront between the free voxels beside the ends, pulled against `distance`. `pad` is room kept beyond need for the bends the leg's corners will get: a line pulled at need alone grazes what it wraps, and the corner there has no room for an arc. Within twice pad of an end the pull - asks for half the distance from that end instead, since an end stands where it is given. Refuses, naming the - leg: an end nearer an obstacle than need, an end with no free voxel in sight beside it, a box over the limit, and - no way through.""" + asks for half the distance from that end instead, since an end stands where it is given. `offset`, in steps along + each axis, moves the lattice's origin: the polyline is a seed whose vertices follow the lattice, and another origin + gives another seed. Refuses, naming the leg: an end nearer an obstacle than need (Blocked: no grid lifts that), an + end with no free voxel in sight beside it, a box over the limit, and no way through.""" a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64) for label, point in (("start", a), ("end", b)): reads = float(np.asarray(distance(point[None]))[0]) if reads < need - HELD: - raise RouteError(f"{name}: its {label} {spot(point)} stands {reads:.4g} m from an obstacle, under the {need:.4g} m the bundle needs") + raise Blocked(f"{name}: its {label} {spot(point)} stands {reads:.4g} m from an obstacle, under the {need:.4g} m the bundle needs") try: - cells = grid(np.minimum(a, b) - margin, np.maximum(a, b) + margin, step, occupancy, need + pad + REACH * step, limit) + cells = grid(np.minimum(a, b) - margin - step * np.asarray(offset, dtype=np.float64), np.maximum(a, b) + margin, step, occupancy, need + pad + REACH * step, limit) except RouteError as error: raise RouteError(f"{name}: {error}") from None ends = [] @@ -277,23 +294,131 @@ def _radius(point, before, after, turn: float, cap: float, room) -> float: return low -def tangents(points, room, lead: float, keep=None, centred=None) -> np.ndarray: +def _straights(lengths, lead: float, keep, centred): + """(free, each, centred) of a polyline's segments: the straight a segment has to give its corners' tangents (its + length less what it keeps: `keep`, and `lead` more on the first and last), and what one end of it may take: all of + it, or half on a centred segment, whose kept straight stays in its middle.""" + free = np.maximum(lengths - _kept(len(lengths), lead, keep), 0.0) + centred = np.zeros(len(lengths), dtype=bool) if centred is None else np.asarray(centred, dtype=bool) + return free, np.where(centred, free / 2.0, free), centred + + +def _floors(turn, floor: float, least) -> np.ndarray: + """The tangent length each corner needs: its turn's at the floor radius, and `least` where that is more (a corner + that will turn further than it does here: the one at a pin).""" + need = floor * np.tan(np.minimum(turn, STIFF) / 2.0) + return need if least is None else np.maximum(need, np.asarray(least, dtype=np.float64)) + + +def tangents(points, room, lead: float, keep=None, centred=None, floor: float = 0.0, least=None) -> np.ndarray: """The tangent length of the arc at each interior point of a polyline (0 where it runs straight on). Each corner - first gets the largest radius its room allows (_radius) within the straight its two segments have to give: a - segment's length less what it keeps straight (`keep` for each segment, and `lead` more on the first and last), or - half of that at each end of a `centred` segment, whose kept straight stays in its middle. Where two corners' - tangents overlap on a segment both shrink in proportion until they share it.""" + first gets the largest radius its room allows (_radius) within the straight its two segments have to give + (_straights). Where two corners' tangents overlap on a segment, each keeps what it needs (_floors: its tangent at + `floor`, or `least`) and what the segment has beyond that is shared in proportion to what each asked beyond its + need; a corner holds its `least` of a segment even where its arc here is shorter. Where the two needs do not fit + the segment both shrink in proportion, and fillet refuses the corner.""" points = np.asarray(points, dtype=np.float64) lengths, unit, turn = _turns(points) - free = np.maximum(lengths - _kept(len(lengths), lead, keep), 0.0) - each = np.where(np.zeros(len(lengths), dtype=bool) if centred is None else np.asarray(centred, dtype=bool), free / 2.0, free) + free, each, _ = _straights(lengths, lead, keep, centred) t = np.zeros(len(turn)) for c in np.flatnonzero(turn >= STRAIGHT): t[c] = _radius(points[c + 1], unit[c], unit[c + 1], float(turn[c]), float(min(each[c], each[c + 1])), room) * math.tan(turn[c] / 2.0) - share = np.ones(len(lengths)) - both = t[:-1] + t[1:] # on segment s, between corners s - 1 and s - share[1:-1] = np.where(both > free[1:-1], free[1:-1] / np.maximum(both, 1e-300), 1.0) - return t * np.minimum(share[:-1], share[1:]) + need = _floors(turn, floor, least) + claim = np.maximum(t, need) + held = claim.copy() + for s in range(1, len(lengths) - 1): # segment s, between corners s - 1 and s + both, needs = claim[s - 1] + claim[s], need[s - 1] + need[s] + if both > free[s]: + for c in (s - 1, s): + held[c] = min(held[c], need[c] + (claim[c] - need[c]) * (free[s] - needs) / (both - needs) if needs <= free[s] else claim[c] * free[s] / both) + return np.minimum(t, held) + + +def strain(points, floor: float, lead: float, keep=None, centred=None, least=None) -> np.ndarray: + """For each segment of a polyline, the straight its corners' tangents take at the floor radius beyond what the + segment has to give (_straights, _floors); all 0 where every corner has the straight for its bend. What fillet + refuses for want of straight, as lengths relax can lower.""" + lengths, _, turn = _turns(np.asarray(points, dtype=np.float64)) + free, each, centred = _straights(lengths, lead, keep, centred) + need = _floors(turn, floor, least) + first, last = np.r_[0.0, need], np.r_[need, 0.0] # of the corner a segment starts at, and the one it ends at + return np.where(centred, np.maximum(first - each, 0.0) + np.maximum(last - each, 0.0), np.maximum(first + last - free, 0.0)) + + +def relax(points, tags, cost, clear, reach: float, rounds: int = 64): + """(points, tags) of a polyline refined in continuous space until `cost(points, tags)`, an amount for each + segment, is all 0 or nothing tried lowers its sum. A vertex whose tag is None is free; the others stay. Each round + tries, about the segments that cost: a free vertex dropped; a free vertex moved by a length (first `reach`) along + each axis and along its two segments; and a vertex added at a segment's middle, moved that length along an axis. + The try that lowers the sum most among those whose changed segments `clear(a, b)` proves is kept; with none, the + length is halved, down to FINE. The oracle alone says what is clear: no lattice is read.""" + points, tags = np.asarray(points, dtype=np.float64), list(tags) + + def price(p, g): + try: + return float(np.sum(cost(p, g))) + except RouteError: # two vertices on one point + return math.inf + + now, delta, most = price(points, tags), float(reach), len(points) + 4 + for _ in range(rounds): + if not 0.0 < now < math.inf or delta < FINE: + break + strained = np.flatnonzero(np.asarray(cost(points, tags)) > 0.0) + tries = [] + for v in sorted({v for s in strained for v in range(s - 1, s + 3) if 0 < v < len(points) - 1 and tags[v] is None}): + tries.append((np.delete(points, v, axis=0), tags[:v] + tags[v + 1:], (v - 1,))) + along = [(points[v + side] - points[v]) / max(float(np.linalg.norm(points[v + side] - points[v])), 1e-12) for side in (-1, 1)] + for way in AXES + along + [-d for d in along]: + moved = points.copy() + moved[v] += delta * way + tries.append((moved, tags, (v - 1, v))) + if len(points) < most: + for s in sorted({q for s in strained for q in (s - 1, s, s + 1) if 0 <= q < len(points) - 1}): + for way in AXES: + tries.append((np.insert(points, s + 1, (points[s] + points[s + 1]) / 2.0 + delta * way, axis=0), tags[:s + 1] + [None] + tags[s + 1:], (s, s + 1))) + priced = sorted(((price(p, g), index) for index, (p, g, _) in enumerate(tries)), key=lambda row: row[0]) + for value, index in priced: + if not value < now - 1e-12: + delta /= 2.0 + break + p, g, changed = tries[index] + if all(clear(p[q], p[q + 1]) for q in changed): + now, points, tags = value, p, g + break + else: + delta /= 2.0 + return points, tags + + +def leaves(point, heading, floor: float, distance, need: float, cells: int = 6) -> bool: + """Whether a curve that bends no tighter than `floor` and keeps need can get 2 floors away from `point`, which it + leaves along `heading`. False is a proof that none can: the bundle is too stiff for the room there. + + Until such a curve is pi floors long it stays out of every ball of radius floor that touches its line at the + point and never falls behind the point (it has gone floor x sin(length / floor) along its heading), and by then + it stands at least 2 floors from the point (Schwarz's bound on a curve's chord; Dubins, "On curves of minimal + length with a constraint on average curvature", Amer. J. Math. 79, 1957). So it reaches the sphere of 2 floors + through points that keep need, stand outside those balls and are not behind the point. On voxels of floor / cells + a voxel is open unless its centre reads under need less REACH of a voxel, or stands more than that inside the + balls or behind the point: every point of such a curve then lies in an open voxel, and neighbouring points in neighbouring voxels. + When no open voxel on the sphere is joined to the point's, no curve exists; the grid sets how often the proof is + found, never whether it is true.""" + point, heading = np.asarray(point, dtype=np.float64), np.asarray(heading, dtype=np.float64) / np.linalg.norm(heading) + step, n = floor / cells, 4 * cells + 3 # 2 floors and a voxel each way + axis = step * (np.arange(n) - (n - 1) / 2.0) + offsets = np.stack(np.meshgrid(axis, axis, axis, indexing="ij"), axis=-1).reshape(-1, 3) + along = offsets @ heading + inside = floor - np.sqrt((np.linalg.norm(offsets - along[:, None] * heading, axis=1) - floor) ** 2 + along ** 2) + opened = ((np.asarray(distance(point + offsets)) >= need - REACH * step) & (inside <= REACH * step) & (along >= -REACH * step)).reshape(n, n, n) + reached = np.zeros((n, n, n), dtype=bool) + reached[(n - 1) // 2, (n - 1) // 2, (n - 1) // 2] = True + while True: + front = _grow(reached) & opened & ~reached + if not front.any(): + break + reached |= front + return bool((reached.reshape(-1) & (np.linalg.norm(offsets, axis=1) >= 2.0 * floor - REACH * step)).any()) def arcs(points, t): @@ -330,25 +455,25 @@ class Filleted(NamedTuple): radii: np.ndarray # radius at each interior point, inf where the polyline runs straight on -def fillet(polyline, room, floor: float, lead: float, keep=None, centred=None) -> Filleted: +def fillet(polyline, room, floor: float, lead: float, keep=None, centred=None, least=None) -> Filleted: """A polyline with its corners rounded (tangents, arcs). `room(a, b)` is the least obstacle distance along the - segment a..b less need, or None where nothing stands near. Refuses a corner whose radius is under `floor`, naming - the corner, its point, the radius it got and the floor.""" + segment a..b less need, or None where nothing stands near. `least` is the tangent length a corner holds of its + segments whatever it turns here. Refuses a corner whose radius is under `floor`, naming the corner, its point, the + radius it got, the floor and what this polyline lacks there: it speaks of this polyline, not of every route.""" polyline = np.asarray(polyline, dtype=np.float64) if len(polyline) < 3: return Filleted(polyline, np.full(len(polyline), -1), np.zeros(0), np.zeros(0)) - t = tangents(polyline, room, lead, keep, centred) + t = tangents(polyline, room, lead, keep, centred, floor, least) turn = _turns(polyline)[2] radii = np.where(turn >= STRAIGHT, t / np.tan(np.maximum(turn, STRAIGHT) / 2.0), np.inf) under = np.flatnonzero(radii < floor * (1.0 - 1e-9)) if len(under): c = int(under[np.argmin(radii[under])]) lengths, unit, _ = _turns(polyline) - free = np.maximum(lengths - _kept(len(lengths), lead, keep), 0.0) - each = np.where(np.zeros(len(lengths), dtype=bool) if centred is None else np.asarray(centred, dtype=bool), free / 2.0, free) + each = _straights(lengths, lead, keep, centred)[1] straight, tangent, depth = float(min(each[c], each[c + 1])), floor * math.tan(turn[c] / 2.0), floor * (1.0 - math.cos(turn[c] / 2.0)) if straight < tangent: - why = (f"the bundle is too stiff for this route: the corner's segments leave {straight:.4g} m of straight for the {tangent:.4g} m its tangent takes at the floor " + why = (f"the corner's segments leave {straight:.4g} m of straight for the {tangent:.4g} m its tangent takes at the floor " "(a lower bend, thinner hoses, or ends, clamps and the pin point further apart)") elif room is not None and _radius(polyline[c + 1], unit[c], unit[c + 1], float(turn[c]), straight, room) < floor * (1.0 - 1e-9): stands = min(room(polyline[c + 1] - unit[c] * tangent, polyline[c + 1]), room(polyline[c + 1], polyline[c + 1] + unit[c + 1] * tangent)) @@ -422,6 +547,18 @@ def turned(points, origin, axis, degrees: float) -> np.ndarray: return origin + p * c + np.cross(axis, p) * s + axis[None] * (p @ axis)[:, None] * (1.0 - c) +def sharpest_turn(before, after, axis, low: float, high: float) -> float: + """The largest turn, in radians, from the unit `before` to the unit `after` turned about `axis` by any angle of + low..high degrees. The turn's cosine is a + b cos + c sin of the angle, least at one angle of a full turn: the + largest turn is there where the range holds that angle, and at an end of the range where it does not.""" + axis = np.asarray(axis, dtype=np.float64) / np.linalg.norm(axis) + along = axis * float(after @ axis) + a, b, c = float(before @ along), float(before @ (after - along)), float(before @ np.cross(axis, after)) + worst = math.degrees(math.atan2(-c, -b)) + angles = [low, high] + [worst + 360.0 * k for k in range(-2, 3) if low < worst + 360.0 * k < high] + return max(math.acos(max(-1.0, min(1.0, a + b * math.cos(math.radians(v)) + c * math.sin(math.radians(v))))) for v in angles) + + def rolls_of(low: float, high: float, step: float) -> list: """low, then every step up to high, and high.""" return [float(v) for v in np.arange(low, high - 1e-9, step)] + [float(high)] @@ -437,7 +574,7 @@ def passes(polyline, t, j: int, origin, axis, rolls, finest: float, current: flo that stands rho from the axis moves at most rho x w against the other side's parts, so its reading against them counts for that much less (`parent` and `child` read each side's parts where they stand at `current`; samples are turned back for the child's). The bend at the pin has one radius through a bin, the largest that fits at the bin's - sharpest turn: its arc then stands within radius x (1 - cos(turn / 2)) of its two tangent segments, which are swept + sharpest turn (sharpest_turn, over the bin's rolls): its arc then stands within radius x (1 - cos(turn / 2)) of its two tangent segments, which are swept for need and that much more. Everything else outside the leads is swept for need (measure). A bin that falls short is halved and measured at each half's middle, down to `finest` degrees of half width, where it is refused, naming the roll, the side, the point and the reading; so is a bin whose bend at the pin has no room for the floor. @@ -464,7 +601,7 @@ def passes(polyline, t, j: int, origin, axis, rolls, finest: float, current: flo sides = {"parent's side": lambda p: np.minimum(np.asarray(parent(p)), np.asarray(child(back(p))) - moves(p)), "child's side": lambda p: np.minimum(np.asarray(child(back(p))), np.asarray(parent(p)) - moves(p))} lengths_, unit, turn = _turns(posed) - corner, sharpest = posed[j], min(float(turn[c]) + width, math.pi - 1e-6) + corner, sharpest = posed[j], min(sharpest_turn(unit[c], unit[c + 1], axis, low - roll, high - roll), math.pi - 1e-6) cap = min(lengths_[c] - kept[c] - (sharp[c - 1] if c > 0 else 0.0), lengths_[c + 1] - kept[c + 1] - (sharp[c + 1] if c + 1 < len(sharp) else 0.0)) def fits(bend: float): diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 6f50fc9..2651e8c 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -2039,8 +2039,12 @@ class OwnershipTests(unittest.TestCase): work = body.split(" @staticmethod")[0] first = min(work.index(write) for write in ("clear_geometry()", "bpy.data.meshes.new(", "write_mesh(", ".parent =", "[HOSE] =")) self.assertLess(work.rindex("raise Refused("), first) # every refusal before any write - for call in ("route.leg(", "self.shaped(", "self.built(", "self.trees(", "self.crossed(", "self.rows()", "self.frame("): + for call in ("self.seed(", "self.routed(", "route.leaves(", "self.built(", "self.trees(", "self.crossed(", "self.rows()", "self.frame("): self.assertLess(work.rindex(call), first, call) + for write in ("clear_geometry()", "bpy.data.meshes.new(", "write_mesh(", ".parent =", "[HOSE] ="): # what work calls to seed, refine and shape a route writes nothing + self.assertEqual(body.count(write), work.count(write), write) + for owner, call in (("seed", "route.leg("), ("routed", "route.relax("), ("routed", "self.shaped(")): + self.assertIn(call, body.split(f" def {owner}(")[1].split("\n def ")[0], call) shaped = body.split(" def shaped(")[1].split(" def built(")[0] self.assertLess(shaped.index("route.fillet("), shaped.index("route.verify(")) self.assertLess(shaped.index("route.verify("), shaped.index("route.passes(")) diff --git a/surfaces/blender/tests/test_route.py b/surfaces/blender/tests/test_route.py index 973be7a..bd18822 100644 --- a/surfaces/blender/tests/test_route.py +++ b/surfaces/blender/tests/test_route.py @@ -224,13 +224,80 @@ class FilletTests(unittest.TestCase): route.verify(free.curve, distance, 0.05, 0.0) def test_a_corner_under_the_floor_is_refused_by_name(self): - with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[1, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.15 m, under the floor 0\.5: the bundle is too stiff for this route: " + with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[1, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.15 m, under the floor 0\.5: " r"the corner's segments leave 0\.3 m of straight for the 0\.5 m its tangent takes at the floor"): route.fillet(self.ZIGZAG, None, 0.5, 0.2) with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[0, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0(\.00\d+)? m, under the floor 0\.05: the route passes too near an obstacle to bend here: " r"its segments stand 0(\.00\d+)? m clear beyond what the bundle needs and the arc at the floor takes 0\.01464 "): route.fillet(np.array([[-1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]]), room_of(ball([-0.05, 0.05, 0.0], 0.02), 0.05), 0.05, 0.0) # a ball in the corner + def test_a_corner_keeps_its_floor_s_tangent_before_its_neighbour_gets_more(self): + """bend-room-searched. Two corners on a 0.5 segment ask 0.5 and 0.25 of it and need 0.22 each at the floor: + each keeps its need and the 0.06 left is shared by what each asked beyond it. Mutant T1 (shared in proportion + to what each asked, floor = 0 in tangents): the second corner gets 0.167 and the polyline is refused.""" + points = np.array([[0.0, 0.0, 0.0], [3.0, 0.0, 0.0], [3.0, 0.5, 0.0], [3.25, 0.5, 0.0]]) + made = route.fillet(points, None, 0.22, 0.0) + self.assertAlmostEqual(float(made.t.sum()), 0.5, places=12) + self.assertAlmostEqual(float((made.t[0] - 0.22) / (made.t[1] - 0.22)), 0.28 / 0.03, places=9) + self.assertAlmostEqual(float(route.tangents(points, None, 0.0)[1]), 0.5 / 3.0, places=12) # the share a corner got before its need counted + self.assertEqual(float(route.strain(points, 0.22, 0.0).sum()), 0.0) + self.assertAlmostEqual(float(route.strain(points, 0.3, 0.0)[1]), 0.1, places=12) + self.assertAlmostEqual(float(route.strain(points, 0.3, 0.0, keep=[0.0, 0.1, 0.0], centred=[False, True, False])[1]), 0.2, places=12) + held = route.fillet(points, None, 0.1, 0.0, least=[0.4, 0.0]) # a corner that will turn further holds the tangent that takes + self.assertAlmostEqual(float(held.t[0]), 0.4, places=12) + self.assertAlmostEqual(float(held.t[1]), 0.1, places=12) + + def test_a_seed_without_the_straight_for_its_bends_is_refined_where_the_oracle_allows(self): + """bend-room-searched. A seed's vertex stands 0.18 from a held corner and their two tangents at the floor take + 0.25; a ball closes the straight way past it. relax moves the vertex until every segment has its straight, + each moved segment proven clear. Mutant X1 (relax returns its seed): strain stays and fillet refuses.""" + distance, need, floor = ball([1.0, 0.7, 0.0], 0.05), 0.05, 0.3 + seed, tags = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.15, 0.1, 0.0], [1.15, 1.5, 0.0]]), ["P", "E", None, "P"] + self.assertFalse(route.clear(seed[1], seed[3], distance, need)) + self.assertGreater(float(route.strain(seed, floor, 0.0).sum()), 0.05) + with self.assertRaisesRegex(route.RouteError, "under the floor 0.3: it shares a segment with the corner beside it"): + route.fillet(seed, room_of(distance, need), floor, 0.0) + tried = [] + + def sure(a, b): + tried.append((a, b)) + return route.clear(a, b, distance, need) + points, kept = route.relax(seed, tags, lambda p, g: route.strain(p, floor, 0.0), sure, floor) + self.assertTrue(tried) + self.assertEqual(float(route.strain(points, floor, 0.0).sum()), 0.0) + self.assertEqual([tag for tag in kept if tag is not None], ["P", "E", "P"]) + for index in (0, 1, -1): + self.assertTrue((points[index] == seed[index]).all()) + self.assertGreaterEqual(float(distance(np.vstack([dense(p, q, 0.001) for p, q in zip(points[:-1], points[1:])])).min()), need) + made = route.fillet(points, room_of(distance, need), floor, 0.0) + self.assertGreaterEqual(float(made.radii.min()), floor * (1 - 1e-9)) + open_points, open_tags = route.relax(seed, tags, lambda p, g: route.strain(p, floor, 0.0), lambda a, b: True, floor) + self.assertEqual(open_tags, ["P", "E", "P"]) # with nothing in the way the vertex is dropped + same, _ = route.relax(seed, tags, lambda p, g: route.strain(p, floor, 0.0), lambda a, b: False, floor) + self.assertTrue((same == seed).all()) # nothing the oracle does not prove is kept + + def test_too_stiff_is_proven_of_a_pocket_and_of_nothing_else(self): + """bend-room-searched. A wall 0.08 ahead of a point a hose leaves along x: no curve of radius 0.2 turns + aside in the 0.06 its centre line has, and one of radius 0.04 does. Mutant S1 (the balls a curve cannot + enter left out of leaves): the stiff bundle is said to leave.""" + wall = lambda at: (lambda p: at - np.asarray(p)[:, 0]) # noqa: E731 + origin, ahead = np.zeros(3), np.array([1.0, 0.0, 0.0]) + self.assertFalse(route.leaves(origin, ahead, 0.2, wall(0.08), 0.02)) + self.assertTrue(route.leaves(origin, ahead, 0.04, wall(0.08), 0.02)) + self.assertTrue(route.leaves(origin, ahead, 0.2, wall(0.5), 0.02)) + slit = lambda p: np.where(np.abs(np.asarray(p)[:, 1]) < 0.03, 1.0, wall(0.08)(p)) # noqa: E731 the wall, open along a slit 0.06 wide straight ahead + self.assertTrue(route.leaves(origin, ahead, 0.2, slit, 0.02)) + + def test_the_sharpest_turn_of_a_range_is_exact(self): + """range-measured-unposed. The turn at a pin over a range of rolls, against the turn at 4001 rolls of it.""" + rng = np.random.default_rng(7) + for low, high in ((-20.0, 20.0), (-170.0, 5.0), (30.0, 31.0), (-360.0, 360.0), (4.0, 4.0)): + before, after, axis = (v / np.linalg.norm(v) for v in rng.normal(size=(3, 3))) + turns = [math.acos(max(-1.0, min(1.0, float(before @ route.turned(after[None], np.zeros(3), axis, float(roll))[0])))) for roll in np.linspace(low, high, 4001)] + found = route.sharpest_turn(before, after, axis, low, high) + self.assertGreaterEqual(found, max(turns) - 1e-12) + self.assertLess(found - max(turns), 1e-5) + def test_the_floor_is_the_innermost_hose_s(self): """Mutant H8 (the floor taken at the centre line): the innermost of three hoses bends tighter than bend outside diameters.""" From dcd06e9af8cdb081a3e5a626797e9b8f2c2ffe7e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:21:34 +0100 Subject: [PATCH 127/223] live kitbash_hose: the steps refused at s2 route, seeds named, a port proven too stiff under a wall; docs: a seed refined, what a refusal claims, the pose-only gap's follow-up (cut kit-hose, h3) Co-Authored-By: Claude Fable 5.2 --- .../brokkr_kitbash/brokkr_actions.json | 2 +- surfaces/blender/docs/kitbash.md | 76 ++++-- surfaces/blender/tests/live/kitbash_hose.py | 37 ++- .../tests/live/kitbash_hose.result.json | 222 ++++++++++++++---- 4 files changed, 276 insertions(+), 61 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 5483183..3ea95e9 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -784,7 +784,7 @@ }, { "name": "brokkr_kitbash.hose", - "doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut with room for its bends where a way has it, and the whole polyline is rounded, each corner by the largest arc its measured room allows; the innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a pivot connection between its ends' parts): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres, \"range\": [lo, hi]}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. The whole range from lo to hi is measured without posing anything, each side against the other side's parts: a roll every 5 degrees answers for the rolls about it by what a point can move within them, and more are measured between where that falls short; another hose through the same pin is kept clear of where it stands, not across the rolls. Every line is measured so that nothing thinner than a spacing can stand between two readings, whatever the step. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, sag per leg in metres, rolls (how many were measured), worstRoll, worstClearance (least over the range, each reading less what its point can move within its roll's bin), faces, volume, nonManifoldEdges and radii {least, corners}.", + "doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut with room for its bends where a way has it, and the whole polyline is rounded, each corner by the largest arc its measured room allows. That polyline is a seed: one refused for want of straight between its corners is refined in continuous space (vertices dropped, moved and added, each change proven clear), and before a route is refused the legs are searched again on two more grid origins and at half the step. The refusal then names the steps and origins tried and the first seed's refusal, and says this shows no route was found, not that none exists; it says the bundle is too stiff only where that is proven at a port. The innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a pivot connection between its ends' parts): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres, \"range\": [lo, hi]}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. The whole range from lo to hi is measured without posing anything, each side against the other side's parts: a roll every 5 degrees answers for the rolls about it by what a point can move within them, and more are measured between where that falls short; another hose through the same pin is kept clear of where it stands, not across the rolls (follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes that check). Every line is measured so that nothing thinner than a spacing can stand between two readings, whatever the step. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, seed {step, offset, refined} (the grid that gave the route, and whether its polyline was refined), sag per leg in metres, rolls (how many were measured), worstRoll, worstClearance (least over the range, each reading less what its point can move within its roll's bin), faces, volume, nonManifoldEdges and radii {least, corners}.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 3b8ed49..6ddbbfa 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -625,8 +625,9 @@ stands the bundle's half width, the clearance and half a voxel's diagonal from e between neighbouring free voxels keeps the clearance; a 26-connected wavefront finds a shortest way and it is pulled taut. The legs joined are one polyline, and each corner is rounded by the largest arc its measured room allows: the arc stands within `radius * (1 - cos(turn / 2))` of its two tangent segments, so with that much room -beyond the clearance measured along them it keeps the clearance. Where two arcs would overlap on a segment both -shrink in proportion. The floor is `bend` outside diameters for the innermost hose (the centre line's is half the +beyond the clearance measured along them it keeps the clearance. Where two arcs would overlap on a segment each +keeps the tangent its bend takes at the floor and they share what the segment has left, in proportion to what each +asked beyond that; the corner at a pin holds the tangent its sharpest roll takes. The floor is `bend` outside diameters for the innermost hose (the centre line's is half the bundle's spread more). The finished curve is measured once more against every mesh before anything is written. **Measured, not sampled.** Every line the route trusts (a sight line of the pull, a tangent segment's room, the @@ -643,11 +644,46 @@ has no room for an arc; how much it happened to keep changed with `step`, so a b floor beyond the clearance, what the arc of a quarter turn at the floor takes (within twice that of a leg's end the pull asks half the distance from the end instead, since an end stands where it is given). A leg with no way that roomy (a clamp stands nearer its seat than that, and so does a gap the bundle only just passes) is searched -again without, and the hose is longer where the roomy way goes round. A corner under the floor is refused by what -limits it: the bundle too stiff for the route (the corner's segments are shorter than its tangent at the floor), -an obstacle too near the corner's segments for the arc (both distances named), or two corners that cannot share -the segment between them. The remedies are a lower `bend`, thinner or fewer hoses, waypoints further apart (a -larger `standoff`), or a clamp that leads the hose wide; a different `step` is not one. +again without, and the hose is longer where the roomy way goes round. + +**A seed, refined.** The polyline a search gives is a seed. Its vertices stand where the grid's lattice put them, +so whether two corners have the straight between them for both bends follows the lattice too: searched and pulled +with room alone, the first bundle on the knee routed at steps 0.125 and 0.13 and was refused at 0.1275, and the +second was refused at 26 of the 76 steps from 0.0125 to 0.2. Three things take the lattice out of the answer. + +- A corner keeps its floor's tangent before a neighbour gets more (above), and the pin's corner holds what its + sharpest roll takes, exactly (`route.sharpest_turn`: the turn's cosine over a range of rolls is a + b cos + c sin). +- A seed that is refused is refined in continuous space (`route.relax`). About each segment too short for its + corners' tangents at the floor (`route.strain`), a vertex the search placed is dropped, moved along each axis and + along its own two segments, or joined by a new one beside a segment's middle; the try that lowers the shortfall + most is kept if `route.measure` proves its changed segments clear with the room a leg is pulled with. The moves + start a floor long and halve when nothing helps, down to 1 mm. Ports, lead ends, clamp straights and the pin + point do not move. The refinement prices straight only: room for an arc is still measured by the fillet after it. +- A route still refused is searched again on two more grid origins (half a step along each axis; then 0.31, 0.67 + and 0.13 of a step), and then at half the step on all three, each seed refined the same way. `seed` in the + report is the step and origin that gave the route and whether it was refined. + +The cost is in the refusals and in sameness: a route that cannot be made runs up to six seeds, three of them on 8 +times the voxels, before it is refused, and the same request at another `step` may take another way round, though +never one that clears less than the clearance or bends under the floor. + +A refusal after all that says what was tried, and that this shows no route was found, not that none exists: `the +search found no route: it tried steps 0.02 and 0.01, each on grid origins (0, 0, 0), (0.5, 0.5, 0.5), (0.31, 0.67, +0.13) of a step, and refined each seed in continuous space; this does not show that no route exists. The first +refusal: corner 2 at ...`. The first refusal is the requested step's own seed's, by corner, point or roll, with +what that polyline lacked: straight for a tangent, room for an arc (both distances named), or a segment two corners +cannot share. An end that stands nearer an obstacle than the bundle needs is refused at once: no grid lifts that. + +`too stiff` is said only where it is proven (`route.leaves`). For its first pi floors of length a curve that bends +no tighter than the floor stays out of every ball of radius floor that touches its line where it starts, and ahead +of that point, and by then it stands 2 floors away (Schwarz's bound on a chord; Dubins 1957). So where a fitting's +lead ends, the hose must reach the sphere of 2 floors through points that keep the clearance and lie outside those +balls. They are read on voxels of a sixth of the floor with the bound every other measurement uses, and when they +do not join the lead's end to the sphere no route exists at that `bend`: `the bundle is too stiff to leave its +start: from the end of its lead at ... no curve that bends at the floor radius ... or wider keeps ... from what +stands within ... of it`. The proof is tried at both ports when no route was found. It does not look at clamps or +the pin, so a bundle too stiff for the room there gets the search's refusal. The remedies are a lower `bend`, +thinner or fewer hoses, waypoints further apart (a larger `standoff`), or a clamp that leads the hose wide. **Slack.** `sag` (outside diameters, default 1) lowers the middle of each free span's longest segment along world -z, by less where the span runs steeply, and never by more than half the room measured along it: both halves then @@ -672,8 +708,8 @@ radius through a bin, the largest that fits at the bin's sharpest turn, and its for the clearance and the arc's dip more. A bin that falls short is halved and measured again at each half's middle, down to 0.3 degrees of half width, so a range that is clear costs 9 rolls for 40 degrees and one that passes near a part costs more only there (`rolls` reports how many were measured). A range that fails is refused -by roll, side and point (`roll 49.22: the hose's child's side reads 0.02653 m from the parts about the pin at -[-0.2107, -0.2043, 0.7271], counting the 0.0005832 m it can move against the other side's through the 0.156 degrees +by roll, side and point (`roll 50.78: the hose's child's side reads 0.0264 m from the parts about the pin at +[-0.2122, -0.2044, 0.7269], counting the 0.0005875 m it can move against the other side's through the 0.156 degrees either side of it: under the 0.0266 m the bundle needs`); when the sagged route and the taut one both fail the refusal names both. `worstClearance` is the least reading over the range, each less what its point can move within its bin. `lengthChange` is the centre line's longest less its shortest over the rolls measured, as each rounds the @@ -682,7 +718,10 @@ bend. Two pins between the ends are refused: end the hose on a part between them Another hose through the same pin bends with it and belongs to neither side. A route keeps clear of it where it stands, and across the rolls each hose is measured against the parts of the two sides, not against where the other hose stood: give two hoses through one pin different standoffs, and their clearance from each other holds at the -pose they were routed at. +pose they were routed at. That is a ruled limit (`aetheria-release:ruling:hose-same-pin-pose-only-now`), and the +check it leaves out has an owner: follow-up `aetheria-release:follow_up:hose-motion-clearance-from-skinning` will pose +each other hose across the range with the skin blend the output mesh uses. Until it lands nothing measures two hoses +through one pin against each other in motion. **What it writes.** One mesh object, a child of the start's object under identity matrices, with no modifier and no material: each hose, two ferrule collars at each of its ends, and the clamps, all swept by `core.sweep`. @@ -699,8 +738,10 @@ skin weights are `brokkr_rig`'s. names no object, no such socket, or a socket of the wrong type; a bundle wider than a port, naming both sizes; a part that is scaled or that Blender does not evaluate; a pin crossed with no `joint`, a `joint` with no pin, two pins, a `joint` socket off the pin's axis, the current roll outside `range`; a search box over 524288 voxels, -naming a step that fits; an end nearer an obstacle than the bundle needs; no way through; a corner under the -floor, by what limits it; a curve not proven to keep the clearance, naming the point; a roll that fails. +naming a step that fits; an end nearer an obstacle than the bundle needs; a bundle proven too stiff to leave a +port; and, once every seed has been tried, no route found, with the first seed's refusal: no way through, a corner +under the floor by what its polyline lacked, a curve not proven to keep the clearance at a named point, or a roll +that fails. **Cost.** Probes in Blender 5.3 on Starfire, medians of 3 interleaved repetitions: a nearest-face query on a tree of 81,920 faces takes 100 to 123 us uncapped and 3.4 us capped at 0.06 m, so every query is capped; on a grid of @@ -710,10 +751,15 @@ fillet and the verification under 2 ms together, 27 rolls 0.056 s and the sweep knee of `tests/live/kitbash_hose.py` (two struts, two actuators and a plate; two legs of 79,488 and 53,406 voxels at roll 0, timed at roll 10; three hoses, 9 rolls) took 0.80 s a call, median of 3 each after one report action, where it took 0.50 s when lines were sampled at half a voxel and each leg was searched once: the occupancy -is read to a larger cap and the room, the curve and the rolls are measured to 1 mm near what they pass. +is read to a larger cap and the room, the curve and the rolls are measured to 1 mm near what they pass. With +seeds refined and retried the same call took 0.64 s. Over the 76 steps from 0.0125 to 0.2 on that knee, one call +each with three other Blenders running, the first bundle took 0.53 s at the median and 2.34 s at most, and the +second 0.32 s and 2.56 s; of the second's 76 routes 8 came from a refined seed, 3 from another grid origin and 12 +from half the step. `tests/test_route.py` proves the path without Blender (the half-diagonal rule, a plate between two readings, a leg's -room where it wraps, the fillet's tangency, sharing, room and floor, the sag's bound, the frames against the double +room where it wraps, the fillet's tangency, sharing, room and floor, a corner's floor before its neighbour's share, a +seed refined where the oracle allows, the proof of too stiff, the sharpest turn of a range of rolls, the sag's bound, the frames against the double reflection method, the rolls and a plate between two of them, the bend at the pin's room), and `tests/live/kitbash_hose.py` the action in Blender. @@ -751,7 +797,7 @@ vertices overflow. | `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | | `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | -| `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff, range}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. | +| `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff, range}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `seed`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored value (`set_params`). A value outside its bounds is refused with the bounds in the message. diff --git a/surfaces/blender/tests/live/kitbash_hose.py b/surfaces/blender/tests/live/kitbash_hose.py index b9a74ca..65e76c4 100644 --- a/surfaces/blender/tests/live/kitbash_hose.py +++ b/surfaces/blender/tests/live/kitbash_hose.py @@ -68,10 +68,10 @@ LEAD = 8.0 * RADIUS FLOOR = 4.0 * 2.0 * RADIUS + SPREAD # of the centre line: the innermost hose keeps 4 outside diameters BUNDLE = {"count": COUNT_HOSES, "radius": RADIUS, "clearance": CLEARANCE} # Metres between a hose's surface and the nearest other mesh, read on the hose's own vertices further than the lead -# from both its ports (the least is the worst), over every hose this suite makes. Shipped worst 0.032. Least claimed +# from both its ports (the least is the worst), over every hose this suite makes. Shipped worst 0.031. Least claimed # mutant 0.0089: H4b (route.verify measures and refuses nothing) accepts the hose past the plate beside a port's # straight, section "verify", and the ring of it nearest the plate reads that; shipped refuses it and makes no hose. -# The geometric mean, separation 1.9 each side. +# The geometric mean, separation 1.8 and 1.9. CLEAR = 0.017 # Metres a clamped hose's ring vertices stand off the radius about its own line over a clamp (the line through the # clamp point along the socket's y, offset across the bundle), over the 24 nearest; 1 when a hose has no 24 vertices @@ -261,8 +261,8 @@ try: check("a rebuild at the same pose reports what the first call did", {**again, "rebuilt": False} == report and len(bpy.data.meshes) == len(state[1]) + 1, again) check("hose-through-range: the range passes and reports the length's change", report["lengthChange"] is not None and report["lengthChange"] >= 0 and report["worstRoll"] is not None, report) refused("a range that swings the shin's hose into the thigh's parts, naming the sagged attempt and the taut one", {**FEED, "joint": json.dumps({**JOINT, "range": [-20, 90]})}, - "sagged: roll 49.22: the hose's child's side reads 0.02653 m from the parts about the pin at [-0.2107, -0.2043, 0.7271], counting the 0.0005832 m it can move against the other side's " - "through the 0.156 degrees either side of it: under the 0.0266 m the bundle needs; taut: roll 50.78: the hose's child's side reads 0.0264 m") + "sagged: roll 48.59: the hose's child's side reads 0.0269 m from the parts about the pin at [-0.2144, -0.2042, 0.7271], counting the 0.0005933 m it can move against the other side's " + "through the 0.156 degrees either side of it: too near the 0.0266 m the bundle needs to prove it of what stands between two readings; taut: roll 50.78: the hose's child's side reads 0.0264 m") receipt, _ = send("brokkr_kitbash.hose", **{**FEED, "joint": json.dumps({**JOINT, "range": [-20, 90]})}) check("the refusal names both attempts, each by its roll and its side", "sagged: roll " in str(receipt["message"]) and "; taut: roll " in str(receipt["message"]) and str(receipt["message"]).count("the hose's child's side reads") == 2, receipt["message"]) @@ -333,11 +333,38 @@ try: for step in (0.0125, 0.03, 0.04): # feasibility does not turn on the step: a leg is searched with room for its bends receipt, _ = send("brokkr_kitbash.hose", **{**FEED, "step": step}) check(f"the first hose's route also stands at step {step}, beside the second", receipt["status"] == "accepted", receipt["message"]) + # bend-room-not-monotone-in-step: a search's polyline is a seed. These are steps whose seeds were refused before + # seeds were refined and searched on other grid origins (0.1275 of the first bundle, the rest of the second). + seeds = [] + for base, step in [(FEED, 0.1275)] + [(RETURN, step) for step in (0.0225, 0.04, 0.115, 0.1425, 0.155, 0.2)]: + receipt, swept = send("brokkr_kitbash.hose", **{**base, "step": step}) + ok = receipt["status"] == "accepted" + check(f"{base['object_name']} routes at step {step}: no bend under the floor, the clearance kept", ok and swept["radii"]["least"] >= FLOOR * (1 - 1e-6) and swept["clearance"] >= CLEARANCE + and swept["worstClearance"] >= CLEARANCE and reading("clear", surface_clearance(bpy.data.objects[base["object_name"]], [frame(ram, "port_cap" if base is FEED else "port_rod")[:3, 3] for ram in (upper, lower)]), least=True) >= CLEAR, + [receipt["message"], swept, R["readings"]]) + seeds.append(swept["seed"] if ok else None) + R["reports"]["seeds"] = seeds + check("some of those routes come from a refined seed and some from another grid origin, and the report says which", + any(seed and seed["refined"] for seed in seeds) and any(seed and seed["offset"] != [0.0, 0.0, 0.0] for seed in seeds), seeds) send("brokkr_kitbash.hose", **FEED) - refused("a bundle too stiff for the knee, by what limits its bend", {**FEED, "bend": 16.0}, "under the floor 0.2076: ") + send("brokkr_kitbash.hose", **RETURN) + refused("a bend the search finds no route for on the knee, by what its first seed lacked", {**FEED, "bend": 16.0}, "under the floor 0.2076: ") rod_ports = [frame(upper, "port_rod")[:3, 3], frame(lower, "port_rod")[:3, 3]] check("hose-behind-armour: the second hose keeps the clearance from the first", reading("clear", surface_clearance(bpy.data.objects["Return"], rod_ports), least=True) >= CLEAR, R["readings"]) refused("a pin point another hose already passes", {**RETURN, "object_name": "Third"}, "from an obstacle") + section("too stiff") + # too stiff is said where it is proven: a wall 0.08 above a port leaves the centre line 0.021 beyond its lead to + # turn aside in, and a curve of the floor radius 0.048 cannot; one of 0.012 can, and routes. + for name, x in (("Nozzle", 10.0), ("Drain", 10.6)): + empty = bpy.data.objects.new(name, None) + empty.location = (x, 0.0, 0.0) + bpy.context.scene.collection.objects.link(empty) + box("Lid", (9.0, -1.0, 0.08), (11.6, 1.0, 0.1)) + bpy.context.view_layer.update() + LOOP = {"object_name": "Loop", "start": "Nozzle", "end": "Drain", "count": 1, "radius": RADIUS, "clearance": CLEARANCE} + refused("a bundle proven too stiff to leave its port under a wall", LOOP, "the bundle is too stiff to leave its start: from the end of its lead at [10, 0, 0.048] no curve that bends at the floor radius 0.048 m or wider") + receipt, loop = send("brokkr_kitbash.hose", **{**LOOP, "bend": 1.0}) + check("the same hose at bend 1 routes under the wall", receipt["status"] == "accepted" and loop["radii"]["least"] >= 0.012 * (1 - 1e-6) and loop["clearance"] >= CLEARANCE, [receipt["message"], loop]) section("clamps") tank = place("Tank", "tank", "radius=0.22;length=0.9", [3.0, 0.0, 0.0]) seats = [place(name, "plate", "width=0.1;height=0.1", [x, 0.0, 1.25], [0.0, 0.0, math.pi / 2]) for name, x in (("SeatA", 3.45), ("SeatB", 4.05))] diff --git a/surfaces/blender/tests/live/kitbash_hose.result.json b/surfaces/blender/tests/live/kitbash_hose.result.json index 5f50176..acf4864 100644 --- a/surfaces/blender/tests/live/kitbash_hose.result.json +++ b/surfaces/blender/tests/live/kitbash_hose.result.json @@ -137,7 +137,47 @@ "detail": null }, { - "name": "refused, scene unchanged: a bundle too stiff for the knee, by what limits its bend", + "name": "Feed routes at step 0.1275: no bend under the floor, the clearance kept", + "ok": true, + "detail": null + }, + { + "name": "Return routes at step 0.0225: no bend under the floor, the clearance kept", + "ok": true, + "detail": null + }, + { + "name": "Return routes at step 0.04: no bend under the floor, the clearance kept", + "ok": true, + "detail": null + }, + { + "name": "Return routes at step 0.115: no bend under the floor, the clearance kept", + "ok": true, + "detail": null + }, + { + "name": "Return routes at step 0.1425: no bend under the floor, the clearance kept", + "ok": true, + "detail": null + }, + { + "name": "Return routes at step 0.155: no bend under the floor, the clearance kept", + "ok": true, + "detail": null + }, + { + "name": "Return routes at step 0.2: no bend under the floor, the clearance kept", + "ok": true, + "detail": null + }, + { + "name": "some of those routes come from a refined seed and some from another grid origin, and the report says which", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a bend the search finds no route for on the knee, by what its first seed lacked", "ok": true, "detail": null }, @@ -151,6 +191,16 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: a bundle proven too stiff to leave its port under a wall", + "ok": true, + "detail": null + }, + { + "name": "the same hose at bend 1 routes under the wall", + "ok": true, + "detail": null + }, { "name": "hose-clamps-ports: a hose runs from the tank's flange over two clamps to the ram's port", "ok": true, @@ -290,17 +340,17 @@ "hostErrors": [], "readings": { "clamped": 4.6e-08, - "clear": 0.032, + "clear": 0.031, "kept": 0.028, - "slack": 0.021 + "slack": 0.017 }, "reports": { "feed": { "object": "Feed", "rebuilt": false, "hoses": 3, - "length": 1.646929, - "lengthChange": 0.029095, + "length": 1.642855, + "lengthChange": 0.034539, "floor": 0.0636, "clearance": 0.024995, "capped": 0.1522, @@ -308,25 +358,34 @@ 79488, 53406 ], + "seed": { + "step": 0.02, + "offset": [ + 0.0, + 0.0, + 0.0 + ], + "refined": false + }, "sag": [ 0.001879, 0.009076 ], "rolls": 9, "worstRoll": -20.0, - "worstClearance": 0.025029, + "worstClearance": 0.025166, "faces": 3378, - "volume": 0.000578788, + "volume": 0.000577468, "nonManifoldEdges": 0, "radii": { - "least": 0.122563, + "least": 0.134032, "corners": [ 0.297307, - 0.122563, - 31.156603, - 0.207446, - 3.895369, - 0.129781 + 0.134032, + 28.760693, + 0.232497, + 3.487729, + 0.140588 ] } }, @@ -334,52 +393,135 @@ "object": "Return", "rebuilt": false, "hoses": 3, - "length": 1.691847, - "lengthChange": 0.024737, + "length": 1.679265, + "lengthChange": 0.032203, "floor": 0.0636, - "clearance": 0.026695, + "clearance": 0.026679, "capped": 0.1522, "voxels": [ 82110, 92820 ], + "seed": { + "step": 0.02, + "offset": [ + 0.0, + 0.0, + 0.0 + ], + "refined": false + }, "sag": [ 0.008745, 0.00844 ], "rolls": 9, "worstRoll": -20.0, - "worstClearance": 0.027636, - "faces": 5430, - "volume": 0.000593342, + "worstClearance": 0.027159, + "faces": 5466, + "volume": 0.000589265, "nonManifoldEdges": 0, "radii": { - "least": 0.070247, + "least": 0.082543, "corners": [ - 0.070247, - 4.795067, - 0.124489, - 0.24111, - 0.07885, - 10.851944, - 0.095513 + 0.082543, + 4.587721, + 0.136709, + 0.183407, + 0.094636, + 9.943722, + 0.104249 ] } }, + "seeds": [ + { + "step": 0.1275, + "offset": [ + 0.0, + 0.0, + 0.0 + ], + "refined": false + }, + { + "step": 0.0225, + "offset": [ + 0.0, + 0.0, + 0.0 + ], + "refined": false + }, + { + "step": 0.04, + "offset": [ + 0.0, + 0.0, + 0.0 + ], + "refined": true + }, + { + "step": 0.115, + "offset": [ + 0.0, + 0.0, + 0.0 + ], + "refined": true + }, + { + "step": 0.1425, + "offset": [ + 0.31, + 0.67, + 0.13 + ], + "refined": false + }, + { + "step": 0.155, + "offset": [ + 0.0, + 0.0, + 0.0 + ], + "refined": true + }, + { + "step": 0.1, + "offset": [ + 0.0, + 0.0, + 0.0 + ], + "refined": false + } + ], "line": { "object": "Line", "rebuilt": false, "hoses": 3, - "length": 2.10125, + "length": 2.100069, "lengthChange": null, "floor": 0.0636, - "clearance": 0.010962, + "clearance": 0.010959, "capped": 0.1522, "voxels": [ 49815, 34992, 43011 ], + "seed": { + "step": 0.02, + "offset": [ + 0.0, + 0.0, + 0.0 + ], + "refined": false + }, "sag": [ 0.00942, 0.012, @@ -389,20 +531,20 @@ "worstRoll": null, "worstClearance": null, "faces": 2510, - "volume": 0.000777488, + "volume": 0.000777105, "nonManifoldEdges": 0, "radii": { - "least": 0.091455, + "least": 0.100091, "corners": [ - 0.097757, - 4.439012, - 0.091455, - 1.734649, - 2.898844, - 1.734649, - 1.665625, - 7.39548, - 10.86245 + 0.109706, + 4.289628, + 0.100091, + 1.739264, + 2.896538, + 1.739264, + 1.672436, + 7.389576, + 10.858347 ] } } From 317e40e661482fc7d2f12ef801dc842163d00b94 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:40:41 +0100 Subject: [PATCH 128/223] brokkr_reference: refuse marks that decide no camera, pin the uncapped band walk, ReferenceFitError solve() refuses, before any solve and by which they are: fewer than six different world points or pixels, pixels on one line, world points on one line, and world points in one plane unless the lens is held and the centre is not solved. A record that is not finite is refused too. One pixel for every name was a bare ValueError and one world point a record of NaN (finding degenerate-marks-not-refused). test_a_wide_band_is_walked_to_its_end kills a walk capped at 20 steps (M13): 4000 mm shipped, 1177 capped, bound 2170. The lm call count that claims M3 is a bound, 61, between 34 and 109. ReferenceError, which shadowed the builtin, is ReferenceFitError. The docstring says a band of [x, x] is narrower than one step, not an exact lens. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/__init__.py | 2 +- surfaces/blender/brokkr_reference/core.py | 57 ++++++++++++++----- surfaces/blender/tests/test_reference.py | 53 ++++++++++++++--- 3 files changed, 88 insertions(+), 24 deletions(-) diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index 5a96b7f..eb9d58f 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -67,7 +67,7 @@ class BROKKR_REFERENCE_OT_solve_camera(PolishOperator): try: cam = core.solve(core.points(self.world, 3, "world"), core.points(self.pixels, 2, "pixels"), core.numbers(self.box, 4, "box"), model=self.model, lens=self.lens or None, turned=tuple(self.turned.split()), pivot=core.numbers(self.pivot, 2, "pivot") if self.pivot.strip() else (0.0, 0.0)) - except core.ReferenceError as refusal: + except core.ReferenceFitError as refusal: raise Refused(str(refusal)) from None report = {**cam, "residuals": {k: [round(v, 2) for v in r] for k, r in cam["residuals"].items()}, "camera": None} # hundredths of a pixel: 280 points still fit a receipt if self.camera_name: diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index f9f4bf9..eb3fd63 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -40,7 +40,7 @@ MODELS = {"upright": (), "rolled": ("roll",), "free": ("roll", "centre"), "squar QUARTER = math.pi / 2 -class ReferenceError(ValueError): # noqa: A001 the package's refusal; the builtin of the same name (weakref) is not used here +class ReferenceFitError(ValueError): """solve() or a field parser cannot take what it was given; the message names which.""" @@ -194,6 +194,26 @@ def _left_out(W, P, c0, model, logf, f_fixed, near, turned, pivot): return float(np.sqrt(np.mean(np.square(miss)))) +def _decidable(names, W, P, plane_will_do): + """Refuses marks that cannot decide a camera, by which they are, before anything is solved: the place is solved + in units of the marks' extent, so marks of no extent have no solve at all (a logarithm of zero, a record of + NaN). These are exact degeneracies, to nine digits of the marks' extent; points nearly in a line or a plane are + solved, and what they leave undecided is the band's to say.""" + for what, A in (("world point", W), ("pixel", P)): + first = {} + twins = [(first[row], k) for k, row in zip(names, map(tuple, A.tolist())) if row in first or first.setdefault(row, k) is None] + if len(first) < 6: + raise ReferenceFitError(f"{len(first)} different {what}s are marked; six are needed ({twins[0][0]!r} and {twins[0][1]!r} share one)") + flat = lambda A: np.linalg.svd(A - A.mean(0), compute_uv=False) # noqa: E731 the marks' extents along their own axes, widest first + w, p = flat(W), flat(P) + if p[1] <= 1e-9 * p[0]: + raise ReferenceFitError("the pixels lie on one line: marks along a line of the image cannot say how the camera is turned about it") + if w[1] <= 1e-9 * w[0]: + raise ReferenceFitError("the world points lie on one line: the camera could stand anywhere round it") + if w[2] <= 1e-9 * w[0] and not plane_will_do: + raise ReferenceFitError("the world points lie in one plane, which does not decide the lens or the centre: mark a point off the plane, or hold `lens` and name a model other than free") + + def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.0)): """world {name: [x, y, z]}, pixels {name: [u, v]}: the camera that draws the names both hold. `box` is the view's box on the image [u0, v0, u1, v1]. `model` is one of MODELS: "upright" holds the camera level and its @@ -208,26 +228,33 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0. they were given. Returns the camera record: {"C", "R", "f", "c", "box", "lens" (mm), "lens_band" [low, high] (the lenses that - refit within BAND of the best rms, walked out from the best: an equal-error band, not a confidence interval), + refit within BAND of the best rms, walked out from the best in steps of STEP in log f, about 10%, to the first + that misses: an equal-error band, not a confidence interval, and no finer than its step, so [x, x] says the + band is narrower than one step each way, not that the lens is exact), "lens_at_bound" (None, or "short" or "long" when the solve stopped at an end of LENS_MM), "rms", "median" (pixels), "worst" [name, pixels], "left_out" (the leave-one-out rms), "model", "tried" {model: rms, left_out, lens}, "azimuth", "elevation" (degrees: where the camera stands round the points' middle), "distance", "roll", - "twist" (degrees), "residuals" {name: [du, dv]}}. Refuses with ReferenceError.""" + "twist" (degrees), "residuals" {name: [du, dv]}}. Every number in it is finite. + + Refuses with ReferenceFitError, before solving, what cannot decide a camera: fewer than six shared names, or + fewer than six different world points or different pixels among them; pixels on one line; world points on one + line; world points in one plane, unless `lens` is held and the model is upright, rolled or square.""" if model != "auto" and model not in MODELS: - raise ReferenceError(f"unknown model {model!r}: one of auto, {', '.join(MODELS)}") + raise ReferenceFitError(f"unknown model {model!r}: one of auto, {', '.join(MODELS)}") box = [float(v) for v in box] if len(box) != 4 or not all(math.isfinite(v) for v in box) or box[2] - box[0] <= 0 or box[3] - box[1] <= 0: - raise ReferenceError(f"box {box} has no {'width' if len(box) != 4 or not box[2] - box[0] > 0 else 'height'}: it is u0, v0, u1, v1 with u1 past u0 and v1 past v0") + raise ReferenceFitError(f"box {box} has no {'width' if len(box) != 4 or not box[2] - box[0] > 0 else 'height'}: it is u0, v0, u1, v1 with u1 past u0 and v1 past v0") width = box[2] - box[0] if lens is not None and not LENS_MM[0] <= lens <= LENS_MM[1]: - raise ReferenceError(f"lens {lens} mm is outside {LENS_MM[0]:g} to {LENS_MM[1]:g} mm") + raise ReferenceFitError(f"lens {lens} mm is outside {LENS_MM[0]:g} to {LENS_MM[1]:g} mm") names = [k for k in pixels if k in world] if len(names) < 6: - raise ReferenceError(f"{len(names)} points are named in both world and pixels; six are needed") + raise ReferenceFitError(f"{len(names)} points are named in both world and pixels; six are needed") for k in names: if len(world[k]) != 3 or len(pixels[k]) != 2 or not all(math.isfinite(v) for v in (*world[k], *pixels[k])): - raise ReferenceError(f"point {k!r} is not three finite world numbers and two finite pixel numbers: {list(world[k])}, {list(pixels[k])}") + raise ReferenceFitError(f"point {k!r} is not three finite world numbers and two finite pixel numbers: {list(world[k])}, {list(pixels[k])}") W, P = np.array([world[k] for k in names], float), np.array([pixels[k] for k in names], float) + _decidable(names, W, P, lens is not None and model not in ("auto", "free")) T = np.array([k in turned for k in names]) c0 = [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2] logf = (math.log(LENS_MM[0] * width / SENSOR), math.log(LENS_MM[1] * width / SENSOR)) @@ -254,6 +281,8 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0. step += 1 off = cam["C"] - X.mean(0) res = project(cam, X) - P + if not (math.isfinite(rms) and math.isfinite(left) and np.isfinite(cam["C"]).all() and np.isfinite(res).all()): + raise ReferenceFitError("the solve did not come to finite numbers: the marks do not decide a camera") worst = int(np.argmax(np.linalg.norm(res, axis=1))) edge = None if fixed is not None else "short" if best <= logf[0] + 1e-9 else "long" if best >= logf[1] - 1e-9 else None return {"C": [float(v) for v in cam["C"]], "R": [[float(v) for v in row] for row in cam["R"]], "f": float(cam["f"]), "c": [float(v) for v in cam["c"]], @@ -285,7 +314,7 @@ def camera_of(params, box=None, width=None): the frame in the image's pixels; without one it is the frame itself from (0, 0), `width` pixels across (the render's own width when that is not given either).""" if params.get("sensor_fit", "HORIZONTAL") != "HORIZONTAL": - raise ReferenceError(f"sensor fit {params['sensor_fit']!r}: camera_of reads a HORIZONTAL fit only") + raise ReferenceFitError(f"sensor fit {params['sensor_fit']!r}: camera_of reads a HORIZONTAL fit only") M = np.asarray(params["matrix_world"], float) if box is None: rx, ry = params["resolution"] @@ -306,18 +335,18 @@ def in_frame(cam, pixels, width): def numbers(text, count, what): - """'1, 2.5, 3' as `count` finite floats; ReferenceError names `what`.""" + """'1, 2.5, 3' as `count` finite floats; ReferenceFitError names `what`.""" try: values = [float(v) for v in text.split(",")] except ValueError: values = [] if len(values) != count or not all(math.isfinite(v) for v in values): - raise ReferenceError(f"{what} {text.strip()!r} is not {count} finite numbers with commas between") + raise ReferenceFitError(f"{what} {text.strip()!r} is not {count} finite numbers with commas between") return values def points(text, size, what): - """'a=1,2,3; b=4,5,6' as {name: [numbers]}, each of `size` numbers; ReferenceError names `what` and the entry. + """'a=1,2,3; b=4,5,6' as {name: [numbers]}, each of `size` numbers; ReferenceFitError names `what` and the entry. A name given twice is refused: which of the two was meant is not this parser's to choose.""" out = {} for entry in (piece.strip() for piece in text.split(";")): @@ -326,8 +355,8 @@ def points(text, size, what): name, _, values = entry.partition("=") name = name.strip() if not name: - raise ReferenceError(f"{what} entry {entry!r} has no name") + raise ReferenceFitError(f"{what} entry {entry!r} has no name") if name in out: - raise ReferenceError(f"{what} names {name!r} twice") + raise ReferenceFitError(f"{what} names {name!r} twice") out[name] = numbers(values, size, f"{what} point {name!r}:") return out diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index 9b11ba6..18d77e4 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -14,6 +14,7 @@ tolerances round a known truth that no mutant claims. The mutants, each run once M5 shift_y's sign flipped in blender() test_blender_params_draw_the_same_pixels M6 the turned group is not turned test_a_turned_torso_is_recovered_as_twist M7 square holds the yaw along y only test_square_solves_elevations_along_both_axes + M13 the walk stops after 20 steps each way test_a_wide_band_is_walked_to_its_end """ from __future__ import annotations @@ -131,8 +132,9 @@ class SolveTests(unittest.TestCase): self.assertEqual((held["lens"], held["lens_band"], held["lens_at_bound"]), (low, [low, low], None)) def test_the_band_is_walked_from_the_last_solve(self): - """M3: each step of the walk is one solve started at the one before. Counted: 16 starts, 13 left-out solves, - one per lens inside the band and one past each end; restarting from the grid costs 16 per step.""" + """M3: each step of the walk is one solve started at the one before; restarting from the grid costs 16 per + step. lm calls: 34 shipped (16 starts, 13 left-out solves, 3 lenses inside the band and one past each end), + 109 restarted, separation 3.2: bound 61.""" world, pixels = marks(self.oblique, self.points, build=0.04) calls, lm = [0], core.lm @@ -144,9 +146,16 @@ class SolveTests(unittest.TestCase): s = core.solve(world, pixels, BOX, model="upright") finally: core.lm = lm - inside = round(math.log(s["lens_band"][1] / s["lens_band"][0]) / core.STEP) - self.assertGreater(inside, 2) - self.assertEqual(calls[0], 16 + 13 + inside + 2) + self.assertGreater(s["lens_band"][1] / s["lens_band"][0], math.exp(2.5 * core.STEP)) # a band of steps to walk + self.assertLess(calls[0], 61) + + def test_a_wide_band_is_walked_to_its_end(self): + """M13: a 135 mm view of a build 8 cm off cannot tell 72 mm from the bound, 32 steps above its best lens + (159.3 mm). The band's long end is 4000 mm shipped and 1177 (the best times e^2) when the walk stops after + 20 steps, separation 3.4: bound 2170.""" + s = core.solve(*marks(camera(self.points, 35, 20, 135), self.points, build=0.08), BOX, model="upright") + self.assertGreater(s["lens_band"][1], 2170) + self.assertEqual((s["lens_band"][1], s["lens_at_bound"]), (core.LENS_MM[1], None)) # the band reaches the bound; the best lens does not def test_long_lenses_stay_finite_and_inside_the_range(self): """long-lens-bounded, M4: with no bound the 400 mm view on a build 4 cm off runs log f to OverflowError and @@ -196,10 +205,36 @@ class SolveTests(unittest.TestCase): ((self.world, self.pixels, [100, 50, 100, 800]), {}, "no width"), ((self.world, self.pixels, [100, 50, 1100, 50]), {}, "no height"), ((self.world, self.pixels, BOX), {"model": "x"}, "unknown model 'x'"), ((self.world, self.pixels, BOX), {"lens": 5000.0}, "5000")) for args, kwargs, said in cases: - with self.assertRaises(core.ReferenceError) as caught: + with self.assertRaises(core.ReferenceFitError) as caught: core.solve(*args, **kwargs) self.assertIn(said, str(caught.exception)) - self.assertTrue(issubclass(core.ReferenceError, ValueError)) + self.assertTrue(issubclass(core.ReferenceFitError, ValueError)) + + def test_marks_that_decide_no_camera_are_refused(self): + """refusals: marks with no extent, in a line or in a plane are refused by which they are before any solve + (one pixel for every name was a bare ValueError, one world point a record of NaN). A plane is enough once + the lens is held and the centre is not solved.""" + solved, lm = [], core.lm + core.lm = lambda *args, **kwargs: solved.append(1) or lm(*args, **kwargs) + self.addCleanup(setattr, core, "lm", lm) + plane = np.c_[self.points[:, :2], np.zeros(13)] + on_plane = dict(zip(NAMES, plane.tolist())), dict(zip(NAMES, core.project(self.oblique, plane).tolist())) + line = dict(zip(NAMES, np.outer(np.arange(13.0), [1.0, 2.0, 0.5]).tolist())) + cases = (((self.world, {k: [500.0, 400.0] for k in NAMES}), {}, "1 different pixels"), + (({k: [1.0, 2.0, 3.0] for k in NAMES}, self.pixels), {}, "1 different world points"), + ((self.world, {**self.pixels, **{k: self.pixels["p0"] for k in NAMES[:9]}}), {}, "5 different pixels are marked; six are needed ('p0' and 'p1'"), + ((self.world, {k: [100.0 + 10 * i, 200.0 + 5 * i] for i, k in enumerate(NAMES)}), {}, "pixels lie on one line"), + ((line, self.pixels), {}, "world points lie on one line"), + (on_plane, {}, "one plane"), (on_plane, {"model": "upright"}, "one plane"), (on_plane, {"model": "free", "lens": 50.0}, "one plane")) + for args, kwargs, said in cases: + with self.assertRaises(core.ReferenceFitError) as caught: + core.solve(*args, BOX, **kwargs) + self.assertIn(said, str(caught.exception)) + self.assertEqual(solved, []) + held = core.solve(*on_plane, BOX, model="upright", lens=50.0) + self.assertLess(held["rms"], 1e-3) + self.assertAlmostEqual(held["azimuth"], 35.0, delta=0.01) + self.assertNotIn("NaN", json.dumps(held)) @unittest.skipIf(np is None, "numpy") @@ -236,7 +271,7 @@ class CameraTests(unittest.TestCase): framed = core.camera_of(core.blender(self.cam, 1200)) # no box: the frame itself, in its own pixels self.assertEqual(framed["box"], [0.0, 0.0, 1200.0, 900.0]) self.assertLess(np.abs(core.project(framed, self.points) - core.in_frame(self.cam, core.project(self.cam, self.points), 1200)).max(), 1e-6) - with self.assertRaises(core.ReferenceError): + with self.assertRaises(core.ReferenceFitError): core.camera_of(dict(core.blender(self.cam, 1200), sensor_fit="VERTICAL")) def test_a_lifted_pixel_lies_on_its_plane_and_draws_back(self): @@ -248,7 +283,7 @@ class CameraTests(unittest.TestCase): self.assertEqual(core.points("a=1,2,3; b = 4, 5.5 ,6;", 3, "world"), {"a": [1.0, 2.0, 3.0], "b": [4.0, 5.5, 6.0]}) self.assertEqual(core.numbers("100, 50,1100,800", 4, "box"), BOX) for text, size, said in (("a=1,2", 3, "'a'"), ("a=1,2,3; a=4,5,6", 3, "twice"), ("=1,2", 2, "no name"), ("a=1,nan", 2, "'a'"), ("a=1,x", 2, "'a'")): - with self.assertRaises(core.ReferenceError) as caught: + with self.assertRaises(core.ReferenceFitError) as caught: core.points(text, size, "world") self.assertIn(said, str(caught.exception)) From 7c95538ea64714a01a48cc47cfff399fdf2edd27 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:40:42 +0100 Subject: [PATCH 129/223] docs/reference.md: the refusals of undecidable marks, and the band's step as its resolution Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/reference.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index 70edc4b..83e967f 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -70,7 +70,11 @@ and `worst` (`[name, pixels]`), `left_out` (the leave-one-out rms), `model`, `tr object's name or null) and, when a camera was stood, `blender` (what `core.blender` gave it). Refusals name their cause: fewer than six shared names, a point that is not finite numbers, a name given twice, a -box of no width or height, a lens outside 4 to 4000 mm. +box of no width or height, a lens outside 4 to 4000 mm. Marks that cannot decide a camera are refused before any +solve: fewer than six different world points or six different pixels among the shared names (the message names two +that share one), pixels all on one line, world points all on one line, and world points all in one plane unless +`lens` is held and the model is `upright`, `rolled` or `square`. These are exact cases; points nearly in a line or +a plane are solved, and the band says what they leave open. A report never holds a number that is not finite. ## How far to trust the lens @@ -85,6 +89,9 @@ and focal length trade against each other (a dolly zoom) and the picture barely from the best in steps of a tenth in log f until one misses or the bound is reached. It is an **equal-error band, not a confidence interval**: it says which lenses the marks cannot tell apart, not where the true lens lies, and on a probe one such band excluded the true lens. A band that ends at 4000 was stopped by the bound. + The walk's step is the band's resolution: each end is the last step that still fitted, so the true end lies up + to one step (about 10%) further out, and a band of `[x, x]` means the first step each way already missed, that + is, a band narrower than one 10% step each way, not a lens known exactly. - There is no prior. Where the data cannot decide, the answer is a wide band rather than a plausible-looking 50 mm. - Hold `lens` only when views must agree: two views of one subject solved alone may each sit anywhere in their bands, and a fit rendered from elsewhere than the reference view depends on the lens the band does not fix. From 8686a8cc09b8cef4a4d0726c944f44ef5c39dddf Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 17:49:43 +0100 Subject: [PATCH 130/223] brokkr_kitbash.ram: a ram and linkage solver across a hinge (direct, four_bar, bell_crank) Every pose quantity is a pure function of the record and the hinge angle; rates are closed form; clearance is a capped distance oracle met in every body's rest frame (cut kit-ram-core). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/ram.py | 497 +++++++++++++++++++++++++ 1 file changed, 497 insertions(+) create mode 100644 surfaces/blender/brokkr_kitbash/ram.py diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py new file mode 100644 index 0000000..ef20a4b --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -0,0 +1,497 @@ +"""Rams and linkages across a one-axis hinge: numpy and the standard library only, and nothing from the package, so +a rig, a runtime or a test loads this file alone. + +A Mechanism is the record of one hinge's drive: the hinge (pivot, unit axis, lo and hi in degrees, positive +right-handed about the axis), a kind, and pins, each in its own body's rest frame (the pose at angle 0, where +every body's frame is the parent's). + + direct the ram runs from a on the parent to b on the child. + four_bar a rocker pinned on the parent at `rocker` (R) carries the pin p; a coupler joins p to c on the child; + the ram runs from a on the parent to d on the rocker, and d is p (the excavator bucket linkage). + bell_crank the same loop with d elsewhere on the rocker. + +Every pose quantity is a pure function of (record, angle): pose() holds no solve state. The loop is solved in the +plane across the axis; a pin's coordinate along the axis only says where its member stands: the rocker bars at R's, +the coupler bar at c's, the ram at a's plus each of `offsets`. + + pose(m, degrees) every body's rotation, the ram's base and eye, L, dL/dtheta, per angle + length(m, degrees) pin-to-pin ram length + extension(m, ram, barrel, degrees) rod extension from closed + fit(m, ram, ...) the gates over the range: assembly, stroke, arm, load, clearance + clearance(m, ram, barrel, degrees, distance) the clearance gate's reading at any angles + search(kind, hinge, ram, seats, ...) the best of a seat grid, or the tally and the nearest miss + record(m, ram, barrel), from_record the JSON record a rig or runtime drives from + swept(fit, body, ...) points of the swept ram's surface in a body's rest frame + +Clearance takes a distance oracle, distance(body, points) -> distances, body one of BODIES[kind] and points (N, 3) +in that body's rest frame. The oracle may cap what it returns at Ram.reach(spacing): nothing farther is asked. +""" +import math +from dataclasses import dataclass, field, fields + +import numpy as np + +KINDS = ("direct", "four_bar", "bell_crank") +BODIES = {"direct": ("parent", "child"), "four_bar": ("parent", "child", "rocker", "coupler"), + "bell_crank": ("parent", "child", "rocker", "coupler")} +PINS = {"direct": ("a", "b"), "four_bar": ("a", "rocker", "p", "c", "d"), "bell_crank": ("a", "rocker", "p", "c", "d")} +GATES = ("assembly", "stroke", "toggle", "arm", "load", "clash") +BAND = 1e-9 # the loop is refused within this of a dead centre of the rocker and coupler + + +class RamError(ValueError): + """A refusal: the mechanism kind, the gate, and the angle or pin it failed at. `fit` holds the readings when + the gates got far enough to take them.""" + + def __init__(self, kind, gate, message, angle=None, pin=None, fit=None): + where = f" at {angle:g} deg" if angle is not None else f" (pin {pin})" if pin else "" + super().__init__(f"{kind} ram: {gate}{where}: {message}") + self.kind, self.gate, self.angle, self.pin, self.fit = kind, gate, angle, pin, fit + + +@dataclass +class Ram: + """A ram's proportions. Lengths default from the bore radius.""" + bore: float + rod: float = None # rod radius + barrel_r: float = None # barrel outer radius + e_a: float = None # base pin centre to the barrel's back end + e_b: float = None # rod eye centre to the rod's shoulder (what stays out of the barrel, closed) + gland: float = None # piston and gland: barrel length that is not stroke + over: float = None # spare travel at each end of the stroke + tail: float = 0.0 # trunnion mount: barrel behind the base pin (replaces e_a) + min_arm: float = None # least effective arm |dL/dtheta|, length per radian + gap: float = None # least clearance to a body + link_r: float = None # half thickness of a rocker or coupler bar + max_load: float = 3.0 # greatest coupler pin load per unit ram force + + def __post_init__(self): + b = self.bore + for name, value in (("rod", 0.5 * b), ("barrel_r", 1.25 * b), ("e_a", 1.7 * b), ("e_b", 1.7 * b), ("gland", 1.3 * b), + ("over", 0.2 * b), ("min_arm", 1.5 * b), ("gap", 0.15 * b), ("link_r", 0.7 * b)): + if getattr(self, name) is None: + setattr(self, name, value) + + @property + def back(self): + """Signed distance from the base pin to the barrel's back end along the ram (negative: behind the pin).""" + return -self.tail if self.tail > 0 else self.e_a + + def spacing(self, spacing=None): + return self.barrel_r if spacing is None else float(spacing) + + def reach(self, spacing=None): + """The greatest distance the clearance gate asks of any member: what a distance oracle may cap at.""" + return max(self.barrel_r, self.rod, self.link_r) + self.gap + self.spacing(spacing) / 2 + + +def _flat(v, n): + """v without its part along the unit axis n.""" + return v - n * (v @ n)[..., None] + + +def _rot(v, n, t): + """v (..., 3) turned about the unit axis n by t radians (Rodrigues); t broadcasts over v's leading shape.""" + t = np.asarray(t, dtype=float)[..., None] + return v * np.cos(t) + np.cross(n, v) * np.sin(t) + n * (v @ n)[..., None] * (1.0 - np.cos(t)) + + +def _angle(v0, v, n): + """Signed angle about n from v0 to v, both across n.""" + return np.arctan2(np.cross(v0, v) @ n, v @ v0) + + +@dataclass +class Mechanism: + kind: str + pivot: np.ndarray + axis: np.ndarray + lo: float + hi: float + a: np.ndarray + b: np.ndarray = None + rocker: np.ndarray = None + p: np.ndarray = None + c: np.ndarray = None + d: np.ndarray = None + offsets: tuple = (0.0,) + + def __post_init__(self): + if self.kind not in KINDS: + raise RamError(str(self.kind), "record", f"kind is one of {', '.join(KINDS)}") + for name in ("pivot", "axis", "a", "b", "rocker", "p", "c", "d"): + value = getattr(self, name) + if value is not None: + value = np.array(value, dtype=float) + if value.shape != (3,) or not np.isfinite(value).all(): + raise RamError(self.kind, "record", "three finite numbers", pin=name) + setattr(self, name, value) + if abs(np.linalg.norm(self.axis) - 1.0) > 1e-6: + raise RamError(self.kind, "record", f"the axis is a unit vector, length {np.linalg.norm(self.axis):.6f}", pin="axis") + self.lo, self.hi = float(self.lo), float(self.hi) + if not self.lo < self.hi or self.hi - self.lo > 360.0: + raise RamError(self.kind, "record", f"lo < hi and hi - lo <= 360, got {self.lo:g}..{self.hi:g}") + self.offsets = tuple(float(o) for o in self.offsets) + if not self.offsets: + raise RamError(self.kind, "record", "at least one offset") + for name in ("a", "b", "rocker", "p", "c", "d"): + needed, given = name in PINS[self.kind], getattr(self, name) is not None + if needed != given: + raise RamError(self.kind, "record", "this kind needs the pin" if needed else "this kind has no such pin", pin=name) + if self.kind == "direct": + return + n = self.axis + apart = float(np.linalg.norm(self.d - self.p)) + if self.kind == "four_bar" and apart > 0.0: + raise RamError(self.kind, "record", f"a four-bar's ram eye is the rocker's coupler pin; d is {apart:.4f} from p", pin="d") + if self.kind == "bell_crank" and apart == 0.0: + raise RamError(self.kind, "record", "a bell crank's ram eye stands off the coupler pin; d on p is a four_bar", pin="d") + self.lr = float(np.linalg.norm(_flat(self.p - self.rocker, n))) + self.lc = float(np.linalg.norm(_flat(self.p - self.c, n))) + side = float(n @ np.cross(_flat(self.c - self.rocker, n), _flat(self.p - self.rocker, n))) + if min(self.lr, self.lc) < BAND or abs(side) < BAND: + raise RamError(self.kind, "assembly", "the rest pose is a dead centre: R, p and c are in line", pin="p") + self.branch = 1.0 if side > 0 else -1.0 # which side of R -> c the pin p keeps, through the whole range + + +@dataclass +class Pose: + degrees: np.ndarray # (S,) + base: np.ndarray # (S, 3) ram base pin, parent frame, at offset 0 + eye: np.ndarray # (S, 3) ram eye + u: np.ndarray # (S, 3) unit vector base -> eye + L: np.ndarray # (S,) pin to pin + dL: np.ndarray # (S,) dL/dtheta, length per radian: the effective arm, signed + phi: np.ndarray = None # (S,) rocker angle from rest, radians, in (-pi, pi] + psi: np.ndarray = None # (S,) coupler angle from rest + dphi: np.ndarray = None # (S,) dphi/dtheta + P: np.ndarray = None # (S, 3) the rocker's coupler pin + C: np.ndarray = None # (S, 3) the child's coupler pin + load: np.ndarray = None # (S,) coupler pin load per unit ram force + mu_c: np.ndarray = None # (S,) transmission angle at c, degrees, folded to 0..90 + mu_p: np.ndarray = None # (S,) transmission angle at p + + +def pose(m, degrees): + """The mechanism at each of `degrees` (a number or an array): a pure function of the record and the angle.""" + deg = np.atleast_1d(np.asarray(degrees, dtype=float)) + t, n, O = np.radians(deg), m.axis, m.pivot + if m.kind == "direct": + eye = O + _rot(m.b - O, n, t) + base = np.broadcast_to(m.a, eye.shape) + L = np.linalg.norm(eye - base, axis=1) + u = (eye - base) / np.maximum(L, 1e-12)[:, None] + return Pose(deg, base, eye, u, L, (np.cross(n, eye - O) * u).sum(axis=1)) + R = m.rocker + C = O + _rot(m.c - O, n, t) + g = _flat(C - R, n) + dist = np.linalg.norm(g, axis=1) + lo, hi = abs(m.lr - m.lc) + BAND, m.lr + m.lc - BAND + bad = (dist <= lo) | (dist >= hi) + if bad.any(): + i = int(np.argmax(bad)) + raise RamError(m.kind, "assembly", f"|c - R| is {dist[i]:.4f}, outside ({lo:.4f}, {hi:.4f}): the rocker ({m.lr:.4f}) and coupler " + f"({m.lc:.4f}) cannot close the loop, or reach a dead centre where the branch would change", angle=float(deg[i])) + x = (m.lr * m.lr - m.lc * m.lc + dist * dist) / (2.0 * dist) + h = np.sqrt(np.maximum(m.lr * m.lr - x * x, 0.0)) + across = g / dist[:, None] + v = across * x[:, None] + m.branch * np.cross(n, across) * h[:, None] # p - R across the axis + phi = _angle(_flat(m.p - R, n), v, n) + P = R + _rot(m.p - R, n, phi) + eye = R + _rot(m.d - R, n, phi) + w = _flat(P - C, n) # the coupler, c -> p + k = w / np.linalg.norm(w, axis=1)[:, None] + psi = _angle(_flat(m.p - m.c, n), w, n) + # the coupler's two ends move equally along it + dphi = (np.cross(n, C - O) * k).sum(axis=1) / (np.cross(n, P - R) * k).sum(axis=1) + base = np.broadcast_to(m.a, eye.shape) + L = np.linalg.norm(eye - base, axis=1) + u = (eye - base) / np.maximum(L, 1e-12)[:, None] + dL = (np.cross(n, eye - R) * u).sum(axis=1) * dphi + crank, link = _flat(O - C, n), _flat(R - P, n) + moment = np.abs(np.cross(-crank, k) @ n) + load = np.abs(dL) / np.maximum(moment, 1e-12) + mu_c = np.degrees(np.arcsin(np.clip(moment / np.linalg.norm(crank, axis=1), 0.0, 1.0))) + mu_p = np.degrees(np.arcsin(np.clip(np.abs(np.cross(link, k) @ n) / np.linalg.norm(link, axis=1), 0.0, 1.0))) + return Pose(deg, base, eye, u, L, dL, phi, psi, dphi, P, C, load, mu_c, mu_p) + + +def length(m, degrees): + """Pin-to-pin ram length at each angle.""" + return pose(m, degrees).L + + +def extension(m, ram, barrel, degrees): + """Rod extension from closed at each angle: L - (back + barrel + e_b).""" + return pose(m, degrees).L - (ram.back + barrel + ram.e_b) + + +def _members(m, ram, barrel, p): + """(name, start (S, 3), end (S, 3), radius, own body) of every member in the parent frame, clevis ends left + out: e_a at the ram's base (the barrel starts there), 0.4 e_b at its eye, 1.5 link_r at a link's pins.""" + n = m.axis + for off in m.offsets: + base, eye = p.base + off * n, p.eye + off * n + front = base + p.u * (ram.back + max(barrel, 1e-6)) + yield f"barrel[{off:g}]", base + p.u * ram.back, front, ram.barrel_r, None + yield f"rod[{off:g}]", front, eye - p.u * (0.4 * ram.e_b), ram.rod, None + if m.kind == "direct": + return + R = np.broadcast_to(m.rocker, p.P.shape) + bars = [("rocker", R, p.P - n * ((p.P - R) @ n)[:, None], "rocker"), ("coupler", p.P - n * ((p.P - p.C) @ n)[:, None], p.C, "coupler")] + if m.kind == "bell_crank": + bars.append(("rocker arm", R, p.eye - n * ((p.eye - R) @ n)[:, None], "rocker")) + for name, start, end, own in bars: + along = end - start + span = np.linalg.norm(along, axis=1)[:, None] + cut = along / np.maximum(span, 1e-12) * np.minimum(1.5 * ram.link_r, span / 2.0) + yield name, start + cut, end - cut, ram.link_r, own + + +def _into(m, p, body, pts): + """Parent-frame points (S, N, 3) carried into a body's rest frame at each angle.""" + n = m.axis + if body == "parent": + return pts + if body == "child": + return m.pivot + _rot(pts - m.pivot, n, -np.radians(p.degrees)[:, None]) + if body == "rocker": + return m.rocker + _rot(pts - m.rocker, n, -p.phi[:, None]) + return m.p + _rot(pts - p.P[:, None, :], n, -p.psi[:, None]) + + +def clearance(m, ram, barrel, degrees, distance, spacing=None, at=None): + """The clearance gate's reading: (margin per angle, (angle, member, body) of the least). A member is clear + where margin >= 0: each sample of its axis, taken at most `spacing` apart (default barrel_r), is at least + radius + gap + spacing / 2 from every body, measured in that body's rest frame at that angle. A sample is at + most spacing / 2 from any point of the axis, so the member's surface keeps the gap. Every member meets every + body of the mechanism but its own.""" + p = pose(m, degrees) if at is None else at + step = ram.spacing(spacing) + margin, least, where = np.full(len(p.degrees), math.inf), math.inf, None + for name, start, end, radius, own in _members(m, ram, barrel, p): + count = max(int(math.ceil(float(np.linalg.norm(end - start, axis=1).max()) / step)) + 1, 2) + pts = start[:, None, :] + (end - start)[:, None, :] * np.linspace(0.0, 1.0, count)[None, :, None] + need = radius + ram.gap + step / 2.0 + for body in BODIES[m.kind]: + if body == own: + continue + got = np.asarray(distance(body, _into(m, p, body, pts).reshape(-1, 3)), dtype=float).reshape(len(p.degrees), count) + row = got.min(axis=1) - need + margin = np.minimum(margin, row) + i = int(np.argmin(row)) + if row[i] < least: + least, where = float(row[i]), (float(p.degrees[i]), name, body) + return margin, where + + +@dataclass +class Fit: + m: Mechanism + ram: Ram + why: list # (gate, angle or None, message) of every gate that failed; empty when it fits + degrees: np.ndarray + l_min: float + l_max: float + travel: float # L_max - L_min + barrel: float # barrel length + closed: float # pin to pin with the rod home: back + barrel + e_b + stroke: float # travel the barrel holds + spare: float # stroke - (travel + 2 over): negative when the stroke does not fit + arm_min: float # least |dL/dtheta| + arm_at: float # the angle of it + arm_sign: int # 0 when dL/dtheta changes sign (a dead centre inside the range) + swing: float = 0.0 # the rocker's travel, degrees + load_max: float = 0.0 # greatest coupler pin load per unit ram force + mu_c: float = None # least transmission angle at c, degrees: reported, never gated + mu_p: float = None # least transmission angle at p + clear_min: float = math.inf # least clearance beyond what the gate asks; inf with no oracle + clear_at: tuple = None # (angle, member, body) of it + table: list = field(default_factory=list) # (angle, L, dL/dtheta, clearance margin) per step + + @property + def ok(self): + return not self.why + + def error(self): + gate, angle, message = self.why[0] + return RamError(self.m.kind, gate, message, angle=angle, fit=self) + + def report(self): + """One line for a log or a sheet.""" + state = "OK" if self.ok else "NO (" + "; ".join(f"{g}: {msg}" for g, _, msg in self.why) + ")" + links = "" if self.m.kind == "direct" else f", rocker swing {self.swing:.1f}, pin load <= {self.load_max:.2f}, transmission >= {min(self.mu_c, self.mu_p):.1f} deg" + return (f"{state}: L {self.l_min:.3f}..{self.l_max:.3f}, barrel {self.barrel:.3f}, stroke {self.stroke:.3f} for travel {self.travel:.3f} " + f"(spare {self.spare:+.3f}), arm >= {self.arm_min:.3f}{links}, clear {self.clear_min:+.3f}") + + +def _fit(m, ram, steps=25, distance=None, spacing=None, clear=True): + """Every gate's reading; raises only where the loop does not assemble or a bell crank's eye crowds its pin.""" + if m.kind == "bell_crank" and np.linalg.norm(m.d - m.p) < 2.0 * ram.bore: + raise RamError(m.kind, "pins", f"the ram eye stands at least 2 bore ({2.0 * ram.bore:.4f}) from the coupler pin; d is {np.linalg.norm(m.d - m.p):.4f} from p", pin="d") + if (m.kind != "direct") and not (m.lo <= 0.0 <= m.hi): + pose(m, np.linspace(0.0, m.lo if m.lo > 0.0 else m.hi, steps)) # the branch is carried from rest: no dead centre on the way + p = pose(m, np.linspace(m.lo, m.hi, steps)) + l_min, l_max = float(p.L.min()), float(p.L.max()) + travel = l_max - l_min + barrel = l_min - ram.over - ram.back - ram.e_b + stroke = barrel - ram.gland + spare = stroke - (travel + 2.0 * ram.over) + i = int(np.argmin(np.abs(p.dL))) + arm_min, arm_at = float(abs(p.dL[i])), float(p.degrees[i]) + signs = set(np.sign(p.dL[np.abs(p.dL) > 1e-9]).tolist()) + arm_sign = int(signs.pop()) if len(signs) == 1 else 0 + f = Fit(m, ram, [], p.degrees, l_min, l_max, travel, barrel, ram.back + barrel + ram.e_b, stroke, spare, arm_min, arm_at, arm_sign) + if barrel <= ram.gland or spare < -1e-9: + f.why.append(("stroke", None, f"travel {travel:.3f} needs {travel + 3.0 * ram.over + ram.gland + ram.back + ram.e_b:.3f} closed, L_min is {l_min:.3f}")) + if arm_sign == 0: + flip = np.nonzero(np.sign(p.dL[1:]) != np.sign(p.dL[:-1]))[0] + f.why.append(("toggle", float(p.degrees[flip[0] + 1]) if len(flip) else arm_at, "dL/dtheta changes sign: a dead centre inside the range")) + elif arm_min < ram.min_arm: + f.why.append(("arm", arm_at, f"least effective arm {arm_min:.3f} under {ram.min_arm:.3f}")) + if m.kind != "direct": + phi = np.degrees(np.unwrap(p.phi)) + j = int(np.argmax(p.load)) + f.swing, f.load_max = float(phi.max() - phi.min()), float(p.load[j]) + f.mu_c, f.mu_p = float(p.mu_c.min()), float(p.mu_p.min()) + if f.load_max > ram.max_load: + f.why.append(("load", float(p.degrees[j]), f"coupler pin load {f.load_max:.2f} x the ram force, over {ram.max_load:.2f}")) + margin = np.full(steps, math.inf) + if distance is not None and clear: + margin, f.clear_at = clearance(m, ram, barrel, None, distance, spacing, at=p) + f.clear_min = float(margin.min()) + if f.clear_min < 0.0: + angle, member, body = f.clear_at + f.why.append(("clash", angle, f"{member} is {-f.clear_min:.3f} inside the clearance of body {body}")) + f.table = [tuple(row) for row in np.stack([p.degrees, p.L, p.dL, margin], axis=1).tolist()] + return f + + +def fit(m, ram, steps=25, distance=None, spacing=None): + """Check one mechanism from lo to hi. Gates, in order, each over all steps at once: assembly; stroke; effective + arm (one sign, and at least min_arm); coupler pin load (linkages); clearance, when a distance oracle is given. + Returns the Fit; a failed gate raises RamError, its `fit` holding the readings.""" + f = _fit(m, ram, steps, distance, spacing) + if not f.ok: + raise f.error() + return f + + +@dataclass +class Search: + best: Fit # the winner, or the nearest miss when none fits + found: bool + tried: int + fits: int # candidates that pass every gate but clearance + tally: dict # gate -> candidates it failed (a candidate can fail several) + seat: dict # the winner's or nearest miss's pins + + def report(self): + head = f"{self.fits} of {self.tried} candidates pass the gates before clearance" if self.found else f"no candidate of {self.tried} fits" + reasons = ", ".join(f"{k} {v}" for k, v in sorted(self.tally.items())) + return f"{head}{' (failed: ' + reasons + ')' if reasons else ''}; {'best' if self.found else 'nearest'}: {self.best.report() if self.best else 'none assembles'}" + + +def _polar(n, centre, toward, radii, step): + """Points about `centre` across the axis n: each radius, every `step` degrees from the direction `toward`.""" + e = _flat(np.asarray(toward, dtype=float) - centre, n) + if np.linalg.norm(e) < 1e-9: + e = _flat(np.array([0.0, 0.0, 1.0]) if abs(n[2]) < 0.9 else np.array([1.0, 0.0, 0.0]), n) + e = e / np.linalg.norm(e) + return [centre + r * _rot(e, n, math.radians(turn)) for r in radii for turn in range(0, 360, step)] + + +def candidates(kind, hinge, seats): + """The pins of every candidate of a seat grid. direct: seats['a'] x seats['b']. Linkages: seats['rocker'] x + seats['c'] x p on a polar grid about R (lengths seats['link'] = (lo, hi, n), every 15 degrees) x seats['a'], + and for a bell crank x d on a polar grid about R (seats['d'] = (lo, hi, n), every 30 degrees).""" + n = np.asarray(hinge["axis"], dtype=float) + if kind == "direct": + return [{"a": a, "b": b} for a in seats["a"] for b in seats["b"]] + out = [] + for R in seats["rocker"]: + R = np.asarray(R, dtype=float) + for c in seats["c"]: + for p in _polar(n, R, c, np.linspace(*seats["link"]), 15): + eyes = [p] if kind == "four_bar" else _polar(n, R, p, np.linspace(*seats["d"]), 30) + out.extend({"a": a, "rocker": R, "p": p, "c": c, "d": d} for a in seats["a"] for d in eyes) + return out + + +def search(kind, hinge, ram, seats, distance=None, limit=20000, steps=25, spacing=None): + """Seat a mechanism from a grid (see candidates). hinge = {pivot, axis, lo, hi, offsets (optional)}. Best + first: every gate but clearance over all candidates, then clearance in order of least arm, greatest first; + the first clear one wins. A grid past `limit` candidates is refused naming the count. A miss returns the + tally and the nearest miss (the least total shortfall: stroke, arm, load excess, clearance).""" + pins = candidates(kind, hinge, seats) + if len(pins) > limit: + raise RamError(kind, "search", f"{len(pins)} candidates, over the limit of {limit}: thin the seat grid") + tally, passed, miss = {}, [], None + + def missed(f, seat): + nonlocal miss + for gate in {g for g, _, _ in f.why}: + tally[gate] = tally.get(gate, 0) + 1 + short = (max(-f.spare, 0.0) + max(ram.min_arm - f.arm_min, 0.0) + (ram.min_arm if f.arm_sign == 0 else 0.0) + + max(f.load_max - ram.max_load, 0.0) + (max(-f.clear_min, 0.0) if f.clear_min < math.inf else 0.0)) + if miss is None or short < miss[0]: + miss = (short, f, seat) + + for seat in pins: + try: + m = Mechanism(kind, hinge["pivot"], hinge["axis"], hinge["lo"], hinge["hi"], offsets=hinge.get("offsets", (0.0,)), **seat) + f = _fit(m, ram, steps, clear=False) + except RamError as refusal: + tally[refusal.gate] = tally.get(refusal.gate, 0) + 1 + continue + if f.ok: + passed.append((f, seat)) + else: + missed(f, seat) + passed.sort(key=lambda entry: -entry[0].arm_min) + for f, seat in passed: + if distance is None: + return Search(f, True, len(pins), len(passed), tally, seat) + f = _fit(f.m, ram, steps, distance, spacing) + if f.ok: + return Search(f, True, len(pins), len(passed), tally, seat) + missed(f, seat) + return Search(miss[1] if miss else None, False, len(pins), len(passed), tally, miss[2] if miss else None) + + +def record(m, ram, barrel): + """The mechanism record: plain JSON types, everything a rig or runtime needs to drive the ram from the hinge + angle (from_record, then length or extension).""" + out = {"kind": m.kind, "hinge": {"pivot": m.pivot.tolist(), "axis": m.axis.tolist(), "lo": m.lo, "hi": m.hi}, + "pins": {name: getattr(m, name).tolist() for name in PINS[m.kind]}, "offsets": list(m.offsets), + "ram": {f.name: getattr(ram, f.name) for f in fields(Ram)}, "barrel": float(barrel), "closed": float(ram.back + barrel + ram.e_b)} + if m.kind != "direct": + out["links"] = {"rocker": m.lr, "coupler": m.lc} + return out + + +def from_record(data): + """(Mechanism, Ram, barrel) of a record.""" + ram = Ram(**data["ram"]) + hinge = data["hinge"] + m = Mechanism(data["kind"], hinge["pivot"], hinge["axis"], hinge["lo"], hinge["hi"], offsets=tuple(data["offsets"]), **data["pins"]) + return m, ram, float(data["barrel"]) + + +def swept(f, body, margin=0.0, steps=13, around=8): + """Points on the swept ram's surface in a body's rest frame, the barrel radius grown by `margin`, a trunnion's + tail included: what a recess in that body must clear (their hull or bounding box).""" + m, ram = f.m, f.ram + if body not in BODIES[m.kind]: + raise RamError(m.kind, "swept", f"no body {body!r}; this kind has {', '.join(BODIES[m.kind])}") + p = pose(m, np.linspace(m.lo, m.hi, steps)) + side = np.cross(p.u, m.axis) + side = side / np.linalg.norm(side, axis=1)[:, None] + up = np.cross(side, p.u) + turn = np.linspace(0.0, 2.0 * math.pi, around, endpoint=False) + ring = (ram.barrel_r + margin) * (np.cos(turn)[None, :, None] * side[:, None, :] + np.sin(turn)[None, :, None] * up[:, None, :]) + pts = [] + for off in m.offsets: + for centre in (p.base + off * m.axis + p.u * min(ram.back, 0.0), p.eye + off * m.axis): + pts.append(centre[:, None, :] + ring) + return _into(m, p, body, np.concatenate(pts, axis=1)).reshape(-1, 3) From 1b12ef9a08cf26f6ee9193a676bff3276659e7f4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 17:49:45 +0100 Subject: [PATCH 131/223] tests/test_ram: hand cases, loop closure, rates, the R-3 deep knee, the third body, the bell crank clear of every body test_kitbash's package file list admits ram.py, which puts it under the package's negative patterns. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/test_kitbash.py | 2 +- surfaces/blender/tests/test_ram.py | 618 +++++++++++++++++++++++++ 2 files changed, 619 insertions(+), 1 deletion(-) create mode 100644 surfaces/blender/tests/test_ram.py diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 2651e8c..6b5da5f 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1941,7 +1941,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", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json", "route.py"]) + self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json", "ram.py", "route.py"]) for pattern in self.PACKAGE: for name, text in self.sources().items(): if pattern is self.PACKAGE[2] and name == "__init__.py": diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py new file mode 100644 index 0000000..d47a760 --- /dev/null +++ b/surfaces/blender/tests/test_ram.py @@ -0,0 +1,618 @@ +"""brokkr_kitbash/ram.py under plain Python: each case is a mechanism whose answer is known by hand, by a second +method (central differences, loop closure) or from the R-3 knee probes the docs cite. Bodies are analytic distance +oracles: boxes, capsules and cylinders across x. + +Bounds follow lodur:ruling:deterministic-bound-margin: the geometric mean of the shipped reading and the least +mutant's, both written beside the constant.""" +import importlib.util +import json +import math +import sys +import unittest +from pathlib import Path + +try: + import numpy as np +except ImportError: # pragma: no cover + np = None + +SURFACE = Path(__file__).resolve().parents[1] +if np is not None: + spec = importlib.util.spec_from_file_location("brokkr_kitbash_ram", SURFACE / "brokkr_kitbash" / "ram.py") + R = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = R + spec.loader.exec_module(R) + +X, O = (1.0, 0.0, 0.0), (0.0, 0.0, 0.0) + + +def turned(point, degrees, pivot=O, axis=X): + """A point turned about an axis: Rodrigues by matrix, a second route to ram._rot.""" + x, y, z = axis + c, s = math.cos(math.radians(degrees)), math.sin(math.radians(degrees)) + k = np.array([[0, -z, y], [z, 0, -x], [-y, x, 0]], dtype=float) + m = np.eye(3) * c + s * k + (1 - c) * np.outer(axis, axis) + return np.asarray(pivot, float) + m @ (np.asarray(point, float) - np.asarray(pivot, float)) + + +class Bodies: + """A distance oracle over analytic shapes per body: ("capsule", p, q, r), ("box", lo, hi), and + ("cyl", centre, r, half): a cylinder across x. Inside a shape the distance is 0. `cap` caps what it returns.""" + + def __init__(self, cap=None, **shapes): + self.shapes, self.cap, self.asked = shapes, cap, 0 + + @staticmethod + def one(shape, pts): + if shape[0] == "capsule": + p, q = np.asarray(shape[1], float), np.asarray(shape[2], float) + along = q - p + t = np.clip(((pts - p) @ along) / max(along @ along, 1e-18), 0.0, 1.0) + return np.maximum(np.linalg.norm(pts - p - t[:, None] * along, axis=1) - shape[3], 0.0) + if shape[0] == "box": + out = np.maximum(np.maximum(np.asarray(shape[1], float) - pts, pts - np.asarray(shape[2], float)), 0.0) + return np.linalg.norm(out, axis=1) + centre = np.asarray(shape[1], float) + rel = pts - centre + return np.hypot(np.maximum(np.hypot(rel[:, 1], rel[:, 2]) - shape[2], 0.0), np.maximum(np.abs(rel[:, 0]) - shape[3], 0.0)) + + def __call__(self, body, pts): + self.asked += len(pts) + out = np.full(len(pts), math.inf) + for shape in self.shapes.get(body, ()): + out = np.minimum(out, self.one(shape, pts)) + return out if self.cap is None else np.minimum(out, self.cap) + + +def yz(p, x=0.0): + return (x, float(p[0]), float(p[1])) + + +def grid(lo, hi, counts): + lo, hi = np.asarray(lo, float), np.asarray(hi, float) + axes = [np.linspace(lo[k], hi[k], n) if n > 1 else np.array([(lo[k] + hi[k]) / 2]) for k, n in enumerate(counts)] + return [np.array((x, y, z)) for x in axes[0] for y in axes[1] for z in axes[2]] + + +# The R-3 knee (pivot at the origin, hinge x, shin hanging -z, flexing negative), bore 0.042: the bodies of the +# clevis knee as the joint library draws them, without its ram. +BORE = 0.042 +R3_THIGH = [("box", (-0.13, -0.14, 0.3), (0.13, 0.14, 1.15)), ("box", (-0.095, -0.12, 0.0), (0.095, 0.12, 0.4)), ("cyl", O, 0.225, 0.095)] +R3_SHIN = ([("cyl", O, 0.25, 0.18), ("cyl", O, 0.19, 0.205), ("box", (-0.11, -0.11, -0.95), (0.11, 0.11, -0.49)), + ("box", (-0.21, 0.12, -0.91), (0.21, 0.18, -0.33)), ("box", (-0.2325, -0.1, -0.87), (-0.1875, 0.1, -0.37)), + ("box", (0.1875, -0.1, -0.87), (0.2325, 0.1, -0.37))] + # the cheeks taper from the hub's 0.25 to 0.12 at the foot: five steps outside the taper + + [("box", (-0.18, -(0.25 - 0.026 * k), -0.19 * (k + 1)), (0.18, 0.25 - 0.026 * k, -0.19 * k)) for k in range(5)]) +X_COUPLER, X_ROCKER = 0.33, 0.43 # where the twin link plates stand: outside the shin's side armour (0.2325) + +# P2's deep knee: a four-bar behind the knee (y < 0), where the shin folds to. +DEEP = {"a": (-0.45, 1.15), "rocker": (-0.2320142211320173, 0.4604939911625098), "p": (-0.43650046730511183, -0.017951928782268284), + "c": (0.06881023105761902, -0.3143743967236484), "d": (-0.43650046730511183, -0.017951928782268284)} +# P2's bell crank: in front of the knee (y > 0), which the shin leaves as it folds. +CRANK = {"a": (0.45, 1.15), "rocker": (0.3171126791600819, 0.3216537818398838), "p": (0.7282866960904424, 0.43261578669776135), + "c": (0.34929485118682846, 0.14862538079826304), "d": (0.48651463351122515, 0.49166254003196397)} + + +def r3(kind, pins, side=1.0, lo=-125.0, hi=0.0): + """An R-3 linkage with its links' plates on one side of the knee: the ram on the centre plane.""" + at = {"a": 0.0, "p": 0.0, "d": 0.0, "rocker": side * X_ROCKER, "c": side * X_COUPLER} + return R.Mechanism(kind, O, X, lo, hi, **{name: yz(pins[name], at[name]) for name in pins}) + + +def r3_bodies(m, ram, cap=None): + """The R-3 thigh and shin, and the mechanism's own links as bodies: twin bars of link_r, and the rocker's axle + through the knee's width. The pins at p and d belong to the clevises that turn on them, not to a body.""" + def twin(p, q, x): + return [("capsule", (s * x, p[1], p[2]), (s * x, q[1], q[2]), ram.link_r) for s in (-1.0, 1.0)] + Rk = m.rocker + rocker = twin(Rk, m.p, X_ROCKER) + [("capsule", (-X_ROCKER, Rk[1], Rk[2]), (X_ROCKER, Rk[1], Rk[2]), 0.028)] + if m.kind == "bell_crank": + rocker += twin(Rk, m.d, X_ROCKER) + return Bodies(cap, parent=R3_THIGH, child=R3_SHIN, rocker=rocker, coupler=twin(m.p, m.c, X_COUPLER)) + + +@unittest.skipIf(np is None, "numpy is not installed") +class HandCases(unittest.TestCase): + """The six hand cases of the solver this one replaces, on a direct ram.""" + A, B = (0, -0.3, 1.0), (0, -0.3, -1.0) + + def direct(self, lo, hi, a=None, b=None): + return R.Mechanism("direct", O, X, lo, hi, a=self.A if a is None else a, b=self.B if b is None else b) + + def test_lengths_by_hand(self): + m = self.direct(-60, 0) + rest = R.pose(m, 0.0) + self.assertAlmostEqual(float(rest.L[0]), 2.0, places=12) + # at rest the ram runs along z at y = -0.3: its arm about x is 0.3 + self.assertAlmostEqual(abs(float(rest.dL[0])), 0.3, places=12) + f = R.fit(m, R.Ram(0.05)) + eye = turned(self.B, -60) + self.assertAlmostEqual(f.l_min, float(np.linalg.norm(eye - np.array(self.A))), places=12) + self.assertAlmostEqual(f.barrel + f.ram.e_a + f.ram.e_b + f.ram.over, f.l_min, places=12) + self.assertAlmostEqual(float(R.extension(m, f.ram, f.barrel, 0.0)[0]), f.travel + f.ram.over, places=12) + self.assertAlmostEqual(float(R.extension(m, f.ram, f.barrel, -60.0)[0]), f.ram.over, places=12) + + def test_stroke_refused_and_a_trunnion_holds_more(self): + m = self.direct(-120, 0, (0, -0.25, 0.3), (0, -0.25, -0.3)) + with self.assertRaises(R.RamError) as caught: + R.fit(m, R.Ram(0.05)) + self.assertEqual((caught.exception.kind, caught.exception.gate), ("direct", "stroke")) + self.assertIn("direct ram: stroke", str(caught.exception)) + trunnion = R._fit(m, R.Ram(0.05, tail=0.25)) + self.assertGreater(trunnion.barrel, caught.exception.fit.barrel + 0.3) + + def test_spare_counts_the_overtravel_at_both_ends(self): + # barrel = L_min - over - e_a - e_b and spare = barrel - gland - travel - 2 over, by hand + m, ram = self.direct(-60, 0), R.Ram(0.05) + f = R.fit(m, ram) + self.assertAlmostEqual(f.spare, f.l_min - 3 * ram.over - ram.e_a - ram.e_b - ram.gland - f.travel, places=12) + # a ram whose stroke fits only without the overtravel is refused + tight = R.Ram(0.05, over=(f.l_min - ram.e_a - ram.e_b - ram.gland - f.travel) / 3 + 1e-6) + with self.assertRaises(R.RamError) as caught: + R.fit(m, tight) + self.assertEqual(caught.exception.gate, "stroke") + + def test_toggle_refused(self): + # a ram whose line crosses the hinge axis inside the range has a dead centre; its arm is not small at + # either end, so only the sign tells + m = self.direct(-40, 40, (0, 0.0, 1.0), (0, 0.2, -1.0)) + with self.assertRaises(R.RamError) as caught: + R.fit(m, R.Ram(0.04, min_arm=0.0)) + refusal = caught.exception + self.assertEqual(refusal.gate, "toggle") + self.assertEqual(refusal.fit.arm_sign, 0) + self.assertTrue(-40 < refusal.angle < 40, refusal.angle) + self.assertIn("toggle at", str(refusal)) + + def test_clash_and_which(self): + m, ram = self.direct(-60, 0), R.Ram(0.05) + f = R.fit(m, ram, distance=Bodies(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.2)]), spacing=0.02) + self.assertGreater(f.clear_min, 0.0) + with self.assertRaises(R.RamError) as caught: + R.fit(m, ram, distance=Bodies(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.3)]), spacing=0.02) + self.assertEqual(caught.exception.gate, "clash") + self.assertIn("body parent", str(caught.exception)) + self.assertEqual(caught.exception.fit.clear_at[2], "parent") + # an obstacle that turns with the child is the same obstacle, turned, on the parent + p, q = np.array((-0.2, -0.6, -0.9)), np.array((0.2, -0.6, -0.5)) + wide = self.direct(-50, 35) + barrel = R._fit(wide, ram).barrel + for angle in (-50.0, 0.0, 35.0): + on_child, where = R.clearance(wide, ram, barrel, angle, Bodies(child=[("capsule", p, q, 0.1)])) + on_parent, _ = R.clearance(wide, ram, barrel, angle, Bodies(parent=[("capsule", turned(p, angle), turned(q, angle), 0.1)])) + self.assertAlmostEqual(float(on_child[0]), float(on_parent[0]), places=9) + self.assertEqual(where[2], "child") + box = Bodies(parent=[("box", (-0.2, -0.36, -0.2), (0.2, -0.2, 0.2))]) + self.assertLess(R._fit(self.direct(-10, 0), ram, distance=box).clear_min, 0.0) + + def test_search_tally_and_nearest_miss(self): + ram, hinge = R.Ram(0.05), {"pivot": O, "axis": X, "lo": -70, "hi": 0} + seats = {"a": grid((0, -0.5, 0.4), (0, -0.2, 1.2), (1, 3, 5)), "b": grid((0, -0.5, -1.2), (0, -0.2, -0.4), (1, 3, 5))} + pin = Bodies(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.18)]) + s = R.search("direct", hinge, ram, seats, distance=pin) + self.assertTrue(s.found and s.best.ok and s.fits < s.tried == 225 and s.tally, s.report()) + for a in seats["a"]: # no fitting pair has a larger least arm + for b in seats["b"]: + f = R._fit(R.Mechanism("direct", O, X, -70, 0, a=a, b=b), ram, distance=pin) + self.assertTrue(not f.ok or f.arm_min <= s.best.arm_min + 1e-9) + none = R.search("direct", {**hinge, "lo": -100}, ram, {"a": [(0, -0.1, 0.2)], "b": [(0, -0.1, -0.2)]}) + self.assertFalse(none.found) + self.assertIn("stroke", none.tally) + self.assertIn("no candidate of 1 fits", none.report()) + self.assertFalse(none.best.ok) + self.assertEqual(tuple(none.seat["a"]), (0, -0.1, 0.2)) + + def test_swept_holds_the_ram(self): + f = R.fit(self.direct(-60, 0), R.Ram(0.05)) + for body in ("parent", "child"): + pts = R.swept(f, body, margin=0.02) + lo, hi = pts.min(axis=0), pts.max(axis=0) + p = R.pose(f.m, np.linspace(-60, 0, 31)) + line = p.base[:, None, :] + (p.eye - p.base)[:, None, :] * np.linspace(0, 1, 9)[None, :, None] + inside = R._into(f.m, p, body, line).reshape(-1, 3) + self.assertTrue((inside >= lo - 1e-9).all() and (inside <= hi + 1e-9).all(), body) + # seen from the child the eye stands still + self.assertLess(float(np.abs(R._into(f.m, p, "child", p.eye[:, None, :]) - np.array(self.B)).max()), 1e-12) + with self.assertRaises(R.RamError): + R.swept(f, "rocker") + + +@unittest.skipIf(np is None, "numpy is not installed") +class Loop(unittest.TestCase): + def test_loop_closes(self): + for kind, pins in (("four_bar", DEEP), ("bell_crank", CRANK)): + m = r3(kind, pins) + p = R.pose(m, np.linspace(-125, 0, 49)) + n = np.array(X) + # the coupler keeps its length, the rocker its own + self.assertLess(float(np.abs(np.linalg.norm(R._flat(p.P - p.C, n), axis=1) - m.lc).max()), 1e-9, kind) + self.assertLess(float(np.abs(np.linalg.norm(R._flat(p.P - m.rocker, n), axis=1) - m.lr).max()), 1e-9, kind) + # the coupler body, carried by its angle from the rocker's pin, lands its c on the child's c + for i, angle in enumerate(p.degrees): + c_on_coupler = p.P[i] + R._flat(turned(m.c - m.p, math.degrees(p.psi[i]), O), n) + self.assertLess(float(np.linalg.norm(R._flat(c_on_coupler - turned(m.c, angle), n))), 1e-9, (kind, angle)) + # and the rest pose is the record's + self.assertLess(float(np.abs(p.P[-1] - m.p).max()), 1e-12) + self.assertLess(float(np.abs(p.eye[-1] - m.d).max()), 1e-12) + + def test_the_branch_is_the_rest_poses_at_every_angle(self): + # the pin p keeps its side of R -> c from rest: an angle alone gives the pose, in any order, and a mirror + # solution (the other circle crossing) is never taken, however close it comes + m = r3("four_bar", DEEP) + n = np.array(X) + angles = np.linspace(-125, 0, 49) + shuffled = np.random.default_rng(5).permutation(angles) + whole = R.pose(m, shuffled) + for i in (0, 17, 48): + alone = R.pose(m, float(shuffled[i])) + self.assertEqual(alone.P[0].tolist(), whole.P[i].tolist()) + side = np.cross(R._flat(whole.C - m.rocker, n), R._flat(whole.P - m.rocker, n)) @ n + self.assertTrue((np.sign(side) == m.branch).all()) + # a loop that all but reaches its dead centre (the two crossings 1 mm apart there) and leaves again: asked + # in any order, p keeps its side + near = near_dead_centre() + p = R.pose(near, np.random.default_rng(6).permutation(np.linspace(-60, 60, 241))) + side = np.cross(R._flat(p.C - near.rocker, n), R._flat(p.P - near.rocker, n)) @ n + self.assertTrue((np.sign(side) == near.branch).all()) + self.assertLess(float(np.abs(side).min()), 1e-3) + + def test_assembly_refused_naming_the_angle(self): + # the same loop with the child's pin 1 mm farther out: past 19 degrees the rocker and coupler cannot reach + with self.assertRaises(R.RamError) as caught: + R.pose(near_dead_centre(reach=-1e-3), np.linspace(-60, 60, 241)) + refusal = caught.exception + self.assertEqual((refusal.kind, refusal.gate), ("four_bar", "assembly")) + self.assertTrue(10.0 < refusal.angle < 20.0, refusal.angle) + self.assertIn(f"assembly at {refusal.angle:g} deg", str(refusal)) + # a range that does not hold the rest pose is reached from rest: a dead centre on the way is refused, + # though every angle of the range itself assembles + far = near_dead_centre(reach=-1e-3, lo=30, hi=60) + self.assertEqual(len(R.pose(far, [30.0, 60.0]).L), 2) + with self.assertRaises(R.RamError) as caught: + R.fit(far, R.Ram(0.03)) + self.assertEqual(caught.exception.gate, "assembly") + self.assertTrue(0.0 < caught.exception.angle < 30.0) + + +def near_dead_centre(reach=1e-6, lo=-60.0, hi=60.0): + """A four-bar whose rocker (0.6) and coupler (0.5 + reach) lie all but in line at +20 degrees, where the child's + pin is farthest from R (1.1): with a negative reach they cannot span it.""" + Rk, lr, lc = np.array((0.0, -0.6, 0.0)), 0.6, 0.5 + reach + c = np.array((0.0, 0.5 * math.cos(math.radians(-20)), 0.5 * math.sin(math.radians(-20)))) + span = np.linalg.norm(c - Rk) + x = (lr * lr - lc * lc + span * span) / (2 * span) + across = (c - Rk) / span + p = Rk + across * x + np.cross(np.array(X), across) * math.sqrt(lr * lr - x * x) + return R.Mechanism("four_bar", O, X, lo, hi, a=(0, -0.9, 1.0), rocker=Rk, p=p, c=c, d=p) + + +@unittest.skipIf(np is None, "numpy is not installed") +class Rates(unittest.TestCase): + H = 1e-4 # degrees + + def central(self, m, angles, what): + up, down = R.pose(m, angles + self.H), R.pose(m, angles - self.H) + if what == "phi": + return (up.phi - down.phi) / math.radians(2 * self.H) + return (up.L - down.L) / math.radians(2 * self.H) + + def test_rates_equal_central_differences(self): + angles = np.linspace(-124.9, -0.1, 49) + worst = 0.0 + for kind, pins in (("four_bar", DEEP), ("bell_crank", CRANK)): + m = r3(kind, pins) + p = R.pose(m, angles) + worst = max(worst, float(np.abs(p.dphi - self.central(m, angles, "phi")).max()), float(np.abs(p.dL - self.central(m, angles, "L")).max())) + self.assertLess(worst, RATE_BOUND) + + def test_direct_rate_is_the_lever_arm(self): + m = R.Mechanism("direct", O, X, -60, 20, a=(0.1, -0.3, 1.0), b=(-0.05, -0.35, -0.8)) + angles = np.linspace(-59.9, 19.9, 33) + p = R.pose(m, angles) + arm = np.array([np.array(X) @ np.cross(turned(m.b, t), (turned(m.b, t) - m.a) / np.linalg.norm(turned(m.b, t) - m.a)) for t in angles]) + self.assertLess(float(np.abs(p.dL - arm).max()), 1e-9) + self.assertLess(float(np.abs(p.dL - self.central(m, angles, "L")).max()), RATE_BOUND) + + def test_load_is_the_coupler_force(self): + # virtual work: the ram's force F over dL is the coupler's force over the child pin's travel along the coupler + m = r3("bell_crank", CRANK) + angles = np.linspace(-124.9, -0.1, 25) + p = R.pose(m, angles) + up, down = R.pose(m, angles + self.H), R.pose(m, angles - self.H) + k = R._flat(p.P - p.C, np.array(X)) + k = k / np.linalg.norm(k, axis=1)[:, None] + along = ((up.C - down.C) * k).sum(axis=1) / math.radians(2 * self.H) + self.assertLess(float(np.abs(p.load - np.abs(self.central(m, angles, "L") / along)).max()), 1e-5) + + +# The greatest gap between a closed-form rate and its central difference (h 1e-4 deg), per radian. +# Shipped 2.44e-10; M2 (the direct arm formula on a linkage, dphi/dtheta dropped) 0.741; separation 3.0e9. +RATE_BOUND = 1.34e-5 + + +@unittest.skipIf(np is None, "numpy is not installed") +class DeepKnee(unittest.TestCase): + """The R-3 knee over 0..-125 (probes P1 to P3).""" + + def test_four_bar_fits_and_reproduces_the_probe(self): + f = R.fit(r3("four_bar", DEEP), R.Ram(BORE), steps=49) + self.assertAlmostEqual(f.swing, 70.537, places=2) + self.assertAlmostEqual(f.l_min, 0.7220, places=3) + self.assertAlmostEqual(f.l_max, 1.1680, places=3) + self.assertAlmostEqual(f.spare, 0.0533, places=3) + self.assertAlmostEqual(f.mu_c, 16.50, places=1) + greatest = max(abs(row[2]) for row in f.table) + # the least and greatest knee arm and the greatest pin load, each under a bound the direct-arm mutant passes + self.assertAlmostEqual(f.arm_min, 0.0962, places=3) + self.assertLess(f.arm_min, ARM_LEAST) + self.assertLess(greatest, ARM_GREATEST) + self.assertLess(f.load_max, LOAD) + + def test_load_gate(self): + m = r3("four_bar", DEEP) + with self.assertRaises(R.RamError) as caught: + R.fit(m, R.Ram(BORE, max_load=LOAD_GATE), steps=49) + refusal = caught.exception + self.assertEqual((refusal.kind, refusal.gate), ("four_bar", "load")) + self.assertIn("load at", str(refusal)) + self.assertTrue(R.fit(m, R.Ram(BORE), steps=49).ok) + + def test_the_same_seats_as_a_direct_ram_are_refused(self): + # the ram's own seats with no linkage, a on the thigh and the eye on the shin's pin: refused + direct = R.Mechanism("direct", O, X, -125, 0, a=yz(DEEP["a"]), b=yz(DEEP["c"])) + with self.assertRaises(R.RamError) as caught: + R.fit(direct, R.Ram(BORE), steps=49) + self.assertEqual(caught.exception.gate, "arm") + # and no direct seat of a wide grid behind the knee fits 0..-125 (P1), while the joint library's fits 0..-62 + ram = R.Ram(BORE) + bodies = Bodies(parent=R3_THIGH, child=R3_SHIN) + wide = {"a": grid((0, -0.40, 0.35), (0, -0.16, 1.3), (1, 5, 10)), "b": grid((0, -0.40, -0.85), (0, -0.14, -0.25), (1, 5, 8))} + self.assertFalse(R.search("direct", {"pivot": O, "axis": X, "lo": -125, "hi": 0}, ram, wide, distance=bodies).found) + seats = {"a": grid((0, -0.36, 0.45), (0, -0.24, 1.05), (1, 3, 6)), "b": grid((0, -0.34, -0.85), (0, -0.2, -0.35), (1, 3, 6))} + found = R.search("direct", {"pivot": O, "axis": X, "lo": -62, "hi": 0}, ram, seats, distance=bodies) + self.assertTrue(found.found and found.best.clear_min >= 0.0, found.report()) + + def test_third_body(self): + # the four-bar's ram spans the thigh and the rocker; at -125 the shin has folded into it (P3's mesh check) + m, ram = r3("four_bar", DEEP), R.Ram(BORE) + with self.assertRaises(R.RamError) as caught: + R.fit(m, ram, steps=49, distance=r3_bodies(m, ram)) + refusal = caught.exception + self.assertEqual((refusal.kind, refusal.gate), ("four_bar", "clash")) + self.assertEqual(refusal.fit.clear_at[2], "child") + self.assertIn("barrel", refusal.fit.clear_at[1]) + self.assertIn("body child", str(refusal)) + self.assertLess(refusal.angle, -100.0) + # against the thigh and the rocker alone, the two bodies the ram spans, the same ram is clear + two = r3_bodies(m, ram) + del two.shapes["child"], two.shapes["coupler"] + margin, _ = R.clearance(m, ram, refusal.fit.barrel, np.linspace(-125, 0, 49), two) + self.assertGreaterEqual(float(margin.min()), 0.0) + + def test_a_link_body_in_the_rams_way(self): + # a gusset on the bell crank's rocker, between its plates where the ram runs: refused naming the rocker + m, ram = r3("bell_crank", CRANK), R.Ram(BORE) + bodies = r3_bodies(m, ram) + rest = R.pose(m, 0.0) + web = rest.eye[0] - 0.06 * rest.u[0] # on the rod's line at rest, clear of the eye's clevis + bodies.shapes["rocker"].append(("capsule", web - (0.1, 0, 0), web + (0.1, 0, 0), 0.02)) + with self.assertRaises(R.RamError) as caught: + R.fit(m, ram, steps=49, distance=bodies) + self.assertEqual(caught.exception.gate, "clash") + self.assertEqual(caught.exception.fit.clear_at[2], "rocker") + self.assertIn(caught.exception.fit.clear_at[1], ("rod[0]", "barrel[0]")) + self.assertIn("body rocker", str(caught.exception)) + + def test_bell_crank_seats_and_clears_every_body(self): + # the bell crank stands in front of the knee: over 0..-125 its ram, rocker and coupler clear the thigh, the + # shin, and each other's bodies, with the links' plates on either side + ram = R.Ram(BORE) + for side in (1.0, -1.0): + m = r3("bell_crank", CRANK, side) + bodies = r3_bodies(m, ram) + f = R.fit(m, ram, steps=49, distance=bodies) + self.assertGreaterEqual(f.clear_min, 0.0) + self.assertAlmostEqual(f.swing, 105.732, places=2) + self.assertAlmostEqual(f.l_min, 0.6593, places=3) + self.assertAlmostEqual(f.l_max, 1.0376, places=3) + # every member met every body but its own, the shin among them, at -125 as at every step + fine = np.linspace(-125, 0, 251) + seen = {} + for name, start, end, radius, own in R._members(m, ram, f.barrel, R.pose(m, fine)): + for body in R.BODIES["bell_crank"]: + if body == own: + continue + pts = start[:, None, :] + (end - start)[:, None, :] * np.linspace(0, 1, 40)[None, :, None] + got = bodies(body, R._into(m, R.pose(m, fine), body, pts).reshape(-1, 3)).reshape(len(fine), 40) + seen[(name, body)] = float(got.min() - radius - ram.gap) + at_deep = float(got[0].min() - radius - ram.gap) + self.assertGreaterEqual(at_deep, 0.0, (name, body, "at -125")) + self.assertEqual(len(seen), 2 * 4 + 3 * 3) # barrel and rod meet four bodies; three bars meet three + self.assertGreaterEqual(min(seen.values()), 0.0, min(seen, key=seen.get)) + self.assertEqual(sum(1 for _, body in seen if body == "child"), 5) + + +# The R-3 four-bar's readings over 0..-125 at 49 steps, each bound the geometric mean of the shipped reading and +# M2's (the direct arm formula on a linkage). +ARM_LEAST = 0.205 # least knee arm: shipped 0.0962, M2 0.4367, separation 4.5 +ARM_GREATEST = 0.485 # greatest knee arm: shipped 0.2648, M2 0.8888, separation 3.4 +LOAD = 3.95 # greatest coupler pin load per unit ram force: shipped 1.609, M2 9.722, separation 6.0 +LOAD_GATE = 1.34 # a max_load the shipped four-bar's 1.609 exceeds by 1.2: with the gate off (M8) it fits + + +@unittest.skipIf(np is None, "numpy is not installed") +class OracleRule(unittest.TestCase): + def setUp(self): + self.m = R.Mechanism("direct", O, X, -30, 0, a=(0, -0.3, 1.0), b=(0, -0.3, -1.0)) + self.ram = R.Ram(0.05) + self.barrel = R._fit(self.m, self.ram).barrel + + def ball(self, at, r, cap=None): + return Bodies(cap, parent=[("capsule", at, at, r)]) + + def test_need_is_radius_gap_and_half_the_spacing(self): + # a ball beside a sample of the barrel at rest, its surface at the need less or more a micron + ram, spacing = self.ram, 0.05 + p = R.pose(self.m, 0.0) + members = {name: (start, end, radius) for name, start, end, radius, _ in R._members(self.m, ram, self.barrel, p)} + start, end, radius = members["barrel[0]"] + count = int(math.ceil(float(np.linalg.norm(end - start)) / spacing)) + 1 + sample = (start + (end - start) * (3 / (count - 1)))[0] + need = radius + ram.gap + spacing / 2 + for slip, clear in ((-1e-6, False), (1e-6, True)): + centre = sample + np.array((0.0, -(need + slip + 0.2), 0.0)) + margin, where = R.clearance(self.m, ram, self.barrel, 0.0, self.ball(centre, 0.2), spacing) + self.assertEqual(bool(margin[0] >= 0.0), clear, (slip, margin)) + self.assertAlmostEqual(float(margin[0]), slip, places=9) + self.assertEqual(where, (0.0, "barrel[0]", "parent")) + self.assertAlmostEqual(ram.reach(spacing), need, places=15) + + def test_clevis_ends_are_exempt(self): + # a ball on the base pin and one on the eye touch no sample: the barrel starts e_a from the base, the rod + # stops 0.4 e_b short of the eye + ram = self.ram + for at, r in ((self.m.a, ram.e_a - ram.barrel_r - ram.gap - ram.barrel_r / 2 - 1e-6), (self.m.b, 0.4 * ram.e_b - ram.rod - ram.gap - ram.barrel_r / 2 - 1e-6)): + margin, _ = R.clearance(self.m, ram, self.barrel, 0.0, self.ball(np.array(at, float), r)) + self.assertGreaterEqual(float(margin[0]), 0.0) + margin, _ = R.clearance(self.m, ram, self.barrel, 0.0, self.ball(np.array(at, float), r + 2e-6)) + self.assertLess(float(margin[0]), 0.0) + + def test_a_capped_oracle_gives_the_same_verdicts(self): + ram = R.Ram(BORE) + asked = [] + for kind, pins in (("four_bar", DEEP), ("bell_crank", CRANK)): + m = r3(kind, pins) + barrel = R._fit(m, ram, steps=49).barrel + angles = np.linspace(-125, 0, 49) + free, _ = R.clearance(m, ram, barrel, angles, r3_bodies(m, ram)) + capped, _ = R.clearance(m, ram, barrel, angles, r3_bodies(m, ram, cap=ram.reach())) + self.assertEqual((free >= 0.0).tolist(), (capped >= 0.0).tolist(), kind) + self.assertTrue(np.allclose(np.minimum(free, 0.0), np.minimum(capped, 0.0), atol=1e-12)) + asked.append(bool((free < 0.0).any())) + self.assertEqual(asked, [True, False]) # one of each verdict was compared + + +@unittest.skipIf(np is None, "numpy is not installed") +class SearchBestFirst(unittest.TestCase): + HINGE = {"pivot": O, "axis": X, "lo": -60, "hi": 0} + + def test_the_best_arm_that_clashes_is_passed_over(self): + ram = R.Ram(0.05) + seats = {"a": [(0, -0.2, 1.0), (0, -0.3, 1.0), (0, -0.4, 1.0)], "b": [(0, -0.3, -1.0)]} + free = R.search("direct", self.HINGE, ram, seats) + arms = sorted((R._fit(R.Mechanism("direct", O, X, -60, 0, a=a, b=seats["b"][0]), ram).arm_min, a) for a in seats["a"]) + self.assertEqual(tuple(free.seat["a"]), arms[-1][1]) + # a ball in the way of the best seat's ram only + best = R.Mechanism("direct", O, X, -60, 0, a=arms[-1][1], b=seats["b"][0]) + mid = R.pose(best, 0.0) + away = math.copysign(0.14, arms[-1][1][1] - arms[-2][1][1]) + centre = mid.base[0] + 0.05 * (mid.eye[0] - mid.base[0]) + np.array((0.0, away, 0.0)) + block = Bodies(parent=[("capsule", centre, centre, 0.07)]) + found = R.search("direct", self.HINGE, ram, seats, distance=block) + clear = [a for _, a in arms if R._fit(R.Mechanism("direct", O, X, -60, 0, a=a, b=seats["b"][0]), ram, distance=block).ok] + self.assertTrue(clear and arms[-1][1] not in clear, clear) + self.assertTrue(found.found) + self.assertEqual(tuple(found.seat["a"]), clear[-1]) # the best arm of those that are clear + self.assertGreaterEqual(found.best.clear_min, 0.0) + self.assertEqual(found.tally, {"clash": 3 - len(clear)}) + self.assertEqual(found.fits, 3) + + def test_the_limit_is_refused_naming_the_count(self): + seats = {"a": grid((0, -0.5, 0.4), (0, -0.2, 1.2), (1, 3, 5)), "b": grid((0, -0.5, -1.2), (0, -0.2, -0.4), (1, 3, 5))} + with self.assertRaises(R.RamError) as caught: + R.search("direct", self.HINGE, R.Ram(0.05), seats, limit=224) + self.assertIn("225 candidates", str(caught.exception)) + + def test_a_linkage_grid(self): + # a small grid about the probe's four-bar holds it: the search seats a linkage over 0..-125 + ram = R.Ram(BORE) + hinge = {"pivot": O, "axis": X, "lo": -125, "hi": 0} + seats = {"rocker": [yz(DEEP["rocker"])], "c": [yz(DEEP["c"])], "a": [yz(DEEP["a"]), yz((-0.3, 1.0))], "link": (0.4, 0.6, 5)} + self.assertEqual(len(R.candidates("four_bar", hinge, seats)), 2 * 5 * 24) + found = R.search("four_bar", hinge, ram, seats, steps=49) + self.assertTrue(found.found, found.report()) + self.assertIn("assembly", found.tally) + crank = R.candidates("bell_crank", hinge, {**seats, "d": (0.12, 0.24, 3)}) + self.assertEqual(len(crank), 2 * 5 * 24 * 3 * 12) + + +@unittest.skipIf(np is None, "numpy is not installed") +class RecordDrives(unittest.TestCase): + def test_round_trip_and_drive(self): + ram = R.Ram(BORE) + for m in (r3("four_bar", DEEP), r3("bell_crank", CRANK), R.Mechanism("direct", O, X, -62, 0, a=(0.05, -0.3, 0.8), b=(0.05, -0.3, -0.6), offsets=(-0.1, 0.1))): + f = R.fit(m, ram, steps=49) + data = R.record(m, ram, f.barrel) + wire = json.loads(json.dumps(data)) + self.assertEqual(wire, data) + again, ram2, barrel = R.from_record(wire) + self.assertEqual(R.record(again, ram2, barrel), data) + angles = np.linspace(m.lo, m.hi, 49) + self.assertEqual(R.length(again, angles).tolist(), R.length(m, angles).tolist()) + ext = R.extension(again, ram2, barrel, angles) + self.assertEqual(ext.tolist(), (R.length(m, angles) - data["closed"]).tolist()) + # the extension follows the angle: home plus the overtravel at the short end, travel more at the long + self.assertAlmostEqual(float(ext.min()), ram.over, places=12) + self.assertAlmostEqual(float(ext.max()), ram.over + f.travel, places=12) + self.assertGreater(abs(float(ext[0] - ext[-1])), 0.3) + self.assertAlmostEqual(data["closed"], f.closed, places=15) + + def test_offsets_stand_the_ram_along_the_axis(self): + m = R.Mechanism("direct", O, X, -60, 0, a=(0, -0.3, 1.0), b=(0, -0.3, -1.0), offsets=(-0.2, 0.2)) + ram = R.Ram(0.05) + barrel = R._fit(m, ram).barrel + # a ball beside the twin at +0.2 only + ball = Bodies(parent=[("capsule", (0.2, -0.45, 0.5), (0.2, -0.45, 0.5), 0.06)]) + margin, where = R.clearance(m, ram, barrel, 0.0, ball) + self.assertLess(float(margin[0]), 0.0) + self.assertEqual(where[1], "barrel[0.2]") + + +@unittest.skipIf(np is None, "numpy is not installed") +class Refusals(unittest.TestCase): + def refused(self, gate, pin=None, **changes): + base = {"kind": "four_bar", "pivot": O, "axis": X, "lo": -125, "hi": 0, **{name: yz(DEEP[name]) for name in DEEP}} + base.update(changes) + with self.assertRaises(R.RamError) as caught: + R.Mechanism(**base) + self.assertEqual((caught.exception.gate, caught.exception.pin), (gate, pin), str(caught.exception)) + self.assertIn(str(base["kind"]), str(caught.exception)) + return caught.exception + + def test_every_record_refusal(self): + self.refused("record", kind="scissor") + self.refused("record", "axis", axis=(1.0, 0.1, 0.0)) + self.refused("record", lo=0, hi=0) + self.refused("record", lo=-200, hi=200) + self.refused("record", offsets=()) + self.refused("record", "a", a=(0, 1)) + self.refused("record", "c", c=(0, float("nan"), 1)) + self.refused("record", "b", b=(0, 0, -1)) # a four-bar has no b + self.refused("record", "rocker", rocker=None) + self.refused("record", "b", kind="direct", rocker=None, p=None, c=None, d=None) # a direct ram needs b + self.refused("record", "d", d=(0, -0.4, 0.0)) # a four-bar's eye is p + self.refused("record", "d", kind="bell_crank") # a bell crank's is not + self.refused("assembly", "p", p=yz((0.5 * (DEEP["rocker"][0] + DEEP["c"][0]), 0.5 * (DEEP["rocker"][1] + DEEP["c"][1]))), + d=yz((0.5 * (DEEP["rocker"][0] + DEEP["c"][0]), 0.5 * (DEEP["rocker"][1] + DEEP["c"][1])))) + + def test_a_bell_cranks_eye_stands_off_its_pin(self): + near = dict(CRANK, d=(CRANK["p"][0] + 2 * BORE - 1e-6, CRANK["p"][1])) + with self.assertRaises(R.RamError) as caught: + R.fit(r3("bell_crank", near), R.Ram(BORE)) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("pins", "d")) + + def test_arm_refused(self): + m = R.Mechanism("direct", O, X, -30, 0, a=(0, -0.05, 1.0), b=(0, -0.05, -1.0)) + with self.assertRaises(R.RamError) as caught: + R.fit(m, R.Ram(0.05)) + self.assertEqual(caught.exception.gate, "arm") + self.assertIn("arm at", str(caught.exception)) + + def test_no_blender(self): + source = (SURFACE / "brokkr_kitbash" / "ram.py").read_text(encoding="utf-8") + for word in ("bpy", "mathutils", "np.gradient"): + self.assertNotIn(word, source) + + +if __name__ == "__main__": + unittest.main() From 048b3b3d7c070d895a6c3ba91cf854a48892cc61 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 17:52:42 +0100 Subject: [PATCH 132/223] docs/kitbash.md: Rams and linkages: the model, the three kinds, the gates, the oracle rule, R-3 readings and costs Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 66 ++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 6ddbbfa..74e2bdd 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -777,6 +777,72 @@ field. Nothing in a kit is run as Python. Division by zero, a result that is not or `segments` that is not whole are refused when the part is built, naming the expression; so is a shape whose vertices overflow. +## Rams and linkages + +`brokkr_kitbash/ram.py` owns the motion of a ram across one hinge. It is numpy and the standard library, imports +nothing from the package, and no action calls it yet: a rig or a runtime loads the file alone. Its input is a +mechanism record: the hinge (pivot, unit axis, `lo` and `hi` in degrees, positive right-handed about the axis like +a pin joint's roll), a kind, and pins, each in its own body's rest frame. + +| kind | pins | the ram runs | +| --- | --- | --- | +| `direct` | `a` on the parent, `b` on the child | `a` to `b` | +| `four_bar` | `a`; `rocker` (R), the rocker's pivot on the parent; `p` on the rocker; `c` on the child; `d` = `p` | `a` to `p`: the excavator bucket linkage, a coupler from `p` to `c` turning the child | +| `bell_crank` | the same, `d` elsewhere on the rocker, at least 2 bore from `p` | `a` to `d` | + +Everything is a function of the record and the hinge angle: `pose` gives each body's rotation, the ram's base and +eye, its pin-to-pin length L and dL/dtheta; `length` and `extension` (L less the closed length) are what a rig +drives a rod from. Nothing stores a rocker angle or an extension. The loop is solved in the plane across the axis: +`p` lies where the rocker's circle about R meets the coupler's about `c`, on the side of R -> `c` it has at rest, +so an angle gives the same pose whatever was asked before it. A pin's coordinate along the axis says only where +its member stands: the rocker bars at R's, the coupler at `c`'s, the ram at `a`'s plus each of `offsets` (twins). +Rates are closed form: for a linkage dphi/dtheta = (axis x (c - O)) . k / ((axis x (p - R)) . k), k along the +coupler, and dL/dtheta = (axis x (d - R)) . u x dphi/dtheta, u along the ram. + +`fit` runs the gates over the range, in this order, and a failed gate is a `RamError` naming the kind, the gate +and the angle or pin, with the readings attached: + +- **assembly**: the rocker and coupler close the loop at every step, and on the way from rest when the range does + not hold 0; within 1e-9 of a dead centre is refused, since the branch would change there. +- **stroke**: barrel = L_min - over - back - e_b, and it holds the travel, the overtravel at both ends and the gland. +- **toggle**, **arm**: dL/dtheta keeps one sign, and |dL/dtheta| (the effective arm: hinge torque per unit ram + force) stays at or above `min_arm`. +- **load** (linkages): the coupler's pin load per unit ram force, |dL/dtheta| over the coupler's moment arm about + the hinge, stays at or under `max_load` (3). +- **clash**: clearance, when a distance oracle is given. + +Transmission angles at `c` and `p` are reported and not gated. Over the R-3 knee's 125 degrees the best least +transmission angle of 200,000 sampled four-bars was 21.9 degrees, under the 30 to 40 a textbook asks; a gate there +would have refused every one of them. What a poor angle costs is pin load, and that is the gate. + +Clearance takes `distance(body, points) -> distances`: `body` one of parent, child, rocker, coupler, `points` in +that body's rest frame. The barrel, the rod (per offset) and the link bars are sampled along their axes at most +`spacing` apart (default the barrel's radius) and carried into every body's rest frame at each angle but their +own; a sample is clear at radius + gap + spacing / 2 or more, which keeps the gap for the surface between samples. +Only the clevis ends are left out: `e_a` at the ram's base, 0.4 `e_b` at its eye, 1.5 `link_r` at a link's pins; +the pin a clevis turns on is not part of the body the oracle answers for. The oracle may cap what it returns at +`Ram.reach(spacing)`: on the R-3 meshes (3,564 triangles) a BVH nearest query capped there cost 0.55 us against +3.12 us uncapped. A four-bar at the default spacing asks 155 points an angle. + +`search` seats a mechanism from a grid (ram seats; for linkages rocker pivots, child pins, `p` on a polar grid +about R, and `d` about R for a bell crank), refuses a grid over `limit` candidates naming the count, runs every +gate but clearance on all of them, then clearance in order of least arm; a miss returns the tally by gate and the +nearest miss. `record` and `from_record` carry a fitted mechanism as JSON; `swept` gives the ram's swept surface in +any body's frame, for a recess. + +Readings on the R-3 knee (bore 0.042, tests/test_ram.py; bodies as boxes and cylinders, links as twin plates +outside the shin's side armour): + +| drive | range | reading | +| --- | --- | --- | +| direct, the joint library's seats | 0..-62 | fits | +| direct, 2,000 seat pairs behind the knee | 0..-125 | none fits | +| four-bar behind the knee | 0..-125 | passes every gate before clearance: rocker swing 70.5, L 0.722..1.168, arm 0.096..0.265, pin load 1.61, transmission 16.5; refused on clearance: at -125 the barrel is inside the shin, a body the ram is not pinned to | +| bell crank in front of the knee | 0..-125 | fits: rocker swing 105.7, L 0.659..1.038, arm 0.091..0.215, pin load 1.13, transmission 13.8; ram and links clear the thigh, the shin and each other's bodies on both sides, least 0.109 beyond radius and gap to the shin (the coupler at -125) | + +One candidate's gates before clearance cost 1.7 to 3.8 ms at 49 steps on Starfire (median 3.6 of five reps of 200 +under other load); `limit` (20,000) is about a minute of them. + ## The actions | action | fields | what it does | From 780b0dae6609d89e2903538585449c217c42090c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:01:37 +0100 Subject: [PATCH 133/223] brokkr_kitbash.ram: clearance by parts and what a member may touch; a signed oracle; the barrel derived; a versioned record The record names parts (part -> body) and touch (member -> parts it may touch): the allowed-collision pairs are skipped whole and every other member-part pair is checked. The end cuts (e_a, 0.4 e_b, 1.5 link_r) and the own-body exemption are gone; every body owns a part or the gate refuses. Distances are signed, capped outside only; nan is refused. search takes world(m) -> (parts, touch, distance), so a candidate's own brackets and links are its parts; a candidate's eye stands at a's place along the axis. barrel_length derives the barrel; record holds nothing derived, carries schema, version and a reserved compliance block, and from_record refuses another version, an unknown key or a compliance block whole. Gate refusals name the angle and the pin. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/ram.py | 237 +++++++++++++++++-------- 1 file changed, 161 insertions(+), 76 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py index ef20a4b..cdb475e 100644 --- a/surfaces/blender/brokkr_kitbash/ram.py +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -16,18 +16,31 @@ the coupler bar at c's, the ram at a's plus each of `offsets`. pose(m, degrees) every body's rotation, the ram's base and eye, L, dL/dtheta, per angle length(m, degrees) pin-to-pin ram length - extension(m, ram, barrel, degrees) rod extension from closed + barrel_length(m, ram) the barrel the range's shorter end leaves room for + extension(m, ram, degrees) rod extension from closed fit(m, ram, ...) the gates over the range: assembly, stroke, arm, load, clearance - clearance(m, ram, barrel, degrees, distance) the clearance gate's reading at any angles + clearance(m, ram, degrees, distance) the clearance gate's reading at any angles, per member and part search(kind, hinge, ram, seats, ...) the best of a seat grid, or the tally and the nearest miss - record(m, ram, barrel), from_record the JSON record a rig or runtime drives from + record(m, ram), from_record the JSON record a rig or runtime drives from swept(fit, body, ...) points of the swept ram's surface in a body's rest frame -Clearance takes a distance oracle, distance(body, points) -> distances, body one of BODIES[kind] and points (N, 3) -in that body's rest frame. The oracle may cap what it returns at Ram.reach(spacing): nothing farther is asked. +Clearance. The record names the mechanism's `parts`, each a piece of one body (part -> the body whose rest frame +it turns with: a thigh's core, the bracket that carries the rocker's pivot, a link's plates, a pin), and `touch`: +for each member of MEMBERS[kind], the parts it may touch. A member may touch what it is pinned to and what is +stacked on its pins: the pin, its own eye and clevis, the plates beside it on that pin, the bracket or horn the pin +stands in. Those pairs are skipped whole and every other (member, part) pair is checked; nothing is exempt by a +name, a length or the member's own body. Every body of the kind owns at least one part, or the gate refuses. + +The oracle is distance(part, points) -> distances, points (N, 3) in the rest frame of the part's body. A distance +is signed: negative inside the part, by any depth. The oracle may cap what it returns at Ram.reach(spacing), +outside a part only: a point inside reads negative however deep it lies. An oracle that cannot tell inside from +outside (a nearest-surface query on an open mesh) raises instead of answering; nan is refused here. + +A RamError of a gate (assembly, stroke, toggle, arm, load, clash) names the angle and the pin; one of the record +or of a call (an unknown kind, a range, a grid over the limit, a version) names the pin or the field it refuses. """ import math -from dataclasses import dataclass, field, fields +from dataclasses import dataclass, field, fields, replace import numpy as np @@ -35,16 +48,20 @@ KINDS = ("direct", "four_bar", "bell_crank") BODIES = {"direct": ("parent", "child"), "four_bar": ("parent", "child", "rocker", "coupler"), "bell_crank": ("parent", "child", "rocker", "coupler")} PINS = {"direct": ("a", "b"), "four_bar": ("a", "rocker", "p", "c", "d"), "bell_crank": ("a", "rocker", "p", "c", "d")} +MEMBERS = {"direct": ("barrel", "rod"), "four_bar": ("barrel", "rod", "rocker", "coupler"), + "bell_crank": ("barrel", "rod", "rocker", "coupler", "rocker arm")} GATES = ("assembly", "stroke", "toggle", "arm", "load", "clash") +SCHEMA, VERSION = "brokkr.ram", 1 +COMPLIANCE = ("stiffness", "damping", "travel") # reserved: a load-path ram's settle, solved by a later version BAND = 1e-9 # the loop is refused within this of a dead centre of the rocker and coupler class RamError(ValueError): - """A refusal: the mechanism kind, the gate, and the angle or pin it failed at. `fit` holds the readings when + """A refusal: the mechanism kind, the gate, the angle and the pin it failed at. `fit` holds the readings when the gates got far enough to take them.""" def __init__(self, kind, gate, message, angle=None, pin=None, fit=None): - where = f" at {angle:g} deg" if angle is not None else f" (pin {pin})" if pin else "" + where = (f" at {angle:g} deg" if angle is not None else "") + (f" (pin {pin})" if pin else "") super().__init__(f"{kind} ram: {gate}{where}: {message}") self.kind, self.gate, self.angle, self.pin, self.fit = kind, gate, angle, pin, fit @@ -115,6 +132,8 @@ class Mechanism: c: np.ndarray = None d: np.ndarray = None offsets: tuple = (0.0,) + parts: dict = field(default_factory=dict) # part -> the body it turns with + touch: dict = field(default_factory=dict) # member -> the parts it may touch def __post_init__(self): if self.kind not in KINDS: @@ -130,10 +149,21 @@ class Mechanism: raise RamError(self.kind, "record", f"the axis is a unit vector, length {np.linalg.norm(self.axis):.6f}", pin="axis") self.lo, self.hi = float(self.lo), float(self.hi) if not self.lo < self.hi or self.hi - self.lo > 360.0: - raise RamError(self.kind, "record", f"lo < hi and hi - lo <= 360, got {self.lo:g}..{self.hi:g}") + raise RamError(self.kind, "record", f"lo < hi and hi - lo <= 360, got {self.lo:g}..{self.hi:g}", angle=self.lo) self.offsets = tuple(float(o) for o in self.offsets) if not self.offsets: - raise RamError(self.kind, "record", "at least one offset") + raise RamError(self.kind, "record", "at least one offset: where the ram stands along the axis from a", pin="a") + self.parts = {str(part): body for part, body in dict(self.parts).items()} + for part, body in self.parts.items(): + if body not in BODIES[self.kind]: + raise RamError(self.kind, "record", f"part {part!r} turns with {body!r}; this kind has {', '.join(BODIES[self.kind])}") + self.touch = {member: tuple(parts) for member, parts in dict(self.touch).items()} + for member, parts in self.touch.items(): + if member not in MEMBERS[self.kind]: + raise RamError(self.kind, "record", f"touch names {member!r}; this kind's members are {', '.join(MEMBERS[self.kind])}") + for part in parts: + if part not in self.parts: + raise RamError(self.kind, "record", f"{member} may touch {part!r}, which is no part of the record") for name in ("a", "b", "rocker", "p", "c", "d"): needed, given = name in PINS[self.kind], getattr(self, name) is not None if needed != given: @@ -191,7 +221,7 @@ def pose(m, degrees): if bad.any(): i = int(np.argmax(bad)) raise RamError(m.kind, "assembly", f"|c - R| is {dist[i]:.4f}, outside ({lo:.4f}, {hi:.4f}): the rocker ({m.lr:.4f}) and coupler " - f"({m.lc:.4f}) cannot close the loop, or reach a dead centre where the branch would change", angle=float(deg[i])) + f"({m.lc:.4f}) cannot close the loop, or reach a dead centre where the branch would change", angle=float(deg[i]), pin="c") x = (m.lr * m.lr - m.lc * m.lc + dist * dist) / (2.0 * dist) h = np.sqrt(np.maximum(m.lr * m.lr - x * x, 0.0)) across = g / dist[:, None] @@ -221,31 +251,38 @@ def length(m, degrees): return pose(m, degrees).L -def extension(m, ram, barrel, degrees): +def barrel_length(m, ram): + """The barrel the mechanism leaves room for: the ram's length at the shorter end of the range, less the + overtravel, the base clevis (or nothing, on a trunnion) and the eye. L runs one way over a range that fits + (the toggle gate), so that end is the least. Derived, never stored: a record holds the pins and the ram.""" + return _barrel(ram, pose(m, (m.lo, m.hi)).L) + + +def _barrel(ram, ends): + return float(min(ends[0], ends[-1])) - ram.over - ram.back - ram.e_b + + +def extension(m, ram, degrees): """Rod extension from closed at each angle: L - (back + barrel + e_b).""" - return pose(m, degrees).L - (ram.back + barrel + ram.e_b) + return pose(m, degrees).L - (ram.back + barrel_length(m, ram) + ram.e_b) def _members(m, ram, barrel, p): - """(name, start (S, 3), end (S, 3), radius, own body) of every member in the parent frame, clevis ends left - out: e_a at the ram's base (the barrel starts there), 0.4 e_b at its eye, 1.5 link_r at a link's pins.""" - n = m.axis + """(member, label, start (S, 3), end (S, 3), radius, (pin at start, pin at end)) of every member in the parent + frame, each from pin to pin: the barrel from its back end, the rod to the eye, a bar between its pins.""" + n, eye = m.axis, "b" if m.kind == "direct" else "d" for off in m.offsets: - base, eye = p.base + off * n, p.eye + off * n + base, tip = p.base + off * n, p.eye + off * n front = base + p.u * (ram.back + max(barrel, 1e-6)) - yield f"barrel[{off:g}]", base + p.u * ram.back, front, ram.barrel_r, None - yield f"rod[{off:g}]", front, eye - p.u * (0.4 * ram.e_b), ram.rod, None + yield "barrel", f"barrel[{off:g}]", base + p.u * ram.back, front, ram.barrel_r, ("a", eye) + yield "rod", f"rod[{off:g}]", front, tip, ram.rod, ("a", eye) if m.kind == "direct": return R = np.broadcast_to(m.rocker, p.P.shape) - bars = [("rocker", R, p.P - n * ((p.P - R) @ n)[:, None], "rocker"), ("coupler", p.P - n * ((p.P - p.C) @ n)[:, None], p.C, "coupler")] + yield "rocker", "rocker", R, p.P - n * ((p.P - R) @ n)[:, None], ram.link_r, ("rocker", "p") + yield "coupler", "coupler", p.P - n * ((p.P - p.C) @ n)[:, None], p.C, ram.link_r, ("p", "c") if m.kind == "bell_crank": - bars.append(("rocker arm", R, p.eye - n * ((p.eye - R) @ n)[:, None], "rocker")) - for name, start, end, own in bars: - along = end - start - span = np.linalg.norm(along, axis=1)[:, None] - cut = along / np.maximum(span, 1e-12) * np.minimum(1.5 * ram.link_r, span / 2.0) - yield name, start + cut, end - cut, ram.link_r, own + yield "rocker arm", "rocker arm", R, p.eye - n * ((p.eye - R) @ n)[:, None], ram.link_r, ("rocker", "d") def _into(m, p, body, pts): @@ -260,41 +297,63 @@ def _into(m, p, body, pts): return m.p + _rot(pts - p.P[:, None, :], n, -p.psi[:, None]) -def clearance(m, ram, barrel, degrees, distance, spacing=None, at=None): - """The clearance gate's reading: (margin per angle, (angle, member, body) of the least). A member is clear - where margin >= 0: each sample of its axis, taken at most `spacing` apart (default barrel_r), is at least - radius + gap + spacing / 2 from every body, measured in that body's rest frame at that angle. A sample is at - most spacing / 2 from any point of the axis, so the member's surface keeps the gap. Every member meets every - body of the mechanism but its own.""" - p = pose(m, degrees) if at is None else at +@dataclass +class Clearance: + margin: np.ndarray # (S,) the least margin of any checked pair at each angle + where: tuple # (angle, member label, part, pin) of the least: the pin is the member's nearer one + pairs: dict # (member label, part) -> (least margin, angle) of every pair checked + allowed: list # (member label, part) of every pair the record's `touch` skipped + + +def clearance(m, ram, degrees, distance, spacing=None): + """The clearance gate's reading. A member is clear where margin >= 0: each sample of its axis, taken at most + `spacing` apart (default barrel_r), is at least radius + gap + spacing / 2 from every part, measured in the + rest frame of the part's body at that angle. A sample is at most spacing / 2 from any point of the axis, so + the member's surface keeps the gap. Every member meets every part of the record but those `touch` gives it.""" + return _clearance(m, ram, barrel_length(m, ram), pose(m, degrees), distance, spacing) + + +def _clearance(m, ram, barrel, p, distance, spacing): + for body in BODIES[m.kind]: + if body not in m.parts.values(): + raise RamError(m.kind, "record", f"no part turns with body {body}: the clearance gate would pass it unseen") step = ram.spacing(spacing) - margin, least, where = np.full(len(p.degrees), math.inf), math.inf, None - for name, start, end, radius, own in _members(m, ram, barrel, p): + out = Clearance(np.full(len(p.degrees), math.inf), None, {}, []) + least = math.inf + for member, label, start, end, radius, pins in _members(m, ram, barrel, p): count = max(int(math.ceil(float(np.linalg.norm(end - start, axis=1).max()) / step)) + 1, 2) pts = start[:, None, :] + (end - start)[:, None, :] * np.linspace(0.0, 1.0, count)[None, :, None] need = radius + ram.gap + step / 2.0 - for body in BODIES[m.kind]: - if body == own: + seen = {} + for part, body in m.parts.items(): + if part in m.touch.get(member, ()): + out.allowed.append((label, part)) continue - got = np.asarray(distance(body, _into(m, p, body, pts).reshape(-1, 3)), dtype=float).reshape(len(p.degrees), count) + if body not in seen: + seen[body] = _into(m, p, body, pts).reshape(-1, 3) + got = np.asarray(distance(part, seen[body]), dtype=float).reshape(len(p.degrees), count) + if np.isnan(got).any(): + raise RamError(m.kind, "oracle", f"the distance oracle answered nan for part {part!r}") row = got.min(axis=1) - need - margin = np.minimum(margin, row) + out.margin = np.minimum(out.margin, row) i = int(np.argmin(row)) + out.pairs[(label, part)] = (float(row[i]), float(p.degrees[i])) if row[i] < least: - least, where = float(row[i]), (float(p.degrees[i]), name, body) - return margin, where + least = float(row[i]) + out.where = (float(p.degrees[i]), label, part, pins[int(np.argmin(got[i])) * 2 >= count]) + return out @dataclass class Fit: m: Mechanism ram: Ram - why: list # (gate, angle or None, message) of every gate that failed; empty when it fits + why: list # (gate, angle, pin, message) of every gate that failed; empty when it fits degrees: np.ndarray l_min: float l_max: float travel: float # L_max - L_min - barrel: float # barrel length + barrel: float # barrel length: barrel_length(m, ram) closed: float # pin to pin with the rod home: back + barrel + e_b stroke: float # travel the barrel holds spare: float # stroke - (travel + 2 over): negative when the stroke does not fit @@ -306,7 +365,9 @@ class Fit: mu_c: float = None # least transmission angle at c, degrees: reported, never gated mu_p: float = None # least transmission angle at p clear_min: float = math.inf # least clearance beyond what the gate asks; inf with no oracle - clear_at: tuple = None # (angle, member, body) of it + clear_at: tuple = None # (angle, member, part, pin) of it + pairs: dict = field(default_factory=dict) # (member, part) -> (least margin, angle) of every pair checked + allowed: list = field(default_factory=list) # (member, part) of every pair `touch` skipped table: list = field(default_factory=list) # (angle, L, dL/dtheta, clearance margin) per step @property @@ -314,12 +375,12 @@ class Fit: return not self.why def error(self): - gate, angle, message = self.why[0] - return RamError(self.m.kind, gate, message, angle=angle, fit=self) + gate, angle, pin, message = self.why[0] + return RamError(self.m.kind, gate, message, angle=angle, pin=pin, fit=self) def report(self): """One line for a log or a sheet.""" - state = "OK" if self.ok else "NO (" + "; ".join(f"{g}: {msg}" for g, _, msg in self.why) + ")" + state = "OK" if self.ok else "NO (" + "; ".join(f"{g}: {msg}" for g, _, _, msg in self.why) + ")" links = "" if self.m.kind == "direct" else f", rocker swing {self.swing:.1f}, pin load <= {self.load_max:.2f}, transmission >= {min(self.mu_c, self.mu_p):.1f} deg" return (f"{state}: L {self.l_min:.3f}..{self.l_max:.3f}, barrel {self.barrel:.3f}, stroke {self.stroke:.3f} for travel {self.travel:.3f} " f"(spare {self.spare:+.3f}), arm >= {self.arm_min:.3f}{links}, clear {self.clear_min:+.3f}") @@ -333,8 +394,9 @@ def _fit(m, ram, steps=25, distance=None, spacing=None, clear=True): pose(m, np.linspace(0.0, m.lo if m.lo > 0.0 else m.hi, steps)) # the branch is carried from rest: no dead centre on the way p = pose(m, np.linspace(m.lo, m.hi, steps)) l_min, l_max = float(p.L.min()), float(p.L.max()) + eye = "b" if m.kind == "direct" else "d" travel = l_max - l_min - barrel = l_min - ram.over - ram.back - ram.e_b + barrel = _barrel(ram, p.L) # the samples' ends are lo and hi: barrel_length's own two angles stroke = barrel - ram.gland spare = stroke - (travel + 2.0 * ram.over) i = int(np.argmin(np.abs(p.dL))) @@ -343,33 +405,35 @@ def _fit(m, ram, steps=25, distance=None, spacing=None, clear=True): arm_sign = int(signs.pop()) if len(signs) == 1 else 0 f = Fit(m, ram, [], p.degrees, l_min, l_max, travel, barrel, ram.back + barrel + ram.e_b, stroke, spare, arm_min, arm_at, arm_sign) if barrel <= ram.gland or spare < -1e-9: - f.why.append(("stroke", None, f"travel {travel:.3f} needs {travel + 3.0 * ram.over + ram.gland + ram.back + ram.e_b:.3f} closed, L_min is {l_min:.3f}")) + f.why.append(("stroke", float(p.degrees[int(np.argmin(p.L))]), eye, f"travel {travel:.3f} needs {travel + 3.0 * ram.over + ram.gland + ram.back + ram.e_b:.3f} closed, L_min is {l_min:.3f}")) if arm_sign == 0: flip = np.nonzero(np.sign(p.dL[1:]) != np.sign(p.dL[:-1]))[0] - f.why.append(("toggle", float(p.degrees[flip[0] + 1]) if len(flip) else arm_at, "dL/dtheta changes sign: a dead centre inside the range")) + f.why.append(("toggle", float(p.degrees[flip[0] + 1]) if len(flip) else arm_at, eye, "dL/dtheta changes sign: a dead centre inside the range")) elif arm_min < ram.min_arm: - f.why.append(("arm", arm_at, f"least effective arm {arm_min:.3f} under {ram.min_arm:.3f}")) + f.why.append(("arm", arm_at, eye, f"least effective arm {arm_min:.3f} under {ram.min_arm:.3f}")) if m.kind != "direct": phi = np.degrees(np.unwrap(p.phi)) j = int(np.argmax(p.load)) f.swing, f.load_max = float(phi.max() - phi.min()), float(p.load[j]) f.mu_c, f.mu_p = float(p.mu_c.min()), float(p.mu_p.min()) if f.load_max > ram.max_load: - f.why.append(("load", float(p.degrees[j]), f"coupler pin load {f.load_max:.2f} x the ram force, over {ram.max_load:.2f}")) + f.why.append(("load", float(p.degrees[j]), "c", f"coupler pin load {f.load_max:.2f} x the ram force, over {ram.max_load:.2f}")) margin = np.full(steps, math.inf) if distance is not None and clear: - margin, f.clear_at = clearance(m, ram, barrel, None, distance, spacing, at=p) + c = _clearance(m, ram, barrel, p, distance, spacing) + margin, f.clear_at, f.pairs, f.allowed = c.margin, c.where, c.pairs, c.allowed f.clear_min = float(margin.min()) if f.clear_min < 0.0: - angle, member, body = f.clear_at - f.why.append(("clash", angle, f"{member} is {-f.clear_min:.3f} inside the clearance of body {body}")) + angle, member, part, pin = f.clear_at + f.why.append(("clash", angle, pin, f"{member} is {-f.clear_min:.3f} inside the clearance of part {part!r} ({m.parts[part]})")) f.table = [tuple(row) for row in np.stack([p.degrees, p.L, p.dL, margin], axis=1).tolist()] return f def fit(m, ram, steps=25, distance=None, spacing=None): """Check one mechanism from lo to hi. Gates, in order, each over all steps at once: assembly; stroke; effective - arm (one sign, and at least min_arm); coupler pin load (linkages); clearance, when a distance oracle is given. + arm (one sign, and at least min_arm); coupler pin load (linkages); clearance, when a distance oracle is given + (see clearance: the record's parts and touch say what it meets). Returns the Fit; a failed gate raises RamError, its `fit` holding the readings.""" f = _fit(m, ram, steps, distance, spacing) if not f.ok: @@ -404,7 +468,8 @@ def _polar(n, centre, toward, radii, step): def candidates(kind, hinge, seats): """The pins of every candidate of a seat grid. direct: seats['a'] x seats['b']. Linkages: seats['rocker'] x seats['c'] x p on a polar grid about R (lengths seats['link'] = (lo, hi, n), every 15 degrees) x seats['a'], - and for a bell crank x d on a polar grid about R (seats['d'] = (lo, hi, n), every 30 degrees).""" + and for a bell crank x d on a polar grid about R (seats['d'] = (lo, hi, n), every 30 degrees). The ram's eye + (d, and a four-bar's p) stands at a's place along the axis, so the ram runs across it.""" n = np.asarray(hinge["axis"], dtype=float) if kind == "direct": return [{"a": a, "b": b} for a in seats["a"] for b in seats["b"]] @@ -414,15 +479,22 @@ def candidates(kind, hinge, seats): for c in seats["c"]: for p in _polar(n, R, c, np.linspace(*seats["link"]), 15): eyes = [p] if kind == "four_bar" else _polar(n, R, p, np.linspace(*seats["d"]), 30) - out.extend({"a": a, "rocker": R, "p": p, "c": c, "d": d} for a in seats["a"] for d in eyes) + for a in seats["a"]: + a = np.asarray(a, dtype=float) + for d in eyes: + d = d - n * ((d - a) @ n) + out.append({"a": a, "rocker": R, "p": d if kind == "four_bar" else p, "c": c, "d": d}) return out -def search(kind, hinge, ram, seats, distance=None, limit=20000, steps=25, spacing=None): +def search(kind, hinge, ram, seats, world=None, limit=20000, steps=25, spacing=None): """Seat a mechanism from a grid (see candidates). hinge = {pivot, axis, lo, hi, offsets (optional)}. Best first: every gate but clearance over all candidates, then clearance in order of least arm, greatest first; - the first clear one wins. A grid past `limit` candidates is refused naming the count. A miss returns the - tally and the nearest miss (the least total shortfall: stroke, arm, load excess, clearance).""" + the first clear one wins. world(m) -> (parts, touch, distance) builds a candidate's own parts, the brackets + and links its pins place among them, and the oracle that answers for them: a linkage's links are the + candidate's, so no one oracle serves a grid. A grid past `limit` candidates is refused naming the count. A + miss returns the tally and the nearest miss (the least total shortfall: stroke, arm, load excess, + clearance).""" pins = candidates(kind, hinge, seats) if len(pins) > limit: raise RamError(kind, "search", f"{len(pins)} candidates, over the limit of {limit}: thin the seat grid") @@ -430,7 +502,7 @@ def search(kind, hinge, ram, seats, distance=None, limit=20000, steps=25, spacin def missed(f, seat): nonlocal miss - for gate in {g for g, _, _ in f.why}: + for gate in {g for g, _, _, _ in f.why}: tally[gate] = tally.get(gate, 0) + 1 short = (max(-f.spare, 0.0) + max(ram.min_arm - f.arm_min, 0.0) + (ram.min_arm if f.arm_sign == 0 else 0.0) + max(f.load_max - ram.max_load, 0.0) + (max(-f.clear_min, 0.0) if f.clear_min < math.inf else 0.0)) @@ -450,32 +522,45 @@ def search(kind, hinge, ram, seats, distance=None, limit=20000, steps=25, spacin missed(f, seat) passed.sort(key=lambda entry: -entry[0].arm_min) for f, seat in passed: - if distance is None: + if world is None: return Search(f, True, len(pins), len(passed), tally, seat) - f = _fit(f.m, ram, steps, distance, spacing) + parts, touch, distance = world(f.m) + f = _fit(replace(f.m, parts=parts, touch=touch), ram, steps, distance, spacing) if f.ok: return Search(f, True, len(pins), len(passed), tally, seat) missed(f, seat) return Search(miss[1] if miss else None, False, len(pins), len(passed), tally, miss[2] if miss else None) -def record(m, ram, barrel): +def record(m, ram): """The mechanism record: plain JSON types, everything a rig or runtime needs to drive the ram from the hinge - angle (from_record, then length or extension).""" - out = {"kind": m.kind, "hinge": {"pivot": m.pivot.tolist(), "axis": m.axis.tolist(), "lo": m.lo, "hi": m.hi}, - "pins": {name: getattr(m, name).tolist() for name in PINS[m.kind]}, "offsets": list(m.offsets), - "ram": {f.name: getattr(ram, f.name) for f in fields(Ram)}, "barrel": float(barrel), "closed": float(ram.back + barrel + ram.e_b)} - if m.kind != "direct": - out["links"] = {"rocker": m.lr, "coupler": m.lc} - return out + angle (from_record, then length or extension). It holds what is authored and nothing derived from it: barrel, + closed length and link lengths come from the pins and the ram. `compliance` is reserved for a load-path ram's + settle (COMPLIANCE: stiffness, damping, travel); version 1 writes it null and solves none.""" + return {"schema": SCHEMA, "version": VERSION, "kind": m.kind, + "hinge": {"pivot": m.pivot.tolist(), "axis": m.axis.tolist(), "lo": m.lo, "hi": m.hi}, + "pins": {name: getattr(m, name).tolist() for name in PINS[m.kind]}, "offsets": list(m.offsets), + "ram": {f.name: getattr(ram, f.name) for f in fields(Ram)}, + "parts": dict(m.parts), "touch": {member: list(parts) for member, parts in m.touch.items()}, "compliance": None} def from_record(data): - """(Mechanism, Ram, barrel) of a record.""" - ram = Ram(**data["ram"]) + """(Mechanism, Ram) of a record. A record of another schema or version, with a key this version does not + know, or with a compliance block is refused whole: nothing is read past and dropped.""" + kind = str(data.get("kind")) + if data.get("schema") != SCHEMA or data.get("version") != VERSION: + raise RamError(kind, "record", f"this reader reads {SCHEMA} version {VERSION}; the record is {data.get('schema')} version {data.get('version')}") + keys = {"schema", "version", "kind", "hinge", "pins", "offsets", "ram", "parts", "touch", "compliance"} + for name, given, known in (("record", set(data), keys), ("ram", set(data.get("ram", ())), {f.name for f in fields(Ram)}), + ("hinge", set(data.get("hinge", ())), {"pivot", "axis", "lo", "hi"})): + if given != known: + raise RamError(kind, "record", f"the {name}'s keys are not version {VERSION}'s: unknown {sorted(given - known)}, missing {sorted(known - given)}") + if data["compliance"] is not None: + raise RamError(kind, "record", f"a compliance block ({', '.join(COMPLIANCE)}) is a later version's: version {VERSION} solves none and will not drop it") hinge = data["hinge"] - m = Mechanism(data["kind"], hinge["pivot"], hinge["axis"], hinge["lo"], hinge["hi"], offsets=tuple(data["offsets"]), **data["pins"]) - return m, ram, float(data["barrel"]) + m = Mechanism(data["kind"], hinge["pivot"], hinge["axis"], hinge["lo"], hinge["hi"], offsets=tuple(data["offsets"]), + parts=data["parts"], touch=data["touch"], **data["pins"]) + return m, Ram(**data["ram"]) def swept(f, body, margin=0.0, steps=13, around=8): From 1da1c213fa1987a1406dc63c9a5c0d63ecac9a30 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:01:37 +0100 Subject: [PATCH 134/223] tests/test_ram: parts and touch on the R-3 knee at the probe's plate stack, inside a part, a candidate's own links, the record's version wall, bounds with their readings Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/test_ram.py | 468 +++++++++++++++++++++-------- 1 file changed, 338 insertions(+), 130 deletions(-) diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py index d47a760..314e747 100644 --- a/surfaces/blender/tests/test_ram.py +++ b/surfaces/blender/tests/test_ram.py @@ -1,6 +1,7 @@ """brokkr_kitbash/ram.py under plain Python: each case is a mechanism whose answer is known by hand, by a second -method (central differences, loop closure) or from the R-3 knee probes the docs cite. Bodies are analytic distance -oracles: boxes, capsules and cylinders across x. +method (central differences, loop closure) or from the R-3 knee probes the docs cite. Bodies are analytic signed +distance oracles: boxes, capsules and cylinders across x, each a named part of a body. They defend the gate's rule; +the R-3 knee's clearance on meshes is the Blender reading docs/kitbash.md states, not these stand-ins. Bounds follow lodur:ruling:deterministic-bound-margin: the geometric mean of the shipped reading and the least mutant's, both written beside the constant.""" @@ -9,6 +10,7 @@ import json import math import sys import unittest +from dataclasses import replace from pathlib import Path try: @@ -36,11 +38,14 @@ def turned(point, degrees, pivot=O, axis=X): class Bodies: - """A distance oracle over analytic shapes per body: ("capsule", p, q, r), ("box", lo, hi), and - ("cyl", centre, r, half): a cylinder across x. Inside a shape the distance is 0. `cap` caps what it returns.""" + """A signed distance oracle over analytic shapes. parts: name -> (body, shapes), a shape ("capsule", p, q, r), + ("box", lo, hi) or ("cyl", centre, r, half): a cylinder across x. Inside a shape the distance is negative, its + depth. `cap` caps what it returns outside. A part it was not given raises.""" - def __init__(self, cap=None, **shapes): - self.shapes, self.cap, self.asked = shapes, cap, 0 + def __init__(self, parts, cap=None): + self.parts = {name: body for name, (body, _) in parts.items()} + self.shapes = {name: list(shapes) for name, (_, shapes) in parts.items()} + self.cap, self.asked = cap, 0 @staticmethod def one(shape, pts): @@ -48,22 +53,32 @@ class Bodies: p, q = np.asarray(shape[1], float), np.asarray(shape[2], float) along = q - p t = np.clip(((pts - p) @ along) / max(along @ along, 1e-18), 0.0, 1.0) - return np.maximum(np.linalg.norm(pts - p - t[:, None] * along, axis=1) - shape[3], 0.0) + return np.linalg.norm(pts - p - t[:, None] * along, axis=1) - shape[3] if shape[0] == "box": - out = np.maximum(np.maximum(np.asarray(shape[1], float) - pts, pts - np.asarray(shape[2], float)), 0.0) - return np.linalg.norm(out, axis=1) - centre = np.asarray(shape[1], float) - rel = pts - centre - return np.hypot(np.maximum(np.hypot(rel[:, 1], rel[:, 2]) - shape[2], 0.0), np.maximum(np.abs(rel[:, 0]) - shape[3], 0.0)) + out = np.maximum(np.asarray(shape[1], float) - pts, pts - np.asarray(shape[2], float)) + return np.linalg.norm(np.maximum(out, 0.0), axis=1) + np.minimum(out.max(axis=1), 0.0) + rel = pts - np.asarray(shape[1], float) + round_, flat = np.hypot(rel[:, 1], rel[:, 2]) - shape[2], np.abs(rel[:, 0]) - shape[3] + return np.hypot(np.maximum(round_, 0.0), np.maximum(flat, 0.0)) + np.minimum(np.maximum(round_, flat), 0.0) - def __call__(self, body, pts): + def __call__(self, part, pts): self.asked += len(pts) out = np.full(len(pts), math.inf) - for shape in self.shapes.get(body, ()): + for shape in self.shapes[part]: out = np.minimum(out, self.one(shape, pts)) return out if self.cap is None else np.minimum(out, self.cap) +def two(parent=(), child=(), cap=None, **more): + """Bodies of a direct ram: one part a body, named for it, and any more parts given as name=(body, shapes).""" + return Bodies({"parent": ("parent", parent), "child": ("child", child), **more}, cap) + + +def dressed(m, bodies, touch=None): + """The mechanism with the bodies' parts in its record, and what each member may touch.""" + return replace(m, parts=bodies.parts, touch=touch or {}) + + def yz(p, x=0.0): return (x, float(p[0]), float(p[1])) @@ -83,7 +98,7 @@ R3_SHIN = ([("cyl", O, 0.25, 0.18), ("cyl", O, 0.19, 0.205), ("box", (-0.11, -0. ("box", (0.1875, -0.1, -0.87), (0.2325, 0.1, -0.37))] # the cheeks taper from the hub's 0.25 to 0.12 at the foot: five steps outside the taper + [("box", (-0.18, -(0.25 - 0.026 * k), -0.19 * (k + 1)), (0.18, 0.25 - 0.026 * k, -0.19 * k)) for k in range(5)]) -X_COUPLER, X_ROCKER = 0.33, 0.43 # where the twin link plates stand: outside the shin's side armour (0.2325) +X_COUPLER, X_ROCKER = 0.3275, 0.3675 # the twin link plates' centres as the R-3 probe stacks them (0.31..0.345, 0.35..0.385) # P2's deep knee: a four-bar behind the knee (y < 0), where the shin folds to. DEEP = {"a": (-0.45, 1.15), "rocker": (-0.2320142211320173, 0.4604939911625098), "p": (-0.43650046730511183, -0.017951928782268284), @@ -100,15 +115,25 @@ def r3(kind, pins, side=1.0, lo=-125.0, hi=0.0): def r3_bodies(m, ram, cap=None): - """The R-3 thigh and shin, and the mechanism's own links as bodies: twin bars of link_r, and the rocker's axle - through the knee's width. The pins at p and d belong to the clevises that turn on them, not to a body.""" + """(Bodies, touch) of an R-3 linkage: the thigh and shin, and the mechanism's own links as parts: twin plates + of link_r, the rocker's axle through the knee's width, and the pins at p, c and (a bell crank) d. Each member + may touch its own plates and pins and the plates stacked beside it on a pin it rides; the ram, its eye's pin.""" def twin(p, q, x): return [("capsule", (s * x, p[1], p[2]), (s * x, q[1], q[2]), ram.link_r) for s in (-1.0, 1.0)] - Rk = m.rocker - rocker = twin(Rk, m.p, X_ROCKER) + [("capsule", (-X_ROCKER, Rk[1], Rk[2]), (X_ROCKER, Rk[1], Rk[2]), 0.028)] - if m.kind == "bell_crank": - rocker += twin(Rk, m.d, X_ROCKER) - return Bodies(cap, parent=R3_THIGH, child=R3_SHIN, rocker=rocker, coupler=twin(m.p, m.c, X_COUPLER)) + + def across(at, r): + return [("capsule", (-X_ROCKER, at[1], at[2]), (X_ROCKER, at[1], at[2]), r)] + crank = m.kind == "bell_crank" + parts = {"thigh": ("parent", R3_THIGH), "shin": ("child", R3_SHIN), + "rocker plates": ("rocker", twin(m.rocker, m.p, X_ROCKER) + (twin(m.rocker, m.d, X_ROCKER) if crank else [])), + "rocker axle": ("rocker", across(m.rocker, 0.028)), "pin p": ("rocker", across(m.p, 0.026)), + "coupler plates": ("coupler", twin(m.p, m.c, X_COUPLER)), "pin c": ("coupler", across(m.c, 0.026))} + own = ["rocker plates", "rocker axle", "pin p"] + (["pin d"] if crank else []) + touch = {"barrel": ["pin p"], "rod": ["pin p"], "rocker": own + ["coupler plates"], "coupler": ["coupler plates", "pin c", "rocker plates", "pin p"]} + if crank: + parts["pin d"] = ("rocker", across(m.d, 0.026)) + touch.update({"barrel": ["pin d"], "rod": ["pin d"], "rocker arm": own}) + return Bodies(parts, cap), touch @unittest.skipIf(np is None, "numpy is not installed") @@ -129,15 +154,20 @@ class HandCases(unittest.TestCase): eye = turned(self.B, -60) self.assertAlmostEqual(f.l_min, float(np.linalg.norm(eye - np.array(self.A))), places=12) self.assertAlmostEqual(f.barrel + f.ram.e_a + f.ram.e_b + f.ram.over, f.l_min, places=12) - self.assertAlmostEqual(float(R.extension(m, f.ram, f.barrel, 0.0)[0]), f.travel + f.ram.over, places=12) - self.assertAlmostEqual(float(R.extension(m, f.ram, f.barrel, -60.0)[0]), f.ram.over, places=12) + self.assertAlmostEqual(float(R.extension(m, f.ram, 0.0)[0]), f.travel + f.ram.over, places=12) + self.assertAlmostEqual(float(R.extension(m, f.ram, -60.0)[0]), f.ram.over, places=12) + self.assertEqual(f.barrel, R.barrel_length(m, f.ram)) def test_stroke_refused_and_a_trunnion_holds_more(self): m = self.direct(-120, 0, (0, -0.25, 0.3), (0, -0.25, -0.3)) with self.assertRaises(R.RamError) as caught: R.fit(m, R.Ram(0.05)) self.assertEqual((caught.exception.kind, caught.exception.gate), ("direct", "stroke")) - self.assertIn("direct ram: stroke", str(caught.exception)) + # the refusal names the angle of the shortest length and the eye's pin + angles = np.linspace(-120, 0, 25) + shortest = float(angles[int(np.argmin(R.length(m, angles)))]) + self.assertEqual((caught.exception.angle, caught.exception.pin), (shortest, "b")) + self.assertIn(f"direct ram: stroke at {shortest:g} deg (pin b)", str(caught.exception)) trunnion = R._fit(m, R.Ram(0.05, tail=0.25)) self.assertGreater(trunnion.barrel, caught.exception.fit.barrel + 0.3) @@ -162,38 +192,49 @@ class HandCases(unittest.TestCase): self.assertEqual(refusal.gate, "toggle") self.assertEqual(refusal.fit.arm_sign, 0) self.assertTrue(-40 < refusal.angle < 40, refusal.angle) - self.assertIn("toggle at", str(refusal)) + self.assertEqual(refusal.pin, "b") + self.assertIn(f"toggle at {refusal.angle:g} deg (pin b)", str(refusal)) + # the dead centre 1.7 degrees inside one end: past it the arm is 0.015 at most, and its sign still tells + edge = R._fit(self.direct(-13, 40, (0, 0.0, 1.0), (0, 0.2, -1.0)), R.Ram(0.04, min_arm=0.0)) + self.assertEqual([w[0] for w in edge.why], ["toggle"]) + self.assertLess(max(row[2] for row in edge.table), TOGGLE_ARM) def test_clash_and_which(self): m, ram = self.direct(-60, 0), R.Ram(0.05) - f = R.fit(m, ram, distance=Bodies(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.2)]), spacing=0.02) + thin = two(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.2)]) + f = R.fit(dressed(m, thin), ram, distance=thin, spacing=0.02) self.assertGreater(f.clear_min, 0.0) + thick = two(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.3)]) with self.assertRaises(R.RamError) as caught: - R.fit(m, ram, distance=Bodies(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.3)]), spacing=0.02) - self.assertEqual(caught.exception.gate, "clash") - self.assertIn("body parent", str(caught.exception)) - self.assertEqual(caught.exception.fit.clear_at[2], "parent") + R.fit(dressed(m, thick), ram, distance=thick, spacing=0.02) + refusal = caught.exception + self.assertEqual(refusal.gate, "clash") + self.assertIn("part 'parent' (parent)", str(refusal)) + self.assertEqual(refusal.fit.clear_at[2], "parent") + # the refusal names the angle and the nearer pin of the member + self.assertEqual(refusal.pin, refusal.fit.clear_at[3]) + self.assertIn(refusal.pin, ("a", "b")) + self.assertIn(f"clash at {refusal.angle:g} deg (pin {refusal.pin})", str(refusal)) # an obstacle that turns with the child is the same obstacle, turned, on the parent p, q = np.array((-0.2, -0.6, -0.9)), np.array((0.2, -0.6, -0.5)) wide = self.direct(-50, 35) - barrel = R._fit(wide, ram).barrel for angle in (-50.0, 0.0, 35.0): - on_child, where = R.clearance(wide, ram, barrel, angle, Bodies(child=[("capsule", p, q, 0.1)])) - on_parent, _ = R.clearance(wide, ram, barrel, angle, Bodies(parent=[("capsule", turned(p, angle), turned(q, angle), 0.1)])) - self.assertAlmostEqual(float(on_child[0]), float(on_parent[0]), places=9) - self.assertEqual(where[2], "child") - box = Bodies(parent=[("box", (-0.2, -0.36, -0.2), (0.2, -0.2, 0.2))]) - self.assertLess(R._fit(self.direct(-10, 0), ram, distance=box).clear_min, 0.0) + on_child, on_parent = two(child=[("capsule", p, q, 0.1)]), two(parent=[("capsule", turned(p, angle), turned(q, angle), 0.1)]) + mine, theirs = R.clearance(dressed(wide, on_child), ram, angle, on_child), R.clearance(dressed(wide, on_parent), ram, angle, on_parent) + self.assertAlmostEqual(float(mine.margin[0]), float(theirs.margin[0]), places=9) + self.assertEqual(mine.where[2], "child") + box = two(parent=[("box", (-0.2, -0.36, -0.2), (0.2, -0.2, 0.2))]) + self.assertLess(R._fit(dressed(self.direct(-10, 0), box), ram, distance=box).clear_min, 0.0) def test_search_tally_and_nearest_miss(self): ram, hinge = R.Ram(0.05), {"pivot": O, "axis": X, "lo": -70, "hi": 0} seats = {"a": grid((0, -0.5, 0.4), (0, -0.2, 1.2), (1, 3, 5)), "b": grid((0, -0.5, -1.2), (0, -0.2, -0.4), (1, 3, 5))} - pin = Bodies(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.18)]) - s = R.search("direct", hinge, ram, seats, distance=pin) + pin = two(parent=[("capsule", (-0.5, 0, 0), (0.5, 0, 0), 0.18)]) + s = R.search("direct", hinge, ram, seats, world=lambda m: (pin.parts, {}, pin)) self.assertTrue(s.found and s.best.ok and s.fits < s.tried == 225 and s.tally, s.report()) for a in seats["a"]: # no fitting pair has a larger least arm for b in seats["b"]: - f = R._fit(R.Mechanism("direct", O, X, -70, 0, a=a, b=b), ram, distance=pin) + f = R._fit(dressed(R.Mechanism("direct", O, X, -70, 0, a=a, b=b), pin), ram, distance=pin) self.assertTrue(not f.ok or f.arm_min <= s.best.arm_min + 1e-9) none = R.search("direct", {**hinge, "lo": -100}, ram, {"a": [(0, -0.1, 0.2)], "b": [(0, -0.1, -0.2)]}) self.assertFalse(none.found) @@ -216,6 +257,15 @@ class HandCases(unittest.TestCase): with self.assertRaises(R.RamError): R.swept(f, "rocker") + def test_swept_grows_by_the_margin_and_holds_a_trunnions_tail(self): + m = self.direct(-60, 0) + f = R.fit(m, R.Ram(0.05)) + bare, grown = R.swept(f, "parent"), R.swept(f, "parent", margin=0.02) + self.assertAlmostEqual(float(grown[:, 0].max() - bare[:, 0].max()), 0.02, places=12) # across the ram, along the axis + # a trunnion's barrel runs `tail` behind the base pin, here upward: the sweep reaches there + tail = R.swept(R._fit(m, R.Ram(0.05, tail=0.25)), "parent") + self.assertTrue(0.2 < float(tail[:, 2].max() - bare[:, 2].max()) <= 0.25) + @unittest.skipIf(np is None, "numpy is not installed") class Loop(unittest.TestCase): @@ -225,12 +275,12 @@ class Loop(unittest.TestCase): p = R.pose(m, np.linspace(-125, 0, 49)) n = np.array(X) # the coupler keeps its length, the rocker its own - self.assertLess(float(np.abs(np.linalg.norm(R._flat(p.P - p.C, n), axis=1) - m.lc).max()), 1e-9, kind) - self.assertLess(float(np.abs(np.linalg.norm(R._flat(p.P - m.rocker, n), axis=1) - m.lr).max()), 1e-9, kind) + self.assertLess(float(np.abs(np.linalg.norm(R._flat(p.P - p.C, n), axis=1) - m.lc).max()), LOOP_BOUND, kind) + self.assertLess(float(np.abs(np.linalg.norm(R._flat(p.P - m.rocker, n), axis=1) - m.lr).max()), LOOP_BOUND, kind) # the coupler body, carried by its angle from the rocker's pin, lands its c on the child's c for i, angle in enumerate(p.degrees): c_on_coupler = p.P[i] + R._flat(turned(m.c - m.p, math.degrees(p.psi[i]), O), n) - self.assertLess(float(np.linalg.norm(R._flat(c_on_coupler - turned(m.c, angle), n))), 1e-9, (kind, angle)) + self.assertLess(float(np.linalg.norm(R._flat(c_on_coupler - turned(m.c, angle), n))), LOOP_BOUND, (kind, angle)) # and the rest pose is the record's self.assertLess(float(np.abs(p.P[-1] - m.p).max()), 1e-12) self.assertLess(float(np.abs(p.eye[-1] - m.d).max()), 1e-12) @@ -254,7 +304,21 @@ class Loop(unittest.TestCase): p = R.pose(near, np.random.default_rng(6).permutation(np.linspace(-60, 60, 241))) side = np.cross(R._flat(p.C - near.rocker, n), R._flat(p.P - near.rocker, n)) @ n self.assertTrue((np.sign(side) == near.branch).all()) - self.assertLess(float(np.abs(side).min()), 1e-3) + self.assertLess(float(np.abs(side).min()), NEAR_BOUND) + + def test_swing_counts_a_rocker_past_half_a_turn(self): + # a drag link (ground 0.2, crank 0.6, rocker 0.7, coupler 0.55) turns its rocker with the crank, past 180 + # degrees from rest: the swing is the travel, the integral of dphi/dtheta, not the spread of wrapped angles + Rk, c, lr, lc, n = np.array((0, 0.2, 0.0)), np.array((0, 0.0, -0.6)), 0.7, 0.55, np.array(X) + span = np.linalg.norm(c - Rk) + x = (lr * lr - lc * lc + span * span) / (2 * span) + p = Rk + (c - Rk) / span * x + np.cross(n, (c - Rk) / span) * math.sqrt(lr * lr - x * x) + m = R.Mechanism("four_bar", O, X, -300, 0, a=(0, -1.5, 1.0), rocker=Rk, p=p, c=c, d=p) + f = R._fit(m, R.Ram(0.03), steps=121) + at = R.pose(m, np.linspace(-300, 0, 121)) + travel = abs(math.degrees(float(((at.dphi[1:] + at.dphi[:-1]) / 2 * np.diff(np.radians(at.degrees))).sum()))) + self.assertAlmostEqual(travel, 291.40, places=1) + self.assertLess(abs(f.swing - travel), SWING_BOUND) def test_assembly_refused_naming_the_angle(self): # the same loop with the child's pin 1 mm farther out: past 19 degrees the rocker and coupler cannot reach @@ -263,7 +327,8 @@ class Loop(unittest.TestCase): refusal = caught.exception self.assertEqual((refusal.kind, refusal.gate), ("four_bar", "assembly")) self.assertTrue(10.0 < refusal.angle < 20.0, refusal.angle) - self.assertIn(f"assembly at {refusal.angle:g} deg", str(refusal)) + self.assertEqual(refusal.pin, "c") + self.assertIn(f"assembly at {refusal.angle:g} deg (pin c)", str(refusal)) # a range that does not hold the rest pose is reached from rest: a dead centre on the way is refused, # though every angle of the range itself assembles far = near_dead_centre(reach=-1e-3, lo=30, hi=60) @@ -310,7 +375,7 @@ class Rates(unittest.TestCase): angles = np.linspace(-59.9, 19.9, 33) p = R.pose(m, angles) arm = np.array([np.array(X) @ np.cross(turned(m.b, t), (turned(m.b, t) - m.a) / np.linalg.norm(turned(m.b, t) - m.a)) for t in angles]) - self.assertLess(float(np.abs(p.dL - arm).max()), 1e-9) + self.assertLess(float(np.abs(p.dL - arm).max()), LEVER_BOUND) self.assertLess(float(np.abs(p.dL - self.central(m, angles, "L")).max()), RATE_BOUND) def test_load_is_the_coupler_force(self): @@ -322,12 +387,42 @@ class Rates(unittest.TestCase): k = R._flat(p.P - p.C, np.array(X)) k = k / np.linalg.norm(k, axis=1)[:, None] along = ((up.C - down.C) * k).sum(axis=1) / math.radians(2 * self.H) - self.assertLess(float(np.abs(p.load - np.abs(self.central(m, angles, "L") / along)).max()), 1e-5) + self.assertLess(float(np.abs(p.load - np.abs(self.central(m, angles, "L") / along)).max()), LOAD_WORK_BOUND) + + def test_transmission_at_p_is_the_angle_between_coupler_and_rocker(self): + m = r3("bell_crank", CRANK) + p = R.pose(m, np.linspace(-125, 0, 49)) + n = np.array(X) + k, link = R._flat(p.P - p.C, n), R._flat(p.P - m.rocker, n) + cos = np.abs((k * link).sum(axis=1)) / np.linalg.norm(k, axis=1) / np.linalg.norm(link, axis=1) + self.assertLess(float(np.abs(np.degrees(np.arccos(cos)) - p.mu_p).max()), MU_BOUND) + self.assertAlmostEqual(R._fit(m, R.Ram(BORE), steps=49).mu_p, 21.743, places=2) +# Each bound is the geometric mean of the shipped reading and the least mutant's (lodur:ruling:deterministic-bound-margin). # The greatest gap between a closed-form rate and its central difference (h 1e-4 deg), per radian. # Shipped 2.44e-10; M2 (the direct arm formula on a linkage, dphi/dtheta dropped) 0.741; separation 3.0e9. RATE_BOUND = 1.34e-5 +# Loop closure, the links' lengths and the coupler's far end: shipped 2.2e-16; the rocker and coupler lengths +# swapped in the circle crossing 0.141; separation 6.4e14. +LOOP_BOUND = 5.6e-9 +# The direct ram's dL/dtheta against the lever arm by hand: shipped 0 (the same arithmetic by a second route; 1e-16, +# one rounding, stands for it); the arm taken at the rest eye 0.776; separation 7.8e15. +LEVER_BOUND = 8.8e-9 +# Pin load against virtual work by central differences: shipped 3.19e-10; X5 (the moment arm taken as the crank's +# length) 0.857; separation 2.7e9. +LOAD_WORK_BOUND = 1.65e-5 +# The transmission angle at p against the angle by hand, degrees: shipped 2.0e-13; X14 (mu_p read from the crank's) +# 11.3; separation 5.7e13. +MU_BOUND = 1.5e-6 +# How near its dead centre the fixture loop comes (|side|, a fixture guard): reach 1e-6 reads 8.12e-4; the next +# coarser fixture, reach 1e-5, 2.57e-3; separation 3.2. +NEAR_BOUND = 1.44e-3 +# The drag link's swing against its travel, degrees: shipped 0.00 (to the 0.01 the test reads); X2 (no unwrap) 65.9; +# 0.01 stands for the shipped reading; separation 6.6e3. +SWING_BOUND = 0.81 +# The greatest arm past the dead centre of the edge toggle case: shipped 0.0149; X12's threshold 0.1; separation 6.7. +TOGGLE_ARM = 0.0386 @unittest.skipIf(np is None, "numpy is not installed") @@ -353,8 +448,8 @@ class DeepKnee(unittest.TestCase): with self.assertRaises(R.RamError) as caught: R.fit(m, R.Ram(BORE, max_load=LOAD_GATE), steps=49) refusal = caught.exception - self.assertEqual((refusal.kind, refusal.gate), ("four_bar", "load")) - self.assertIn("load at", str(refusal)) + self.assertEqual((refusal.kind, refusal.gate, refusal.pin), ("four_bar", "load", "c")) + self.assertIn(f"load at {refusal.angle:g} deg (pin c)", str(refusal)) self.assertTrue(R.fit(m, R.Ram(BORE), steps=49).ok) def test_the_same_seats_as_a_direct_ram_are_refused(self): @@ -365,71 +460,84 @@ class DeepKnee(unittest.TestCase): self.assertEqual(caught.exception.gate, "arm") # and no direct seat of a wide grid behind the knee fits 0..-125 (P1), while the joint library's fits 0..-62 ram = R.Ram(BORE) - bodies = Bodies(parent=R3_THIGH, child=R3_SHIN) + bodies = two(R3_THIGH, R3_SHIN) + world = lambda m: (bodies.parts, {}, bodies) wide = {"a": grid((0, -0.40, 0.35), (0, -0.16, 1.3), (1, 5, 10)), "b": grid((0, -0.40, -0.85), (0, -0.14, -0.25), (1, 5, 8))} - self.assertFalse(R.search("direct", {"pivot": O, "axis": X, "lo": -125, "hi": 0}, ram, wide, distance=bodies).found) + self.assertFalse(R.search("direct", {"pivot": O, "axis": X, "lo": -125, "hi": 0}, ram, wide, world=world).found) seats = {"a": grid((0, -0.36, 0.45), (0, -0.24, 1.05), (1, 3, 6)), "b": grid((0, -0.34, -0.85), (0, -0.2, -0.35), (1, 3, 6))} - found = R.search("direct", {"pivot": O, "axis": X, "lo": -62, "hi": 0}, ram, seats, distance=bodies) + found = R.search("direct", {"pivot": O, "axis": X, "lo": -62, "hi": 0}, ram, seats, world=world) self.assertTrue(found.found and found.best.clear_min >= 0.0, found.report()) def test_third_body(self): # the four-bar's ram spans the thigh and the rocker; at -125 the shin has folded into it (P3's mesh check) m, ram = r3("four_bar", DEEP), R.Ram(BORE) + bodies, touch = r3_bodies(m, ram) with self.assertRaises(R.RamError) as caught: - R.fit(m, ram, steps=49, distance=r3_bodies(m, ram)) + R.fit(dressed(m, bodies, touch), ram, steps=49, distance=bodies) refusal = caught.exception self.assertEqual((refusal.kind, refusal.gate), ("four_bar", "clash")) - self.assertEqual(refusal.fit.clear_at[2], "child") - self.assertIn("barrel", refusal.fit.clear_at[1]) - self.assertIn("body child", str(refusal)) + self.assertEqual(refusal.fit.clear_at[2], "shin") + self.assertIn(refusal.fit.clear_at[1], ("barrel[0]", "rod[0]")) + self.assertIn("part 'shin' (child)", str(refusal)) self.assertLess(refusal.angle, -100.0) - # against the thigh and the rocker alone, the two bodies the ram spans, the same ram is clear - two = r3_bodies(m, ram) - del two.shapes["child"], two.shapes["coupler"] - margin, _ = R.clearance(m, ram, refusal.fit.barrel, np.linspace(-125, 0, 49), two) - self.assertGreaterEqual(float(margin.min()), 0.0) + self.assertLess(refusal.fit.pairs[("barrel[0]", "shin")][0], 0.0) + # with the shin and the coupler's parts emptied, the thigh and the rocker the ram spans leave it clear + for part in ("shin", "coupler plates", "pin c"): + bodies.shapes[part] = [] + self.assertGreaterEqual(float(R.clearance(dressed(m, bodies, touch), ram, np.linspace(-125, 0, 49), bodies).margin.min()), 0.0) - def test_a_link_body_in_the_rams_way(self): - # a gusset on the bell crank's rocker, between its plates where the ram runs: refused naming the rocker + def test_a_part_in_the_rams_way_on_each_link(self): + # a lug on the rocker, then on the coupler, where the rod runs at -60: refused naming the part and its + # body, unless the record lets the rod and the barrel touch it; letting another member touch it changes nothing m, ram = r3("bell_crank", CRANK), R.Ram(BORE) - bodies = r3_bodies(m, ram) - rest = R.pose(m, 0.0) - web = rest.eye[0] - 0.06 * rest.u[0] # on the rod's line at rest, clear of the eye's clevis - bodies.shapes["rocker"].append(("capsule", web - (0.1, 0, 0), web + (0.1, 0, 0), 0.02)) - with self.assertRaises(R.RamError) as caught: - R.fit(m, ram, steps=49, distance=bodies) - self.assertEqual(caught.exception.gate, "clash") - self.assertEqual(caught.exception.fit.clear_at[2], "rocker") - self.assertIn(caught.exception.fit.clear_at[1], ("rod[0]", "barrel[0]")) - self.assertIn("body rocker", str(caught.exception)) + at = R.pose(m, -60.0) + on_rod = (at.eye - 0.12 * at.u)[:, None, :] + for body in ("rocker", "coupler"): + bodies, touch = r3_bodies(m, ram) + spot = R._into(m, at, body, on_rod)[0, 0] + bodies.parts["lug"], bodies.shapes["lug"] = body, [("capsule", spot - (0.1, 0, 0), spot + (0.1, 0, 0), 0.02)] + for allowed in ({}, {"coupler": touch["coupler"] + ["lug"]}): + with self.assertRaises(R.RamError) as caught: + R.fit(dressed(m, bodies, {**touch, **allowed}), ram, steps=49, distance=bodies) + self.assertEqual((caught.exception.gate, caught.exception.fit.clear_at[2]), ("clash", "lug"), body) + self.assertIn(caught.exception.fit.clear_at[1], ("rod[0]", "barrel[0]")) + self.assertIn(f"part 'lug' ({body})", str(caught.exception)) + free = {**touch, "rod": touch["rod"] + ["lug"], "barrel": touch["barrel"] + ["lug"]} + f = R.fit(dressed(m, bodies, free), ram, steps=49, distance=bodies) + self.assertIn(("rod[0]", "lug"), f.allowed) + self.assertIn(("rocker arm", "lug"), f.pairs) - def test_bell_crank_seats_and_clears_every_body(self): - # the bell crank stands in front of the knee: over 0..-125 its ram, rocker and coupler clear the thigh, the - # shin, and each other's bodies, with the links' plates on either side + def test_bell_crank_clears_every_part_it_may_not_touch(self): + # the bell crank stands in front of the knee, its plates at the probe's stack: over 0..-125 the gate meets + # every member with every part but those the record lets it touch, on either side, and all are clear ram = R.Ram(BORE) for side in (1.0, -1.0): m = r3("bell_crank", CRANK, side) - bodies = r3_bodies(m, ram) + bodies, touch = r3_bodies(m, ram) + m = dressed(m, bodies, touch) f = R.fit(m, ram, steps=49, distance=bodies) self.assertGreaterEqual(f.clear_min, 0.0) self.assertAlmostEqual(f.swing, 105.732, places=2) self.assertAlmostEqual(f.l_min, 0.6593, places=3) self.assertAlmostEqual(f.l_max, 1.0376, places=3) - # every member met every body but its own, the shin among them, at -125 as at every step - fine = np.linspace(-125, 0, 251) - seen = {} - for name, start, end, radius, own in R._members(m, ram, f.barrel, R.pose(m, fine)): - for body in R.BODIES["bell_crank"]: - if body == own: - continue - pts = start[:, None, :] + (end - start)[:, None, :] * np.linspace(0, 1, 40)[None, :, None] - got = bodies(body, R._into(m, R.pose(m, fine), body, pts).reshape(-1, 3)).reshape(len(fine), 40) - seen[(name, body)] = float(got.min() - radius - ram.gap) - at_deep = float(got[0].min() - radius - ram.gap) - self.assertGreaterEqual(at_deep, 0.0, (name, body, "at -125")) - self.assertEqual(len(seen), 2 * 4 + 3 * 3) # barrel and rod meet four bodies; three bars meet three - self.assertGreaterEqual(min(seen.values()), 0.0, min(seen, key=seen.get)) - self.assertEqual(sum(1 for _, body in seen if body == "child"), 5) + members = ("barrel[0]", "rod[0]", "rocker", "coupler", "rocker arm") + let = {(label, part) for label in members for part in touch[label.split("[")[0]]} + self.assertEqual(set(f.allowed), let) + self.assertEqual(len(let), 1 + 1 + 5 + 4 + 4) # the ram its eye's pin; rocker, coupler and arm theirs + self.assertEqual(set(f.pairs), {(label, part) for label in members for part in bodies.parts} - let) + self.assertEqual(len(f.pairs), 5 * 8 - 15) + self.assertEqual(sum(1 for _, part in f.pairs if part == "shin"), 5) + self.assertEqual(sum(1 for _, part in f.pairs if bodies.parts[part] == "coupler"), 2 * 2 + 1 + 2) # the rocker may touch the plates beside it on p + self.assertGreaterEqual(min(v[0] for v in f.pairs.values()), 0.0) + self.assertGreaterEqual(float(R.clearance(m, ram, np.linspace(-125, 0, 251), bodies).margin.min()), 0.0) + # asked for the fit's own angles, clearance reads what the fit read + same = R.clearance(m, ram, f.degrees, bodies) + self.assertEqual((same.pairs, same.where, sorted(same.allowed)), (f.pairs, f.clear_at, sorted(f.allowed))) + # with nothing let, the gate refuses, and only pairs the record lets: the pins a member rides + bare = R._fit(replace(m, touch={}), ram, steps=49, distance=bodies) + refused = {pair for pair, reading in bare.pairs.items() if reading[0] < 0.0} + self.assertTrue(refused and refused <= let, refused - let) + self.assertEqual(len(bare.pairs), 40) # The R-3 four-bar's readings over 0..-125 at 49 steps, each bound the geometric mean of the shipped reading and @@ -448,44 +556,77 @@ class OracleRule(unittest.TestCase): self.barrel = R._fit(self.m, self.ram).barrel def ball(self, at, r, cap=None): - return Bodies(cap, parent=[("capsule", at, at, r)]) + return two(parent=[("capsule", at, at, r)], cap=cap) def test_need_is_radius_gap_and_half_the_spacing(self): # a ball beside a sample of the barrel at rest, its surface at the need less or more a micron ram, spacing = self.ram, 0.05 p = R.pose(self.m, 0.0) - members = {name: (start, end, radius) for name, start, end, radius, _ in R._members(self.m, ram, self.barrel, p)} + members = {label: (start, end, radius) for _, label, start, end, radius, _ in R._members(self.m, ram, self.barrel, p)} start, end, radius = members["barrel[0]"] count = int(math.ceil(float(np.linalg.norm(end - start)) / spacing)) + 1 sample = (start + (end - start) * (3 / (count - 1)))[0] need = radius + ram.gap + spacing / 2 for slip, clear in ((-1e-6, False), (1e-6, True)): centre = sample + np.array((0.0, -(need + slip + 0.2), 0.0)) - margin, where = R.clearance(self.m, ram, self.barrel, 0.0, self.ball(centre, 0.2), spacing) - self.assertEqual(bool(margin[0] >= 0.0), clear, (slip, margin)) - self.assertAlmostEqual(float(margin[0]), slip, places=9) - self.assertEqual(where, (0.0, "barrel[0]", "parent")) + ball = self.ball(centre, 0.2) + c = R.clearance(dressed(self.m, ball), ram, 0.0, ball, spacing) + self.assertEqual(bool(c.margin[0] >= 0.0), clear, (slip, c.margin)) + self.assertAlmostEqual(float(c.margin[0]), slip, places=9) + self.assertEqual(c.where, (0.0, "barrel[0]", "parent", "a")) # sample 3 of the barrel: nearer the base self.assertAlmostEqual(ram.reach(spacing), need, places=15) - def test_clevis_ends_are_exempt(self): - # a ball on the base pin and one on the eye touch no sample: the barrel starts e_a from the base, the rod - # stops 0.4 e_b short of the eye + def test_touch_is_the_only_exemption(self): + # a clevis on the base pin and one on the eye, each a part: with nothing let they refuse the ram at its own + # pins; let to the member that rides the pin they are skipped; let to the other member they still refuse ram = self.ram - for at, r in ((self.m.a, ram.e_a - ram.barrel_r - ram.gap - ram.barrel_r / 2 - 1e-6), (self.m.b, 0.4 * ram.e_b - ram.rod - ram.gap - ram.barrel_r / 2 - 1e-6)): - margin, _ = R.clearance(self.m, ram, self.barrel, 0.0, self.ball(np.array(at, float), r)) - self.assertGreaterEqual(float(margin[0]), 0.0) - margin, _ = R.clearance(self.m, ram, self.barrel, 0.0, self.ball(np.array(at, float), r + 2e-6)) - self.assertLess(float(margin[0]), 0.0) + seats = two(a=("parent", [("capsule", self.m.a, self.m.a, 0.03)]), b=("child", [("capsule", self.m.b, self.m.b, 0.03)])) + bare = R.clearance(dressed(self.m, seats), ram, 0.0, seats) + self.assertLess(bare.pairs[("barrel[0]", "a")][0], 0.0) + # the rod runs to the eye: its last sample is the pin's centre, the ball's depth inside it + self.assertAlmostEqual(bare.pairs[("rod[0]", "b")][0], -0.03 - (ram.rod + ram.gap + ram.barrel_r / 2), places=12) + self.assertEqual(bare.allowed, []) + let = R.clearance(dressed(self.m, seats, {"barrel": ["a"], "rod": ["b"]}), ram, 0.0, seats) + self.assertGreaterEqual(float(let.margin[0]), 0.0) + self.assertEqual(sorted(let.allowed), [("barrel[0]", "a"), ("rod[0]", "b")]) + self.assertEqual(len(let.pairs), 2 * 4 - 2) + crossed = R.clearance(dressed(self.m, seats, {"barrel": ["b"], "rod": ["a"]}), ram, 0.0, seats) + self.assertLess(float(crossed.margin[0]), 0.0) + + def test_every_body_owns_a_part(self): + ball = Bodies({"ball": ("parent", [("capsule", (0, 0, 0), (0, 0, 0), 0.1)])}) + with self.assertRaises(R.RamError) as caught: + R.fit(dressed(self.m, ball), self.ram, distance=ball) + self.assertEqual(caught.exception.gate, "record") + self.assertIn("no part turns with body child", str(caught.exception)) + + def test_inside_a_part_is_negative_however_deep(self): + # a ram down the core of a thick box (Soul's buried ram): every sample is deeper inside than the oracle's + # cap, and reads its depth, negative; the cap changes nothing inside + m = R.Mechanism("direct", O, X, -10, 0, a=(0, 0.0, 1.1), b=(0, 0.0, -0.5)) + ram = R.Ram(BORE) + core = [("box", (-0.13, -0.14, 0.3), (0.13, 0.14, 1.15))] + self.assertGreater(0.13, ram.reach()) + for cap in (None, ram.reach()): + thigh = two(core, cap=cap) + self.assertAlmostEqual(float(thigh("parent", np.array([(0.0, 0.0, 0.7)]))[0]), -0.13, places=12) + self.assertAlmostEqual(float(thigh("parent", np.array([(0.11, 0.0, 0.7)]))[0]), -0.02, places=12) + c = R.clearance(dressed(m, thigh), ram, 0.0, thigh) + self.assertAlmostEqual(c.pairs[("barrel[0]", "parent")][0], -0.13 - (ram.barrel_r + ram.gap + ram.barrel_r / 2), places=9) + # an oracle that answers nan is refused + with self.assertRaises(R.RamError) as caught: + R.clearance(dressed(m, thigh), ram, 0.0, lambda part, pts: np.full(len(pts), math.nan)) + self.assertEqual(caught.exception.gate, "oracle") def test_a_capped_oracle_gives_the_same_verdicts(self): ram = R.Ram(BORE) asked = [] for kind, pins in (("four_bar", DEEP), ("bell_crank", CRANK)): m = r3(kind, pins) - barrel = R._fit(m, ram, steps=49).barrel angles = np.linspace(-125, 0, 49) - free, _ = R.clearance(m, ram, barrel, angles, r3_bodies(m, ram)) - capped, _ = R.clearance(m, ram, barrel, angles, r3_bodies(m, ram, cap=ram.reach())) + bodies, touch = r3_bodies(m, ram) + free = R.clearance(dressed(m, bodies, touch), ram, angles, bodies).margin + capped = R.clearance(dressed(m, bodies, touch), ram, angles, r3_bodies(m, ram, cap=ram.reach())[0]).margin self.assertEqual((free >= 0.0).tolist(), (capped >= 0.0).tolist(), kind) self.assertTrue(np.allclose(np.minimum(free, 0.0), np.minimum(capped, 0.0), atol=1e-12)) asked.append(bool((free < 0.0).any())) @@ -507,9 +648,9 @@ class SearchBestFirst(unittest.TestCase): mid = R.pose(best, 0.0) away = math.copysign(0.14, arms[-1][1][1] - arms[-2][1][1]) centre = mid.base[0] + 0.05 * (mid.eye[0] - mid.base[0]) + np.array((0.0, away, 0.0)) - block = Bodies(parent=[("capsule", centre, centre, 0.07)]) - found = R.search("direct", self.HINGE, ram, seats, distance=block) - clear = [a for _, a in arms if R._fit(R.Mechanism("direct", O, X, -60, 0, a=a, b=seats["b"][0]), ram, distance=block).ok] + block = two(parent=[("capsule", centre, centre, 0.07)]) + found = R.search("direct", self.HINGE, ram, seats, world=lambda m: (block.parts, {}, block)) + clear = [a for _, a in arms if R._fit(dressed(R.Mechanism("direct", O, X, -60, 0, a=a, b=seats["b"][0]), block), ram, distance=block).ok] self.assertTrue(clear and arms[-1][1] not in clear, clear) self.assertTrue(found.found) self.assertEqual(tuple(found.seat["a"]), clear[-1]) # the best arm of those that are clear @@ -535,37 +676,101 @@ class SearchBestFirst(unittest.TestCase): crank = R.candidates("bell_crank", hinge, {**seats, "d": (0.12, 0.24, 3)}) self.assertEqual(len(crank), 2 * 5 * 24 * 3 * 12) + def test_a_candidates_own_links_are_its_bodies(self): + # a bell-crank grid about the probe's, each candidate met with the parts its own pins place: its plates, + # axle and pins. The winner has met them; a world that leaves a link without a part is refused + ram = R.Ram(BORE) + hinge = {"pivot": O, "axis": X, "lo": -125, "hi": 0} + seats = {"rocker": [yz(CRANK["rocker"], X_ROCKER)], "c": [yz(CRANK["c"], X_COUPLER)], "a": [yz(CRANK["a"])], "link": (0.5, 0.5, 1), "d": (0.2, 0.26, 2)} + pins = R.candidates("bell_crank", hinge, seats) + self.assertEqual(len(pins), 24 * 2 * 12) + self.assertTrue(all(seat["d"][0] == seat["a"][0] and seat["p"][0] == X_ROCKER for seat in pins)) # the ram runs across the axis + seen = [] + + def world(m): + bodies, touch = r3_bodies(m, ram) + seen.append(m) + return bodies.parts, touch, bodies + found = R.search("bell_crank", hinge, ram, seats, world=world, steps=49) + self.assertTrue(found.found and found.best.ok, found.report()) + self.assertEqual(len(seen), found.tally.get("clash", 0) + 1) # a world for each candidate the gate met + self.assertTrue(np.array_equal(seen[-1].p, found.best.m.p) and np.array_equal(seen[-1].d, found.best.m.d)) + for pair in (("rod[0]", "rocker plates"), ("barrel[0]", "pin p"), ("rocker arm", "coupler plates"), ("coupler", "pin d"), ("rocker", "shin")): + self.assertGreaterEqual(found.best.pairs[pair][0], 0.0, pair) + bodies, touch = r3_bodies(found.best.m, ram) + self.assertTrue(R.fit(dressed(found.best.m, bodies, touch), ram, steps=49, distance=bodies).ok) + thigh_and_shin = two(R3_THIGH, R3_SHIN) + with self.assertRaises(R.RamError) as caught: + R.search("bell_crank", hinge, ram, seats, world=lambda m: (thigh_and_shin.parts, {}, thigh_and_shin), steps=49) + self.assertIn("no part turns with body rocker", str(caught.exception)) + @unittest.skipIf(np is None, "numpy is not installed") class RecordDrives(unittest.TestCase): def test_round_trip_and_drive(self): ram = R.Ram(BORE) - for m in (r3("four_bar", DEEP), r3("bell_crank", CRANK), R.Mechanism("direct", O, X, -62, 0, a=(0.05, -0.3, 0.8), b=(0.05, -0.3, -0.6), offsets=(-0.1, 0.1))): + crank = r3("bell_crank", CRANK) + bodies, touch = r3_bodies(crank, ram) + for m in (r3("four_bar", DEEP), dressed(crank, bodies, touch), R.Mechanism("direct", O, X, -62, 0, a=(0.05, -0.3, 0.8), b=(0.05, -0.3, -0.6), offsets=(-0.1, 0.1))): f = R.fit(m, ram, steps=49) - data = R.record(m, ram, f.barrel) + data = R.record(m, ram) wire = json.loads(json.dumps(data)) self.assertEqual(wire, data) - again, ram2, barrel = R.from_record(wire) - self.assertEqual(R.record(again, ram2, barrel), data) + self.assertEqual(sorted(data), ["compliance", "hinge", "kind", "offsets", "parts", "pins", "ram", "schema", "touch", "version"]) + self.assertEqual((data["schema"], data["version"], data["compliance"]), ("brokkr.ram", 1, None)) + again, ram2 = R.from_record(wire) + self.assertEqual(R.record(again, ram2), data) + self.assertEqual((again.parts, again.touch), (m.parts, {k: tuple(v) for k, v in m.touch.items()})) angles = np.linspace(m.lo, m.hi, 49) self.assertEqual(R.length(again, angles).tolist(), R.length(m, angles).tolist()) - ext = R.extension(again, ram2, barrel, angles) - self.assertEqual(ext.tolist(), (R.length(m, angles) - data["closed"]).tolist()) + ext = R.extension(again, ram2, angles) + self.assertEqual(ext.tolist(), (R.length(m, angles) - f.closed).tolist()) # the extension follows the angle: home plus the overtravel at the short end, travel more at the long self.assertAlmostEqual(float(ext.min()), ram.over, places=12) self.assertAlmostEqual(float(ext.max()), ram.over + f.travel, places=12) self.assertGreater(abs(float(ext[0] - ext[-1])), 0.3) - self.assertAlmostEqual(data["closed"], f.closed, places=15) + self.assertEqual(R.barrel_length(again, ram2), f.barrel) + + def test_nothing_derived_is_stored(self): + # the barrel comes from the pins and the ram: a record whose overtravel is edited drives a rod that keeps + # the new overtravel, and a trunnion's tail rides the record + m = R.Mechanism("direct", O, X, -62, 0, a=(0.05, -0.3, 0.8), b=(0.05, -0.3, -0.6)) + data = R.record(m, R.Ram(BORE, tail=0.2)) + self.assertEqual(data["ram"]["tail"], 0.2) + again, ram = R.from_record(data) + self.assertEqual((ram.tail, ram.back), (0.2, -0.2)) + self.assertAlmostEqual(R.barrel_length(again, ram) - R.barrel_length(m, R.Ram(BORE)), 0.2 + R.Ram(BORE).e_a, places=12) + data["ram"]["over"] = 2.0 * data["ram"]["over"] + again, ram = R.from_record(data) + self.assertAlmostEqual(float(R.extension(again, ram, np.linspace(-62, 0, 49)).min()), data["ram"]["over"], places=12) + + def test_a_record_this_version_cannot_read_is_refused_whole(self): + data = R.record(R.Mechanism("direct", O, X, -62, 0, a=(0.05, -0.3, 0.8), b=(0.05, -0.3, -0.6)), R.Ram(BORE)) + settle = {"stiffness": 2.0e6, "damping": 4.0e3, "travel": 0.02} + self.assertEqual(tuple(settle), R.COMPLIANCE) + ram = dict(data["ram"], stiffness=2.0e6) + short = {k: v for k, v in data.items() if k != "touch"} + for change, said in (({"version": 2}, "version 2"), ({"version": 2, "compliance": settle}, "version 2"), ({"compliance": settle}, "compliance block"), + ({"schema": "brokkr.kit"}, "brokkr.kit"), ({"settle": settle}, "unknown ['settle']"), ({"ram": ram}, "unknown ['stiffness']"), + ({"hinge": dict(data["hinge"], rate=1.0)}, "unknown ['rate']")): + with self.assertRaises(R.RamError) as caught: + R.from_record({**data, **change}) + self.assertEqual(caught.exception.gate, "record", change) + self.assertIn(said, str(caught.exception)) + with self.assertRaises(R.RamError) as caught: + R.from_record(short) + self.assertIn("missing ['touch']", str(caught.exception)) + self.assertEqual(R.from_record(data)[0].kind, "direct") def test_offsets_stand_the_ram_along_the_axis(self): m = R.Mechanism("direct", O, X, -60, 0, a=(0, -0.3, 1.0), b=(0, -0.3, -1.0), offsets=(-0.2, 0.2)) ram = R.Ram(0.05) - barrel = R._fit(m, ram).barrel # a ball beside the twin at +0.2 only - ball = Bodies(parent=[("capsule", (0.2, -0.45, 0.5), (0.2, -0.45, 0.5), 0.06)]) - margin, where = R.clearance(m, ram, barrel, 0.0, ball) - self.assertLess(float(margin[0]), 0.0) - self.assertEqual(where[1], "barrel[0.2]") + ball = two(parent=[("capsule", (0.2, -0.45, 0.5), (0.2, -0.45, 0.5), 0.06)]) + c = R.clearance(dressed(m, ball), ram, 0.0, ball) + self.assertLess(float(c.margin[0]), 0.0) + self.assertEqual(c.where[1], "barrel[0.2]") + self.assertGreaterEqual(c.pairs[("barrel[-0.2]", "parent")][0], 0.0) @unittest.skipIf(np is None, "numpy is not installed") @@ -582,9 +787,12 @@ class Refusals(unittest.TestCase): def test_every_record_refusal(self): self.refused("record", kind="scissor") self.refused("record", "axis", axis=(1.0, 0.1, 0.0)) - self.refused("record", lo=0, hi=0) - self.refused("record", lo=-200, hi=200) - self.refused("record", offsets=()) + self.assertEqual(self.refused("record", lo=0, hi=0).angle, 0.0) # a range's refusal names its lo + self.assertEqual(self.refused("record", lo=-200, hi=200).angle, -200.0) + self.refused("record", "a", offsets=()) # the ram stands along the axis from a + self.assertIn("'knee' turns with 'foot'", str(self.refused("record", parts={"knee": "foot"}))) + self.assertIn("touch names 'piston'", str(self.refused("record", parts={"knee": "parent"}, touch={"piston": ["knee"]}))) + self.assertIn("rod may touch 'hip'", str(self.refused("record", parts={"knee": "parent"}, touch={"rod": ["hip"]}))) self.refused("record", "a", a=(0, 1)) self.refused("record", "c", c=(0, float("nan"), 1)) self.refused("record", "b", b=(0, 0, -1)) # a four-bar has no b @@ -605,8 +813,8 @@ class Refusals(unittest.TestCase): m = R.Mechanism("direct", O, X, -30, 0, a=(0, -0.05, 1.0), b=(0, -0.05, -1.0)) with self.assertRaises(R.RamError) as caught: R.fit(m, R.Ram(0.05)) - self.assertEqual(caught.exception.gate, "arm") - self.assertIn("arm at", str(caught.exception)) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("arm", "b")) + self.assertIn(f"arm at {caught.exception.angle:g} deg (pin b)", str(caught.exception)) def test_no_blender(self): source = (SURFACE / "brokkr_kitbash" / "ram.py").read_text(encoding="utf-8") From 2678c09101eb92f267f3292cf0ab6931c07bce80 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 19:01:38 +0100 Subject: [PATCH 135/223] docs/kitbash.md: Rams and linkages: parts and touch, the signed oracle, the record, R-3 readings on meshes, costs with their conditions Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 99 ++++++++++++++++++++++---------- 1 file changed, 70 insertions(+), 29 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 74e2bdd..55c9cf6 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -799,49 +799,90 @@ its member stands: the rocker bars at R's, the coupler at `c`'s, the ram at `a`' Rates are closed form: for a linkage dphi/dtheta = (axis x (c - O)) . k / ((axis x (p - R)) . k), k along the coupler, and dL/dtheta = (axis x (d - R)) . u x dphi/dtheta, u along the ram. -`fit` runs the gates over the range, in this order, and a failed gate is a `RamError` naming the kind, the gate -and the angle or pin, with the readings attached: +`fit` runs the gates over the range, in this order. A failed gate is a `RamError` naming the kind, the gate, the +angle and the pin, with the readings attached; a refusal of the record or of a call (an unknown kind, a range, a +grid over the limit, a version) names the pin or the field it refuses. - **assembly**: the rocker and coupler close the loop at every step, and on the way from rest when the range does - not hold 0; within 1e-9 of a dead centre is refused, since the branch would change there. -- **stroke**: barrel = L_min - over - back - e_b, and it holds the travel, the overtravel at both ends and the gland. + not hold 0; within 1e-9 of a dead centre is refused, since the branch would change there. Names `c`. +- **stroke**: the barrel holds the travel, the overtravel at both ends and the gland. Names the angle of the + shortest length and the eye's pin. - **toggle**, **arm**: dL/dtheta keeps one sign, and |dL/dtheta| (the effective arm: hinge torque per unit ram - force) stays at or above `min_arm`. + force) stays at or above `min_arm`. Name the eye's pin. - **load** (linkages): the coupler's pin load per unit ram force, |dL/dtheta| over the coupler's moment arm about - the hinge, stays at or under `max_load` (3). -- **clash**: clearance, when a distance oracle is given. + the hinge, stays at or under `max_load` (3). Names `c`. +- **clash**: clearance, when a distance oracle is given. Names the member, the part, and the member's nearer pin. + +The barrel is derived, never stored: `barrel_length` is the length at the shorter end of the range less the +overtravel, the base clevis and the eye, and `fit` reads it from its own two end samples. Transmission angles at `c` and `p` are reported and not gated. Over the R-3 knee's 125 degrees the best least transmission angle of 200,000 sampled four-bars was 21.9 degrees, under the 30 to 40 a textbook asks; a gate there would have refused every one of them. What a poor angle costs is pin load, and that is the gate. -Clearance takes `distance(body, points) -> distances`: `body` one of parent, child, rocker, coupler, `points` in -that body's rest frame. The barrel, the rod (per offset) and the link bars are sampled along their axes at most -`spacing` apart (default the barrel's radius) and carried into every body's rest frame at each angle but their -own; a sample is clear at radius + gap + spacing / 2 or more, which keeps the gap for the surface between samples. -Only the clevis ends are left out: `e_a` at the ram's base, 0.4 `e_b` at its eye, 1.5 `link_r` at a link's pins; -the pin a clevis turns on is not part of the body the oracle answers for. The oracle may cap what it returns at -`Ram.reach(spacing)`: on the R-3 meshes (3,564 triangles) a BVH nearest query capped there cost 0.55 us against -3.12 us uncapped. A four-bar at the default spacing asks 155 points an angle. +### Clearance: parts and what a member may touch + +The record names the mechanism's `parts`, each a piece of one body (part -> parent, child, rocker or coupler: the +body whose rest frame it turns with), and `touch`: for each member (`barrel`, `rod`, `rocker`, `coupler`, and a +bell crank's `rocker arm`), the parts it may touch. This is the allowed-collision matrix of motion planning +(MoveIt's ACM): a pair listed there is skipped whole and every other (member, part) pair is checked. A member may +touch what it is pinned to and what is stacked on its pins: the pin, its own eye and clevis, its own plates, the +plates beside it on that pin, the bracket or horn the pin stands in. Nothing is exempt by a name, by a length cut +from a member's end, or by the member's own body: the barrel runs from its back end, the rod to the eye, a bar +from pin to pin. Every body of the kind owns at least one part, or the gate refuses the record. + +What it gives up: a pair in `touch` is not checked anywhere, so a coupler let touch the horn that carries `c` may +also pass through that horn's far end unseen. Parts are the grain: cut a body into the piece that carries the pin +and the rest, and let only the first. + +The oracle is `distance(part, points) -> distances`, `points` in the rest frame of the part's body. Each member is +sampled along its axis at most `spacing` apart (default the barrel's radius) and carried into each body's rest +frame at each angle; a sample is clear at radius + gap + spacing / 2 or more, which keeps the gap for the surface +between samples. A distance is signed: negative inside a part, by any depth. The oracle may cap what it returns at +`Ram.reach(spacing)`, outside a part only; a point inside reads negative however deep it lies. An oracle that +cannot tell inside from outside raises instead of answering (a nearest-surface query alone reads 0.13 at the +centre of the R-3 thigh's core, and reads clear when capped); nan is refused. `Fit.pairs` holds the least margin +and its angle for every pair checked, `Fit.allowed` every pair skipped. `search` seats a mechanism from a grid (ram seats; for linkages rocker pivots, child pins, `p` on a polar grid -about R, and `d` about R for a bell crank), refuses a grid over `limit` candidates naming the count, runs every -gate but clearance on all of them, then clearance in order of least arm; a miss returns the tally by gate and the -nearest miss. `record` and `from_record` carry a fitted mechanism as JSON; `swept` gives the ram's swept surface in -any body's frame, for a recess. +about R, and `d` about R for a bell crank, the eye standing at `a`'s place along the axis), refuses a grid over +`limit` candidates naming the count, runs every gate but clearance on all of them, then clearance in order of +least arm; a miss returns the tally by gate and the nearest miss. Clearance takes `world(m) -> (parts, touch, +distance)`: a linkage's brackets and links are the candidate's own, so each candidate that reaches the gate is met +with the parts its own pins place. `swept` gives the ram's swept surface in any body's frame, for a recess. -Readings on the R-3 knee (bore 0.042, tests/test_ram.py; bodies as boxes and cylinders, links as twin plates -outside the shin's side armour): +### The record -| drive | range | reading | -| --- | --- | --- | -| direct, the joint library's seats | 0..-62 | fits | -| direct, 2,000 seat pairs behind the knee | 0..-125 | none fits | -| four-bar behind the knee | 0..-125 | passes every gate before clearance: rocker swing 70.5, L 0.722..1.168, arm 0.096..0.265, pin load 1.61, transmission 16.5; refused on clearance: at -125 the barrel is inside the shin, a body the ram is not pinned to | -| bell crank in front of the knee | 0..-125 | fits: rocker swing 105.7, L 0.659..1.038, arm 0.091..0.215, pin load 1.13, transmission 13.8; ram and links clear the thigh, the shin and each other's bodies on both sides, least 0.109 beyond radius and gap to the shin (the coupler at -125) | +`record` and `from_record` carry a mechanism as JSON: `schema` (`brokkr.ram`), `version` (1), `kind`, `hinge`, +`pins`, `offsets`, `ram`, `parts`, `touch`, and `compliance`. It holds what is authored; barrel, closed length and +link lengths are derived by the reader. `compliance` is reserved for a load-path ram's settle (stiffness, damping, +travel); version 1 writes it null and solves none. A record of another schema or version, with a key version 1 +does not know (at the top, in `ram` or in `hinge`), or with a compliance block is refused whole: a reader never +reads past what it cannot solve. -One candidate's gates before clearance cost 1.7 to 3.8 ms at 49 steps on Starfire (median 3.6 of five reps of 200 -under other load); `limit` (20,000) is about a minute of them. +### Readings on the R-3 knee + +Bore 0.042, range 0..-125. The kinematic rows are tests/test_ram.py's. The clearance rows are Blender 5.3 readings +on meshes built with the joint library the knee was drawn with (thigh with its front plate, shin with caps and +armour, the bracket that carries R, the horn that carries `c`, twin link plates stacked 5 mm apart at x 0.31..0.345 +and 0.35..0.385, pins through the knee's width, a clevis at each ram pin; 4,176 triangles, 12 parts), a signed BVH +oracle (winding number along a ray for the side, nearest face for the depth). + +| drive | reading | +| --- | --- | +| direct, the joint library's seats, 0..-62 | fits (analytic thigh and shin) | +| direct, 2,000 seat pairs behind the knee | none fits (analytic thigh and shin) | +| four-bar behind the knee | passes every gate before clearance: rocker swing 70.5, L 0.722..1.168, arm 0.096..0.265, pin load 1.61, transmission 16.5. Refused on the meshes: of 23 checked pairs two fail, the barrel and the rod against the shin's body (0.277 and 0.246 inside their clearance at -122.5, 251 steps), a body the ram is not pinned to | +| bell crank in front of the knee | fits on the meshes, the plates on either side: rocker swing 105.7, L 0.659..1.038, arm 0.091..0.215, pin load 1.13, transmission 13.8. 36 pairs checked, 24 let. Over 251 steps the least margin beyond radius, gap and half the spacing is 0.039 (the rod and the rocker's pivot pin at -125), then 0.042 (the coupler and the bracket at 0) and 0.058 (the rocker's arm and the coupler's plates at 0); at spacing 0.01, 0.061. With `touch` empty the same gate refuses 19 pairs, each a member against a pin it rides, its own plates or clevis, a plate stacked on its pin, or the bracket or horn that pin stands in | +| bell-crank search on the meshes | 13,824 candidates, each world built from the candidate's pins: 78 pass the gates before clearance, 21 of them are refused on their own parts, the 22nd fits (arm 0.090, swing 99.9, pin load 0.73) | + +Cost on Starfire, 300 repetitions paired and interleaved with the previous revision, other work holding the cores +at 100 percent: one candidate's gates before clearance at 49 steps took 0.98 ms median on the four-bar (5th to 95th +percentile 0.88 to 3.35) and 0.96 on the bell crank (0.88 to 2.03), the previous revision 1.03 and 1.00 beside +them. A search without a world ran 1.6 to 1.8 ms a candidate over 3,456, so `limit` (20,000) is 30 to 40 s. The +bell crank's clearance against analytic parts added 11 ms; on the meshes its 36 pairs asked 17,248 points and +took 0.12 s capped, in a Python loop of BVH queries; a candidate's world built in 0.045 s, and the 13,824-candidate +mesh search took 29 s (55 s in a busier minute). ## The actions From f3d8a73f2a041c3e5bed94af057527d81da73173 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:01:36 +0100 Subject: [PATCH 136/223] brokkr_kitbash.ram: touch is zones about a member's pins, each a radius and a depth; a strict record; what a world returns is read as a record Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/ram.py | 168 ++++++++++++++++++------- 1 file changed, 123 insertions(+), 45 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py index cdb475e..80ef95d 100644 --- a/surfaces/blender/brokkr_kitbash/ram.py +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -26,10 +26,14 @@ the coupler bar at c's, the ram at a's plus each of `offsets`. Clearance. The record names the mechanism's `parts`, each a piece of one body (part -> the body whose rest frame it turns with: a thigh's core, the bracket that carries the rocker's pivot, a link's plates, a pin), and `touch`: -for each member of MEMBERS[kind], the parts it may touch. A member may touch what it is pinned to and what is -stacked on its pins: the pin, its own eye and clevis, the plates beside it on that pin, the bracket or horn the pin -stands in. Those pairs are skipped whole and every other (member, part) pair is checked; nothing is exempt by a -name, a length or the member's own body. Every body of the kind owns at least one part, or the gate refuses. +for each member of MEMBERS[kind], zones (part, pin, radius, depth). Every member meets every part. A zone lowers +what the member's samples keep from one part, and only within `radius` of the axis of `pin`, one of the member's +own (RIDES), measured across the hinge axis: there a sample may come as near the part as -depth and no nearer. +depth is 0 for what is stacked beside the member on the pin (a plate, the bracket or horn the pin stands in: the +member's axis stays outside it, so a pin whose place along the axis is inside the part it claims to stand beside +is refused), the pin's radius for the pin through the member's eye, half the thickness for the member's own plate +or clevis. Beyond the radius the pair is checked like any other; nothing is exempt by a name, a length or the +member's own body. Every body of the kind owns at least one part, or the gate refuses. The oracle is distance(part, points) -> distances, points (N, 3) in the rest frame of the part's body. A distance is signed: negative inside the part, by any depth. The oracle may cap what it returns at Ram.reach(spacing), @@ -50,8 +54,12 @@ BODIES = {"direct": ("parent", "child"), "four_bar": ("parent", "child", "rocker PINS = {"direct": ("a", "b"), "four_bar": ("a", "rocker", "p", "c", "d"), "bell_crank": ("a", "rocker", "p", "c", "d")} MEMBERS = {"direct": ("barrel", "rod"), "four_bar": ("barrel", "rod", "rocker", "coupler"), "bell_crank": ("barrel", "rod", "rocker", "coupler", "rocker arm")} +EYE = {"direct": "b", "four_bar": "d", "bell_crank": "d"} # the pin the rod's eye rides +RIDES = {kind: {"barrel": ("a", EYE[kind]), "rod": ("a", EYE[kind]), "rocker": ("rocker", "p"), "coupler": ("p", "c"), "rocker arm": ("rocker", "d")} + for kind in KINDS} # member -> the pins at its start and its end GATES = ("assembly", "stroke", "toggle", "arm", "load", "clash") SCHEMA, VERSION = "brokkr.ram", 1 +ZONE = ("part", "pin", "radius", "depth") # a zone of `touch`, as the record writes it COMPLIANCE = ("stiffness", "damping", "travel") # reserved: a load-path ram's settle, solved by a later version BAND = 1e-9 # the loop is refused within this of a dead centre of the rocker and coupler @@ -66,9 +74,19 @@ class RamError(ValueError): self.kind, self.gate, self.angle, self.pin, self.fit = kind, gate, angle, pin, fit +def _number(kind, name, value, least=None): + """A record's number: an int or a float, finite, never a bool, a string or null; above `least` when given.""" + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise RamError(kind, "record", f"a finite number, got {value!r}", pin=name) + if least is not None and not value > least: + raise RamError(kind, "record", f"a number greater than {least:g}, got {value!r}", pin=name) + return float(value) + + @dataclass class Ram: - """A ram's proportions. Lengths default from the bore radius.""" + """A ram's proportions. Lengths default from the bore radius. Every one is a finite number and the bore is + greater than 0, or the ram is refused naming the field (as the ram of `any` kind: a ram knows none).""" bore: float rod: float = None # rod radius barrel_r: float = None # barrel outer radius @@ -83,11 +101,13 @@ class Ram: max_load: float = 3.0 # greatest coupler pin load per unit ram force def __post_init__(self): - b = self.bore + b = self.bore = _number("any", "bore", self.bore, 0.0) for name, value in (("rod", 0.5 * b), ("barrel_r", 1.25 * b), ("e_a", 1.7 * b), ("e_b", 1.7 * b), ("gland", 1.3 * b), ("over", 0.2 * b), ("min_arm", 1.5 * b), ("gap", 0.15 * b), ("link_r", 0.7 * b)): if getattr(self, name) is None: setattr(self, name, value) + for f in fields(self): + setattr(self, f.name, _number("any", f.name, getattr(self, f.name))) @property def back(self): @@ -133,7 +153,7 @@ class Mechanism: d: np.ndarray = None offsets: tuple = (0.0,) parts: dict = field(default_factory=dict) # part -> the body it turns with - touch: dict = field(default_factory=dict) # member -> the parts it may touch + touch: dict = field(default_factory=dict) # member -> zones (part, pin, radius, depth) def __post_init__(self): if self.kind not in KINDS: @@ -157,13 +177,25 @@ class Mechanism: for part, body in self.parts.items(): if body not in BODIES[self.kind]: raise RamError(self.kind, "record", f"part {part!r} turns with {body!r}; this kind has {', '.join(BODIES[self.kind])}") - self.touch = {member: tuple(parts) for member, parts in dict(self.touch).items()} - for member, parts in self.touch.items(): + touch = {} + for member, zones in dict(self.touch).items(): if member not in MEMBERS[self.kind]: raise RamError(self.kind, "record", f"touch names {member!r}; this kind's members are {', '.join(MEMBERS[self.kind])}") - for part in parts: + touch[member] = [] + for zone in zones: + if isinstance(zone, (str, dict)) or len(zone) != 4: + raise RamError(self.kind, "record", f"{member}'s zone is (part, pin, radius, depth), got {zone!r}") + part, pin, radius, depth = zone if part not in self.parts: raise RamError(self.kind, "record", f"{member} may touch {part!r}, which is no part of the record") + if pin not in RIDES[self.kind][member]: + raise RamError(self.kind, "record", f"{member} may touch {part!r} about a pin it rides ({', '.join(RIDES[self.kind][member])}), not {pin!r}", pin=str(pin)) + radius, depth = _number(self.kind, f"{member} {part} radius", radius, 0.0), _number(self.kind, f"{member} {part} depth", depth) + if depth < 0.0: + raise RamError(self.kind, "record", f"a depth of 0 or more, got {depth!r}", pin=f"{member} {part} depth") + touch[member].append((part, pin, radius, depth)) + touch[member] = tuple(touch[member]) + self.touch = touch for name in ("a", "b", "rocker", "p", "c", "d"): needed, given = name in PINS[self.kind], getattr(self, name) is not None if needed != given: @@ -270,19 +302,19 @@ def extension(m, ram, degrees): def _members(m, ram, barrel, p): """(member, label, start (S, 3), end (S, 3), radius, (pin at start, pin at end)) of every member in the parent frame, each from pin to pin: the barrel from its back end, the rod to the eye, a bar between its pins.""" - n, eye = m.axis, "b" if m.kind == "direct" else "d" + n, rides = m.axis, RIDES[m.kind] for off in m.offsets: base, tip = p.base + off * n, p.eye + off * n front = base + p.u * (ram.back + max(barrel, 1e-6)) - yield "barrel", f"barrel[{off:g}]", base + p.u * ram.back, front, ram.barrel_r, ("a", eye) - yield "rod", f"rod[{off:g}]", front, tip, ram.rod, ("a", eye) + yield "barrel", f"barrel[{off:g}]", base + p.u * ram.back, front, ram.barrel_r, rides["barrel"] + yield "rod", f"rod[{off:g}]", front, tip, ram.rod, rides["rod"] if m.kind == "direct": return R = np.broadcast_to(m.rocker, p.P.shape) - yield "rocker", "rocker", R, p.P - n * ((p.P - R) @ n)[:, None], ram.link_r, ("rocker", "p") - yield "coupler", "coupler", p.P - n * ((p.P - p.C) @ n)[:, None], p.C, ram.link_r, ("p", "c") + yield "rocker", "rocker", R, p.P - n * ((p.P - R) @ n)[:, None], ram.link_r, rides["rocker"] + yield "coupler", "coupler", p.P - n * ((p.P - p.C) @ n)[:, None], p.C, ram.link_r, rides["coupler"] if m.kind == "bell_crank": - yield "rocker arm", "rocker arm", R, p.eye - n * ((p.eye - R) @ n)[:, None], ram.link_r, ("rocker", "d") + yield "rocker arm", "rocker arm", R, p.eye - n * ((p.eye - R) @ n)[:, None], ram.link_r, rides["rocker arm"] def _into(m, p, body, pts): @@ -301,15 +333,17 @@ def _into(m, p, body, pts): class Clearance: margin: np.ndarray # (S,) the least margin of any checked pair at each angle where: tuple # (angle, member label, part, pin) of the least: the pin is the member's nearer one - pairs: dict # (member label, part) -> (least margin, angle) of every pair checked - allowed: list # (member label, part) of every pair the record's `touch` skipped + pairs: dict # (member label, part) -> (least margin, angle) of every pair: every member, every part + allowed: list # (member label, part) of every pair a zone of the record's `touch` lets near a pin def clearance(m, ram, degrees, distance, spacing=None): """The clearance gate's reading. A member is clear where margin >= 0: each sample of its axis, taken at most `spacing` apart (default barrel_r), is at least radius + gap + spacing / 2 from every part, measured in the rest frame of the part's body at that angle. A sample is at most spacing / 2 from any point of the axis, so - the member's surface keeps the gap. Every member meets every part of the record but those `touch` gives it.""" + the member's surface keeps the gap. Every member meets every part of the record. Inside a zone of `touch` + (within its radius of its pin's axis, across the hinge axis) a sample keeps -depth from the zone's part + instead: the margin there is the distance plus the depth.""" return _clearance(m, ram, barrel_length(m, ram), pose(m, degrees), distance, spacing) @@ -320,27 +354,33 @@ def _clearance(m, ram, barrel, p, distance, spacing): step = ram.spacing(spacing) out = Clearance(np.full(len(p.degrees), math.inf), None, {}, []) least = math.inf + at = {"a": p.base, EYE[m.kind]: p.eye, "rocker": m.rocker, "p": p.P, "c": p.C} # each pin over the angles, parent frame for member, label, start, end, radius, pins in _members(m, ram, barrel, p): count = max(int(math.ceil(float(np.linalg.norm(end - start, axis=1).max()) / step)) + 1, 2) pts = start[:, None, :] + (end - start)[:, None, :] * np.linspace(0.0, 1.0, count)[None, :, None] need = radius + ram.gap + step / 2.0 seen = {} for part, body in m.parts.items(): - if part in m.touch.get(member, ()): - out.allowed.append((label, part)) - continue if body not in seen: seen[body] = _into(m, p, body, pts).reshape(-1, 3) got = np.asarray(distance(part, seen[body]), dtype=float).reshape(len(p.degrees), count) if np.isnan(got).any(): raise RamError(m.kind, "oracle", f"the distance oracle answered nan for part {part!r}") - row = got.min(axis=1) - need + keep = np.full(got.shape, need) # what each sample keeps from the part + zones = [zone for zone in m.touch.get(member, ()) if zone[0] == part] + for _, pin, reach, depth in zones: + across = np.linalg.norm(_flat(pts - np.broadcast_to(at[pin], start.shape)[:, None, :], m.axis), axis=2) + keep = np.where(across <= reach, np.minimum(keep, -depth), keep) + if zones: + out.allowed.append((label, part)) + over = got - keep + row = over.min(axis=1) out.margin = np.minimum(out.margin, row) i = int(np.argmin(row)) out.pairs[(label, part)] = (float(row[i]), float(p.degrees[i])) if row[i] < least: least = float(row[i]) - out.where = (float(p.degrees[i]), label, part, pins[int(np.argmin(got[i])) * 2 >= count]) + out.where = (float(p.degrees[i]), label, part, pins[int(np.argmin(over[i])) * 2 >= count]) return out @@ -366,8 +406,8 @@ class Fit: mu_p: float = None # least transmission angle at p clear_min: float = math.inf # least clearance beyond what the gate asks; inf with no oracle clear_at: tuple = None # (angle, member, part, pin) of it - pairs: dict = field(default_factory=dict) # (member, part) -> (least margin, angle) of every pair checked - allowed: list = field(default_factory=list) # (member, part) of every pair `touch` skipped + pairs: dict = field(default_factory=dict) # (member, part) -> (least margin, angle) of every pair + allowed: list = field(default_factory=list) # (member, part) of every pair a zone of `touch` lets near a pin table: list = field(default_factory=list) # (angle, L, dL/dtheta, clearance margin) per step @property @@ -394,7 +434,7 @@ def _fit(m, ram, steps=25, distance=None, spacing=None, clear=True): pose(m, np.linspace(0.0, m.lo if m.lo > 0.0 else m.hi, steps)) # the branch is carried from rest: no dead centre on the way p = pose(m, np.linspace(m.lo, m.hi, steps)) l_min, l_max = float(p.L.min()), float(p.L.max()) - eye = "b" if m.kind == "direct" else "d" + eye = EYE[m.kind] travel = l_max - l_min barrel = _barrel(ram, p.L) # the samples' ends are lo and hi: barrel_length's own two angles stroke = barrel - ram.gland @@ -433,7 +473,7 @@ def _fit(m, ram, steps=25, distance=None, spacing=None, clear=True): def fit(m, ram, steps=25, distance=None, spacing=None): """Check one mechanism from lo to hi. Gates, in order, each over all steps at once: assembly; stroke; effective arm (one sign, and at least min_arm); coupler pin load (linkages); clearance, when a distance oracle is given - (see clearance: the record's parts and touch say what it meets). + (see clearance: the record's parts say what it meets, its touch how near a pin). Returns the Fit; a failed gate raises RamError, its `fit` holding the readings.""" f = _fit(m, ram, steps, distance, spacing) if not f.ok: @@ -492,7 +532,8 @@ def search(kind, hinge, ram, seats, world=None, limit=20000, steps=25, spacing=N first: every gate but clearance over all candidates, then clearance in order of least arm, greatest first; the first clear one wins. world(m) -> (parts, touch, distance) builds a candidate's own parts, the brackets and links its pins place among them, and the oracle that answers for them: a linkage's links are the - candidate's, so no one oracle serves a grid. A grid past `limit` candidates is refused naming the count. A + candidate's, so no one oracle serves a grid. What it returns is read as a record's: anything but the three, + a part on no body of the kind or a zone that is not (part, pin the member rides, radius, depth) is refused. A grid past `limit` candidates is refused naming the count. A miss returns the tally and the nearest miss (the least total shortfall: stroke, arm, load excess, clearance).""" pins = candidates(kind, hinge, seats) @@ -524,7 +565,10 @@ def search(kind, hinge, ram, seats, world=None, limit=20000, steps=25, spacing=N for f, seat in passed: if world is None: return Search(f, True, len(pins), len(passed), tally, seat) - parts, touch, distance = world(f.m) + made = world(f.m) + if not isinstance(made, tuple) or len(made) != 3 or not callable(made[2]): + raise RamError(kind, "search", f"world(m) returns (parts, touch, distance), got {type(made).__name__}") + parts, touch, distance = made f = _fit(replace(f.m, parts=parts, touch=touch), ram, steps, distance, spacing) if f.ok: return Search(f, True, len(pins), len(passed), tally, seat) @@ -541,26 +585,60 @@ def record(m, ram): "hinge": {"pivot": m.pivot.tolist(), "axis": m.axis.tolist(), "lo": m.lo, "hi": m.hi}, "pins": {name: getattr(m, name).tolist() for name in PINS[m.kind]}, "offsets": list(m.offsets), "ram": {f.name: getattr(ram, f.name) for f in fields(Ram)}, - "parts": dict(m.parts), "touch": {member: list(parts) for member, parts in m.touch.items()}, "compliance": None} + "parts": dict(m.parts), "compliance": None, + "touch": {member: [dict(zip(ZONE, zone)) for zone in zones] for member, zones in m.touch.items()}} def from_record(data): - """(Mechanism, Ram) of a record. A record of another schema or version, with a key this version does not - know, or with a compliance block is refused whole: nothing is read past and dropped.""" - kind = str(data.get("kind")) - if data.get("schema") != SCHEMA or data.get("version") != VERSION: - raise RamError(kind, "record", f"this reader reads {SCHEMA} version {VERSION}; the record is {data.get('schema')} version {data.get('version')}") - keys = {"schema", "version", "kind", "hinge", "pins", "offsets", "ram", "parts", "touch", "compliance"} - for name, given, known in (("record", set(data), keys), ("ram", set(data.get("ram", ())), {f.name for f in fields(Ram)}), - ("hinge", set(data.get("hinge", ())), {"pivot", "axis", "lo", "hi"})): - if given != known: - raise RamError(kind, "record", f"the {name}'s keys are not version {VERSION}'s: unknown {sorted(given - known)}, missing {sorted(known - given)}") + """(Mechanism, Ram) of a record. A record of another schema or version (the integer 1: not 1.0, not true), with + a key this version does not know or without one it does, with a compliance block, or with a value that is not + its field's type (a finite number, three of them, a name) is refused whole, as a RamError naming the field: + nothing is read past and dropped.""" + if not isinstance(data, dict): + raise RamError("None", "record", f"a record is an object, got {type(data).__name__}") + kind, version = str(data.get("kind")), data.get("version") + if data.get("schema") != SCHEMA or type(version) is not int or version != VERSION: + raise RamError(kind, "record", f"this reader reads {SCHEMA} version {VERSION}; the record is {data.get('schema')} version {version!r}") + if kind not in KINDS: + raise RamError(kind, "record", f"kind is one of {', '.join(KINDS)}") + + def keys(name, given, known): + if not isinstance(given, dict): + raise RamError(kind, "record", f"an object, got {type(given).__name__}", pin=name) + if set(given) != set(known): + raise RamError(kind, "record", f"the {name}'s keys are not version {VERSION}'s: unknown {sorted(set(given) - set(known), key=str)}, missing {sorted(set(known) - set(given))}") + + def point(name, value): + if not isinstance(value, list) or len(value) != 3: + raise RamError(kind, "record", f"three finite numbers, got {value!r}", pin=name) + return [_number(kind, name, x) for x in value] + + keys("record", data, ("schema", "version", "kind", "hinge", "pins", "offsets", "ram", "parts", "touch", "compliance")) + hinge, pins, ram = data["hinge"], data["pins"], data["ram"] + keys("hinge", hinge, ("pivot", "axis", "lo", "hi")) + keys("pins", pins, PINS[kind]) + keys("ram", ram, [f.name for f in fields(Ram)]) if data["compliance"] is not None: raise RamError(kind, "record", f"a compliance block ({', '.join(COMPLIANCE)}) is a later version's: version {VERSION} solves none and will not drop it") - hinge = data["hinge"] - m = Mechanism(data["kind"], hinge["pivot"], hinge["axis"], hinge["lo"], hinge["hi"], offsets=tuple(data["offsets"]), - parts=data["parts"], touch=data["touch"], **data["pins"]) - return m, Ram(**data["ram"]) + for name, value in ram.items(): + _number(kind, name, value, 0.0 if name == "bore" else None) + if not isinstance(data["offsets"], list): + raise RamError(kind, "record", f"a list of numbers, got {data['offsets']!r}", pin="offsets") + if not isinstance(data["parts"], dict) or not all(isinstance(body, str) for body in data["parts"].values()): + raise RamError(kind, "record", "an object of part: body", pin="parts") + if not isinstance(data["touch"], dict): + raise RamError(kind, "record", "an object of member: zones", pin="touch") + touch = {} + for member, zones in data["touch"].items(): + if not isinstance(zones, list): + raise RamError(kind, "record", f"{member}'s zones are a list, got {zones!r}", pin="touch") + for zone in zones: + keys(f"{member} zone", zone, ZONE) + touch[member] = [tuple(zone[key] for key in ZONE) for zone in zones] + m = Mechanism(kind, point("pivot", hinge["pivot"]), point("axis", hinge["axis"]), _number(kind, "lo", hinge["lo"]), _number(kind, "hi", hinge["hi"]), + offsets=tuple(_number(kind, "offsets", o) for o in data["offsets"]), parts=data["parts"], touch=touch, + **{name: point(name, value) for name, value in pins.items()}) + return m, Ram(**ram) def swept(f, body, margin=0.0, steps=13, around=8): From 451f1c4ee261878704a4aac15b32fe203a12bf4f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:01:36 +0100 Subject: [PATCH 137/223] tests/test_ram: zones end at their radius, a pin stood inside what it stands beside, frames, the barrel's back end, the record's wall, a world's answer Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/test_ram.py | 362 ++++++++++++++++++++++++----- 1 file changed, 303 insertions(+), 59 deletions(-) diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py index 314e747..b80d4ab 100644 --- a/surfaces/blender/tests/test_ram.py +++ b/surfaces/blender/tests/test_ram.py @@ -1,7 +1,7 @@ """brokkr_kitbash/ram.py under plain Python: each case is a mechanism whose answer is known by hand, by a second method (central differences, loop closure) or from the R-3 knee probes the docs cite. Bodies are analytic signed distance oracles: boxes, capsules and cylinders across x, each a named part of a body. They defend the gate's rule; -the R-3 knee's clearance on meshes is the Blender reading docs/kitbash.md states, not these stand-ins. +the R-3 knee's clearance on meshes is tests/live/ram_knee.py's, in a Blender, not these stand-ins. Bounds follow lodur:ruling:deterministic-bound-margin: the geometric mean of the shipped reading and the least mutant's, both written beside the constant.""" @@ -75,7 +75,7 @@ def two(parent=(), child=(), cap=None, **more): def dressed(m, bodies, touch=None): - """The mechanism with the bodies' parts in its record, and what each member may touch.""" + """The mechanism with the bodies' parts in its record, and each member's zones (part, pin, radius, depth).""" return replace(m, parts=bodies.parts, touch=touch or {}) @@ -98,6 +98,7 @@ R3_SHIN = ([("cyl", O, 0.25, 0.18), ("cyl", O, 0.19, 0.205), ("box", (-0.11, -0. ("box", (0.1875, -0.1, -0.87), (0.2325, 0.1, -0.37))] # the cheeks taper from the hub's 0.25 to 0.12 at the foot: five steps outside the taper + [("box", (-0.18, -(0.25 - 0.026 * k), -0.19 * (k + 1)), (0.18, 0.25 - 0.026 * k, -0.19 * k)) for k in range(5)]) +AXLE, PIN = 0.028, 0.026 # the rocker's axle and a link pin, radius X_COUPLER, X_ROCKER = 0.3275, 0.3675 # the twin link plates' centres as the R-3 probe stacks them (0.31..0.345, 0.35..0.385) # P2's deep knee: a four-bar behind the knee (y < 0), where the shin folds to. @@ -114,26 +115,64 @@ def r3(kind, pins, side=1.0, lo=-125.0, hi=0.0): return R.Mechanism(kind, O, X, lo, hi, **{name: yz(pins[name], at[name]) for name in pins}) -def r3_bodies(m, ram, cap=None): - """(Bodies, touch) of an R-3 linkage: the thigh and shin, and the mechanism's own links as parts: twin plates - of link_r, the rocker's axle through the knee's width, and the pins at p, c and (a bell crank) d. Each member - may touch its own plates and pins and the plates stacked beside it on a pin it rides; the ram, its eye's pin.""" +def r3_parts(m, ram, cap=None): + """Bodies of an R-3 linkage: the thigh and shin, the bracket the rocker's pivot stands in (a boss on the thigh, + x 0.13..0.35) and the horn c stands in (on the shin, 0.18..0.31), and the mechanism's own links as parts: twin + plates of link_r, the rocker's axle through the knee's width, and the pins at p, c and (a bell crank) d.""" def twin(p, q, x): return [("capsule", (s * x, p[1], p[2]), (s * x, q[1], q[2]), ram.link_r) for s in (-1.0, 1.0)] def across(at, r): return [("capsule", (-X_ROCKER, at[1], at[2]), (X_ROCKER, at[1], at[2]), r)] + + def boss(at, r, x0, x1): + return [("cyl", (s * 0.5 * (x0 + x1), at[1], at[2]), r, 0.5 * (x1 - x0)) for s in (-1.0, 1.0)] crank = m.kind == "bell_crank" - parts = {"thigh": ("parent", R3_THIGH), "shin": ("child", R3_SHIN), + parts = {"thigh": ("parent", R3_THIGH), "shin": ("child", R3_SHIN), "bracket": ("parent", boss(m.rocker, 0.055, 0.13, 0.35)), + "horn": ("child", boss(m.c, 0.05, 0.18, 0.31)), "rocker plates": ("rocker", twin(m.rocker, m.p, X_ROCKER) + (twin(m.rocker, m.d, X_ROCKER) if crank else [])), - "rocker axle": ("rocker", across(m.rocker, 0.028)), "pin p": ("rocker", across(m.p, 0.026)), - "coupler plates": ("coupler", twin(m.p, m.c, X_COUPLER)), "pin c": ("coupler", across(m.c, 0.026))} - own = ["rocker plates", "rocker axle", "pin p"] + (["pin d"] if crank else []) - touch = {"barrel": ["pin p"], "rod": ["pin p"], "rocker": own + ["coupler plates"], "coupler": ["coupler plates", "pin c", "rocker plates", "pin p"]} + "rocker axle": ("rocker", across(m.rocker, AXLE)), "pin p": ("rocker", across(m.p, PIN)), + "coupler plates": ("coupler", twin(m.p, m.c, X_COUPLER)), "pin c": ("coupler", across(m.c, PIN))} if crank: - parts["pin d"] = ("rocker", across(m.d, 0.026)) - touch.update({"barrel": ["pin d"], "rod": ["pin d"], "rocker arm": own}) - return Bodies(parts, cap), touch + parts["pin d"] = ("rocker", across(m.d, PIN)) + return Bodies(parts, cap) + + +def near(ram, member, spacing=None): + """What a member's sample keeps from a part outside a zone: its radius, the gap and half the spacing.""" + radius = {"barrel": ram.barrel_r, "rod": ram.rod}.get(member, ram.link_r) + return radius + ram.gap + ram.spacing(spacing) / 2 + + +def scissor(m, ram): + """How far from p a link and the plates beside it on p part: they cross at the transmission angle, their + centres X_ROCKER - X_COUPLER apart along the axis, and part where the bars' axes are link_r + near apart.""" + mu = math.radians(float(R.pose(m, np.linspace(m.lo, m.hi, 49)).mu_p.min())) + return math.sqrt((ram.link_r + near(ram, "rocker")) ** 2 - (X_ROCKER - X_COUPLER) ** 2) / math.sin(mu) + + +def r3_bodies(m, ram, cap=None): + """(Bodies, touch) of an R-3 linkage. A zone about a pin is the eye's radius plus what the member keeps: the + pin's or boss's radius plus near(member). Its depth is the pin's radius where the pin runs through the member's + eye, 0 for the boss or plate the member stands beside, link_r over a link's own plates, whole length. The plates + beside a link on p are let as far as the two part (scissor).""" + bodies, crank = r3_parts(m, ram, cap), m.kind == "bell_crank" + link, eye, cross = near(ram, "rocker"), "pin d" if crank else "pin p", scissor(m, ram) + arm = float(np.linalg.norm(m.d - m.rocker)) + touch = {"barrel": [(eye, "d", PIN + near(ram, "barrel"), 0.0)], "rod": [(eye, "d", PIN + near(ram, "rod"), PIN)], + "rocker": [("bracket", "rocker", 0.055 + link, 0.0), ("rocker axle", "rocker", AXLE + link, AXLE), ("pin p", "p", PIN + link, PIN), + ("rocker plates", "rocker", 1.01 * m.lr, ram.link_r), ("coupler plates", "p", cross, 0.0)], + "coupler": [("horn", "c", 0.05 + link, 0.0), ("pin c", "c", PIN + link, PIN), ("pin p", "p", PIN + link, PIN), + ("coupler plates", "p", 1.01 * m.lc, ram.link_r), ("rocker plates", "p", cross, 0.0)]} + if crank: + touch["rocker arm"] = [("bracket", "rocker", 0.055 + link, 0.0), ("rocker axle", "rocker", AXLE + link, AXLE), ("pin d", "d", PIN + link, PIN), + ("rocker plates", "rocker", 1.01 * arm, ram.link_r)] + return bodies, touch + + +def let(touch): + """(member, part) of every zone.""" + return {(member, zone[0]) for member, zones in touch.items() for zone in zones} @unittest.skipIf(np is None, "numpy is not installed") @@ -226,6 +265,31 @@ class HandCases(unittest.TestCase): box = two(parent=[("box", (-0.2, -0.36, -0.2), (0.2, -0.2, 0.2))]) self.assertLess(R._fit(dressed(self.direct(-10, 0), box), ram, distance=box).clear_min, 0.0) + def test_the_barrel_runs_from_its_back_end(self): + # a ball beside the barrel's last 0.03, 0.005 inside what the barrel keeps: refused naming the barrel, and + # clear of the rod by 0.0265. S1 (the barrel's front taken from the base pin, e_a = 0.085 short) reads the + # barrel +0.007 clear and fits + m, ram, spacing = self.direct(-60, 0), R.Ram(0.05), 0.005 + p = R.pose(m, 0.0) + side = np.cross(p.u[0], X) + front = p.base[0] + p.u[0] * (ram.back + R.barrel_length(m, ram)) + centre = front - 0.03 * p.u[0] + side * (near(ram, "barrel", spacing) + 0.01 - 0.005) + ball = two(parent=[("capsule", centre, centre, 0.01)]) + c = R.clearance(dressed(m, ball), ram, 0.0, ball, spacing) + self.assertAlmostEqual(c.pairs[("barrel[0]", "parent")][0], -0.005, places=6) # the nearest sample stands up to 0.0025 along + self.assertEqual(c.where[:3], (0.0, "barrel[0]", "parent")) + self.assertGreater(c.pairs[("rod[0]", "parent")][0], 0.02) + # and the rod from there: a ball beside the rod just past the front keeps the rod's need, not the barrel's + centre = front + 0.03 * p.u[0] + side * (near(ram, "rod", spacing) + 0.01 + 0.005) + ball = two(parent=[("capsule", centre, centre, 0.01)]) + c = R.clearance(dressed(m, ball), ram, 0.0, ball, spacing) + self.assertAlmostEqual(c.pairs[("rod[0]", "parent")][0], 0.005, places=6) + + def test_reach_is_the_widest_members(self): + fat = R.Ram(0.05, link_r=0.1) # S9: a link wider than the barrel + self.assertAlmostEqual(fat.reach(0.02), 0.1 + fat.gap + 0.01, places=15) + self.assertAlmostEqual(R.Ram(0.05).reach(), 0.0625 + 0.0075 + 0.03125, places=15) + def test_search_tally_and_nearest_miss(self): ram, hinge = R.Ram(0.05), {"pivot": O, "axis": X, "lo": -70, "hi": 0} seats = {"a": grid((0, -0.5, 0.4), (0, -0.2, 1.2), (1, 3, 5)), "b": grid((0, -0.5, -1.2), (0, -0.2, -0.4), (1, 3, 5))} @@ -235,7 +299,7 @@ class HandCases(unittest.TestCase): for a in seats["a"]: # no fitting pair has a larger least arm for b in seats["b"]: f = R._fit(dressed(R.Mechanism("direct", O, X, -70, 0, a=a, b=b), pin), ram, distance=pin) - self.assertTrue(not f.ok or f.arm_min <= s.best.arm_min + 1e-9) + self.assertTrue(not f.ok or f.arm_min <= s.best.arm_min) # the same arithmetic on the same pins: no tolerance none = R.search("direct", {**hinge, "lo": -100}, ram, {"a": [(0, -0.1, 0.2)], "b": [(0, -0.1, -0.2)]}) self.assertFalse(none.found) self.assertIn("stroke", none.tally) @@ -251,9 +315,9 @@ class HandCases(unittest.TestCase): p = R.pose(f.m, np.linspace(-60, 0, 31)) line = p.base[:, None, :] + (p.eye - p.base)[:, None, :] * np.linspace(0, 1, 9)[None, :, None] inside = R._into(f.m, p, body, line).reshape(-1, 3) - self.assertTrue((inside >= lo - 1e-9).all() and (inside <= hi + 1e-9).all(), body) + self.assertTrue((inside >= lo).all() and (inside <= hi).all(), body) # each end of the line is its ring's centre, to the bit # seen from the child the eye stands still - self.assertLess(float(np.abs(R._into(f.m, p, "child", p.eye[:, None, :]) - np.array(self.B)).max()), 1e-12) + self.assertLess(float(np.abs(R._into(f.m, p, "child", p.eye[:, None, :]) - np.array(self.B)).max()), EYE_STILL) with self.assertRaises(R.RamError): R.swept(f, "rocker") @@ -267,6 +331,12 @@ class HandCases(unittest.TestCase): self.assertTrue(0.2 < float(tail[:, 2].max() - bare[:, 2].max()) <= 0.25) +# Frames, each bound the geometric mean of the shipped reading and its mutant's (scratch readings.py, h3). +EYE_STILL = 2.0e-8 # the eye seen from the child: shipped 2.2e-16, S4 (the child's frame turned the other way) 1.76, separation 9e7 +REST_BOUND = 9.6e-9 # the rest pose against the record: shipped 1.1e-16, the loop closed on the other branch 0.835, separation 9e7 +OWN_FRAME = 1.6e-8 # a member seen from its own body: shipped 3.3e-16, S3 (the coupler's frame turned by the rocker's angle) 0.742, S4 0.728, separation 5e7 + + @unittest.skipIf(np is None, "numpy is not installed") class Loop(unittest.TestCase): def test_loop_closes(self): @@ -282,8 +352,8 @@ class Loop(unittest.TestCase): c_on_coupler = p.P[i] + R._flat(turned(m.c - m.p, math.degrees(p.psi[i]), O), n) self.assertLess(float(np.linalg.norm(R._flat(c_on_coupler - turned(m.c, angle), n))), LOOP_BOUND, (kind, angle)) # and the rest pose is the record's - self.assertLess(float(np.abs(p.P[-1] - m.p).max()), 1e-12) - self.assertLess(float(np.abs(p.eye[-1] - m.d).max()), 1e-12) + self.assertLess(float(np.abs(p.P[-1] - m.p).max()), REST_BOUND) + self.assertLess(float(np.abs(p.eye[-1] - m.d).max()), REST_BOUND) def test_the_branch_is_the_rest_poses_at_every_angle(self): # the pin p keeps its side of R -> c from rest: an angle alone gives the pose, in any order, and a mirror @@ -487,8 +557,9 @@ class DeepKnee(unittest.TestCase): self.assertGreaterEqual(float(R.clearance(dressed(m, bodies, touch), ram, np.linspace(-125, 0, 49), bodies).margin.min()), 0.0) def test_a_part_in_the_rams_way_on_each_link(self): - # a lug on the rocker, then on the coupler, where the rod runs at -60: refused naming the part and its - # body, unless the record lets the rod and the barrel touch it; letting another member touch it changes nothing + # a lug on the rocker, then on the coupler, on the rod's axis 0.12 from the eye at -60: refused naming the part + # and its body. A zone about the eye lets the rod and the barrel by it only if it reaches the lug and is as + # deep as the lug; a zone of another member's changes nothing m, ram = r3("bell_crank", CRANK), R.Ram(BORE) at = R.pose(m, -60.0) on_rod = (at.eye - 0.12 * at.u)[:, None, :] @@ -496,20 +567,24 @@ class DeepKnee(unittest.TestCase): bodies, touch = r3_bodies(m, ram) spot = R._into(m, at, body, on_rod)[0, 0] bodies.parts["lug"], bodies.shapes["lug"] = body, [("capsule", spot - (0.1, 0, 0), spot + (0.1, 0, 0), 0.02)] - for allowed in ({}, {"coupler": touch["coupler"] + ["lug"]}): + + def zones(radius, depth, members=("rod", "barrel")): + return {**touch, **{member: touch[member] + [("lug", "d" if member != "coupler" else "p", radius, depth)] for member in members}} + for label, given in (("nothing let", touch), ("the coupler's zone", zones(1.0, 0.02, ("coupler",))), ("a zone short of the lug", zones(0.1, 0.02)), + ("a zone too shallow", zones(1.0, 0.01))): with self.assertRaises(R.RamError) as caught: - R.fit(dressed(m, bodies, {**touch, **allowed}), ram, steps=49, distance=bodies) - self.assertEqual((caught.exception.gate, caught.exception.fit.clear_at[2]), ("clash", "lug"), body) + R.fit(dressed(m, bodies, given), ram, steps=49, distance=bodies) + self.assertEqual((caught.exception.gate, caught.exception.fit.clear_at[2]), ("clash", "lug"), (body, label)) self.assertIn(caught.exception.fit.clear_at[1], ("rod[0]", "barrel[0]")) self.assertIn(f"part 'lug' ({body})", str(caught.exception)) - free = {**touch, "rod": touch["rod"] + ["lug"], "barrel": touch["barrel"] + ["lug"]} - f = R.fit(dressed(m, bodies, free), ram, steps=49, distance=bodies) + f = R.fit(dressed(m, bodies, zones(1.0, 0.02)), ram, steps=49, distance=bodies) self.assertIn(("rod[0]", "lug"), f.allowed) + self.assertNotIn(("rocker arm", "lug"), f.allowed) self.assertIn(("rocker arm", "lug"), f.pairs) - def test_bell_crank_clears_every_part_it_may_not_touch(self): + def test_bell_crank_clears_every_part_but_near_its_pins(self): # the bell crank stands in front of the knee, its plates at the probe's stack: over 0..-125 the gate meets - # every member with every part but those the record lets it touch, on either side, and all are clear + # every member with every part, on either side, and all are clear: beside its pins by the record's zones ram = R.Ram(BORE) for side in (1.0, -1.0): m = r3("bell_crank", CRANK, side) @@ -520,24 +595,84 @@ class DeepKnee(unittest.TestCase): self.assertAlmostEqual(f.swing, 105.732, places=2) self.assertAlmostEqual(f.l_min, 0.6593, places=3) self.assertAlmostEqual(f.l_max, 1.0376, places=3) - members = ("barrel[0]", "rod[0]", "rocker", "coupler", "rocker arm") - let = {(label, part) for label in members for part in touch[label.split("[")[0]]} - self.assertEqual(set(f.allowed), let) - self.assertEqual(len(let), 1 + 1 + 5 + 4 + 4) # the ram its eye's pin; rocker, coupler and arm theirs - self.assertEqual(set(f.pairs), {(label, part) for label in members for part in bodies.parts} - let) - self.assertEqual(len(f.pairs), 5 * 8 - 15) - self.assertEqual(sum(1 for _, part in f.pairs if part == "shin"), 5) - self.assertEqual(sum(1 for _, part in f.pairs if bodies.parts[part] == "coupler"), 2 * 2 + 1 + 2) # the rocker may touch the plates beside it on p + members = {"barrel[0]": "barrel", "rod[0]": "rod", "rocker": "rocker", "coupler": "coupler", "rocker arm": "rocker arm"} + zoned = {(label, part) for label, member in members.items() for part in bodies.parts if (member, part) in let(touch)} + self.assertEqual(set(f.allowed), zoned) + self.assertEqual(len(zoned), 1 + 1 + 5 + 5 + 4) # the ram its eye's pin; rocker, coupler and arm theirs + self.assertEqual(set(f.pairs), {(label, part) for label in members for part in bodies.parts}) + self.assertEqual(len(f.pairs), 5 * 10) self.assertGreaterEqual(min(v[0] for v in f.pairs.values()), 0.0) self.assertGreaterEqual(float(R.clearance(m, ram, np.linspace(-125, 0, 251), bodies).margin.min()), 0.0) # asked for the fit's own angles, clearance reads what the fit read same = R.clearance(m, ram, f.degrees, bodies) self.assertEqual((same.pairs, same.where, sorted(same.allowed)), (f.pairs, f.clear_at, sorted(f.allowed))) - # with nothing let, the gate refuses, and only pairs the record lets: the pins a member rides + # with nothing let, the gate refuses, and only pairs the record zones: the pins a member rides bare = R._fit(replace(m, touch={}), ram, steps=49, distance=bodies) refused = {pair for pair, reading in bare.pairs.items() if reading[0] < 0.0} - self.assertTrue(refused and refused <= let, refused - let) - self.assertEqual(len(bare.pairs), 40) + self.assertEqual(refused, zoned) + self.assertEqual((len(bare.pairs), bare.allowed), (50, [])) + + def test_a_zone_ends_at_its_radius(self): + # each zone cut to half its radius: the pair is met beyond it like any other, and refused there. Soul's + # let_hide: the whole pair was skipped, whatever lay along the member + m, ram = r3("bell_crank", CRANK), R.Ram(BORE) + bodies, touch = r3_bodies(m, ram) + for member, zones in touch.items(): + for k, (part, pin, radius, depth) in enumerate(zones): + short = {**touch, member: zones[:k] + [(part, pin, 0.5 * radius, depth)] + zones[k + 1:]} + f = R._fit(dressed(m, bodies, short), ram, steps=49, distance=bodies) + label = member + "[0]" if member in ("barrel", "rod") else member + self.assertEqual([pair for pair, reading in f.pairs.items() if reading[0] < 0.0], [(label, part)], (member, part)) + # a rail on the thigh the rocker runs into 0.25 from its pivot, at rest: a zone on the pivot that takes in the + # thigh's boss does not take in the rail, however deep it is stated + spot = m.rocker + 0.25 * R._flat(m.p - m.rocker, np.array(X)) / m.lr + bodies.parts["rail"], bodies.shapes["rail"] = "parent", [("capsule", spot - (0.05, 0, 0), spot + (0.05, 0, 0), 0.02)] + for radius, clear in ((0.117, False), (0.26, False), (0.34, True)): # the rail's 0.02 and what the rocker keeps past 0.25 + f = R._fit(dressed(m, bodies, {**touch, "rocker": touch["rocker"] + [("rail", "rocker", radius, 0.03)]}), ram, steps=49, distance=bodies) + self.assertEqual(f.pairs[("rocker", "rail")][0] >= 0.0, clear, radius) + + def test_a_pin_stood_inside_what_it_stands_beside_is_refused(self): + # Soul's moved-x probes: the rocker's x moved from its plate's place (0.3675) into the bracket's 0.13..0.35, + # the coupler's (0.3275) into the horn's 0.18..0.31. The zones are the shipped ones and take in the whole of + # each boss; the member's axis is inside the boss by its radius (0.055, 0.05), and a zone of depth 0 keeps it out + ram = R.Ram(BORE) + bodies, touch = r3_bodies(r3("bell_crank", CRANK), ram) + for moved, member, part, depth, pin in (("rocker", "rocker", "bracket", 0.055, "rocker"), ("c", "coupler", "horn", 0.05, "c")): + pins = {name: yz(CRANK[name], {"rocker": X_ROCKER, "c": X_COUPLER}.get(name, 0.0)) for name in CRANK} + pins[moved] = yz(CRANK[moved], 0.25) + m = R.Mechanism("bell_crank", O, X, -125.0, 0.0, **pins, parts=bodies.parts, touch=touch) + with self.assertRaises(R.RamError) as caught: + R.fit(m, ram, steps=49, distance=bodies) + refusal = caught.exception + self.assertEqual((refusal.gate, refusal.pin), ("clash", pin)) + self.assertEqual(refusal.fit.clear_at[1:3], (member, part)) + self.assertAlmostEqual(refusal.fit.pairs[(member, part)][0], -depth, places=9) + # stated as deep as the boss, the zone lets it: the depth is the record's to state and to be read + deep = {**touch, member: [(part, pin, zone[2], depth) if zone[0] == part else zone for zone in touch[member]]} + self.assertGreaterEqual(R._fit(replace(m, touch=deep), ram, steps=49, distance=bodies).pairs[(member, part)][0], 0.0) + + def test_a_member_stands_still_in_its_own_bodys_frame(self): + # what the oracle is asked: the coupler's samples in the coupler's frame, the rocker's and the arm's in the + # rocker's, the coupler's end at c in the child's and the rod's eye in the rocker's are the rest pose's at + # every angle + ram = R.Ram(BORE) + for kind, pins in (("four_bar", DEEP), ("bell_crank", CRANK)): + m = r3(kind, pins) + bodies, asked = r3_parts(m, ram), [] + + def spy(part, pts): + asked.append((part, np.array(pts))) + return bodies(part, pts) + angles = np.linspace(-125, 0, 26) + R.clearance(dressed(m, bodies), ram, angles, spy) + labels = [label for _, label, *_ in R._members(m, ram, R.barrel_length(m, ram), R.pose(m, angles))] + seen = {(labels[k // len(bodies.parts)], part): pts.reshape(len(angles), -1, 3) for k, (part, pts) in enumerate(asked)} + still = [seen[("coupler", "coupler plates")], seen[("rocker", "rocker plates")], seen[("coupler", "shin")][:, -1:], seen[("rod[0]", "pin p")][:, -1:]] + if kind == "bell_crank": + still.append(seen[("rocker arm", "pin d")]) + for pts in still: + self.assertLess(float(np.abs(pts - pts[-1]).max()), OWN_FRAME, kind) + self.assertLess(float(np.abs(seen[("coupler", "coupler plates")][-1, 0] - (X_COUPLER, m.p[1], m.p[2])).max()), OWN_FRAME) # The R-3 four-bar's readings over 0..-125 at 49 steps, each bound the geometric mean of the shipped reading and @@ -576,22 +711,40 @@ class OracleRule(unittest.TestCase): self.assertEqual(c.where, (0.0, "barrel[0]", "parent", "a")) # sample 3 of the barrel: nearer the base self.assertAlmostEqual(ram.reach(spacing), need, places=15) - def test_touch_is_the_only_exemption(self): - # a clevis on the base pin and one on the eye, each a part: with nothing let they refuse the ram at its own - # pins; let to the member that rides the pin they are skipped; let to the other member they still refuse - ram = self.ram - seats = two(a=("parent", [("capsule", self.m.a, self.m.a, 0.03)]), b=("child", [("capsule", self.m.b, self.m.b, 0.03)])) - bare = R.clearance(dressed(self.m, seats), ram, 0.0, seats) - self.assertLess(bare.pairs[("barrel[0]", "a")][0], 0.0) - # the rod runs to the eye: its last sample is the pin's centre, the ball's depth inside it - self.assertAlmostEqual(bare.pairs[("rod[0]", "b")][0], -0.03 - (ram.rod + ram.gap + ram.barrel_r / 2), places=12) + def test_a_zone_is_the_only_allowance(self): + # a clevis on the base pin and one on the eye, each a part (a ball of 0.03): with nothing let they refuse the + # ram at its own pins. A zone about the pin lets the member by: of the ball's radius plus what the member + # keeps, and for the rod, whose last sample is the pin's centre, as deep as the ball + ram, m = self.ram, self.m + seats = two(a=("parent", [("capsule", m.a, m.a, 0.03)]), b=("child", [("capsule", m.b, m.b, 0.03)])) + bare = R.clearance(dressed(m, seats), ram, 0.0, seats) + self.assertAlmostEqual(bare.pairs[("barrel[0]", "a")][0], ram.e_a - 0.03 - near(ram, "barrel"), places=12) # the barrel starts e_a from a + self.assertAlmostEqual(bare.pairs[("rod[0]", "b")][0], -0.03 - near(ram, "rod"), places=12) + self.assertEqual(bare.where, (0.0, "rod[0]", "b", "b")) # the least, and the pin at the rod's far end self.assertEqual(bare.allowed, []) - let = R.clearance(dressed(self.m, seats, {"barrel": ["a"], "rod": ["b"]}), ram, 0.0, seats) - self.assertGreaterEqual(float(let.margin[0]), 0.0) - self.assertEqual(sorted(let.allowed), [("barrel[0]", "a"), ("rod[0]", "b")]) - self.assertEqual(len(let.pairs), 2 * 4 - 2) - crossed = R.clearance(dressed(self.m, seats, {"barrel": ["b"], "rod": ["a"]}), ram, 0.0, seats) - self.assertLess(float(crossed.margin[0]), 0.0) + zones = {"barrel": [("a", "a", 0.03 + near(ram, "barrel"), 0.0)], "rod": [("b", "b", 0.03 + near(ram, "rod"), 0.03)]} + let_ = R.clearance(dressed(m, seats, zones), ram, 0.0, seats) + self.assertGreaterEqual(float(let_.margin[0]), 0.0) + self.assertEqual(sorted(let_.allowed), [("barrel[0]", "a"), ("rod[0]", "b")]) + self.assertEqual(len(let_.pairs), 2 * 4) + self.assertAlmostEqual(let_.pairs[("rod[0]", "b")][0], 0.0, places=12) # at the pin's centre: the ball's depth, and the zone's + # a micron shallower and the rod is a micron inside; a zone that stops short of what the member keeps is refused + # beyond it; the other member's zone, or a zone about the member's other pin, lets nothing + shallow = R.clearance(dressed(m, seats, {**zones, "rod": [("b", "b", 0.03 + near(ram, "rod"), 0.03 - 1e-6)]}), ram, 0.0, seats) + self.assertAlmostEqual(shallow.pairs[("rod[0]", "b")][0], -1e-6, places=12) + self.assertEqual(shallow.where, (0.0, "rod[0]", "b", "b")) + short = R.clearance(dressed(m, seats, {**zones, "rod": [("b", "b", 0.02, 0.03)]}), ram, 0.0, seats, spacing=0.01) + rod = float(np.linalg.norm(m.b - m.a)) - ram.back - self.barrel + step = rod / math.ceil(rod / 0.01) + first = step * (math.floor(0.02 / step) + 1) # the first sample past the zone, from the eye + self.assertAlmostEqual(short.pairs[("rod[0]", "b")][0], first - 0.03 - near(ram, "rod", 0.01), places=12) + self.assertLess(first, 0.03) + # a zone names its part whole: a lug at the eye named for the pin's part is no part of the zone (S20) + lugged = two(a=seats.shapes["a"] and ("parent", seats.shapes["a"]), b=("child", seats.shapes["b"]), **{"b.lug": ("child", seats.shapes["b"])}) + got = R.clearance(dressed(m, lugged, zones), ram, 0.0, lugged) + self.assertEqual({pair: round(reading[0], 9) for pair, reading in got.pairs.items() if reading[0] < 0.0}, {("rod[0]", "b.lug"): round(-0.03 - near(ram, "rod"), 9)}) + for crossed in ({"barrel": [("b", "b", 0.2, 0.03)], "rod": [("a", "a", 0.2, 0.03)]}, {"barrel": [("a", "b", 0.2, 0.03)], "rod": [("b", "a", 0.2, 0.03)]}): + self.assertLess(float(R.clearance(dressed(m, seats, crossed), ram, 0.0, seats).margin[0]), 0.0) def test_every_body_owns_a_part(self): ball = Bodies({"ball": ("parent", [("capsule", (0, 0, 0), (0, 0, 0), 0.1)])}) @@ -628,7 +781,7 @@ class OracleRule(unittest.TestCase): free = R.clearance(dressed(m, bodies, touch), ram, angles, bodies).margin capped = R.clearance(dressed(m, bodies, touch), ram, angles, r3_bodies(m, ram, cap=ram.reach())[0]).margin self.assertEqual((free >= 0.0).tolist(), (capped >= 0.0).tolist(), kind) - self.assertTrue(np.allclose(np.minimum(free, 0.0), np.minimum(capped, 0.0), atol=1e-12)) + self.assertTrue(np.array_equal(np.minimum(free, 0.0), np.minimum(capped, 0.0))) # a cap changes no reading under it asked.append(bool((free < 0.0).any())) self.assertEqual(asked, [True, False]) # one of each verdict was compared @@ -657,6 +810,44 @@ class SearchBestFirst(unittest.TestCase): self.assertGreaterEqual(found.best.clear_min, 0.0) self.assertEqual(found.tally, {"clash": 3 - len(clear)}) self.assertEqual(found.fits, 3) + # the caller's spacing is the winner's gate's (S12): its reading is the fit's at that spacing, not the default's + fine = R.search("direct", self.HINGE, ram, seats, world=lambda m: (block.parts, {}, block), spacing=0.01) + finely = [a for _, a in arms if R._fit(dressed(R.Mechanism("direct", O, X, -60, 0, a=a, b=seats["b"][0]), block), ram, distance=block, spacing=0.01).ok] + self.assertEqual(tuple(fine.seat["a"]), finely[-1]) + self.assertEqual(fine.best.clear_min, R._fit(dressed(fine.best.m, block), ram, distance=block, spacing=0.01).clear_min) + self.assertNotEqual((finely[-1], fine.best.clear_min), (clear[-1], found.best.clear_min)) + + def test_the_nearest_miss_counts_the_clash(self): + # a bar every seat's ram runs into, deepest for the best arm: the nearest miss is the shallowest clash, not + # the first met (S5: the shortfall without the clearance) + ram = R.Ram(0.05) + seats = {"a": [(0, -0.2, 1.0), (0, -0.3, 1.0), (0, -0.4, 1.0)], "b": [(0, -0.3, -1.0)]} + bar = two(parent=[("capsule", (-0.5, -0.7, 0.9), (0.5, -0.7, 0.9), 0.42)]) + fits = [R._fit(dressed(R.Mechanism("direct", O, X, -60, 0, a=a, b=seats["b"][0]), bar), ram, distance=bar) for a in seats["a"]] + self.assertTrue(all(f.why and f.why[0][0] == "clash" for f in fits), [f.report() for f in fits]) + first = max(range(3), key=lambda k: fits[k].arm_min) + nearest = max(range(3), key=lambda k: fits[k].clear_min) + self.assertNotEqual(first, nearest) + missed = R.search("direct", self.HINGE, ram, seats, world=lambda m: (bar.parts, {}, bar)) + self.assertFalse(missed.found) + self.assertEqual(missed.tally, {"clash": 3}) + self.assertEqual(tuple(missed.seat["a"]), seats["a"][nearest]) + self.assertEqual(missed.best.clear_min, fits[nearest].clear_min) + + def test_what_a_world_returns_is_read_as_a_record(self): + ram = R.Ram(0.05) + seats = {"a": [(0, -0.3, 1.0)], "b": [(0, -0.3, -1.0)]} + ball = two(parent=[("capsule", (0, 0.5, 0), (0, 0.5, 0), 0.05)]) + for made, gate, said in (((ball.parts, ball), "search", "world(m) returns (parts, touch, distance), got tuple"), (None, "search", "got NoneType"), + ((ball.parts, {}, None), "search", "world(m) returns"), ((ball.parts, {"rod": ["parent"]}, ball), "record", "zone is (part, pin, radius, depth)"), + ((ball.parts, {"rod": [("parent", "c", 1.0, 0.0)]}, ball), "record", "a pin it rides (a, b)"), + ((ball.parts, {"rod": [("thigh", "b", 1.0, 0.0)]}, ball), "record", "no part of the record"), + (({"ball": "rocker"}, {}, ball), "record", "turns with 'rocker'"), (({"ball": "parent"}, {}, ball), "record", "no part turns with body child")): + with self.assertRaises(R.RamError) as caught: + R.search("direct", self.HINGE, ram, seats, world=lambda m: made) + self.assertEqual(caught.exception.gate, gate, said) + self.assertIn(said, str(caught.exception)) + self.assertTrue(R.search("direct", self.HINGE, ram, seats, world=lambda m: (ball.parts, {}, ball)).found) def test_the_limit_is_refused_naming_the_count(self): seats = {"a": grid((0, -0.5, 0.4), (0, -0.2, 1.2), (1, 3, 5)), "b": grid((0, -0.5, -1.2), (0, -0.2, -0.4), (1, 3, 5))} @@ -673,6 +864,13 @@ class SearchBestFirst(unittest.TestCase): found = R.search("four_bar", hinge, ram, seats, steps=49) self.assertTrue(found.found, found.report()) self.assertIn("assembly", found.tally) + # with the links' plates at the probe's stack the ram still runs across the axis: a four-bar's eye is p, and + # both stand at a's place (S18: p left at the rocker's is a record no four-bar reads) + stacked = {**seats, "rocker": [yz(DEEP["rocker"], X_ROCKER)], "c": [yz(DEEP["c"], X_COUPLER)]} + self.assertTrue(all(seat["p"][0] == seat["a"][0] == 0.0 and np.array_equal(seat["p"], seat["d"]) for seat in R.candidates("four_bar", hinge, stacked))) + beside = R.search("four_bar", hinge, ram, stacked, steps=49) + self.assertTrue(beside.found and "record" not in beside.tally, beside.report()) + self.assertEqual((beside.tally, beside.fits, beside.best.arm_min), (found.tally, found.fits, found.best.arm_min)) crank = R.candidates("bell_crank", hinge, {**seats, "d": (0.12, 0.24, 3)}) self.assertEqual(len(crank), 2 * 5 * 24 * 3 * 12) @@ -720,7 +918,8 @@ class RecordDrives(unittest.TestCase): self.assertEqual((data["schema"], data["version"], data["compliance"]), ("brokkr.ram", 1, None)) again, ram2 = R.from_record(wire) self.assertEqual(R.record(again, ram2), data) - self.assertEqual((again.parts, again.touch), (m.parts, {k: tuple(v) for k, v in m.touch.items()})) + self.assertEqual((again.parts, again.touch), (m.parts, m.touch)) + self.assertEqual([sorted(zone) for zones in wire["touch"].values() for zone in zones], [sorted(R.ZONE)] * sum(len(z) for z in m.touch.values())) angles = np.linspace(m.lo, m.hi, 49) self.assertEqual(R.length(again, angles).tolist(), R.length(m, angles).tolist()) ext = R.extension(again, ram2, angles) @@ -752,11 +951,45 @@ class RecordDrives(unittest.TestCase): short = {k: v for k, v in data.items() if k != "touch"} for change, said in (({"version": 2}, "version 2"), ({"version": 2, "compliance": settle}, "version 2"), ({"compliance": settle}, "compliance block"), ({"schema": "brokkr.kit"}, "brokkr.kit"), ({"settle": settle}, "unknown ['settle']"), ({"ram": ram}, "unknown ['stiffness']"), - ({"hinge": dict(data["hinge"], rate=1.0)}, "unknown ['rate']")): + ({"hinge": dict(data["hinge"], rate=1.0)}, "unknown ['rate']"), + # a block that is falsy is a block (S23); the version is the integer 1 + ({"compliance": {}}, "compliance block"), ({"compliance": 0}, "compliance block"), ({"compliance": False}, "compliance block"), + ({"version": 1.0}, "version 1.0"), ({"version": True}, "version True"), ({"version": "1"}, "version '1'"), + ({"kind": "scissor"}, "kind is one of"), + # a pin this kind has not, or a key that is no pin, is refused by name; so is one missing + ({"pins": dict(data["pins"], q=[0.0, 0.0, 0.0])}, "the pins's keys are not version 1's: unknown ['q']"), + ({"pins": dict(data["pins"], parts={})}, "unknown ['parts']"), ({"pins": {"a": data["pins"]["a"]}}, "missing ['b']"), + ({"pins": [1, 2]}, "(pin pins): an object, got list"), ({"ram": None}, "(pin ram): an object, got NoneType"), + # every number is a finite number, the bore over 0; three of them make a point + ({"ram": dict(data["ram"], bore=None)}, "(pin bore): a finite number, got None"), ({"ram": dict(data["ram"], bore=-1.0)}, "(pin bore): a number greater than 0, got -1.0"), + ({"ram": dict(data["ram"], bore=0)}, "(pin bore)"), ({"ram": dict(data["ram"], min_arm=float("nan"))}, "(pin min_arm): a finite number, got nan"), + ({"ram": dict(data["ram"], gap=float("inf"))}, "(pin gap)"), ({"ram": dict(data["ram"], rod=True)}, "(pin rod): a finite number, got True"), + ({"ram": dict(data["ram"], rod=None)}, "direct ram: record (pin rod): a finite number, got None"), # a record's ram holds every proportion: none defaults + ({"ram": dict(data["ram"], tail="0.2")}, "(pin tail): a finite number, got '0.2'"), + ({"hinge": dict(data["hinge"], lo="a")}, "(pin lo): a finite number, got 'a'"), ({"hinge": dict(data["hinge"], hi=None)}, "(pin hi)"), + ({"hinge": dict(data["hinge"], pivot=[0.0, 0.0])}, "(pin pivot): three finite numbers"), ({"hinge": dict(data["hinge"], axis="xyz")}, "(pin axis): three finite numbers"), + ({"pins": dict(data["pins"], a=["0", "1", "2"])}, "(pin a): a finite number, got '0'"), ({"pins": dict(data["pins"], b=[0.0, 1.0, float("inf")])}, "(pin b)"), + ({"offsets": "0"}, "(pin offsets)"), ({"offsets": [None]}, "(pin offsets): a finite number"), ({"offsets": []}, "at least one offset"), + ({"parts": ["knee"]}, "(pin parts)"), ({"parts": {"knee": 1}}, "(pin parts)"), ({"touch": []}, "(pin touch)"), + ({"parts": {"knee": "parent"}, "touch": {"rod": ["knee"]}}, "(pin rod zone): an object, got str"), + ({"parts": {"knee": "parent"}, "touch": {"rod": "knee"}}, "rod's zones are a list"), + ({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1}]}}, "missing ['depth']"), + ({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0.0, "whole": True}]}}, "unknown ['whole']"), + ({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": None, "depth": 0.0}]}}, "(pin rod knee radius)")): with self.assertRaises(R.RamError) as caught: R.from_record({**data, **change}) self.assertEqual(caught.exception.gate, "record", change) self.assertIn(said, str(caught.exception)) + with self.assertRaises(R.RamError) as caught: + R.from_record([data]) + self.assertIn("a record is an object, got list", str(caught.exception)) + zoned = R.from_record({**data, "parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0}]}})[0] + self.assertEqual(zoned.touch, {"rod": (("knee", "b", 0.1, 0.0),)}) + # a ram refuses the same numbers when built by hand + for bad in ({"bore": -0.05}, {"bore": 0.0}, {"bore": None}, {"bore": True}, {"bore": 0.05, "gap": float("nan")}, {"bore": 0.05, "tail": float("inf")}, {"bore": 0.05, "rod": "0.02"}): + with self.assertRaises(R.RamError) as caught: + R.Ram(**bad) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", list(bad)[-1])) with self.assertRaises(R.RamError) as caught: R.from_record(short) self.assertIn("missing ['touch']", str(caught.exception)) @@ -791,8 +1024,19 @@ class Refusals(unittest.TestCase): self.assertEqual(self.refused("record", lo=-200, hi=200).angle, -200.0) self.refused("record", "a", offsets=()) # the ram stands along the axis from a self.assertIn("'knee' turns with 'foot'", str(self.refused("record", parts={"knee": "foot"}))) - self.assertIn("touch names 'piston'", str(self.refused("record", parts={"knee": "parent"}, touch={"piston": ["knee"]}))) - self.assertIn("rod may touch 'hip'", str(self.refused("record", parts={"knee": "parent"}, touch={"rod": ["hip"]}))) + self.assertIn("touch names 'piston'", str(self.refused("record", parts={"knee": "parent"}, touch={"piston": [("knee", "d", 0.1, 0.0)]}))) + self.assertIn("rod may touch 'hip'", str(self.refused("record", parts={"knee": "parent"}, touch={"rod": [("hip", "d", 0.1, 0.0)]}))) + # a zone is (part, a pin the member rides, radius over 0, depth of 0 or more): a bare part name lets nothing + knee = {"parts": {"knee": "parent"}} + self.assertIn("zone is (part, pin, radius, depth), got 'knee'", str(self.refused("record", **knee, touch={"rod": ["knee"]}))) + self.assertIn("zone is (part, pin, radius, depth)", str(self.refused("record", **knee, touch={"rod": [("knee", "d", 0.1)]}))) + self.assertIn("a pin it rides (a, d), not 'c'", str(self.refused("record", "c", **knee, touch={"rod": [("knee", "c", 0.1, 0.0)]}))) + self.assertIn("a pin it rides (p, c), not 'rocker'", str(self.refused("record", "rocker", **knee, touch={"coupler": [("knee", "rocker", 0.1, 0.0)]}))) + self.refused("record", "rod knee radius", **knee, touch={"rod": [("knee", "d", 0.0, 0.0)]}) + self.refused("record", "rod knee radius", **knee, touch={"rod": [("knee", "d", float("inf"), 0.0)]}) + self.refused("record", "rod knee radius", **knee, touch={"rod": [("knee", "d", "0.1", 0.0)]}) + self.refused("record", "rod knee depth", **knee, touch={"rod": [("knee", "d", 0.1, -0.01)]}) + self.refused("record", "rod knee depth", **knee, touch={"rod": [("knee", "d", 0.1, float("nan"))]}) self.refused("record", "a", a=(0, 1)) self.refused("record", "c", c=(0, float("nan"), 1)) self.refused("record", "b", b=(0, 0, -1)) # a four-bar has no b From bafdb171cd1bb8488479706e4bad0e525b7535a0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:01:36 +0100 Subject: [PATCH 138/223] live ram_knee: the R-3 knee on generated meshes under a three-ray signed oracle, zones, moved x, the seated clevis, the search Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/ram_knee.py | 450 ++++++++++++++++++ .../blender/tests/live/ram_knee.result.json | 444 +++++++++++++++++ 2 files changed, 894 insertions(+) create mode 100644 surfaces/blender/tests/live/ram_knee.py create mode 100644 surfaces/blender/tests/live/ram_knee.result.json diff --git a/surfaces/blender/tests/live/ram_knee.py b/surfaces/blender/tests/live/ram_knee.py new file mode 100644 index 0000000..d364092 --- /dev/null +++ b/surfaces/blender/tests/live/ram_knee.py @@ -0,0 +1,450 @@ +"""Live proof, in a background Blender, of brokkr_kitbash/ram.py's clearance gate on meshes: the R-3 knee (thigh, +shin, the bracket and horn, a bell crank's or a four-bar's plates, pins and clevises), every piece a closed mesh this +file generates, each a named part of a body, and the gate answered by a signed BVH oracle over them. Not part of the +unittest run: it needs Blender (mathutils' BVHTree). + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/ram_knee.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 .r3_.png (the bell crank at 0, +-62.5 and -125) and exits 1 when a check failed. + +The oracle. distance(part, points) is the nearest face's distance, negative where the point is inside one of the +part's shells. Inside is the crossing parity of three rays, by majority: one ray that grazes an edge or a vertex +miscounts, and an isolated sample then reads inside a plate it stands clear of. + +A clearance verdict is a sign, the gate's own. FLAT follows lodur:ruling:deterministic-bound-margin. The checks run +inside one try: an uncaught error is a failed check that names its section, and the result file is always written. +""" +import importlib.util +import json +import math +import os +import sys +import time +import traceback +from dataclasses import replace +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") +spec = importlib.util.spec_from_file_location("brokkr_kitbash_ram", SURFACE / "brokkr_kitbash" / "ram.py") +R = importlib.util.module_from_spec(spec) # ram.py as the unit tests load it +sys.modules[spec.name] = R +spec.loader.exec_module(R) + +RES = {"blender": bpy.app.version_string, "checks": [], "readings": {}} +SECTION = ["setup"] +# Metres between the oracle's reading and 0.0225, on a grid a plate's thickness off a rocker plate's face. Shipped +# worst 1.3e-08 (float32 faces); least claimed mutant 0.045 (a sample signed inside reads -0.0225); the geometric mean. +FLAT = 2.4e-5 + +BORE, PIN, AXLE = 0.042, 0.026, 0.028 +SLAB_C, SLAB_R = (0.31, 0.345), (0.35, 0.385) # the twin link plates along the axis: the coupler's inside the rocker's +X_C, X_R = 0.5 * sum(SLAB_C), 0.5 * sum(SLAB_R) +HALF = 0.5 * (SLAB_R[1] - SLAB_R[0]) # half a plate's thickness +W_ROCKER, W_COUPLER, W_ARM, W_HORN, W_BRACKET, COLLAR = 0.045, 0.04, 0.04, 0.05, 0.055, 0.05 +CHEEK = (0.03, 0.05) # a clevis's cheeks, either side of the ram's eye +SLACK = 0.001 # a zone's depth over the burial it lets: a float32 face reads a burial to 1e-8 +# P2's seats, (y, z): the deep four-bar behind the knee and the bell crank in front of it +DEEP = {"a": (-0.45, 1.15), "rocker": (-0.2320142211320173, 0.4604939911625098), "p": (-0.43650046730511183, -0.017951928782268284), + "c": (0.06881023105761902, -0.3143743967236484), "d": (-0.43650046730511183, -0.017951928782268284)} +CRANK = {"a": (0.45, 1.15), "rocker": (0.3171126791600819, 0.3216537818398838), "p": (0.7282866960904424, 0.43261578669776135), + "c": (0.34929485118682846, 0.14862538079826304), "d": (0.48651463351122515, 0.49166254003196397)} +ROOTS = {"bell_crank": {"horn": (0.10, -0.40), "bracket": (0.10, 0.55)}, "four_bar": {"horn": (0.0, -0.42), "bracket": (-0.10, 0.55)}} +THIGH_FRONT, EMBED = 0.14, 0.01 # the thigh core's faces stand at y +-0.14; a foot runs this far into it +RAYS = [Vector(v).normalized() for v in ((0.5377, 0.6211, 0.5701), (-0.7071, 0.2903, 0.6447), (0.1873, -0.8011, -0.5684))] + + +def check(name, ok, detail=None): + RES["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) + + +def prism(outline, x0, x1): + """A closed shell: the convex (y, z) outline, counter-clockwise seen from +x, run from x0 to x1.""" + x0, x1 = min(x0, x1), max(x0, x1) + n = len(outline) + verts = [(x, y, z) for x in (x0, x1) for y, z in outline] + faces = [tuple(range(n - 1, -1, -1)), tuple(range(n, 2 * n))] + [(k, (k + 1) % n, n + (k + 1) % n, n + k) for k in range(n)] + return np.array(verts, dtype=float), faces + + +def box(centre, size): + (cx, cy, cz), (sx, sy, sz) = centre, size + return prism([(cy - sy / 2, cz - sz / 2), (cy + sy / 2, cz - sz / 2), (cy + sy / 2, cz + sz / 2), (cy - sy / 2, cz + sz / 2)], cx - sx / 2, cx + sx / 2) + + +def disc(at, r, x0, x1, n=32): + return prism([(at[0] + r * math.cos(2 * math.pi * k / n), at[1] + r * math.sin(2 * math.pi * k / n)) for k in range(n)], x0, x1) + + +def bar(p, q, w, x0, x1, n=10): + """A link plate: the stadium of half width w about the segment p -> q.""" + p, q = np.array(p, float), np.array(q, float) + base = math.atan2(*((q - p) / np.linalg.norm(q - p))[::-1]) + pts = [(c[0] + w * math.cos(a0 + math.pi * k / n), c[1] + w * math.sin(a0 + math.pi * k / n)) for c, a0 in ((q, base - math.pi / 2), (p, base + math.pi / 2)) for k in range(n + 1)] + return prism(pts, x0, x1) + + +def knee(kind, pn, links=True): + """part -> [shell], part -> body: the knee at rest (angle 0, every frame the parent's).""" + shells, front = {}, kind == "bell_crank" + + def add(part, *made): + shells.setdefault(part, []).extend(made) + r, gap, cheek = 0.25, 0.22, 0.07 + half = gap / 2 + cheek + add("parent.body", box((0, 0, 0.725), (0.26, 2 * THIGH_FRONT, 0.85)), box((0, 0.185, 0.725), (0.34, 0.06, 0.77)), box((0, 0, 0.2), (gap - 0.03, 0.24, 0.4)), + disc((0, 0), 0.9 * r, -(gap - 0.03) / 2, (gap - 0.03) / 2)) + outline = [(r * math.cos(math.radians(a)), r * math.sin(math.radians(a))) for a in range(0, 181, 15)] + [(-0.12, -0.95), (0.12, -0.95)] + add("child.body", box((0, 0, -0.72), (gap, 0.22, 0.46)), box((0, 0.15, -0.62), (2 * half + 0.06, 0.06, 0.58))) + Rk, P, C, A, D = (pn[k] for k in ("rocker", "p", "c", "a", "d")) + for s in (-1, 1): + add("child.body", prism(outline, s * gap / 2, s * half), disc((0, 0), 0.19, s * half, s * (half + 0.025)), box((s * (half + 0.03), 0.0, -0.62), (0.045, 0.2, 0.5))) + add("child.horn", bar(ROOTS[kind]["horn"], C, W_HORN, s * (half + 0.05), s * SLAB_C[0])) + add("parent.bracket", bar(ROOTS[kind]["bracket"], Rk, W_BRACKET, s * 0.13, s * SLAB_R[0])) + # the base clevis: cheeks about the pin and a foot that runs into the thigh's core, toward it + toward = -1.0 if front else 1.0 + foot = (A[0] + toward * 0.2, A[1]) + add("parent.seat", bar(A, foot, 1.7 * BORE, s * CHEEK[0], s * CHEEK[1])) + if links: + add("rocker.plate", bar(Rk, P, W_ROCKER, s * SLAB_R[0], s * SLAB_R[1])) + add("coupler.plate", bar(P, C, W_COUPLER, s * SLAB_C[0], s * SLAB_C[1])) + add("rocker.seat", disc(D, COLLAR, s * CHEEK[0], s * CHEEK[1])) # the eye's collars on its pin + if front: + add("rocker.plate", bar(Rk, D, W_ARM, s * SLAB_R[0], s * SLAB_R[1])) + face = toward * (THIGH_FRONT - EMBED) + add("parent.seat", box((0, 0.5 * (face + foot[0]), A[1]), (2 * CHEEK[1], abs(foot[0] - face), 3.4 * BORE))) + if links: + add("rocker.pin.R", disc(Rk, AXLE, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015)) + add("rocker.pin.p", disc(P, PIN, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015)) + add("coupler.pin.c", disc(C, PIN, -SLAB_C[1] - 0.015, SLAB_C[1] + 0.015)) + if front: + add("rocker.pin.d", disc(D, PIN, -SLAB_R[1] - 0.015, SLAB_R[1] + 0.015)) + return shells, {part: {"parent": "parent", "child": "child", "rocker": "rocker", "coupler": "coupler"}[part.split(".")[0]] for part in shells} + + +class Signed: + """distance(part, points): negative inside a part's shell (the depth below its nearest face), capped outside + only. Inside is the crossing parity of `rays` rays, by majority. An unknown part raises.""" + + def __init__(self, shells, cap=None, rays=3): + self.cap, self.asked, self.rays = cap, 0, RAYS[:rays] + self.trees = {part: [(BVHTree.FromPolygons(v.tolist(), f, epsilon=0.0), v.min(axis=0), v.max(axis=0)) for v, f in made] for part, made in shells.items()} + + @staticmethod + def crossings(tree, v, ray): + count, o = 0, v + for _ in range(64): + loc = tree.ray_cast(o, ray)[0] + if loc is None: + break + count, o = count + 1, loc + ray * 1e-6 + return count + + def inside(self, tree, v): + return 2 * sum(self.crossings(tree, v, ray) % 2 for ray in self.rays) > len(self.rays) + + def __call__(self, part, pts): + pts = np.asarray(pts, dtype=float) + self.asked += len(pts) + out = np.full(len(pts), math.inf if self.cap is None else self.cap) + for tree, lo, hi in self.trees[part]: + boxed = ((pts >= lo) & (pts <= hi)).all(axis=1) + for i, p in enumerate(pts): + v = Vector(p) + if boxed[i] and self.inside(tree, v): + out[i] = min(out[i], -tree.find_nearest(v)[3]) + continue + hit = tree.find_nearest(v, self.cap) if self.cap else tree.find_nearest(v) + if hit[0] is not None and hit[3] < out[i]: + out[i] = hit[3] + return out + + +def near(ram, member): + return {"barrel": ram.barrel_r, "rod": ram.rod}.get(member, ram.link_r) + ram.gap + ram.spacing() / 2 + + +def parting(ram, w, degrees): + """How far from a pin a link parts from a plate of half width w that stands beside it on the pin, a plate's + thickness off along the axis, the two crossing at `degrees` at the least: where the link's axis is what a link + keeps from the plate's edge, and never less than the plate's round end.""" + lateral = math.sqrt(near(ram, "rocker") ** 2 - HALF ** 2) + return max((w + lateral) / math.sin(math.radians(min(degrees, 90.0))), w + near(ram, "rocker")) + + +def crossing(m, kind): + """The least angle, over the range, at which the rocker, the rocker arm and the coupler cross what stands beside + them: the bracket's bar at the pivot, the horn's at c (seen from the shin), each other at p.""" + p, n = R.pose(m, np.linspace(m.lo, m.hi, 126)), m.axis + + def least(a, b): + a, b = R._flat(a, n), R._flat(np.broadcast_to(b, a.shape), n) + return float(np.degrees(np.arccos(np.clip((a * b).sum(axis=1) / (np.linalg.norm(a, axis=1) * np.linalg.norm(b, axis=1)), -1.0, 1.0))).min()) + root = {key: np.array((0.0, *value)) for key, value in ROOTS[kind].items()} + seen = R._into(m, p, "child", p.P[:, None, :])[:, 0, :] + return {"rocker": least(p.P - m.rocker, root["bracket"] - m.rocker), "rocker arm": least(p.eye - m.rocker, root["bracket"] - m.rocker), + "coupler": least(seen - m.c, root["horn"] - m.c), "p": float(p.mu_p.min())} + + +def zones(m, ram, parts): + """Each member's zones. About a pin: the pin's, collar's or cheek's radius plus what the member keeps, as deep as + the pin where it runs through the member's eye and 0 beside a collar, a cheek, the bracket or the horn; a link's + own plate over its length, half its thickness deep; a plate beside a link as far as the two part. A depth that + is not 0 is stated SLACK over the burial.""" + kind, link, at = m.kind, near(ram, "rocker"), crossing(m, m.kind) + PIN, AXLE, HALF = (value + SLACK for value in (globals()["PIN"], globals()["AXLE"], globals()["HALF"])) + reach = {"pin": globals()["PIN"] + link, "axle": globals()["AXLE"] + link} + eye = "rocker.pin.d" if kind == "bell_crank" else "rocker.pin.p" + touch = {member: [("parent.seat", "a", 1.7 * BORE + near(ram, member), 0.0), ("rocker.seat", "d", COLLAR + near(ram, member), 0.0), + (eye, "d", globals()["PIN"] + near(ram, member), PIN if member == "rod" else 0.0)] for member in ("barrel", "rod")} + pivot = [("parent.bracket", "rocker", None, 0.0), ("rocker.pin.R", "rocker", reach["axle"], AXLE)] + touch["rocker"] = pivot + [("rocker.pin.p", "p", reach["pin"], PIN), ("rocker.plate", "rocker", 1.01 * m.lr, HALF), ("coupler.plate", "p", parting(ram, W_COUPLER, at["p"]), 0.0)] + touch["coupler"] = [("child.horn", "c", parting(ram, W_HORN, at["coupler"]), 0.0), ("coupler.pin.c", "c", reach["pin"], PIN), ("rocker.pin.p", "p", reach["pin"], PIN), + ("coupler.plate", "p", 1.01 * m.lc, HALF), ("rocker.plate", "p", parting(ram, W_ROCKER, at["p"]), 0.0)] + if kind == "bell_crank": + touch["rocker arm"] = pivot + [("rocker.pin.d", "d", reach["pin"], PIN), ("rocker.plate", "rocker", 1.01 * float(np.linalg.norm(R._flat(m.d - m.rocker, m.axis))), HALF)] + for member in ("rocker", "rocker arm"): + if member in touch: + touch[member][0] = ("parent.bracket", "rocker", parting(ram, W_BRACKET, at[member]), 0.0) + return {member: [zone for zone in given if zone[0] in parts] for member, given in touch.items()} + + +def pins3(pn, side=1.0, **moved): + at = {"a": 0.0, "p": 0.0, "d": 0.0, "rocker": side * X_R, "c": side * X_C, **moved} + return {k: (at[k], float(pn[k][0]), float(pn[k][1])) for k in pn} + + +def needs(m, ram, parts, distance, steps=49): + """(member, part) -> (pin, radius, depth): for every pair refused with nothing let, the least zone that lets it.""" + p = R.pose(m, np.linspace(m.lo, m.hi, steps)) + at = {"a": p.base, R.EYE[m.kind]: p.eye, "rocker": m.rocker, "p": p.P, "c": p.C} + step, out = ram.spacing(), {} + for member, label, start, end, radius, pins in R._members(m, ram, R.barrel_length(m, ram), p): + count = max(int(math.ceil(float(np.linalg.norm(end - start, axis=1).max()) / step)) + 1, 2) + pts = start[:, None, :] + (end - start)[:, None, :] * np.linspace(0.0, 1.0, count)[None, :, None] + for part, body in parts.items(): + got = distance(part, R._into(m, p, body, pts).reshape(-1, 3)).reshape(len(p.degrees), count) + bad = got < radius + ram.gap + step / 2 + if bad.any(): + best = None + for pin in pins: + across = np.linalg.norm(R._flat(pts - np.broadcast_to(at[pin], start.shape)[:, None, :], m.axis), axis=2) + reach = float(across[bad].max()) + if best is None or reach < best[1]: + best = (pin, reach, max(-float(got[across <= reach].min()), 0.0)) + out[(label, part)] = best + return out + + +def refused(f): + return sorted((pair, round(reading[0], 4), reading[1]) for pair, reading in f.pairs.items() if reading[0] < 0.0) + + +def label(member): + return member + "[0]" if member in ("barrel", "rod") else member + + +def hinge4(pivot, degrees): + return Matrix.Translation(Vector(pivot)) @ Matrix.Rotation(math.radians(degrees), 4, "X") @ Matrix.Translation(-Vector(pivot)) + + +def render(m, ram, f, shells, parts): + """The bell crank at 0, -62.5 and -125, each piece coloured by its part, the ram as the gate holds it.""" + scene = bpy.context.scene + colour = {"horn": (0.95, 0.45, 0.1, 1), "bracket": (0.15, 0.45, 0.9, 1), "plate": (0.75, 0.75, 0.78, 1), "seat": (0.55, 0.3, 0.6, 1), "pin": (0.9, 0.9, 0.3, 1)} + objects = [] + for part, made in shells.items(): + for k, (verts, faces) in enumerate(made): + me = bpy.data.meshes.new(f"{part}.{k}") + me.from_pydata(verts.tolist(), [], faces) + o = bpy.data.objects.new(me.name, me) + scene.collection.objects.link(o) + o.color = colour.get(part.split(".")[1], (0.33, 0.38, 0.24, 1) if parts[part] == "child" else (0.3, 0.32, 0.36, 1)) + objects.append((o, parts[part])) + + def tube(name, r, col): + me, bm = bpy.data.meshes.new(name), bmesh.new() + bmesh.ops.create_cone(bm, cap_ends=True, segments=24, radius1=r, radius2=r, depth=1.0) + bmesh.ops.translate(bm, verts=bm.verts[:], vec=(0, 0, 0.5)) + bm.to_mesh(me) + bm.free() + o = bpy.data.objects.new(name, me) + scene.collection.objects.link(o) + o.color = col + return o + barrel, rod = tube("ram.barrel", ram.barrel_r, (0.85, 0.15, 0.12, 1)), tube("ram.rod", ram.rod, (0.95, 0.95, 0.95, 1)) + scene.render.engine = "BLENDER_WORKBENCH" + scene.display.shading.light, scene.display.shading.color_type = "STUDIO", "OBJECT" + scene.display.shading.show_shadows = scene.display.shading.show_cavity = True + scene.render.resolution_x, scene.render.resolution_y, scene.render.film_transparent = 1400, 1500, False + scene.world = bpy.data.worlds.new("w") + scene.world.color = (0.82, 0.83, 0.85) + cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam")) + scene.collection.objects.link(cam) + cam.data.type, cam.data.ortho_scale = "ORTHO", 2.75 + target = Vector((0.0, 0.1, 0.12)) + cam.location = target + Vector((0.72, 0.62, 0.22)).normalized() * 8.0 + cam.rotation_euler = (target - cam.location).to_track_quat("-Z", "Y").to_euler() + scene.camera = cam + made = [] + for angle in (0.0, -62.5, -125.0): + p = R.pose(m, angle) + T = {"parent": Matrix.Identity(4), "child": hinge4((0, 0, 0), angle), "rocker": hinge4(m.rocker, math.degrees(p.phi[0])), + "coupler": Matrix.Translation(Vector(p.P[0] - m.p)) @ hinge4(m.p, math.degrees(p.psi[0]))} + for o, body in objects: + o.matrix_world = T[body] + u, base = Vector(p.u[0]), Vector(p.base[0]) + frame = u.to_track_quat("Z", "Y").to_matrix().to_4x4() + barrel.matrix_world = Matrix.Translation(base + u * ram.back) @ frame @ Matrix.Diagonal((1, 1, f.barrel, 1)) + rod.matrix_world = Matrix.Translation(base + u * (ram.back + f.barrel)) @ frame @ Matrix.Diagonal((1, 1, float(p.L[0]) - ram.back - f.barrel, 1)) + scene.render.filepath = f"{OUT}.r3_{abs(angle):g}".replace(".5", "p5") + ".png" + bpy.ops.render.render(write_still=True) + made.append(scene.render.filepath) + return made + + +try: + bpy.ops.wm.read_factory_settings(use_empty=True) + ram = R.Ram(BORE) + HINGE = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), -125.0, 0.0) + + SECTION[0] = "oracle" + shells, parts = knee("bell_crank", CRANK) + rows = [] + for name, part, point, depth in (("the thigh core's centre", "parent.body", (0.0, 0.0, 0.7), -0.13), ("0.02 inside the thigh's wall", "parent.body", (0.11, 0.0, 0.7), -0.02), + ("the shin's leg centre", "child.body", (0.0, 0.0, -0.7), -0.11), ("0.125 off the thigh's plate", "parent.body", (0.0, 0.34, 0.7), 0.125)): + capped, free = (float(Signed(shells, cap)(part, np.array([point]))[0]) for cap in (ram.reach(), None)) + rows.append((name, capped, free, abs(free - depth) < FLAT and capped == (free if depth < 0 else min(free, ram.reach())))) + check("inside-is-negative: a point inside a part reads its depth, negative, capped or not; a cap changes only what is outside", all(row[3] for row in rows), rows) + # a grid a plate's thickness off the rocker plates' inner face, over the knee: every point is 0.0225 or more from the + # plates and none is inside; where the plate is under the point the reading is the 0.0225 + ys, zs = np.meshgrid(np.linspace(0.1, 0.9, 96), np.linspace(0.1, 0.7, 72)) + plane = np.stack([np.full(ys.size, X_C), ys.ravel(), zs.ravel()], axis=1) + three, one = Signed(shells)("rocker.plate", plane), Signed(shells, rays=1)("rocker.plate", plane) + def off(a, b): # each grid point's distance from the segment a -> b, across the axis + a, b = np.array(a), np.array(b) + t = np.clip(((plane[:, 1:] - a) @ (b - a)) / ((b - a) @ (b - a)), 0.0, 1.0) + return np.linalg.norm(plane[:, 1:] - a - t[:, None] * (b - a), axis=1) + under = (off(CRANK["rocker"], CRANK["p"]) < W_ROCKER - 0.005) | (off(CRANK["rocker"], CRANK["d"]) < W_ARM - 0.005) + RES["readings"]["FLAT"] = float(np.abs(three[under] - (SLAB_R[0] - X_C)).max()) + RES["readings"]["one ray: samples signed inside, of %d" % len(plane)] = int((one < 0).sum()) + check("three-rays: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225", + (three >= SLAB_R[0] - X_C - FLAT).all() and under.sum() > 500 and RES["readings"]["FLAT"] < FLAT, [float(three.min()), int(under.sum()), RES["readings"]["FLAT"]]) + # against shells whose inside is known in closed form: a box and a disc, random points, each ray's edges and vertices among them + rng = np.random.default_rng(7) + cloud = rng.uniform((-0.2, -0.2, 0.2), (0.2, 0.2, 1.25), (4000, 3)) + core = Signed({"core": [box((0, 0, 0.725), (0.26, 0.28, 0.85))]})("core", cloud) + exact = np.maximum.reduce([np.abs(cloud[:, 0]) - 0.13, np.abs(cloud[:, 1]) - 0.14, np.abs(cloud[:, 2] - 0.725) - 0.425]) + check("three-rays: 4000 random points about a box are signed as the box signs them", ((core < 0) == (exact < 0)).all(), int(((core < 0) != (exact < 0)).sum())) + + SECTION[0] = "seat" + seat = np.concatenate([v for v, _ in shells["parent.seat"]]) + deepest = float(Signed(shells)("parent.body", seat).min()) + RES["readings"]["the base clevis's foot inside the thigh"] = deepest + check("the base clevis is seated: its foot runs 0.01 into the thigh's core, through the front plate", abs(deepest + EMBED) < FLAT, deepest) + + SECTION[0] = "bell crank" + winner = None + for side in (1.0, -1.0): + m = R.Mechanism("bell_crank", *HINGE, **pins3(CRANK, side), parts=parts) + touch = zones(m, ram, parts) + m = replace(m, touch=touch) + zoned = {(label(member), zone[0]) for member, given in touch.items() for zone in given} + t0 = time.perf_counter() + f = R._fit(m, ram, steps=49, distance=Signed(shells, ram.reach())) + seconds = time.perf_counter() - t0 + check(f"bell-crank-clears-on-meshes (side {side:+.0f}): over 0..-125 at 49 steps every member is clear of every part, 5 x {len(parts)} pairs, beside its pins by the record's zones", + f.ok and len(f.pairs) == 5 * len(parts) and set(f.allowed) == zoned, [f.report(), refused(f)]) + fine = R._fit(m, ram, steps=251, distance=Signed(shells)) + check(f"bell-crank-clears-on-meshes (side {side:+.0f}): and at 251 steps with the oracle uncapped", fine.ok, [fine.report(), refused(fine)]) + bare = R._fit(replace(m, touch={}), ram, steps=49, distance=Signed(shells, ram.reach())) + need = needs(m, ram, parts, Signed(shells)) + stated = {(label(member), zone[0]): zone for member, given in touch.items() for zone in given} + slack = {pair: (stated[pair][1] == pin and stated[pair][2] >= radius and stated[pair][3] >= depth) for pair, (pin, radius, depth) in need.items() if pair in stated} + check(f"zones (side {side:+.0f}): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair", + {pair for pair, _, _ in refused(bare)} == set(need) and set(need) <= zoned and all(slack.values()), [refused(bare), sorted(set(need) - zoned), [k for k, v in slack.items() if not v]]) + if side > 0: + winner = (m, f) + def free(fit): # the least margin of the pairs no zone lets: a zoned pair's is its depth's slack at the pin + return min(reading[0] for pair, reading in fit.pairs.items() if pair not in zoned) + RES["readings"].update({"bell crank: least margin of a pair with no zone, 251 steps uncapped": free(fine), + "bell crank: least margin of a zoned pair, 251 steps uncapped": min(reading[0] for pair, reading in fine.pairs.items() if pair in zoned), + "bell crank: pairs": len(f.pairs), "bell crank: zoned pairs": len(f.allowed), "bell crank: pairs refused with nothing let": len(refused(bare)), + "bell crank: seconds, 49 steps capped": seconds}) + RES["zones"] = {f"{pair[0]} | {pair[1]}": {"stated": list(stated[pair][1:]), "least": [pin, round(radius, 4), round(depth, 4)]} for pair, (pin, radius, depth) in sorted(need.items()) if pair in stated} + RES["least pairs"] = sorted((round(v[0], 4), v[1], k[0], k[1]) for k, v in fine.pairs.items() if k not in zoned)[:8] + + SECTION[0] = "zones end" + m, f = winner + for member, part in (("rocker", "parent.bracket"), ("coupler", "child.horn"), ("rod", "rocker.pin.d")): + short = {**m.touch, member: tuple((p_, pin, 0.5 * radius, depth) if p_ == part else (p_, pin, radius, depth) for p_, pin, radius, depth in m.touch[member])} + got = R._fit(replace(m, touch=short), ram, steps=49, distance=Signed(shells, ram.reach())) + check(f"a zone ends at its radius: {member}'s about {part} cut to half, that pair alone is refused", [pair for pair, _, _ in refused(got)] == [(label(member), part)], refused(got)) + + SECTION[0] = "moved x" + # Soul's let_hide probes: a link's place along the axis moved from beside the bracket or horn into it + for name, moved, expect in (("the rocker at x 0.25, inside the bracket's 0.13..0.35", {"rocker": 0.25}, {("rocker", "parent.bracket"), ("rocker arm", "parent.bracket")}), + ("the coupler at x 0.25, inside the horn's 0.23..0.31", {"c": 0.25}, {("coupler", "child.horn")}), + ("both", {"rocker": 0.25, "c": 0.25}, {("rocker", "parent.bracket"), ("rocker arm", "parent.bracket"), ("coupler", "child.horn")})): + mm = R.Mechanism("bell_crank", *HINGE, **pins3(CRANK, 1.0, **moved), parts=parts, touch=m.touch) + got = R._fit(mm, ram, steps=49, distance=Signed(shells, ram.reach())) + inside = {pair: reading for pair, reading, _ in refused(got)} + RES["readings"]["moved x: " + name] = min(inside.values()) if inside else 0.0 + check(f"a pin stood inside what it stands beside is refused: {name}", not got.ok and expect <= set(inside) and all(inside[pair] < -0.015 for pair in expect), refused(got)) + + SECTION[0] = "four bar" + shells4, parts4 = knee("four_bar", DEEP) + m4 = R.Mechanism("four_bar", *HINGE, **pins3(DEEP), parts=parts4) + m4 = replace(m4, touch=zones(m4, ram, parts4)) + f4 = R._fit(m4, ram, steps=49, distance=Signed(shells4, ram.reach())) + hit = {pair: reading for pair, reading, _ in refused(f4)} + RES["readings"]["four bar: barrel inside the shin's clearance"] = hit.get(("barrel[0]", "child.body"), 0.0) + check("third-body: the deep four-bar's ram is refused on the shin, which folds into it", not f4.ok and {("barrel[0]", "child.body"), ("rod[0]", "child.body")} <= set(hit) and f4.clear_at[2] == "child.body", refused(f4)) + + SECTION[0] = "search" + seats = {"rocker": [(X_R, *CRANK["rocker"]), (X_R, CRANK["rocker"][0] - 0.07, CRANK["rocker"][1] + 0.03)], "c": [(X_C, *CRANK["c"]), (X_C, CRANK["c"][0] - 0.05, CRANK["c"][1] + 0.03)], + "a": [(0.0, *CRANK["a"]), (0.0, 0.4, 1.0)], "link": (0.35, 0.5, 3), "d": (0.2, 0.26, 2)} + built = [] + + def world(mech): + made, bodies = knee("bell_crank", {k: (float(getattr(mech, k)[1]), float(getattr(mech, k)[2])) for k in CRANK}) + built.append(mech) + return bodies, zones(mech, ram, bodies), Signed(made, ram.reach()) + t0 = time.perf_counter() + s = R.search("bell_crank", {"pivot": HINGE[0], "axis": HINGE[1], "lo": -125, "hi": 0}, ram, seats, world=world, steps=49) + RES["readings"].update({"search: seconds": time.perf_counter() - t0, "search: candidates": s.tried, "search: pass the gates before clearance": s.fits, + "search: worlds built": len(built), "search: refused on their own parts": s.tally.get("clash", 0)}) + RES["search"] = {"report": s.report(), "seat": {k: np.round(v, 4).tolist() for k, v in (s.seat or {}).items()}, "tally": s.tally} + again = R._fit(s.best.m, ram, steps=251, distance=world(s.best.m)[2]) if s.found else None + check("search-holds-candidate-links: a seat grid about the probe's bell crank, each candidate met with the meshes its own pins place, runs to a fit that holds at 251 steps", + s.found and s.best.ok and len(built) - 1 == s.tally.get("clash", 0) + 1 and again.ok and len(s.best.pairs) == 5 * len(parts), [s.report(), refused(again) if again else None]) + + SECTION[0] = "render" + RES["renders"] = render(winner[0], ram, winner[1], shells, parts) + check("the bell crank is drawn at 0, -62.5 and -125", all(Path(path).is_file() for path in RES["renders"]), RES["renders"]) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file + check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-8:]) +finally: + RES["ok"] = all(c["ok"] for c in RES["checks"]) + RES["readings"] = {name: (float(f"{value:.3g}") if isinstance(value, float) else value) for name, value in sorted(RES["readings"].items())} + Path(OUT + ".result.json").write_text(json.dumps(RES, indent=1, default=str), encoding="utf-8") + for c in RES["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) + print("READINGS", RES["readings"], flush=True) +sys.exit(0 if RES["ok"] else 1) diff --git a/surfaces/blender/tests/live/ram_knee.result.json b/surfaces/blender/tests/live/ram_knee.result.json new file mode 100644 index 0000000..6ad67fe --- /dev/null +++ b/surfaces/blender/tests/live/ram_knee.result.json @@ -0,0 +1,444 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "inside-is-negative: a point inside a part reads its depth, negative, capped or not; a cap changes only what is outside", + "ok": true, + "detail": null + }, + { + "name": "three-rays: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225", + "ok": true, + "detail": null + }, + { + "name": "three-rays: 4000 random points about a box are signed as the box signs them", + "ok": true, + "detail": null + }, + { + "name": "the base clevis is seated: its foot runs 0.01 into the thigh's core, through the front plate", + "ok": true, + "detail": null + }, + { + "name": "bell-crank-clears-on-meshes (side +1): over 0..-125 at 49 steps every member is clear of every part, 5 x 12 pairs, beside its pins by the record's zones", + "ok": true, + "detail": null + }, + { + "name": "bell-crank-clears-on-meshes (side +1): and at 251 steps with the oracle uncapped", + "ok": true, + "detail": null + }, + { + "name": "zones (side +1): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair", + "ok": true, + "detail": null + }, + { + "name": "bell-crank-clears-on-meshes (side -1): over 0..-125 at 49 steps every member is clear of every part, 5 x 12 pairs, beside its pins by the record's zones", + "ok": true, + "detail": null + }, + { + "name": "bell-crank-clears-on-meshes (side -1): and at 251 steps with the oracle uncapped", + "ok": true, + "detail": null + }, + { + "name": "zones (side -1): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair", + "ok": true, + "detail": null + }, + { + "name": "a zone ends at its radius: rocker's about parent.bracket cut to half, that pair alone is refused", + "ok": true, + "detail": null + }, + { + "name": "a zone ends at its radius: coupler's about child.horn cut to half, that pair alone is refused", + "ok": true, + "detail": null + }, + { + "name": "a zone ends at its radius: rod's about rocker.pin.d cut to half, that pair alone is refused", + "ok": true, + "detail": null + }, + { + "name": "a pin stood inside what it stands beside is refused: the rocker at x 0.25, inside the bracket's 0.13..0.35", + "ok": true, + "detail": null + }, + { + "name": "a pin stood inside what it stands beside is refused: the coupler at x 0.25, inside the horn's 0.23..0.31", + "ok": true, + "detail": null + }, + { + "name": "a pin stood inside what it stands beside is refused: both", + "ok": true, + "detail": null + }, + { + "name": "third-body: the deep four-bar's ram is refused on the shin, which folds into it", + "ok": true, + "detail": null + }, + { + "name": "search-holds-candidate-links: a seat grid about the probe's bell crank, each candidate met with the meshes its own pins place, runs to a fit that holds at 251 steps", + "ok": true, + "detail": null + }, + { + "name": "the bell crank is drawn at 0, -62.5 and -125", + "ok": true, + "detail": null + } + ], + "readings": { + "FLAT": 8.34e-09, + "bell crank: least margin of a pair with no zone, 251 steps uncapped": 0.0336, + "bell crank: least margin of a zoned pair, 251 steps uncapped": 0.000118, + "bell crank: pairs": 60, + "bell crank: pairs refused with nothing let": 19, + "bell crank: seconds, 49 steps capped": 0.835, + "bell crank: zoned pairs": 20, + "four bar: barrel inside the shin's clearance": -0.122, + "moved x: both": -0.0543, + "moved x: the coupler at x 0.25, inside the horn's 0.23..0.31": -0.02, + "moved x: the rocker at x 0.25, inside the bracket's 0.13..0.35": -0.0543, + "one ray: samples signed inside, of 6912": 0, + "search: candidates": 13824, + "search: pass the gates before clearance": 78, + "search: refused on their own parts": 21, + "search: seconds": 42.8, + "search: worlds built": 22, + "the base clevis's foot inside the thigh": -0.01 + }, + "zones": { + "barrel[0] | parent.seat": { + "stated": [ + "a", + 0.15645000000000003, + 0.0 + ], + "least": [ + "a", + 0.1222, + 0.0 + ] + }, + "barrel[0] | rocker.pin.d": { + "stated": [ + "d", + 0.11105000000000001, + 0.0 + ], + "least": [ + "d", + 0.1108, + 0.0 + ] + }, + "barrel[0] | rocker.seat": { + "stated": [ + "d", + 0.13505, + 0.0 + ], + "least": [ + "d", + 0.1263, + 0.0 + ] + }, + "coupler | child.horn": { + "stated": [ + "c", + 0.11195, + 0.0 + ], + "least": [ + "c", + 0.0947, + 0.0 + ] + }, + "coupler | coupler.pin.c": { + "stated": [ + "c", + 0.08795, + 0.027 + ], + "least": [ + "c", + 0.0474, + 0.0259 + ] + }, + "coupler | coupler.plate": { + "stated": [ + "p", + 0.47832364050530635, + 0.018500000000000016 + ], + "least": [ + "p", + 0.4736, + 0.0175 + ] + }, + "coupler | rocker.pin.p": { + "stated": [ + "p", + 0.08795, + 0.027 + ], + "least": [ + "p", + 0.0474, + 0.0259 + ] + }, + "coupler | rocker.plate": { + "stated": [ + "p", + 0.2818973893266964, + 0.0 + ], + "least": [ + "p", + 0.2368, + 0.0 + ] + }, + "rocker | coupler.plate": { + "stated": [ + "p", + 0.26840002998268986, + 0.0 + ], + "least": [ + "p", + 0.2366, + 0.0 + ] + }, + "rocker | parent.bracket": { + "stated": [ + "rocker", + 0.11695, + 0.0 + ], + "least": [ + "rocker", + 0.0946, + 0.0 + ] + }, + "rocker | rocker.pin.R": { + "stated": [ + "rocker", + 0.08995, + 0.029 + ], + "least": [ + "rocker", + 0.0473, + 0.0279 + ] + }, + "rocker | rocker.pin.p": { + "stated": [ + "p", + 0.08795, + 0.027 + ], + "least": [ + "p", + 0.0473, + 0.0259 + ] + }, + "rocker | rocker.plate": { + "stated": [ + "rocker", + 0.43014219644091495, + 0.018500000000000016 + ], + "least": [ + "rocker", + 0.4259, + 0.0175 + ] + }, + "rocker arm | parent.bracket": { + "stated": [ + "rocker", + 0.11695, + 0.0 + ], + "least": [ + "rocker", + 0.096, + 0.0 + ] + }, + "rocker arm | rocker.pin.R": { + "stated": [ + "rocker", + 0.08995, + 0.029 + ], + "least": [ + "rocker", + 0.048, + 0.0279 + ] + }, + "rocker arm | rocker.pin.d": { + "stated": [ + "d", + 0.08795, + 0.027 + ], + "least": [ + "d", + 0.048, + 0.0259 + ] + }, + "rocker arm | rocker.plate": { + "stated": [ + "rocker", + 0.24240000000000003, + 0.018500000000000016 + ], + "least": [ + "rocker", + 0.24, + 0.0175 + ] + }, + "rod[0] | rocker.pin.d": { + "stated": [ + "d", + 0.07955, + 0.027 + ], + "least": [ + "d", + 0.0794, + 0.0259 + ] + }, + "rod[0] | rocker.seat": { + "stated": [ + "d", + 0.10355, + 0.0 + ], + "least": [ + "d", + 0.0938, + 0.0 + ] + } + }, + "least pairs": [ + [ + 0.0336, + -125.0, + "rocker", + "rocker.pin.d" + ], + [ + 0.0393, + -125.0, + "rod[0]", + "rocker.pin.R" + ], + [ + 0.0417, + 0.0, + "coupler", + "parent.bracket" + ], + [ + 0.0579, + 0.0, + "rocker arm", + "coupler.plate" + ], + [ + 0.0687, + 0.0, + "coupler", + "rocker.pin.R" + ], + [ + 0.0766, + 0.0, + "rocker", + "child.horn" + ], + [ + 0.0766, + 0.0, + "rocker arm", + "child.horn" + ], + [ + 0.0808, + -125.0, + "coupler", + "child.body" + ] + ], + "search": { + "report": "78 of 13824 candidates pass the gates before clearance (failed: arm 1406, assembly 4800, clash 21, load 1355, stroke 1160, toggle 7352); best: OK: L 0.664..0.968, barrel 0.513, stroke 0.458 for travel 0.304 (spare +0.137), arm >= 0.090, rocker swing 99.9, pin load <= 0.73, transmission >= 17.3 deg, clear +0.000", + "seat": { + "a": [ + 0.0, + 0.45, + 1.15 + ], + "rocker": [ + 0.3675, + 0.3171, + 0.3217 + ], + "p": [ + 0.3675, + 0.7683, + 0.5372 + ], + "c": [ + 0.3275, + 0.3493, + 0.1486 + ], + "d": [ + 0.0, + 0.4303, + 0.4866 + ] + }, + "tally": { + "assembly": 4800, + "toggle": 7352, + "arm": 1406, + "stroke": 1160, + "load": 1355, + "clash": 21 + } + }, + "renders": [ + "F:/aeth-wt/fable-ramcore/scratch/h3/out/live3.r3_0.png", + "F:/aeth-wt/fable-ramcore/scratch/h3/out/live3.r3_62p5.png", + "F:/aeth-wt/fable-ramcore/scratch/h3/out/live3.r3_125.png" + ], + "ok": true +} \ No newline at end of file From 941e146bc65dfdf8b4298c398ada0c07d7687afd Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:01:37 +0100 Subject: [PATCH 139/223] docs/kitbash.md: Rams and linkages: zones, the strict record, the live knee's readings and costs Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 81 +++++++++++++++++++------------- 1 file changed, 49 insertions(+), 32 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 55c9cf6..f24d4e2 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -820,20 +820,31 @@ Transmission angles at `c` and `p` are reported and not gated. Over the R-3 knee transmission angle of 200,000 sampled four-bars was 21.9 degrees, under the 30 to 40 a textbook asks; a gate there would have refused every one of them. What a poor angle costs is pin load, and that is the gate. -### Clearance: parts and what a member may touch +### Clearance: parts, and zones about a member's pins The record names the mechanism's `parts`, each a piece of one body (part -> parent, child, rocker or coupler: the body whose rest frame it turns with), and `touch`: for each member (`barrel`, `rod`, `rocker`, `coupler`, and a -bell crank's `rocker arm`), the parts it may touch. This is the allowed-collision matrix of motion planning -(MoveIt's ACM): a pair listed there is skipped whole and every other (member, part) pair is checked. A member may -touch what it is pinned to and what is stacked on its pins: the pin, its own eye and clevis, its own plates, the -plates beside it on that pin, the bracket or horn the pin stands in. Nothing is exempt by a name, by a length cut -from a member's end, or by the member's own body: the barrel runs from its back end, the rod to the eye, a bar -from pin to pin. Every body of the kind owns at least one part, or the gate refuses the record. +bell crank's `rocker arm`), zones `(part, pin, radius, depth)`. Every member meets every part. A zone changes what +the member's samples keep from one part, and only within `radius` of the axis of `pin`, measured across the hinge +axis; the pin is one the member rides (the ram `a` and its eye, the rocker its pivot and `p`, the coupler `p` and +`c`, the arm the pivot and `d`). Inside the zone a sample may come as near the part as `-depth`; beyond it the +pair is checked like any other. Nothing is exempt by a name, by a length cut from a member's end, or by the +member's own body: the barrel runs from its back end, the rod to the eye, a bar from pin to pin. Every body of the +kind owns at least one part, or the gate refuses the record. -What it gives up: a pair in `touch` is not checked anywhere, so a coupler let touch the horn that carries `c` may -also pass through that horn's far end unseen. Parts are the grain: cut a body into the piece that carries the pin -and the rest, and let only the first. +A zone's radius is the eye's radius plus a margin: the pin's, collar's or cheek's radius plus what the member +keeps (radius, gap, half the spacing). Its depth says how the member stands to the part there. 0 is beside it: a +plate stacked on the pin, the bracket or horn the pin stands in. The member's axis then stays outside the part, so +a pin whose place along the axis is inside what it claims to stand beside is refused: the gate does not take the +record's x on trust. The pin's radius is for the pin through the member's eye, half the plate's thickness for the +member's own plate, let over its length. Two plates stacked on a pin cross like scissors; the zone that lets one +link by the other's plate reaches as far as the two part, (half width + what a link keeps) / sin of the least +angle they cross at. + +What it gives up: inside a zone the gate holds only the member's axis `depth` from the part, not its surface a +gap from it, so a link may graze the plate it scissors with anywhere within the stated radius, and a depth stated +deeper than the eye lets the axis into the part that far. Both are numbers in the record, to be read. The members +are round bars; a plate's flat sides are not modelled, which is why stacked plates need a zone at all. The oracle is `distance(part, points) -> distances`, `points` in the rest frame of the part's body. Each member is sampled along its axis at most `spacing` apart (default the barrel's radius) and carried into each body's rest @@ -842,47 +853,53 @@ between samples. A distance is signed: negative inside a part, by any depth. The `Ram.reach(spacing)`, outside a part only; a point inside reads negative however deep it lies. An oracle that cannot tell inside from outside raises instead of answering (a nearest-surface query alone reads 0.13 at the centre of the R-3 thigh's core, and reads clear when capped); nan is refused. `Fit.pairs` holds the least margin -and its angle for every pair checked, `Fit.allowed` every pair skipped. +and its angle for every pair, `Fit.allowed` the pairs a zone lets near a pin. `search` seats a mechanism from a grid (ram seats; for linkages rocker pivots, child pins, `p` on a polar grid about R, and `d` about R for a bell crank, the eye standing at `a`'s place along the axis), refuses a grid over `limit` candidates naming the count, runs every gate but clearance on all of them, then clearance in order of least arm; a miss returns the tally by gate and the nearest miss. Clearance takes `world(m) -> (parts, touch, distance)`: a linkage's brackets and links are the candidate's own, so each candidate that reaches the gate is met -with the parts its own pins place. `swept` gives the ram's swept surface in any body's frame, for a recess. +with the parts its own pins place. What `world` returns is read as a record's: anything but the three, a part on +no body of the kind, or a zone that is not a part, a pin the member rides, a radius and a depth is refused. +`swept` gives the ram's swept surface in any body's frame, for a recess. ### The record `record` and `from_record` carry a mechanism as JSON: `schema` (`brokkr.ram`), `version` (1), `kind`, `hinge`, -`pins`, `offsets`, `ram`, `parts`, `touch`, and `compliance`. It holds what is authored; barrel, closed length and -link lengths are derived by the reader. `compliance` is reserved for a load-path ram's settle (stiffness, damping, -travel); version 1 writes it null and solves none. A record of another schema or version, with a key version 1 -does not know (at the top, in `ram` or in `hinge`), or with a compliance block is refused whole: a reader never -reads past what it cannot solve. +`pins`, `offsets`, `ram`, `parts`, `touch` (member -> zones, each `{part, pin, radius, depth}`), and `compliance`. +It holds what is authored; barrel, closed length and link lengths are derived by the reader. `compliance` is +reserved for a load-path ram's settle (stiffness, damping, travel); version 1 writes it null and solves none. A +record of another schema or version (the integer 1: 1.0 and true are not it), with a key version 1 does not know or +without one it does (at the top, in `ram`, `hinge`, `pins` or a zone), with a compliance block, or with a value +that is not its field's (a finite number, the bore over 0, three numbers for a point) is refused whole, as a +`RamError` that names the field: a reader never reads past what it cannot solve. A `Ram` built by hand refuses the +same numbers. ### Readings on the R-3 knee -Bore 0.042, range 0..-125. The kinematic rows are tests/test_ram.py's. The clearance rows are Blender 5.3 readings -on meshes built with the joint library the knee was drawn with (thigh with its front plate, shin with caps and -armour, the bracket that carries R, the horn that carries `c`, twin link plates stacked 5 mm apart at x 0.31..0.345 -and 0.35..0.385, pins through the knee's width, a clevis at each ram pin; 4,176 triangles, 12 parts), a signed BVH -oracle (winding number along a ray for the side, nearest face for the depth). +Bore 0.042, range 0..-125. The kinematic rows are tests/test_ram.py's. The clearance rows are +`tests/live/ram_knee.py`'s, Blender 5.3 (`ram_knee.result.json` is the last run): the knee as closed meshes the +test generates (thigh with its front plate, shin with caps and armour, the bracket that carries R, the horn that +carries `c`, twin link plates stacked 5 mm apart at x 0.31..0.345 and 0.35..0.385, pins through the knee's width, +collars at the eye and a base clevis whose foot runs 0.01 into the thigh; 12 parts) and a signed BVH oracle: the +nearest face for the depth, the crossing parity of three rays, by majority, for the side. One ray that grazes an +edge miscounts and signs an isolated sample inside a plate it stands clear of. | drive | reading | | --- | --- | | direct, the joint library's seats, 0..-62 | fits (analytic thigh and shin) | | direct, 2,000 seat pairs behind the knee | none fits (analytic thigh and shin) | -| four-bar behind the knee | passes every gate before clearance: rocker swing 70.5, L 0.722..1.168, arm 0.096..0.265, pin load 1.61, transmission 16.5. Refused on the meshes: of 23 checked pairs two fail, the barrel and the rod against the shin's body (0.277 and 0.246 inside their clearance at -122.5, 251 steps), a body the ram is not pinned to | -| bell crank in front of the knee | fits on the meshes, the plates on either side: rocker swing 105.7, L 0.659..1.038, arm 0.091..0.215, pin load 1.13, transmission 13.8. 36 pairs checked, 24 let. Over 251 steps the least margin beyond radius, gap and half the spacing is 0.039 (the rod and the rocker's pivot pin at -125), then 0.042 (the coupler and the bracket at 0) and 0.058 (the rocker's arm and the coupler's plates at 0); at spacing 0.01, 0.061. With `touch` empty the same gate refuses 19 pairs, each a member against a pin it rides, its own plates or clevis, a plate stacked on its pin, or the bracket or horn that pin stands in | -| bell-crank search on the meshes | 13,824 candidates, each world built from the candidate's pins: 78 pass the gates before clearance, 21 of them are refused on their own parts, the 22nd fits (arm 0.090, swing 99.9, pin load 0.73) | +| four-bar behind the knee | passes every gate before clearance: rocker swing 70.5, L 0.722..1.168, arm 0.096..0.265, pin load 1.61, transmission 16.5. Refused on the meshes: the barrel and the rod against the shin's body (the barrel 0.122 inside its clearance, 49 steps), a body the ram is not pinned to | +| bell crank in front of the knee | fits on the meshes, the plates on either side: rocker swing 105.7, L 0.659..1.038, arm 0.091..0.215, pin load 1.13, transmission 13.8. 60 pairs, 20 of them with a zone. Over 251 steps, uncapped, the least margin of a pair with no zone is 0.034 (the rocker and the eye's pin at -125), then 0.039 (the rod and the rocker's pivot pin at -125) and 0.042 (the coupler and the bracket at 0). With `touch` empty the same gate refuses 19 pairs, each one a zoned pair; each stated zone takes in the least zone that lets its pair. A zone cut to half its radius refuses its pair | +| the same, a link's x moved | the rocker at x 0.25 (inside the bracket's 0.13..0.35) is refused 0.054 inside the bracket; the coupler at 0.25 (inside the horn's 0.23..0.31) 0.020 inside the horn | +| bell-crank search on the meshes | 13,824 candidates, each world built from the candidate's pins: 78 pass the gates before clearance, 21 of them are refused on their own parts, the 22nd fits (arm 0.090, swing 99.9, pin load 0.73) and holds at 251 steps | -Cost on Starfire, 300 repetitions paired and interleaved with the previous revision, other work holding the cores -at 100 percent: one candidate's gates before clearance at 49 steps took 0.98 ms median on the four-bar (5th to 95th -percentile 0.88 to 3.35) and 0.96 on the bell crank (0.88 to 2.03), the previous revision 1.03 and 1.00 beside -them. A search without a world ran 1.6 to 1.8 ms a candidate over 3,456, so `limit` (20,000) is 30 to 40 s. The -bell crank's clearance against analytic parts added 11 ms; on the meshes its 36 pairs asked 17,248 points and -took 0.12 s capped, in a Python loop of BVH queries; a candidate's world built in 0.045 s, and the 13,824-candidate -mesh search took 29 s (55 s in a busier minute). +Cost on Starfire, Python 3.13, 100 repetitions paired and interleaved: one candidate's gates before clearance at +49 steps took 1.07 ms median on the bell crank; its clearance against the analytic parts (50 pairs, 23,520 +points) added 56 ms (5th to 95th percentile 16 to 73, other work on the machine). A search without a world ran 1.6 to 1.8 ms a candidate over 3,456, so `limit` +(20,000) is 30 to 40 s. On the meshes the bell crank's 60 pairs at 49 steps took 0.67 to 0.84 s capped, in a Python loop +of BVH queries with three rays a sample, and the 13,824-candidate search with its 22 worlds 41 to 49 s. ## The actions From 481690fb5cca78a741faa2950555c8d3775bbf48 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:59:27 +0100 Subject: [PATCH 140/223] brokkr_kitbash.ram: a zone is no wider or deeper than its member; between samples in a zone the axis is proved, not sampled; the signed mesh oracle A zone's radius and depth are refused past the member's pin-to-pin length (by the pins alone) and its depth past the member's eye on that pin (Ram.eye; at the gate and in from_record, so a world's answer too). Between samples of which either is in a zone the segment is halved until the readings at its ends prove it holds -depth; at the floor a part the axis is held outside reads as touched. Signed, three rays by majority, moves here from the live test. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/ram.py | 156 ++++++++++++++++++++++--- 1 file changed, 143 insertions(+), 13 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py index 80ef95d..d7cb60f 100644 --- a/surfaces/blender/brokkr_kitbash/ram.py +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -1,5 +1,6 @@ """Rams and linkages across a one-axis hinge: numpy and the standard library only, and nothing from the package, so -a rig, a runtime or a test loads this file alone. +a rig, a runtime or a test loads this file alone. Signed, the mesh oracle, asks for Blender's BVH tree when one is +made and not before. A Mechanism is the record of one hinge's drive: the hinge (pivot, unit axis, lo and hi in degrees, positive right-handed about the axis), a kind, and pins, each in its own body's rest frame (the pose at angle 0, where @@ -23,6 +24,7 @@ the coupler bar at c's, the ram at a's plus each of `offsets`. search(kind, hinge, ram, seats, ...) the best of a seat grid, or the tally and the nearest miss record(m, ram), from_record the JSON record a rig or runtime drives from swept(fit, body, ...) points of the swept ram's surface in a body's rest frame + Signed(shells, cap) the distance oracle over closed meshes, signed by three rays Clearance. The record names the mechanism's `parts`, each a piece of one body (part -> the body whose rest frame it turns with: a thigh's core, the bracket that carries the rocker's pivot, a link's plates, a pin), and `touch`: @@ -35,10 +37,19 @@ is refused), the pin's radius for the pin through the member's eye, half the thi or clevis. Beyond the radius the pair is checked like any other; nothing is exempt by a name, a length or the member's own body. Every body of the kind owns at least one part, or the gate refuses. +A zone is bounded by its member. Its radius and its depth are finite and no more than the member's length from pin +to pin (a bar's between its pins; the ram's at the most its pins allow), which the record refuses by its pins +alone; its depth is no more than the member's eye on that pin (Ram.eye: e_a at the base, e_b at the rod's eye, +link_r on a bar), which from_record and the gate refuse, a world's answer included. Between two samples of which +either is in a zone, the gate does not trust the spacing: it halves the segment until the readings at its ends +prove it holds -depth throughout (see _between), so a part of any thickness that the axis crosses there is read. + The oracle is distance(part, points) -> distances, points (N, 3) in the rest frame of the part's body. A distance is signed: negative inside the part, by any depth. The oracle may cap what it returns at Ram.reach(spacing), outside a part only: a point inside reads negative however deep it lies. An oracle that cannot tell inside from -outside (a nearest-surface query on an open mesh) raises instead of answering; nan is refused here. +outside (a nearest-surface query on an open mesh) raises instead of answering; nan is refused here. It never reads +more than the true distance: the gate's proof between samples is that a distance changes by no more than the way +between two points. A RamError of a gate (assembly, stroke, toggle, arm, load, clash) names the angle and the pin; one of the record or of a call (an unknown kind, a range, a grid over the limit, a version) names the pin or the field it refuses. @@ -62,6 +73,8 @@ SCHEMA, VERSION = "brokkr.ram", 1 ZONE = ("part", "pin", "radius", "depth") # a zone of `touch`, as the record writes it COMPLIANCE = ("stiffness", "damping", "travel") # reserved: a load-path ram's settle, solved by a later version BAND = 1e-9 # the loop is refused within this of a dead centre of the rocker and coupler +FINE = 64 # in a zone a segment between samples is halved down to spacing / FINE +RAYS = ((0.5377, 0.6211, 0.5701), (-0.7071, 0.2903, 0.6447), (0.1873, -0.8011, -0.5684)) # Signed's, in order class RamError(ValueError): @@ -117,6 +130,12 @@ class Ram: def spacing(self, spacing=None): return self.barrel_r if spacing is None else float(spacing) + def eye(self, member, pin): + """The radius of a member's eye on one of its pins: the most a zone's depth lets its axis into a part.""" + if member in ("barrel", "rod"): + return self.e_a if pin == "a" else self.e_b + return self.link_r + def reach(self, spacing=None): """The greatest distance the clearance gate asks of any member: what a distance oracle may cap at.""" return max(self.barrel_r, self.rod, self.link_r) + self.gap + self.spacing(spacing) / 2 @@ -177,6 +196,10 @@ class Mechanism: for part, body in self.parts.items(): if body not in BODIES[self.kind]: raise RamError(self.kind, "record", f"part {part!r} turns with {body!r}; this kind has {', '.join(BODIES[self.kind])}") + for name in ("a", "b", "rocker", "p", "c", "d"): + needed, given = name in PINS[self.kind], getattr(self, name) is not None + if needed != given: + raise RamError(self.kind, "record", "this kind needs the pin" if needed else "this kind has no such pin", pin=name) touch = {} for member, zones in dict(self.touch).items(): if member not in MEMBERS[self.kind]: @@ -193,13 +216,14 @@ class Mechanism: radius, depth = _number(self.kind, f"{member} {part} radius", radius, 0.0), _number(self.kind, f"{member} {part} depth", depth) if depth < 0.0: raise RamError(self.kind, "record", f"a depth of 0 or more, got {depth!r}", pin=f"{member} {part} depth") + span = _span(self, member) + for name, value in (("radius", radius), ("depth", depth)): + if value > span: + raise RamError(self.kind, "record", f"a zone no wider or deeper than its member: {member} is at most {span:.4f} from pin to pin, got {value!r}", + pin=f"{member} {part} {name}") touch[member].append((part, pin, radius, depth)) touch[member] = tuple(touch[member]) self.touch = touch - for name in ("a", "b", "rocker", "p", "c", "d"): - needed, given = name in PINS[self.kind], getattr(self, name) is not None - if needed != given: - raise RamError(self.kind, "record", "this kind needs the pin" if needed else "this kind has no such pin", pin=name) if self.kind == "direct": return n = self.axis @@ -216,6 +240,25 @@ class Mechanism: self.branch = 1.0 if side > 0 else -1.0 # which side of R -> c the pin p keeps, through the whole range +def _span(m, member): + """The most a member measures from pin to pin, by the pins alone: a bar's length across the axis; for the ram's + two, the base's and the eye's distances from the centre the eye turns about, added.""" + if member in ("barrel", "rod"): + centre, eye = m.pivot if m.kind == "direct" else m.rocker, getattr(m, EYE[m.kind]) + return float(np.linalg.norm(m.a - centre) + np.linalg.norm(eye - centre)) + start, end = RIDES[m.kind][member] + return float(np.linalg.norm(_flat(getattr(m, end) - getattr(m, start), m.axis))) + + +def _eyes(m, ram): + """Refuse a zone deeper than its member's eye on its pin.""" + for member, zones in m.touch.items(): + for part, pin, _, depth in zones: + if depth > ram.eye(member, pin): + raise RamError(m.kind, "record", f"a zone no deeper than its member's eye: {member}'s on {pin} is {ram.eye(member, pin):.4f}, got {depth!r}", + pin=f"{member} {part} depth") + + @dataclass class Pose: degrees: np.ndarray # (S,) @@ -343,11 +386,46 @@ def clearance(m, ram, degrees, distance, spacing=None): rest frame of the part's body at that angle. A sample is at most spacing / 2 from any point of the axis, so the member's surface keeps the gap. Every member meets every part of the record. Inside a zone of `touch` (within its radius of its pin's axis, across the hinge axis) a sample keeps -depth from the zone's part - instead: the margin there is the distance plus the depth.""" + instead: the margin there is the distance plus the depth, and the segment to the next sample is proved to + hold -depth throughout (_between). Two zones of one pair that both reach a sample let it the deeper.""" return _clearance(m, ram, barrel_length(m, ram), pose(m, degrees), distance, spacing) +def _between(kind, distance, part, pts, got, keep, zoned, floor): + """(S,) the least margin found between samples, inf where none is: for each segment between consecutive samples + of which either is in a zone, whether the axis holds -depth (the deeper of its ends') all along it. A distance + changes by no more than the way between two points, so along a segment it is at least (g(a) + g(b) - |ab|) / 2; + where that does not prove the segment it is halved, the midpoint read (its margin is counted), down to `floor`. + A segment still unproved at the floor against a part the axis is held outside (depth 0) reads that bound, so + it is refused: the part is within floor / 2 of the axis there, crossed or touched. Against a part the axis may + enter, the samples' readings stand: a burial is read to floor / 2.""" + out = np.full(len(pts), math.inf) + pair = zoned[:, :-1] | zoned[:, 1:] + row = np.nonzero(pair)[0] + a, b, ga, gb = pts[:, :-1][pair], pts[:, 1:][pair], got[:, :-1][pair], got[:, 1:][pair] + hold = np.minimum(keep[:, :-1], keep[:, 1:])[pair] + while len(row): + span = np.linalg.norm(b - a, axis=1) + bound = (ga + gb - span) / 2.0 + unproved = (bound < hold) & (np.minimum(ga, gb) >= hold) # an end under its hold is already refused + touched = unproved & (span <= floor) & (hold == 0.0) + np.minimum.at(out, row[touched], bound[touched]) + go = unproved & (span > floor) + if not go.any(): + break + a, b, ga, gb, hold, row = (x[go] for x in (a, b, ga, gb, hold, row)) + mid = (a + b) / 2.0 + gm = np.asarray(distance(part, mid), dtype=float) + if np.isnan(gm).any(): + raise RamError(kind, "oracle", f"the distance oracle answered nan for part {part!r}") + np.minimum.at(out, row, gm - hold) + a, b, ga, gb = np.concatenate([a, mid]), np.concatenate([mid, b]), np.concatenate([ga, gm]), np.concatenate([gm, gb]) + hold, row = np.concatenate([hold, hold]), np.concatenate([row, row]) + return out + + def _clearance(m, ram, barrel, p, distance, spacing): + _eyes(m, ram) for body in BODIES[m.kind]: if body not in m.parts.values(): raise RamError(m.kind, "record", f"no part turns with body {body}: the clearance gate would pass it unseen") @@ -367,14 +445,17 @@ def _clearance(m, ram, barrel, p, distance, spacing): if np.isnan(got).any(): raise RamError(m.kind, "oracle", f"the distance oracle answered nan for part {part!r}") keep = np.full(got.shape, need) # what each sample keeps from the part + zoned = np.zeros(got.shape, dtype=bool) zones = [zone for zone in m.touch.get(member, ()) if zone[0] == part] for _, pin, reach, depth in zones: across = np.linalg.norm(_flat(pts - np.broadcast_to(at[pin], start.shape)[:, None, :], m.axis), axis=2) keep = np.where(across <= reach, np.minimum(keep, -depth), keep) - if zones: - out.allowed.append((label, part)) + zoned |= across <= reach over = got - keep row = over.min(axis=1) + if zones: + out.allowed.append((label, part)) + row = np.minimum(row, _between(m.kind, distance, part, seen[body].reshape(len(p.degrees), count, 3), got, keep, zoned, step / FINE)) out.margin = np.minimum(out.margin, row) i = int(np.argmin(row)) out.pairs[(label, part)] = (float(row[i]), float(p.degrees[i])) @@ -533,7 +614,8 @@ def search(kind, hinge, ram, seats, world=None, limit=20000, steps=25, spacing=N the first clear one wins. world(m) -> (parts, touch, distance) builds a candidate's own parts, the brackets and links its pins place among them, and the oracle that answers for them: a linkage's links are the candidate's, so no one oracle serves a grid. What it returns is read as a record's: anything but the three, - a part on no body of the kind or a zone that is not (part, pin the member rides, radius, depth) is refused. A grid past `limit` candidates is refused naming the count. A + a part on no body of the kind, a zone that is not (part, pin the member rides, radius, depth) or one wider or + deeper than its member is refused. A grid past `limit` candidates is refused naming the count. A miss returns the tally and the nearest miss (the least total shortfall: stroke, arm, load excess, clearance).""" pins = candidates(kind, hinge, seats) @@ -592,8 +674,8 @@ def record(m, ram): def from_record(data): """(Mechanism, Ram) of a record. A record of another schema or version (the integer 1: not 1.0, not true), with a key this version does not know or without one it does, with a compliance block, or with a value that is not - its field's type (a finite number, three of them, a name) is refused whole, as a RamError naming the field: - nothing is read past and dropped.""" + its field's type (a finite number, three of them, a name), or with a zone wider or deeper than its member is + refused whole, as a RamError naming the field: nothing is read past and dropped.""" if not isinstance(data, dict): raise RamError("None", "record", f"a record is an object, got {type(data).__name__}") kind, version = str(data.get("kind")), data.get("version") @@ -638,7 +720,9 @@ def from_record(data): m = Mechanism(kind, point("pivot", hinge["pivot"]), point("axis", hinge["axis"]), _number(kind, "lo", hinge["lo"]), _number(kind, "hi", hinge["hi"]), offsets=tuple(_number(kind, "offsets", o) for o in data["offsets"]), parts=data["parts"], touch=touch, **{name: point(name, value) for name, value in pins.items()}) - return m, Ram(**ram) + ram = Ram(**ram) + _eyes(m, ram) + return m, ram def swept(f, body, margin=0.0, steps=13, around=8): @@ -658,3 +742,49 @@ def swept(f, body, margin=0.0, steps=13, around=8): for centre in (p.base + off * m.axis + p.u * min(ram.back, 0.0), p.eye + off * m.axis): pts.append(centre[:, None, :] + ring) return _into(m, p, body, np.concatenate(pts, axis=1)).reshape(-1, 3) + + +class Signed: + """The distance oracle over closed meshes: distance(part, points) is the nearest face's distance, negative + where the point is inside one of the part's shells (its depth below the nearest face), capped at `cap` outside + only. shells: part -> [(vertices (N, 3), faces)], each shell closed, in the rest frame of the part's body. + Inside is the crossing parity of `rays` of RAYS, by majority: one ray that runs through an edge or a vertex + miscounts, and a sample then reads inside a plate it stands clear of. An unknown part raises. Needs Blender's + mathutils (BVHTree).""" + + def __init__(self, shells, cap=None, rays=3): + from mathutils import Vector + from mathutils.bvhtree import BVHTree + self.cap, self.asked, self.vector = cap, 0, Vector + self.rays = [Vector(ray).normalized() for ray in RAYS[:rays]] + self.trees = {part: [(BVHTree.FromPolygons(np.asarray(v, dtype=float).tolist(), [tuple(face) for face in f], epsilon=0.0), + np.min(v, axis=0), np.max(v, axis=0)) for v, f in made] for part, made in shells.items()} + + @staticmethod + def crossings(tree, v, ray): + count, o = 0, v + for _ in range(64): + loc = tree.ray_cast(o, ray)[0] + if loc is None: + break + count, o = count + 1, loc + ray * 1e-6 + return count + + def inside(self, tree, v): + return 2 * sum(self.crossings(tree, v, ray) % 2 for ray in self.rays) > len(self.rays) + + def __call__(self, part, pts): + pts = np.asarray(pts, dtype=float) + self.asked += len(pts) + out = np.full(len(pts), math.inf if self.cap is None else self.cap) + for tree, lo, hi in self.trees[part]: + boxed = ((pts >= lo) & (pts <= hi)).all(axis=1) + for i, p in enumerate(pts): + v = self.vector(p) + if boxed[i] and self.inside(tree, v): + out[i] = min(out[i], -tree.find_nearest(v)[3]) + continue + hit = tree.find_nearest(v, self.cap) if self.cap else tree.find_nearest(v) + if hit[0] is not None and hit[3] < out[i]: + out[i] = hit[3] + return out From 5726b37692bb250f8967b26209a7a24a4351eba9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:59:27 +0100 Subject: [PATCH 141/223] tests/test_ram: zone bounds in the record, the gate, from_record and a world; a wall of any thickness crossed in a zone; two zones of one pair; a sample at a zone's radius Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/test_ram.py | 134 ++++++++++++++++++++++++++--- 1 file changed, 122 insertions(+), 12 deletions(-) diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py index b80d4ab..1fbe829 100644 --- a/surfaces/blender/tests/test_ram.py +++ b/surfaces/blender/tests/test_ram.py @@ -154,19 +154,23 @@ def scissor(m, ram): def r3_bodies(m, ram, cap=None): """(Bodies, touch) of an R-3 linkage. A zone about a pin is the eye's radius plus what the member keeps: the pin's or boss's radius plus near(member). Its depth is the pin's radius where the pin runs through the member's - eye, 0 for the boss or plate the member stands beside, link_r over a link's own plates, whole length. The plates + eye, 0 for the boss or plate the member stands beside, link_r over a link's own plates, which are zoned about + both of the link's pins, each a little over half its length (a zone is no wider than its member). The plates beside a link on p are let as far as the two part (scissor).""" bodies, crank = r3_parts(m, ram, cap), m.kind == "bell_crank" link, eye, cross = near(ram, "rocker"), "pin d" if crank else "pin p", scissor(m, ram) - arm = float(np.linalg.norm(m.d - m.rocker)) + arm = float(np.linalg.norm(R._flat(m.d - m.rocker, m.axis))) + + def own(part, a, b, span): + return [(part, a, 0.51 * span, ram.link_r), (part, b, 0.51 * span, ram.link_r)] touch = {"barrel": [(eye, "d", PIN + near(ram, "barrel"), 0.0)], "rod": [(eye, "d", PIN + near(ram, "rod"), PIN)], "rocker": [("bracket", "rocker", 0.055 + link, 0.0), ("rocker axle", "rocker", AXLE + link, AXLE), ("pin p", "p", PIN + link, PIN), - ("rocker plates", "rocker", 1.01 * m.lr, ram.link_r), ("coupler plates", "p", cross, 0.0)], + *own("rocker plates", "rocker", "p", m.lr), ("coupler plates", "p", cross, 0.0)], "coupler": [("horn", "c", 0.05 + link, 0.0), ("pin c", "c", PIN + link, PIN), ("pin p", "p", PIN + link, PIN), - ("coupler plates", "p", 1.01 * m.lc, ram.link_r), ("rocker plates", "p", cross, 0.0)]} + *own("coupler plates", "p", "c", m.lc), ("rocker plates", "p", cross, 0.0)]} if crank: touch["rocker arm"] = [("bracket", "rocker", 0.055 + link, 0.0), ("rocker axle", "rocker", AXLE + link, AXLE), ("pin d", "d", PIN + link, PIN), - ("rocker plates", "rocker", 1.01 * arm, ram.link_r)] + *own("rocker plates", "rocker", "d", arm)] return bodies, touch @@ -570,14 +574,14 @@ class DeepKnee(unittest.TestCase): def zones(radius, depth, members=("rod", "barrel")): return {**touch, **{member: touch[member] + [("lug", "d" if member != "coupler" else "p", radius, depth)] for member in members}} - for label, given in (("nothing let", touch), ("the coupler's zone", zones(1.0, 0.02, ("coupler",))), ("a zone short of the lug", zones(0.1, 0.02)), - ("a zone too shallow", zones(1.0, 0.01))): + for label, given in (("nothing let", touch), ("the coupler's zone", zones(0.4, 0.02, ("coupler",))), ("a zone short of the lug", zones(0.1, 0.02)), + ("a zone too shallow", zones(0.4, 0.01))): with self.assertRaises(R.RamError) as caught: R.fit(dressed(m, bodies, given), ram, steps=49, distance=bodies) self.assertEqual((caught.exception.gate, caught.exception.fit.clear_at[2]), ("clash", "lug"), (body, label)) self.assertIn(caught.exception.fit.clear_at[1], ("rod[0]", "barrel[0]")) self.assertIn(f"part 'lug' ({body})", str(caught.exception)) - f = R.fit(dressed(m, bodies, zones(1.0, 0.02)), ram, steps=49, distance=bodies) + f = R.fit(dressed(m, bodies, zones(0.4, 0.02)), ram, steps=49, distance=bodies) self.assertIn(("rod[0]", "lug"), f.allowed) self.assertNotIn(("rocker arm", "lug"), f.allowed) self.assertIn(("rocker arm", "lug"), f.pairs) @@ -628,9 +632,103 @@ class DeepKnee(unittest.TestCase): spot = m.rocker + 0.25 * R._flat(m.p - m.rocker, np.array(X)) / m.lr bodies.parts["rail"], bodies.shapes["rail"] = "parent", [("capsule", spot - (0.05, 0, 0), spot + (0.05, 0, 0), 0.02)] for radius, clear in ((0.117, False), (0.26, False), (0.34, True)): # the rail's 0.02 and what the rocker keeps past 0.25 - f = R._fit(dressed(m, bodies, {**touch, "rocker": touch["rocker"] + [("rail", "rocker", radius, 0.03)]}), ram, steps=49, distance=bodies) + f = R._fit(dressed(m, bodies, {**touch, "rocker": touch["rocker"] + [("rail", "rocker", radius, ram.link_r)]}), ram, steps=49, distance=bodies) self.assertEqual(f.pairs[("rocker", "rail")][0] >= 0.0, clear, radius) + def test_a_zone_is_no_wider_or_deeper_than_its_member(self): + # Soul's absurd zones (radius 1e9, depth 1e9: every member read +1e9 clear inside a block). A radius or a + # depth past the member's length is refused by the record's pins alone; a depth past the member's eye on + # that pin by the gate and by from_record, which hold the ram + m, ram = r3("bell_crank", CRANK), R.Ram(BORE) + bodies, _ = r3_bodies(m, ram) + self.assertEqual((R._span(m, "rocker"), R._span(m, "coupler")), (m.lr, m.lc)) + self.assertAlmostEqual(R._span(m, "rocker arm"), 0.24, places=9) + self.assertGreaterEqual(R._span(m, "rod"), float(R.pose(m, np.linspace(-125.0, 0.0, 126)).L.max())) + self.assertEqual([ram.eye(*of) for of in (("barrel", "a"), ("rod", "a"), ("rod", "d"), ("coupler", "c"))], [ram.e_a, ram.e_a, ram.e_b, ram.link_r]) + for member, pin in (("barrel", "a"), ("rod", "d"), ("rocker", "p"), ("coupler", "c"), ("rocker arm", "rocker")): + span, eye = R._span(m, member), ram.eye(member, pin) + + def zoned(radius, depth): + return dressed(m, bodies, {member: [("thigh", pin, radius, depth)]}) + zoned(span, 0.0) + for radius, depth, field in ((1.2 * span, 0.0, "radius"), (1e308, 0.0, "radius"), (1e9, 1e9, "radius"), (0.1, 1.2 * span, "depth"), (0.1, 1e308, "depth")): + with self.assertRaises(R.RamError) as caught: + zoned(radius, depth) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} thigh {field}")) + self.assertIn(f"{member} is at most {span:.4f} from pin to pin", str(caught.exception)) + R.clearance(zoned(0.1, eye), ram, [-60.0], bodies) + wrote = R.record(zoned(0.1, eye), ram) + R.from_record(wrote) + wrote["touch"][member][0]["depth"] = 1.2 * eye + for read in (lambda: R.clearance(zoned(0.1, 1.2 * eye), ram, [-60.0], bodies), lambda: R.fit(zoned(0.1, 1.2 * eye), ram, steps=49, distance=bodies), + lambda: R.from_record(wrote)): + with self.assertRaises(R.RamError) as caught: + read() + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} thigh depth")) + self.assertIn(f"{member}'s on {pin} is {eye:.4f}", str(caught.exception)) + + def test_a_wall_the_axis_crosses_in_a_zone_is_read_whatever_its_thickness(self): + # Soul's tunnel: a wall of the thigh across the coupler, midway between two of its samples, inside a zone + # about p of depth 0. Every sample stands outside it; the segment between them is what crosses + m, ram = r3("bell_crank", CRANK), R.Ram(BORE) + at = R.pose(m, -60.0) + start = at.P[0] - np.array(X) * ((at.P[0] - at.C[0]) @ np.array(X)) + count = int(math.ceil(m.lc / ram.spacing())) + 1 + samples = start + (at.C[0] - start) * np.linspace(0.0, 1.0, count)[:, None] + spot = 0.5 * (samples[2] + samples[3]) + along = (at.C[0] - start) / m.lc + k = 1 if abs(along[1]) > abs(along[2]) else 2 + + def reading(half, shift=0.0): + lo, hi = spot - 0.08, spot + 0.08 + lo[k], hi[k] = spot[k] - half, spot[k] + half + lo[0], hi[0] = X_COUPLER - 0.05 + shift, X_COUPLER + 0.05 + shift + bodies = r3_parts(m, ram) + bodies.parts["wall"], bodies.shapes["wall"] = "parent", [("box", lo, hi)] + self.assertGreater(float(bodies("wall", samples).min()), 0.0) + return R.clearance(dressed(m, bodies, {"coupler": [("wall", "p", 0.28, 0.0)]}), ram, [-60.0], bodies).pairs[("coupler", "wall")][0] + for half in (0.01, 0.003, 1e-4, 1e-7, 1e-10): + self.assertLess(reading(half), 0.0, half) + # the same walls beside the axis, 0.02 off along the hinge axis: held outside, and let + for half in (0.01, 1e-7): + self.assertGreaterEqual(reading(half, 0.07), 0.02) + # nearer the axis than the floor of the halving, a part the axis is held outside reads as touched + self.assertLess(reading(0.01, 0.05 + 0.2 * ram.spacing() / R.FINE), 0.0) + self.assertGreaterEqual(reading(0.01, 0.05 + 1.2 * ram.spacing() / R.FINE), 0.0) + # a segment with one end in the zone is proved as well. Sampled 0.3 apart, the sample beyond the zone keeps its + # 0.186 from a bead on the axis 0.008 past the last sample in the zone; the bead is read all the same + wide = start + (at.C[0] - start) * np.linspace(0.0, 1.0, 3)[:, None] + bodies, spot = r3_parts(m, ram), wide[1] + 0.012 * along + bodies.parts["bead"], bodies.shapes["bead"] = "parent", [("capsule", spot, spot, 0.004)] + self.assertGreater(float(bodies("bead", wide[:2]).min()), 0.0) + self.assertGreaterEqual(float(bodies("bead", wide[2:])[0]), near(ram, "coupler", 0.3)) + got = R.clearance(dressed(m, bodies, {"coupler": [("bead", "p", 0.25, 0.0)]}), ram, [-60.0], bodies, spacing=0.3) + self.assertLess(got.pairs[("coupler", "bead")][0], 0.0) + + def test_two_zones_of_one_pair_and_a_sample_at_a_zones_radius(self): + # Soul's W1..W3. A pair zoned twice: a sample both reach is let the deeper, in either order, and each zone + # still ends at its own radius. A sample exactly at a zone's radius is in it + m, ram = r3("bell_crank", CRANK), R.Ram(BORE) + bodies, touch = r3_bodies(m, ram) + rest = [zone for zone in touch["rocker"] if zone[0] != "rocker plates"] + + def reading(*zones, degrees=np.linspace(-125.0, 0.0, 49)): + return R.clearance(dressed(m, bodies, {**touch, "rocker": rest + list(zones)}), ram, degrees, bodies).pairs[("rocker", "rocker plates")][0] + deep, beside, far = ("rocker plates", "rocker", 0.6 * m.lr, ram.link_r), ("rocker plates", "rocker", 0.6 * m.lr, 0.0), ("rocker plates", "p", 0.51 * m.lr, ram.link_r) + self.assertAlmostEqual(reading(deep, beside, far), 0.0, places=12) + self.assertAlmostEqual(reading(beside, deep, far), 0.0, places=12) + self.assertAlmostEqual(reading(far, beside, deep), 0.0, places=12) + for short in ((beside, beside, far), (deep, beside), (far, deep[:2] + (0.3 * m.lr, ram.link_r))): + self.assertLess(reading(*short), -0.9 * ram.link_r, short) + at = R.pose(m, [-60.0]) + end = at.P - np.array(X) * ((at.P - m.rocker) @ np.array(X))[:, None] + count = int(math.ceil(m.lr / ram.spacing())) + 1 + pts = m.rocker + (end - m.rocker)[:, None, :] * np.linspace(0.0, 1.0, count)[None, :, None] + across = np.linalg.norm(R._flat(pts - m.rocker, np.array(X)), axis=2)[0] + edge, beyond = float(across[3]), m.lr - 0.5 * float(across[3] + across[4]) + self.assertAlmostEqual(reading(("rocker plates", "rocker", edge, ram.link_r), ("rocker plates", "p", beyond, ram.link_r), degrees=[-60.0]), 0.0, places=12) + self.assertLess(reading(("rocker plates", "rocker", float(np.nextafter(edge, 0.0)), ram.link_r), ("rocker plates", "p", beyond, ram.link_r), degrees=[-60.0]), -0.9 * ram.link_r) + def test_a_pin_stood_inside_what_it_stands_beside_is_refused(self): # Soul's moved-x probes: the rocker's x moved from its plate's place (0.3675) into the bracket's 0.13..0.35, # the coupler's (0.3275) into the horn's 0.18..0.31. The zones are the shipped ones and take in the whole of @@ -647,9 +745,11 @@ class DeepKnee(unittest.TestCase): self.assertEqual((refusal.gate, refusal.pin), ("clash", pin)) self.assertEqual(refusal.fit.clear_at[1:3], (member, part)) self.assertAlmostEqual(refusal.fit.pairs[(member, part)][0], -depth, places=9) - # stated as deep as the boss, the zone lets it: the depth is the record's to state and to be read + # stated as deep as the boss, the zone is refused: a bar's eye is link_r, and no zone lets its axis deeper deep = {**touch, member: [(part, pin, zone[2], depth) if zone[0] == part else zone for zone in touch[member]]} - self.assertGreaterEqual(R._fit(replace(m, touch=deep), ram, steps=49, distance=bodies).pairs[(member, part)][0], 0.0) + with self.assertRaises(R.RamError) as caught: + R._fit(replace(m, touch=deep), ram, steps=49, distance=bodies) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} {part} depth")) def test_a_member_stands_still_in_its_own_bodys_frame(self): # what the oracle is asked: the coupler's samples in the coupler's frame, the rocker's and the arm's in the @@ -842,12 +942,19 @@ class SearchBestFirst(unittest.TestCase): ((ball.parts, {}, None), "search", "world(m) returns"), ((ball.parts, {"rod": ["parent"]}, ball), "record", "zone is (part, pin, radius, depth)"), ((ball.parts, {"rod": [("parent", "c", 1.0, 0.0)]}, ball), "record", "a pin it rides (a, b)"), ((ball.parts, {"rod": [("thigh", "b", 1.0, 0.0)]}, ball), "record", "no part of the record"), + ((ball.parts, {"rod": [("parent", "b", 1e308, 0.0)]}, ball), "record", "rod is at most"), + ((ball.parts, {"rod": [("parent", "b", 0.5, 1e308)]}, ball), "record", "rod is at most"), + ((ball.parts, {"rod": [("parent", "b", 1e9, 1e9)]}, ball), "record", "rod is at most"), + ((ball.parts, {"rod": [("parent", "b", float("inf"), 0.0)]}, ball), "record", "a finite number"), + ((ball.parts, {"rod": [("parent", "b", 0.5, float("nan"))]}, ball), "record", "a finite number"), + ((ball.parts, {"rod": [("parent", "b", 0.5, 1.2 * ram.e_b)]}, ball), "record", "rod's on b is 0.0850"), (({"ball": "rocker"}, {}, ball), "record", "turns with 'rocker'"), (({"ball": "parent"}, {}, ball), "record", "no part turns with body child")): with self.assertRaises(R.RamError) as caught: R.search("direct", self.HINGE, ram, seats, world=lambda m: made) self.assertEqual(caught.exception.gate, gate, said) self.assertIn(said, str(caught.exception)) self.assertTrue(R.search("direct", self.HINGE, ram, seats, world=lambda m: (ball.parts, {}, ball)).found) + self.assertTrue(R.search("direct", self.HINGE, ram, seats, world=lambda m: (ball.parts, {"rod": [("parent", "b", 0.5, ram.e_b)]}, ball)).found) def test_the_limit_is_refused_naming_the_count(self): seats = {"a": grid((0, -0.5, 0.4), (0, -0.2, 1.2), (1, 3, 5)), "b": grid((0, -0.5, -1.2), (0, -0.2, -0.4), (1, 3, 5))} @@ -1062,8 +1169,11 @@ class Refusals(unittest.TestCase): def test_no_blender(self): source = (SURFACE / "brokkr_kitbash" / "ram.py").read_text(encoding="utf-8") - for word in ("bpy", "mathutils", "np.gradient"): + for word in ("bpy", "np.gradient"): self.assertNotIn(word, source) + # the mesh oracle asks for mathutils when one is made: nothing above it does, and this file loaded without it + self.assertNotIn("mathutils", source.split("\nclass Signed:")[0]) + self.assertEqual(source.count("\nclass Signed:"), 1) if __name__ == "__main__": From f97beab77e8ab47759d2df012b0d13459d05cd77 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:59:27 +0100 Subject: [PATCH 142/223] live ram_knee: the package's oracle; the ray count held by the jointlib rocker plates; own plates zoned about both pins; parting zones no wider than the member Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/fixtures/ram_rays.json | 1 + surfaces/blender/tests/live/ram_knee.py | 95 ++++----- .../blender/tests/live/ram_knee.result.json | 184 ++++++++++++------ 3 files changed, 163 insertions(+), 117 deletions(-) create mode 100644 surfaces/blender/tests/fixtures/ram_rays.json diff --git a/surfaces/blender/tests/fixtures/ram_rays.json b/surfaces/blender/tests/fixtures/ram_rays.json new file mode 100644 index 0000000..788d9ee --- /dev/null +++ b/surfaces/blender/tests/fixtures/ram_rays.json @@ -0,0 +1 @@ +{"about":"The rocker's twin plates of the R-3 bell crank as Imagination's jointlib builds them (one shell, triangulated, at rest), and points between the plates (|x| under 0.349, the plates begin at 0.35): each stands on the oracle's first ray 0.004 to 0.02 short of a vertex or an edge of the shell. Every point is outside.","verts":[[-0.349999994,0.740011215,0.389170021],[-0.349999994,0.752862871,0.394919485],[-0.349999994,0.763308823,0.404358923],[-0.349999994,0.770326555,0.416564375],[-0.349999994,0.773229182,0.430341005],[-0.349999994,0.77173245,0.444340348],[-0.349999994,0.765982985,0.457191974],[-0.349999994,0.756543517,0.467637926],[-0.349999994,0.744338095,0.474655658],[-0.349999994,0.730561495,0.477558255],[-0.349999994,0.716562152,0.476061553],[-0.349999994,0.305388123,0.365099549],[-0.349999994,0.292536497,0.359350085],[-0.349999994,0.282090545,0.349910617],[-0.349999994,0.275072783,0.337705195],[-0.349999994,0.272170216,0.323928565],[-0.349999994,0.273666918,0.309929222],[-0.349999994,0.279416382,0.297077596],[-0.349999994,0.288855821,0.286631644],[-0.349999994,0.301061243,0.279613912],[-0.349999994,0.314837903,0.276711315],[-0.349999994,0.328837216,0.278208017],[-0.38499999,0.740011215,0.389170021],[-0.38499999,0.752862871,0.394919485],[-0.38499999,0.763308823,0.404358923],[-0.38499999,0.770326555,0.416564375],[-0.38499999,0.773229182,0.430341005],[-0.38499999,0.77173245,0.444340348],[-0.38499999,0.765982985,0.457191974],[-0.38499999,0.756543517,0.467637926],[-0.38499999,0.744338095,0.474655658],[-0.38499999,0.730561495,0.477558255],[-0.38499999,0.716562152,0.476061553],[-0.38499999,0.305388123,0.365099549],[-0.38499999,0.292536497,0.359350085],[-0.38499999,0.282090545,0.349910617],[-0.38499999,0.275072783,0.337705195],[-0.38499999,0.272170216,0.323928565],[-0.38499999,0.273666918,0.309929222],[-0.38499999,0.279416382,0.297077596],[-0.38499999,0.288855821,0.286631644],[-0.38499999,0.301061243,0.279613912],[-0.38499999,0.314837903,0.276711315],[-0.38499999,0.328837216,0.278208017],[-0.349999994,0.514849424,0.463428885],[-0.349999994,0.522187293,0.473566681],[-0.349999994,0.526033282,0.485475808],[-0.349999994,0.526010931,0.497990549],[-0.349999994,0.522122383,0.509885848],[-0.349999994,0.514748275,0.519997358],[-0.349999994,0.504610479,0.527335227],[-0.349999994,0.492701381,0.531181216],[-0.349999994,0.480186641,0.531158805],[-0.349999994,0.468291312,0.527270257],[-0.349999994,0.458179832,0.519896209],[-0.349999994,0.288777888,0.349887431],[-0.349999994,0.28144002,0.339749664],[-0.349999994,0.27759403,0.327840507],[-0.349999994,0.277616382,0.315325767],[-0.349999994,0.281504929,0.303430468],[-0.349999994,0.288879007,0.293318987],[-0.349999994,0.299016804,0.285981119],[-0.349999994,0.310925931,0.282135129],[-0.349999994,0.323440671,0.282157511],[-0.349999994,0.335336,0.286046058],[-0.349999994,0.345447481,0.293420136],[-0.38499999,0.514849424,0.463428885],[-0.38499999,0.522187293,0.473566681],[-0.38499999,0.526033282,0.485475808],[-0.38499999,0.526010931,0.497990549],[-0.38499999,0.522122383,0.509885848],[-0.38499999,0.514748275,0.519997358],[-0.38499999,0.504610479,0.527335227],[-0.38499999,0.492701381,0.531181216],[-0.38499999,0.480186641,0.531158805],[-0.38499999,0.468291312,0.527270257],[-0.38499999,0.458179832,0.519896209],[-0.38499999,0.288777888,0.349887431],[-0.38499999,0.28144002,0.339749664],[-0.38499999,0.27759403,0.327840507],[-0.38499999,0.277616382,0.315325767],[-0.38499999,0.281504929,0.303430468],[-0.38499999,0.288879007,0.293318987],[-0.38499999,0.299016804,0.285981119],[-0.38499999,0.310925931,0.282135129],[-0.38499999,0.323440671,0.282157511],[-0.38499999,0.335336,0.286046058],[-0.38499999,0.345447481,0.293420136],[0.349999994,0.740011215,0.389170021],[0.349999994,0.752862871,0.394919485],[0.349999994,0.763308823,0.404358923],[0.349999994,0.770326555,0.416564375],[0.349999994,0.773229182,0.430341005],[0.349999994,0.77173245,0.444340348],[0.349999994,0.765982985,0.457191974],[0.349999994,0.756543517,0.467637926],[0.349999994,0.744338095,0.474655658],[0.349999994,0.730561495,0.477558255],[0.349999994,0.716562152,0.476061553],[0.349999994,0.305388123,0.365099549],[0.349999994,0.292536497,0.359350085],[0.349999994,0.282090545,0.349910617],[0.349999994,0.275072783,0.337705195],[0.349999994,0.272170216,0.323928565],[0.349999994,0.273666918,0.309929222],[0.349999994,0.279416382,0.297077596],[0.349999994,0.288855821,0.286631644],[0.349999994,0.301061243,0.279613912],[0.349999994,0.314837903,0.276711315],[0.349999994,0.328837216,0.278208017],[0.38499999,0.740011215,0.389170021],[0.38499999,0.752862871,0.394919485],[0.38499999,0.763308823,0.404358923],[0.38499999,0.770326555,0.416564375],[0.38499999,0.773229182,0.430341005],[0.38499999,0.77173245,0.444340348],[0.38499999,0.765982985,0.457191974],[0.38499999,0.756543517,0.467637926],[0.38499999,0.744338095,0.474655658],[0.38499999,0.730561495,0.477558255],[0.38499999,0.716562152,0.476061553],[0.38499999,0.305388123,0.365099549],[0.38499999,0.292536497,0.359350085],[0.38499999,0.282090545,0.349910617],[0.38499999,0.275072783,0.337705195],[0.38499999,0.272170216,0.323928565],[0.38499999,0.273666918,0.309929222],[0.38499999,0.279416382,0.297077596],[0.38499999,0.288855821,0.286631644],[0.38499999,0.301061243,0.279613912],[0.38499999,0.314837903,0.276711315],[0.38499999,0.328837216,0.278208017],[0.349999994,0.514849424,0.463428885],[0.349999994,0.522187293,0.473566681],[0.349999994,0.526033282,0.485475808],[0.349999994,0.526010931,0.497990549],[0.349999994,0.522122383,0.509885848],[0.349999994,0.514748275,0.519997358],[0.349999994,0.504610479,0.527335227],[0.349999994,0.492701381,0.531181216],[0.349999994,0.480186641,0.531158805],[0.349999994,0.468291312,0.527270257],[0.349999994,0.458179832,0.519896209],[0.349999994,0.288777888,0.349887431],[0.349999994,0.28144002,0.339749664],[0.349999994,0.27759403,0.327840507],[0.349999994,0.277616382,0.315325767],[0.349999994,0.281504929,0.303430468],[0.349999994,0.288879007,0.293318987],[0.349999994,0.299016804,0.285981119],[0.349999994,0.310925931,0.282135129],[0.349999994,0.323440671,0.282157511],[0.349999994,0.335336,0.286046058],[0.349999994,0.345447481,0.293420136],[0.38499999,0.514849424,0.463428885],[0.38499999,0.522187293,0.473566681],[0.38499999,0.526033282,0.485475808],[0.38499999,0.526010931,0.497990549],[0.38499999,0.522122383,0.509885848],[0.38499999,0.514748275,0.519997358],[0.38499999,0.504610479,0.527335227],[0.38499999,0.492701381,0.531181216],[0.38499999,0.480186641,0.531158805],[0.38499999,0.468291312,0.527270257],[0.38499999,0.458179832,0.519896209],[0.38499999,0.288777888,0.349887431],[0.38499999,0.28144002,0.339749664],[0.38499999,0.27759403,0.327840507],[0.38499999,0.277616382,0.315325767],[0.38499999,0.281504929,0.303430468],[0.38499999,0.288879007,0.293318987],[0.38499999,0.299016804,0.285981119],[0.38499999,0.310925931,0.282135129],[0.38499999,0.323440671,0.282157511],[0.38499999,0.335336,0.286046058],[0.38499999,0.345447481,0.293420136]],"faces":[[19,21,11],[24,22,32],[22,1,0],[23,2,1],[24,3,2],[25,4,3],[26,5,4],[27,6,5],[28,7,6],[29,8,7],[30,9,8],[31,10,9],[32,11,10],[33,12,11],[34,13,12],[35,14,13],[36,15,14],[37,16,15],[38,17,16],[39,18,17],[40,19,18],[41,20,19],[42,21,20],[43,0,21],[63,65,55],[68,66,76],[66,45,44],[67,46,45],[68,47,46],[69,48,47],[70,49,48],[71,50,49],[72,51,50],[73,52,51],[74,53,52],[75,54,53],[76,55,54],[77,56,55],[78,57,56],[79,58,57],[80,59,58],[81,60,59],[82,61,60],[83,62,61],[84,63,62],[85,64,63],[86,65,64],[87,44,65],[95,93,91],[122,124,128],[89,110,88],[90,111,89],[91,112,90],[92,113,91],[93,114,92],[94,115,93],[95,116,94],[96,117,95],[97,118,96],[98,119,97],[99,120,98],[100,121,99],[101,122,100],[102,123,101],[103,124,102],[104,125,103],[105,126,104],[106,127,105],[107,128,106],[108,129,107],[109,130,108],[88,131,109],[141,139,135],[166,168,172],[133,154,132],[134,155,133],[135,156,134],[136,157,135],[137,158,136],[138,159,137],[139,160,138],[140,161,139],[141,162,140],[142,163,141],[143,164,142],[144,165,143],[145,166,144],[146,167,145],[147,168,146],[148,169,147],[149,170,148],[150,171,149],[151,172,150],[152,173,151],[153,174,152],[132,175,153],[21,0,10],[0,1,10],[1,2,3],[3,4,5],[5,6,7],[7,8,9],[9,10,3],[10,11,21],[3,10,1],[11,12,13],[13,14,15],[15,16,19],[16,17,19],[17,18,19],[19,20,21],[3,5,7],[7,9,3],[11,13,19],[13,15,19],[22,43,33],[43,42,33],[42,41,40],[40,39,38],[38,37,40],[37,36,40],[36,35,34],[34,33,40],[33,32,22],[40,33,42],[32,31,30],[30,29,28],[28,27,26],[26,25,28],[25,24,28],[24,23,22],[36,34,40],[32,30,24],[30,28,24],[22,23,1],[23,24,2],[24,25,3],[25,26,4],[26,27,5],[27,28,6],[28,29,7],[29,30,8],[30,31,9],[31,32,10],[32,33,11],[33,34,12],[34,35,13],[35,36,14],[36,37,15],[37,38,16],[38,39,17],[39,40,18],[40,41,19],[41,42,20],[42,43,21],[43,22,0],[65,44,54],[44,45,54],[45,46,47],[47,48,49],[49,50,47],[50,51,47],[51,52,53],[53,54,47],[54,55,65],[47,54,45],[55,56,57],[57,58,59],[59,60,61],[61,62,63],[63,64,65],[51,53,47],[55,57,63],[57,59,63],[59,61,63],[66,87,77],[87,86,77],[86,85,84],[84,83,80],[83,82,80],[82,81,80],[80,79,78],[78,77,84],[77,76,66],[84,77,86],[76,75,74],[74,73,72],[72,71,68],[71,70,68],[70,69,68],[68,67,66],[80,78,84],[76,74,68],[74,72,68],[66,67,45],[67,68,46],[68,69,47],[69,70,48],[70,71,49],[71,72,50],[72,73,51],[73,74,52],[74,75,53],[75,76,54],[76,77,55],[77,78,56],[78,79,57],[79,80,58],[80,81,59],[81,82,60],[82,83,61],[83,84,62],[84,85,63],[85,86,64],[86,87,65],[87,66,44],[89,88,98],[88,109,99],[109,108,107],[107,106,105],[105,104,107],[104,103,107],[103,102,101],[101,100,99],[99,98,88],[98,97,91],[97,96,95],[95,94,93],[93,92,91],[91,90,89],[109,107,99],[103,101,107],[101,99,107],[98,91,89],[97,95,91],[130,131,121],[131,110,120],[110,111,112],[112,113,116],[113,114,116],[114,115,116],[116,117,118],[118,119,120],[120,121,131],[121,122,128],[122,123,124],[124,125,128],[125,126,128],[126,127,128],[128,129,130],[110,112,120],[116,118,112],[118,120,112],[121,128,130],[89,111,110],[90,112,111],[91,113,112],[92,114,113],[93,115,114],[94,116,115],[95,117,116],[96,118,117],[97,119,118],[98,120,119],[99,121,120],[100,122,121],[101,123,122],[102,124,123],[103,125,124],[104,126,125],[105,127,126],[106,128,127],[107,129,128],[108,130,129],[109,131,130],[88,110,131],[133,132,142],[132,153,143],[153,152,151],[151,150,149],[149,148,147],[147,146,145],[145,144,143],[143,142,132],[142,141,135],[141,140,139],[139,138,135],[138,137,135],[137,136,135],[135,134,133],[153,151,143],[151,149,147],[147,145,151],[145,143,151],[142,135,133],[174,175,165],[175,154,164],[154,155,156],[156,157,158],[158,159,156],[159,160,156],[160,161,162],[162,163,164],[164,165,175],[165,166,172],[166,167,168],[168,169,170],[170,171,168],[171,172,168],[172,173,174],[154,156,164],[160,162,156],[162,164,156],[165,172,174],[133,155,154],[134,156,155],[135,157,156],[136,158,157],[137,159,158],[138,160,159],[139,161,160],[140,162,161],[141,163,162],[142,164,163],[143,165,164],[144,166,165],[145,167,166],[146,168,167],[147,169,168],[148,170,169],[149,171,170],[150,172,171],[151,173,172],[152,174,173],[153,175,174],[132,154,175]],"points":[[0.34569818,0.758339776,0.399797897],[0.34569818,0.765357508,0.412003349],[0.33924546,0.757903937,0.405161809],[0.34569818,0.768260135,0.425779979],[0.343547274,0.765775611,0.423499465],[0.33924546,0.760806564,0.418938439],[0.34569818,0.766763402,0.439779322],[0.343547274,0.764278879,0.437498808],[0.33924546,0.759309832,0.432937782],[0.34569818,0.761013938,0.452630947],[0.343547274,0.758529415,0.450350434],[0.33924546,0.753560368,0.445789407],[0.34569818,0.75157447,0.4630769],[0.343547274,0.749089947,0.460796386],[0.33924546,0.744120899,0.45623536],[0.347849087,0.741853572,0.472375145],[0.34569818,0.739369048,0.470094631],[0.343547274,0.736884525,0.467814118],[0.33924546,0.731915478,0.463253092],[0.347849087,0.728076971,0.475277742],[0.34569818,0.725592448,0.472997229],[0.343547274,0.723107924,0.470716715],[0.33924546,0.718138877,0.466155689],[0.347849087,0.714077628,0.473781039]]} \ No newline at end of file diff --git a/surfaces/blender/tests/live/ram_knee.py b/surfaces/blender/tests/live/ram_knee.py index d364092..33dc608 100644 --- a/surfaces/blender/tests/live/ram_knee.py +++ b/surfaces/blender/tests/live/ram_knee.py @@ -1,7 +1,7 @@ """Live proof, in a background Blender, of brokkr_kitbash/ram.py's clearance gate on meshes: the R-3 knee (thigh, shin, the bracket and horn, a bell crank's or a four-bar's plates, pins and clevises), every piece a closed mesh this -file generates, each a named part of a body, and the gate answered by a signed BVH oracle over them. Not part of the -unittest run: it needs Blender (mathutils' BVHTree). +file generates, each a named part of a body, and the gate answered by the package's signed BVH oracle (ram.Signed) +over them. Not part of the unittest run: it needs Blender (mathutils' BVHTree). blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/ram_knee.py -- @@ -9,9 +9,9 @@ Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USE without them). is an absolute path; writes .result.json and .r3_.png (the bell crank at 0, -62.5 and -125) and exits 1 when a check failed. -The oracle. distance(part, points) is the nearest face's distance, negative where the point is inside one of the -part's shells. Inside is the crossing parity of three rays, by majority: one ray that grazes an edge or a vertex -miscounts, and an isolated sample then reads inside a plate it stands clear of. +The oracle is ram.Signed, three rays by majority. Its ray count is held by tests/fixtures/ram_rays.json: the rocker +plates as Imagination's jointlib builds them and points between the plates that stand on the first ray short of an +edge or a vertex. One ray reads them inside a plate they stand clear of; the oracle as it is made reads none inside. A clearance verdict is a sign, the gate's own. FLAT follows lodur:ruling:deterministic-bound-margin. The checks run inside one try: an uncaught error is a failed check that names its section, and the result file is always written. @@ -30,7 +30,6 @@ 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")) @@ -46,6 +45,7 @@ spec = importlib.util.spec_from_file_location("brokkr_kitbash_ram", SURFACE / "b R = importlib.util.module_from_spec(spec) # ram.py as the unit tests load it sys.modules[spec.name] = R spec.loader.exec_module(R) +Signed = R.Signed RES = {"blender": bpy.app.version_string, "checks": [], "readings": {}} SECTION = ["setup"] @@ -67,7 +67,6 @@ CRANK = {"a": (0.45, 1.15), "rocker": (0.3171126791600819, 0.3216537818398838), "c": (0.34929485118682846, 0.14862538079826304), "d": (0.48651463351122515, 0.49166254003196397)} ROOTS = {"bell_crank": {"horn": (0.10, -0.40), "bracket": (0.10, 0.55)}, "four_bar": {"horn": (0.0, -0.42), "bracket": (-0.10, 0.55)}} THIGH_FRONT, EMBED = 0.14, 0.01 # the thigh core's faces stand at y +-0.14; a foot runs this far into it -RAYS = [Vector(v).normalized() for v in ((0.5377, 0.6211, 0.5701), (-0.7071, 0.2903, 0.6447), (0.1873, -0.8011, -0.5684))] def check(name, ok, detail=None): @@ -138,44 +137,6 @@ def knee(kind, pn, links=True): return shells, {part: {"parent": "parent", "child": "child", "rocker": "rocker", "coupler": "coupler"}[part.split(".")[0]] for part in shells} -class Signed: - """distance(part, points): negative inside a part's shell (the depth below its nearest face), capped outside - only. Inside is the crossing parity of `rays` rays, by majority. An unknown part raises.""" - - def __init__(self, shells, cap=None, rays=3): - self.cap, self.asked, self.rays = cap, 0, RAYS[:rays] - self.trees = {part: [(BVHTree.FromPolygons(v.tolist(), f, epsilon=0.0), v.min(axis=0), v.max(axis=0)) for v, f in made] for part, made in shells.items()} - - @staticmethod - def crossings(tree, v, ray): - count, o = 0, v - for _ in range(64): - loc = tree.ray_cast(o, ray)[0] - if loc is None: - break - count, o = count + 1, loc + ray * 1e-6 - return count - - def inside(self, tree, v): - return 2 * sum(self.crossings(tree, v, ray) % 2 for ray in self.rays) > len(self.rays) - - def __call__(self, part, pts): - pts = np.asarray(pts, dtype=float) - self.asked += len(pts) - out = np.full(len(pts), math.inf if self.cap is None else self.cap) - for tree, lo, hi in self.trees[part]: - boxed = ((pts >= lo) & (pts <= hi)).all(axis=1) - for i, p in enumerate(pts): - v = Vector(p) - if boxed[i] and self.inside(tree, v): - out[i] = min(out[i], -tree.find_nearest(v)[3]) - continue - hit = tree.find_nearest(v, self.cap) if self.cap else tree.find_nearest(v) - if hit[0] is not None and hit[3] < out[i]: - out[i] = hit[3] - return out - - def near(ram, member): return {"barrel": ram.barrel_r, "rod": ram.rod}.get(member, ram.link_r) + ram.gap + ram.spacing() / 2 @@ -205,23 +166,30 @@ def crossing(m, kind): def zones(m, ram, parts): """Each member's zones. About a pin: the pin's, collar's or cheek's radius plus what the member keeps, as deep as the pin where it runs through the member's eye and 0 beside a collar, a cheek, the bracket or the horn; a link's - own plate over its length, half its thickness deep; a plate beside a link as far as the two part. A depth that - is not 0 is stated SLACK over the burial.""" + own plate about both its pins, each a little over half its length (a zone is no wider than its member), half + the plate's thickness deep; a plate beside a link as far as the two part. A depth that is not 0 is stated SLACK + over the burial.""" kind, link, at = m.kind, near(ram, "rocker"), crossing(m, m.kind) PIN, AXLE, HALF = (value + SLACK for value in (globals()["PIN"], globals()["AXLE"], globals()["HALF"])) reach = {"pin": globals()["PIN"] + link, "axle": globals()["AXLE"] + link} eye = "rocker.pin.d" if kind == "bell_crank" else "rocker.pin.p" + + def own(part, a, b, span): + return [(part, a, 0.51 * span, HALF), (part, b, 0.51 * span, HALF)] + + def parts_at(member, w, degrees): # never wider than the member: two that cross at a few degrees part beyond its length + return min(parting(ram, w, degrees), R._span(m, member)) touch = {member: [("parent.seat", "a", 1.7 * BORE + near(ram, member), 0.0), ("rocker.seat", "d", COLLAR + near(ram, member), 0.0), (eye, "d", globals()["PIN"] + near(ram, member), PIN if member == "rod" else 0.0)] for member in ("barrel", "rod")} pivot = [("parent.bracket", "rocker", None, 0.0), ("rocker.pin.R", "rocker", reach["axle"], AXLE)] - touch["rocker"] = pivot + [("rocker.pin.p", "p", reach["pin"], PIN), ("rocker.plate", "rocker", 1.01 * m.lr, HALF), ("coupler.plate", "p", parting(ram, W_COUPLER, at["p"]), 0.0)] - touch["coupler"] = [("child.horn", "c", parting(ram, W_HORN, at["coupler"]), 0.0), ("coupler.pin.c", "c", reach["pin"], PIN), ("rocker.pin.p", "p", reach["pin"], PIN), - ("coupler.plate", "p", 1.01 * m.lc, HALF), ("rocker.plate", "p", parting(ram, W_ROCKER, at["p"]), 0.0)] + touch["rocker"] = pivot + [("rocker.pin.p", "p", reach["pin"], PIN), *own("rocker.plate", "rocker", "p", m.lr), ("coupler.plate", "p", parts_at("rocker", W_COUPLER, at["p"]), 0.0)] + touch["coupler"] = [("child.horn", "c", parts_at("coupler", W_HORN, at["coupler"]), 0.0), ("coupler.pin.c", "c", reach["pin"], PIN), ("rocker.pin.p", "p", reach["pin"], PIN), + *own("coupler.plate", "p", "c", m.lc), ("rocker.plate", "p", parts_at("coupler", W_ROCKER, at["p"]), 0.0)] if kind == "bell_crank": - touch["rocker arm"] = pivot + [("rocker.pin.d", "d", reach["pin"], PIN), ("rocker.plate", "rocker", 1.01 * float(np.linalg.norm(R._flat(m.d - m.rocker, m.axis))), HALF)] + touch["rocker arm"] = pivot + [("rocker.pin.d", "d", reach["pin"], PIN), *own("rocker.plate", "rocker", "d", R._span(m, "rocker arm"))] for member in ("rocker", "rocker arm"): if member in touch: - touch[member][0] = ("parent.bracket", "rocker", parting(ram, W_BRACKET, at[member]), 0.0) + touch[member][0] = ("parent.bracket", "rocker", parts_at(member, W_BRACKET, at[member]), 0.0) return {member: [zone for zone in given if zone[0] in parts] for member, given in touch.items()} @@ -353,6 +321,16 @@ try: exact = np.maximum.reduce([np.abs(cloud[:, 0]) - 0.13, np.abs(cloud[:, 1]) - 0.14, np.abs(cloud[:, 2] - 0.725) - 0.425]) check("three-rays: 4000 random points about a box are signed as the box signs them", ((core < 0) == (exact < 0)).all(), int(((core < 0) != (exact < 0)).sum())) + # the ray count: the jointlib rocker plates, and points between them aimed along the first ray at an edge or a vertex + fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_rays.json").read_text(encoding="utf-8")) + plates, aimed = {"plates": [(np.array(fixture["verts"]), fixture["faces"])]}, np.array(fixture["points"]) + made, single = Signed(plates)("plates", aimed), Signed(plates, rays=1)("plates", aimed) + RES["readings"]["jointlib plates: points one ray signs inside, of %d" % len(aimed)] = int((single < 0).sum()) + RES["readings"]["jointlib plates: points the oracle signs inside"] = int((made < 0).sum()) + # one ray reads all 24 inside; the oracle as made reads none. The bound on one ray's count is the geometric mean of 1 and 24 + check("ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray", + (np.abs(aimed[:, 0]) < 0.349).all() and (made > 0).all() and (single < 0).sum() >= 5, [int((made < 0).sum()), int((single < 0).sum())]) + SECTION[0] = "seat" seat = np.concatenate([v for v, _ in shells["parent.seat"]]) deepest = float(Signed(shells)("parent.body", seat).min()) @@ -375,8 +353,15 @@ try: check(f"bell-crank-clears-on-meshes (side {side:+.0f}): and at 251 steps with the oracle uncapped", fine.ok, [fine.report(), refused(fine)]) bare = R._fit(replace(m, touch={}), ram, steps=49, distance=Signed(shells, ram.reach())) need = needs(m, ram, parts, Signed(shells)) - stated = {(label(member), zone[0]): zone for member, given in touch.items() for zone in given} - slack = {pair: (stated[pair][1] == pin and stated[pair][2] >= radius and stated[pair][3] >= depth) for pair, (pin, radius, depth) in need.items() if pair in stated} + stated = {} + for member, given in touch.items(): + for zone in given: + stated.setdefault((label(member), zone[0]), []).append(zone) + + def takes(given, pin, radius, depth): # one zone about the pin, or zones about both of the member's pins that meet + return all(zone[3] >= depth for zone in given) and (any(zone[1] == pin and zone[2] >= radius for zone in given) + or (len({zone[1] for zone in given}) == 2 and sum(zone[2] for zone in given) >= radius)) + slack = {pair: takes(stated[pair], *least) for pair, least in need.items() if pair in stated} check(f"zones (side {side:+.0f}): with nothing let the gate refuses, and only pairs the record zones; each stated zone takes in the least that lets its pair", {pair for pair, _, _ in refused(bare)} == set(need) and set(need) <= zoned and all(slack.values()), [refused(bare), sorted(set(need) - zoned), [k for k, v in slack.items() if not v]]) if side > 0: @@ -387,7 +372,7 @@ try: "bell crank: least margin of a zoned pair, 251 steps uncapped": min(reading[0] for pair, reading in fine.pairs.items() if pair in zoned), "bell crank: pairs": len(f.pairs), "bell crank: zoned pairs": len(f.allowed), "bell crank: pairs refused with nothing let": len(refused(bare)), "bell crank: seconds, 49 steps capped": seconds}) - RES["zones"] = {f"{pair[0]} | {pair[1]}": {"stated": list(stated[pair][1:]), "least": [pin, round(radius, 4), round(depth, 4)]} for pair, (pin, radius, depth) in sorted(need.items()) if pair in stated} + RES["zones"] = {f"{pair[0]} | {pair[1]}": {"stated": [list(zone[1:]) for zone in stated[pair]], "least": [pin, round(radius, 4), round(depth, 4)]} for pair, (pin, radius, depth) in sorted(need.items()) if pair in stated} RES["least pairs"] = sorted((round(v[0], 4), v[1], k[0], k[1]) for k, v in fine.pairs.items() if k not in zoned)[:8] SECTION[0] = "zones end" diff --git a/surfaces/blender/tests/live/ram_knee.result.json b/surfaces/blender/tests/live/ram_knee.result.json index 6ad67fe..8bd0d66 100644 --- a/surfaces/blender/tests/live/ram_knee.result.json +++ b/surfaces/blender/tests/live/ram_knee.result.json @@ -16,6 +16,11 @@ "ok": true, "detail": null }, + { + "name": "ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray", + "ok": true, + "detail": null + }, { "name": "the base clevis is seated: its foot runs 0.01 into the thigh's core, through the front plate", "ok": true, @@ -103,9 +108,11 @@ "bell crank: least margin of a zoned pair, 251 steps uncapped": 0.000118, "bell crank: pairs": 60, "bell crank: pairs refused with nothing let": 19, - "bell crank: seconds, 49 steps capped": 0.835, + "bell crank: seconds, 49 steps capped": 2.12, "bell crank: zoned pairs": 20, "four bar: barrel inside the shin's clearance": -0.122, + "jointlib plates: points one ray signs inside, of 24": 24, + "jointlib plates: points the oracle signs inside": 0, "moved x: both": -0.0543, "moved x: the coupler at x 0.25, inside the horn's 0.23..0.31": -0.02, "moved x: the rocker at x 0.25, inside the bracket's 0.13..0.35": -0.0543, @@ -113,16 +120,18 @@ "search: candidates": 13824, "search: pass the gates before clearance": 78, "search: refused on their own parts": 21, - "search: seconds": 42.8, + "search: seconds": 43.3, "search: worlds built": 22, "the base clevis's foot inside the thigh": -0.01 }, "zones": { "barrel[0] | parent.seat": { "stated": [ - "a", - 0.15645000000000003, - 0.0 + [ + "a", + 0.15645000000000003, + 0.0 + ] ], "least": [ "a", @@ -132,9 +141,11 @@ }, "barrel[0] | rocker.pin.d": { "stated": [ - "d", - 0.11105000000000001, - 0.0 + [ + "d", + 0.11105000000000001, + 0.0 + ] ], "least": [ "d", @@ -144,9 +155,11 @@ }, "barrel[0] | rocker.seat": { "stated": [ - "d", - 0.13505, - 0.0 + [ + "d", + 0.13505, + 0.0 + ] ], "least": [ "d", @@ -156,9 +169,11 @@ }, "coupler | child.horn": { "stated": [ - "c", - 0.11195, - 0.0 + [ + "c", + 0.11195, + 0.0 + ] ], "least": [ "c", @@ -168,9 +183,11 @@ }, "coupler | coupler.pin.c": { "stated": [ - "c", - 0.08795, - 0.027 + [ + "c", + 0.08795, + 0.027 + ] ], "least": [ "c", @@ -180,9 +197,16 @@ }, "coupler | coupler.plate": { "stated": [ - "p", - 0.47832364050530635, - 0.018500000000000016 + [ + "p", + 0.24152975906703586, + 0.018500000000000016 + ], + [ + "c", + 0.24152975906703586, + 0.018500000000000016 + ] ], "least": [ "p", @@ -192,9 +216,11 @@ }, "coupler | rocker.pin.p": { "stated": [ - "p", - 0.08795, - 0.027 + [ + "p", + 0.08795, + 0.027 + ] ], "least": [ "p", @@ -204,9 +230,11 @@ }, "coupler | rocker.plate": { "stated": [ - "p", - 0.2818973893266964, - 0.0 + [ + "p", + 0.2818973893266964, + 0.0 + ] ], "least": [ "p", @@ -216,9 +244,11 @@ }, "rocker | coupler.plate": { "stated": [ - "p", - 0.26840002998268986, - 0.0 + [ + "p", + 0.26840002998268986, + 0.0 + ] ], "least": [ "p", @@ -228,9 +258,11 @@ }, "rocker | parent.bracket": { "stated": [ - "rocker", - 0.11695, - 0.0 + [ + "rocker", + 0.11695, + 0.0 + ] ], "least": [ "rocker", @@ -240,9 +272,11 @@ }, "rocker | rocker.pin.R": { "stated": [ - "rocker", - 0.08995, - 0.029 + [ + "rocker", + 0.08995, + 0.029 + ] ], "least": [ "rocker", @@ -252,9 +286,11 @@ }, "rocker | rocker.pin.p": { "stated": [ - "p", - 0.08795, - 0.027 + [ + "p", + 0.08795, + 0.027 + ] ], "least": [ "p", @@ -264,9 +300,16 @@ }, "rocker | rocker.plate": { "stated": [ - "rocker", - 0.43014219644091495, - 0.018500000000000016 + [ + "rocker", + 0.2172005150345214, + 0.018500000000000016 + ], + [ + "p", + 0.2172005150345214, + 0.018500000000000016 + ] ], "least": [ "rocker", @@ -276,9 +319,11 @@ }, "rocker arm | parent.bracket": { "stated": [ - "rocker", - 0.11695, - 0.0 + [ + "rocker", + 0.11695, + 0.0 + ] ], "least": [ "rocker", @@ -288,9 +333,11 @@ }, "rocker arm | rocker.pin.R": { "stated": [ - "rocker", - 0.08995, - 0.029 + [ + "rocker", + 0.08995, + 0.029 + ] ], "least": [ "rocker", @@ -300,9 +347,11 @@ }, "rocker arm | rocker.pin.d": { "stated": [ - "d", - 0.08795, - 0.027 + [ + "d", + 0.08795, + 0.027 + ] ], "least": [ "d", @@ -312,9 +361,16 @@ }, "rocker arm | rocker.plate": { "stated": [ - "rocker", - 0.24240000000000003, - 0.018500000000000016 + [ + "rocker", + 0.12240000000000001, + 0.018500000000000016 + ], + [ + "d", + 0.12240000000000001, + 0.018500000000000016 + ] ], "least": [ "rocker", @@ -324,9 +380,11 @@ }, "rod[0] | rocker.pin.d": { "stated": [ - "d", - 0.07955, - 0.027 + [ + "d", + 0.07955, + 0.027 + ] ], "least": [ "d", @@ -336,9 +394,11 @@ }, "rod[0] | rocker.seat": { "stated": [ - "d", - 0.10355, - 0.0 + [ + "d", + 0.10355, + 0.0 + ] ], "least": [ "d", @@ -436,9 +496,9 @@ } }, "renders": [ - "F:/aeth-wt/fable-ramcore/scratch/h3/out/live3.r3_0.png", - "F:/aeth-wt/fable-ramcore/scratch/h3/out/live3.r3_62p5.png", - "F:/aeth-wt/fable-ramcore/scratch/h3/out/live3.r3_125.png" + "F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_0.png", + "F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_62p5.png", + "F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_125.png" ], "ok": true } \ No newline at end of file From f1d479b3a15b0108bcd6c3f314a06cbce3942184 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:59:28 +0100 Subject: [PATCH 143/223] docs/kitbash.md: Rams and linkages: a zone's bounds, the proof between samples and what it costs, ram.Signed and the ray count's fixture Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 54 +++++++++++++++++++++++--------- 1 file changed, 39 insertions(+), 15 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index f24d4e2..157b805 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -837,14 +837,32 @@ keeps (radius, gap, half the spacing). Its depth says how the member stands to t plate stacked on the pin, the bracket or horn the pin stands in. The member's axis then stays outside the part, so a pin whose place along the axis is inside what it claims to stand beside is refused: the gate does not take the record's x on trust. The pin's radius is for the pin through the member's eye, half the plate's thickness for the -member's own plate, let over its length. Two plates stacked on a pin cross like scissors; the zone that lets one -link by the other's plate reaches as far as the two part, (half width + what a link keeps) / sin of the least -angle they cross at. +member's own plate, which is zoned about both of the member's pins. Two plates stacked on a pin cross like +scissors; the zone that lets one link by the other's plate reaches as far as the two part, (half width + what a +link keeps) / sin of the least angle they cross at, and no further than the link is long. Two zones of one pair +that both reach a sample let it the deeper of the two. + +A zone is bounded by its member. Its radius and its depth are finite and no more than the member's length from pin +to pin: a bar's length between its pins, and for the barrel and the rod the base's and the eye's distances from +the centre the eye turns about, added. A `Mechanism` refuses a zone past that from its pins alone. Its depth is +also no more than the member's eye on that pin (`Ram.eye`: `e_a` at the base, `e_b` at the rod's eye, `link_r` on +a bar), which `from_record` and the gate refuse, so a world's answer is held to it as well. The record holds no +plate widths, so the radius has no tighter bound than the length. + +Between two samples of which either is in a zone the gate does not rely on the spacing. A distance changes by no +more than the way between two points, so along a segment it is at least (g(a) + g(b) - length) / 2. Where that +does not show the segment keeps `-depth`, the gate halves it and reads the midpoint, down to spacing / 64. A +segment still unproved there against a part the axis is held outside (depth 0) is refused: the part is within +spacing / 128 of the axis, crossed or touched, whatever its thickness. Against a part the axis may enter, the +samples' readings stand, so a burial is read to spacing / 128. This asks of the oracle that it never reads more +than the true distance. What it gives up: inside a zone the gate holds only the member's axis `depth` from the part, not its surface a -gap from it, so a link may graze the plate it scissors with anywhere within the stated radius, and a depth stated -deeper than the eye lets the axis into the part that far. Both are numbers in the record, to be read. The members -are round bars; a plate's flat sides are not modelled, which is why stacked plates need a zone at all. +gap from it, so a link may graze the plate it scissors with anywhere within the stated radius. The members are +round bars; a plate's flat sides are not modelled, which is why stacked plates need a zone at all. The proof +between samples costs oracle calls: a depth stated with no slack over the burial (a bar's own plates at `link_r`) +is halved to the floor along the whole zone. And it is along the axis at each checked angle; between two angles +nothing is proved. The oracle is `distance(part, points) -> distances`, `points` in the rest frame of the part's body. Each member is sampled along its axis at most `spacing` apart (default the barrel's radius) and carried into each body's rest @@ -861,7 +879,8 @@ about R, and `d` about R for a bell crank, the eye standing at `a`'s place along least arm; a miss returns the tally by gate and the nearest miss. Clearance takes `world(m) -> (parts, touch, distance)`: a linkage's brackets and links are the candidate's own, so each candidate that reaches the gate is met with the parts its own pins place. What `world` returns is read as a record's: anything but the three, a part on -no body of the kind, or a zone that is not a part, a pin the member rides, a radius and a depth is refused. +no body of the kind, a zone that is not a part, a pin the member rides, a radius and a depth, or a zone wider or +deeper than its member is refused. `swept` gives the ram's swept surface in any body's frame, for a recess. ### The record @@ -872,7 +891,8 @@ It holds what is authored; barrel, closed length and link lengths are derived by reserved for a load-path ram's settle (stiffness, damping, travel); version 1 writes it null and solves none. A record of another schema or version (the integer 1: 1.0 and true are not it), with a key version 1 does not know or without one it does (at the top, in `ram`, `hinge`, `pins` or a zone), with a compliance block, or with a value -that is not its field's (a finite number, the bore over 0, three numbers for a point) is refused whole, as a +that is not its field's (a finite number, the bore over 0, three numbers for a point), or with a zone wider or +deeper than its member is refused whole, as a `RamError` that names the field: a reader never reads past what it cannot solve. A `Ram` built by hand refuses the same numbers. @@ -882,9 +902,12 @@ Bore 0.042, range 0..-125. The kinematic rows are tests/test_ram.py's. The clear `tests/live/ram_knee.py`'s, Blender 5.3 (`ram_knee.result.json` is the last run): the knee as closed meshes the test generates (thigh with its front plate, shin with caps and armour, the bracket that carries R, the horn that carries `c`, twin link plates stacked 5 mm apart at x 0.31..0.345 and 0.35..0.385, pins through the knee's width, -collars at the eye and a base clevis whose foot runs 0.01 into the thigh; 12 parts) and a signed BVH oracle: the -nearest face for the depth, the crossing parity of three rays, by majority, for the side. One ray that grazes an -edge miscounts and signs an isolated sample inside a plate it stands clear of. +collars at the eye and a base clevis whose foot runs 0.01 into the thigh; 12 parts) and the package's signed BVH +oracle, `ram.Signed(shells, cap)`: the nearest face for the depth, the crossing parity of three rays, by majority, +for the side. One ray that runs through an edge or a vertex miscounts and signs a sample inside a plate it stands +clear of. `tests/fixtures/ram_rays.json` holds the ray count: the rocker plates as the joint library builds them +and 24 points between the plates, each on the first ray short of an edge or a vertex. One ray signs all 24 +inside; three sign none. Three rays are not a proof: of 146 such points one ray missigned, two rays missigned 16. | drive | reading | | --- | --- | @@ -896,10 +919,11 @@ edge miscounts and signs an isolated sample inside a plate it stands clear of. | bell-crank search on the meshes | 13,824 candidates, each world built from the candidate's pins: 78 pass the gates before clearance, 21 of them are refused on their own parts, the 22nd fits (arm 0.090, swing 99.9, pin load 0.73) and holds at 251 steps | Cost on Starfire, Python 3.13, 100 repetitions paired and interleaved: one candidate's gates before clearance at -49 steps took 1.07 ms median on the bell crank; its clearance against the analytic parts (50 pairs, 23,520 -points) added 56 ms (5th to 95th percentile 16 to 73, other work on the machine). A search without a world ran 1.6 to 1.8 ms a candidate over 3,456, so `limit` -(20,000) is 30 to 40 s. On the meshes the bell crank's 60 pairs at 49 steps took 0.67 to 0.84 s capped, in a Python loop -of BVH queries with three rays a sample, and the 13,824-candidate search with its 22 worlds 41 to 49 s. +49 steps took 0.79 ms median on the bell crank; its clearance against the analytic parts (50 pairs) took 42 ms +(5th to 95th percentile 38 to 57) over 97,875 points, of which 23,520 are the samples and the rest the halving in +zones (the own plates, stated with no slack, to the floor); the samples alone took 11 ms. A search without a world ran 1.6 to 1.8 ms a candidate over 3,456, so `limit` +(20,000) is 30 to 40 s. On the meshes the bell crank's 60 pairs at 49 steps took 1.95 to 2.12 s capped (two runs), in a +Python loop of BVH queries with three rays a sample, and the 13,824-candidate search with its 22 worlds 43 s (one run). ## The actions From 8767699767e81e0c8927a612a0afc52f9442141b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:22:03 +0100 Subject: [PATCH 144/223] brokkr_kitbash: cut apply and kit_baked (cut kit-freeze, 1 of 2) apply's class, action row, docs and tests go, with BAKED and report's baked key. A destructive bake removed the stack and the collections that say what cuts a part; freeze and thaw replace it in the next commit. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 64 ++----------- .../brokkr_kitbash/brokkr_actions.json | 20 +--- surfaces/blender/docs/kitbash.md | 27 ++---- .../blender/tests/live/kitbash_assembly.py | 91 +------------------ surfaces/blender/tests/live/kitbash_shell.py | 21 +---- surfaces/blender/tests/test_kitbash.py | 14 +-- 6 files changed, 30 insertions(+), 207 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 299d1e6..3616982 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -10,15 +10,14 @@ WindowManager.brokkr_mesh_polish_result, as the polish operators do. What a placed part is lives on its object as three ID properties: kit_kit, kit_part and kit_params. The mesh is derived from them (set_params rebuilds it), and socket frames are derived again at every report: nothing else in the scene stores them. Two things would give a part a second owner and are refused: a mesh datablock shared with -another object (set_params, apply), and a world transform that scales, mirrors or shears (a part's size is its +another object (set_params), and a world transform that scales, mirrors or shears (a part's size is its params). A connection belongs to the child: its parent pointer (under an identity parent inverse) and three more ID properties, kit_socket, kit_parent_socket and kit_roll. Its matrix_basis is derived from them and both parts' params by core.mate; attach and set_params write it, and a report says how far the child stands from it. write_connection is the one writer of a connection. roll, aim and reach rewrite an attached part's roll through it, -in place: roll states the roll, aim and reach solve it in closed form (core.aim_roll, core.reach_roll). kit_baked -says apply replaced the mesh with the evaluated one: the params then only place the part's sockets. Placing a +in place: roll states the roll, aim and reach solve it in closed form (core.aim_roll, core.reach_roll). Placing a loose part, hiding a cutter, materials and export are Brokkr's own rows (setObjectTransform, setObjectVisibility, assignMaterial, exportGltf). @@ -33,7 +32,7 @@ identity parent inverse: its matrix_basis is the recess frame and its params the the cutter object moves the cut and its floor socket together, and nothing else stores either. Machinery attaches to a floor socket with the ordinary attach. Blender evaluates a changed target after every action, so each cut costs one Boolean evaluation; cut_many places many cutters for one. Every action that evaluates an object (boolean, cut, -cut_many, apply) first refuses one Blender does not evaluate (evaluable). A report's list that would not fit a +cut_many) first refuses one Blender does not evaluate (evaluable). A report's list that would not fit a receipt is trimmed by fitted, the rows left off counted beside it: the scene keeps what they would have said. ribs derives the frame under an armor cage from the cage: ribs behind the plate along plane sections, stopped where @@ -86,7 +85,7 @@ except ImportError as error: # register() says so; the classes below only need from . import core, route KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" -SOCKET, PARENT_SOCKET, ROLL, BAKED = "kit_socket", "kit_parent_socket", "kit_roll", "kit_baked" +SOCKET, PARENT_SOCKET, ROLL = "kit_socket", "kit_parent_socket", "kit_roll" 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" @@ -181,7 +180,7 @@ def kit_part_of(obj, kits=None): def built_part(obj, kits=None): - """(part, the part built at the object's stored params): where its sockets are, baked or not.""" + """(part, the part built at the object's stored params): where its sockets are.""" part, stored = kit_part_of(obj, kits) return part, core.build(part, stored) @@ -353,8 +352,7 @@ def part_report(obj, part, built) -> dict: return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, "faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world)), - "connection": connection_report(obj, part, built), "closure": closure_report(obj, part, built), - "baked": bool(obj.get(BAKED, False))} + "connection": connection_report(obj, part, built), "closure": closure_report(obj, part, built)} def own_mesh(obj, doing: str) -> None: @@ -402,14 +400,14 @@ def uncut(target, cutter) -> None: def evaluated_of(context, obj): """(depsgraph, obj with its modifier stack evaluated). An Exact Boolean costs from a few tenths of a second (a - kit part) to a few seconds (a subdivided shell), so only cut, boolean and apply call this; no report does.""" + kit part) to a few seconds (a subdivided shell), so only boolean and ribs call this; no report does.""" depsgraph = context.evaluated_depsgraph_get() return depsgraph, obj.evaluated_get(depsgraph) def evaluable(context, obj): """evaluated_of, for an object Blender evaluates: refuses one the evaluated depsgraph does not hold, which has no - evaluated mesh to cast at, cut or bake. Membership of the depsgraph is the test, whatever keeps the object out + evaluated mesh to cast at or cut. Membership of the depsgraph is the test, whatever keeps the object out of it. Every action that evaluates calls this before its first write.""" depsgraph, evaluated = evaluated_of(context, obj) if not evaluated.is_evaluated: @@ -558,9 +556,6 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): def work(self, context): obj = mesh_object(self.object_name) part, stored = kit_part_of(obj) - if obj.get(BAKED): - raise Refused(f"{obj.name!r} is baked: apply replaced its mesh, and its params now only place its sockets. " - "place_part a new part to change them; nothing changed.") own_mesh(obj, "rebuilding") built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored)) closing = closure(obj) # a closure this part is an end of must still be one its new sockets may make; where they stand is only reported @@ -879,45 +874,6 @@ class BROKKR_KITBASH_OT_cut_many(PolishOperator): return report -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 - stay as they are, and so do the cutter objects""" - bl_idname = "brokkr_kitbash.apply" - bl_label = "Apply Kit Part" - object_name: bpy.props.StringProperty(name="Object") - - @kit_work - def work(self, context): - obj = mesh_object(self.object_name) - evaluable(context, obj) - part, built = built_part(obj) - own_mesh(obj, "baking") - if not obj.modifiers: - raise Refused(f"{obj.name!r} has no modifiers to apply; nothing changed.") - cutters, slots = [row["cutter"] for row in booleans(obj)], len(obj.data.materials) - depsgraph, evaluated = evaluated_of(context, obj) - baked = bpy.data.meshes.new_from_object(evaluated, preserve_all_data_layers=True, depsgraph=depsgraph) - while len(baked.materials) > slots and baked.materials[len(baked.materials) - 1] is None: - baked.materials.pop() # a Boolean gives a part that had no material slot one empty slot - index = np.zeros(len(baked.polygons), dtype=np.int32) - baked.polygons.foreach_get("material_index", index) - if (index < 0).any(): # faces from a cutter's empty slot: slot 0, as faces from a cutter with no material - baked.polygons.foreach_set("material_index", np.maximum(index, 0)) - old, name = obj.data, obj.data.name - held = [found for found in (operation_collection(obj, operation) for operation in OPERATIONS) if found is not None] - obj.data = baked - obj.modifiers.clear() - for collection in held: # a collection another object's modifier still reads (a copied part) stays - if collection.users == 0: - bpy.data.collections.remove(collection) - if old.users == 0: - bpy.data.meshes.remove(old) - baked.name = name - obj[BAKED] = True - return {**part_report(obj, part, built), **measured(baked), "cutters": cutters} - - RIBS = "kit_ribs" # on a ribs object: the request that derived it, as JSON; nothing reads it to decide geometry SAMPLES_LIMIT = 20000 # section points in one ribs: every chain's length over step, summed SHELL_MODIFIERS = ("SOLIDIFY", "BEVEL", "BOOLEAN") # what makes a designed surface a cut plate: off, the cage shows the surface @@ -1833,7 +1789,7 @@ class BROKKR_KITBASH_OT_describe(PolishOperator): class BROKKR_KITBASH_OT_report(PolishOperator): """Report placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world frame, - the connection and the closure and whether each holds, and whether the part is baked""" + the connection and the closure and whether each holds""" bl_idname = "brokkr_kitbash.report" bl_label = "Report Kit Parts" bl_options = {"REGISTER"} @@ -1848,7 +1804,7 @@ class BROKKR_KITBASH_OT_report(PolishOperator): classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report, BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach, - BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply, BROKKR_KITBASH_OT_ribs, + BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_ribs, BROKKR_KITBASH_OT_shell, BROKKR_KITBASH_OT_hose) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 3ea95e9..2fc918f 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -45,7 +45,7 @@ }, { "name": "brokkr_kitbash.set_params", - "doc": "Change params of a placed kit part and rebuild its mesh in place; modifiers and materials stay, and its connection and the parts attached to it are seated again. Refuses a change that breaks a connection, a baked part, a mesh another object shares and a scaled part. Reports as place_part.", + "doc": "Change params of a placed kit part and rebuild its mesh in place; modifiers and materials stay, and its connection and the parts attached to it are seated again. Refuses a change that breaks a connection, a mesh another object shares and a scaled part. Reports as place_part.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -93,7 +93,7 @@ }, { "name": "brokkr_kitbash.report", - "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds) and baked. Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.", + "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds). Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", @@ -551,22 +551,6 @@ } ] }, - { - "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, a mesh another object shares and a part Blender does not evaluate.", - "changesScene": true, - "editModeSafe": false, - "result": "brokkr_mesh_polish_result", - "fields": [ - { - "name": "object_name", - "type": "string", - "required": true, - "minLength": 1, - "maxLength": 63 - } - ] - }, { "name": "brokkr_kitbash.ribs", "doc": "Derive the frame under an armor cage from the cage itself, so it fits the armor by construction: a rib along each plane's section of the cage's surface, set the standoff behind the plate's inner face (along the plate's normal, at any tilt of the plane and any curvature of the wall: its edge is cut from the inner face offset inward, then measured against the plate) and reaching depth inward, clipped inside a crease tighter than that; lightening holes through the ribs; posts that stand the plate off them; longerons through the ribs. The plate's two faces are read from the cage's one Solidify as it evaluates, whatever its thickness mode. A rib stops where the plate is open (a port cut through it), runs behind an opening shorter than bridge (a panel break) and under a recess: openings are read from the cage as it is cut, so cut first. Inward is the side the cage's normals face away from. Makes one mesh object, a child of the cage, baked at this call: after the cage or its cuts change, delete it and run ribs again (its kit_ribs property keeps the request). Every plane and longeron is checked before anything is written. Reports ribs, thickness, sections [{plane, chains, pieces, length, open}], posts, holes, longerons [{index, stations}], faces, volume and nonManifoldEdges.", diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 157b805..8e789ba 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -30,8 +30,7 @@ Who owns what: - A closure, the joint that closes a loop, belongs to the closing part: its `kit_close_socket`, `kit_close_to` and `kit_close_to_socket` properties. Only `close` writes them and only `detach` clears them. A closure places nothing: whether it holds is derived at each report. -- A boolean belongs to its Boolean modifier on the part that is cut. `kit_baked` says `apply` replaced the part's - mesh with the evaluated one. +- A boolean belongs to its Boolean modifier on the part that is cut. ## A part, end to end @@ -318,22 +317,12 @@ took 1.89 s through the collection modifier, 12.6 s with a Boolean modifier for 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` +evaluated, and Blender evaluates it after every action that changes it or a cutter. `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`. - ## Making a shell `shell` makes an armor plate the way one is modelled by hand: fit a sparse subdivision cage, crease the edges that @@ -430,7 +419,7 @@ medians of three interleaved calls in the live suite (Blender 5.3 on Starfire). are twisted, and the Boolean, which cuts quads into triangles, can read the wall as passing through itself and leave edges with four faces. On the Seraph's cap that began at 0.91 of the thickness at which the first face folds (0.0301 against 0.033), on the left cap and not on its mirror, the right; on its breast plate at 0.91 as -well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, `apply`, or a count on the evaluated +well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, or a count on the evaluated mesh), and keep `thickness` clear of the first folding one with a thinner wall, fewer `levels` or wider facets at the corner. @@ -504,7 +493,7 @@ attaching a part to a floor) costs an evaluation again while the target is visib more cutters than fit (about 150 of long names), the rows left off the end are counted in `booleansOmitted`. The scene keeps every cutter; the target's `Kit` modifier collections list them. -`cut`, `cut_many`, `boolean` and `apply` evaluate their object, and refuse one Blender does not evaluate in the +`cut`, `cut_many` and `boolean` evaluate their object, and refuse one Blender does not evaluate in the view layer: an object disabled in viewports that nothing evaluated depends on, or one whose collections no view layer shows. A disabled object that an evaluated object needs (a parent of one, a cutter of one) is evaluated all the same, and is cut. @@ -931,8 +920,8 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se | --- | --- | --- | | `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | | `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.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. 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` and `closure`. 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; 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.roll` | `object_name`, `roll` (degrees, -360 to 360) | Turns an attached part to that roll where it hangs. Refuses a part that is not attached. Reports the part and `closures` as `set_params` does. | @@ -942,7 +931,6 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se | `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; `booleansOmitted` counts rows a receipt had no room for) 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), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | -| `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | | `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | | `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff, range}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `seed`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. | @@ -979,7 +967,6 @@ assembly by its root: an attached part is placed by its connection. {"action": "createObject", "objectType": "MESH", "name": "Cutter", "location": [0.3, 0.6, 0], "size": 0.2}, {"action": "brokkr_kitbash.boolean", "object_name": "Tank", "cutter": "Cutter"}, {"action": "setObjectVisibility", "targetObjectName": "Cutter", "visible": false}, - {"action": "brokkr_kitbash.apply", "object_name": "Tank"}, {"action": "brokkr_kitbash.report", "object_name": "Nozzle"}, {"action": "exportGltf", "filepath": "engine.glb", "selection": ["Tank", "Tee", "Nozzle"]} ]} @@ -1070,6 +1057,6 @@ frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may `PoseTests` the closed-form rolls. The operators are exercised in a real Blender by `tests/live/kitbash.py` (placing and re-parameterising, and the frame kit: its nine parts placed, the truss re-parameterised, a beam seated on a bracket), `tests/live/kitbash_assembly.py` (attach, detach, -`set_params` on assemblies, a braced leg closed by `close`, boolean and apply), `tests/live/kitbash_shell.py` +`set_params` on assemblies, a braced leg closed by `close` and boolean), `tests/live/kitbash_shell.py` (`cut` and `cut_many` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no collection) and `tests/live/kitbash_pose.py` (roll, aim and reach). diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 33b580e..4371f5f 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -1,6 +1,6 @@ """Live proof, in a background Blender, of brokkr_kitbash assembly through run_intent: attach and its refusals, set_params seating a part and the parts attached to it again, a braced leg closed by close and what set_params, -attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (one Exact Boolean modifier per operation over a collection of cutters, self-intersection on, above the Bevel), and apply with its material slots. Not part +attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (one Exact Boolean modifier per operation over a collection of cutters, self-intersection on, above the Bevel). Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_assembly.py -- @@ -199,8 +199,7 @@ try: radiator = place("Radiator", "radiator_stack", location=[0.0, 10.0, 0.0]) send("createObject", objectType="MESH", name="Plain", location=[0.0, 12.0, 0.0], size=0.3) receipt, report = send("brokkr_kitbash.report", object_name="Tank") - check("a part nobody attached reports connection null and baked false", report and report["parts"][0]["connection"] is None - and report["parts"][0]["baked"] is False, report) + check("a part nobody attached reports connection null", report and report["parts"][0]["connection"] is None, report) receipt, report = send("brokkr_kitbash.attach", object_name="Nozzle", socket="mount", parent_name="Tee", parent_socket="c", roll=37.0) check("attach parents the nozzle to the tee under an identity parent inverse and stores the three properties", receipt["status"] == "accepted" @@ -599,36 +598,6 @@ try: and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], report["params"]).counts) != raw["faces"] and CUT < resized["volume"] < measure(tank.data)["volume"] - 0.005 and holds("Tee", "Tank", "b", "port_a", 180.0)[0], [receipt["message"], resized]) - # --- apply ------------------------------------------------------------------------------------------------------------------------ - refused("apply on a mesh that is not a kit part", "brokkr_kitbash.apply", {"object_name": "Plain"}, "'Plain' is not a kit part") - slots = [s.material and s.material.name for s in tank.material_slots] - shown, shown_slots = evaluated(tank) - index = np.zeros(len(tank.data.polygons), dtype=np.int32) - tank.data.polygons.foreach_get("material_index", index) - mesh_name, meshes, collections = tank.data.name, len(bpy.data.meshes), len(bpy.data.collections) - sockets_before = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["sockets"] - receipt, baked = send("brokkr_kitbash.apply", object_name="Tank") - after = np.zeros(len(tank.data.polygons), dtype=np.int32) - tank.data.polygons.foreach_get("material_index", after) - check("apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name", - receipt["status"] == "accepted" and baked and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown == measure(tank.data) - and len(tank.modifiers) == 0 and tank.data.name == mesh_name and len(bpy.data.meshes) == meshes and baked["cutters"] == ["Box"] - and len(bpy.data.collections) == collections - 1 and "Tank difference" not in bpy.data.collections and "Box" in bpy.context.scene.objects, [receipt["message"], baked, shown]) - check("apply keeps the material slots exactly, and faces of both materials", slots == shown_slots == ["Tank Paint", "Strap Steel"] - and [s.material and s.material.name for s in tank.material_slots] == slots and [m and m.name for m in tank.data.materials] == slots - and index.max() == 1 and sorted(set(after.tolist())) == [0, 1], [slots, [m and m.name for m in tank.data.materials], sorted(set(after.tolist()))]) - check("apply marks the part baked and keeps what it is", tank.get("kit_baked") is True and baked and baked["baked"] is True and tank["kit_part"] == "tank" - and json.loads(tank["kit_params"])["segments"] == 16, dict(tank.items())) - refused("set_params on a baked part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, "'Tank' is baked") - refused("apply on a baked part with no modifiers left", "brokkr_kitbash.apply", {"object_name": "Tank"}, "'Tank' has no modifiers to apply") - receipt, report = send("brokkr_kitbash.report", object_name="Tank") - check("a baked part still reports its sockets where its params put them, and what is attached to it still holds", report and report["parts"][0]["baked"] is True - and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == baked["faces"] and holds("Tee", "Tank", "b", "port_a", 180.0)[0] - and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], report) - receipt, report = send("brokkr_kitbash.attach", object_name="Radiator", socket="base", parent_name="Tank", parent_socket="saddle") - check("a new part attaches to a baked one", receipt["status"] == "accepted" and held(report) - and reading("seated", seated(radiator, "base", tank, "saddle", 0.0)) < SEATED, receipt["message"]) - # --- the second target: a plate with no material slot, cut twice ---------------------------------------------------------------------- plate = place("Plate", "plate", location=[0.0, -3.0, 0.0]) send("createObject", objectType="MESH", name="Slot", location=[0.1, -3.0, 0.0], size=0.1) @@ -643,33 +612,9 @@ try: and all(m.use_self and m.solver == "EXACT" for m in plate.modifiers if m.type == "BOOLEAN"), [[m.name for m in plate.modifiers], first and first["evaluated"], second and second["evaluated"]]) R["plate"] = {"raw": measure(plate.data), "slot": first and first["evaluated"], "slotAndHole": second and second["evaluated"]} - twin = plate.copy() - twin.name = "Plate_twin" - bpy.context.scene.collection.objects.link(twin) - refused("apply on a mesh a linked duplicate shares", "brokkr_kitbash.apply", {"object_name": "Plate"}, "shares its mesh 'Plate' with 1 other user(s): baking it") - bpy.data.objects.remove(twin) - shown, shown_slots = evaluated(plate) - receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") - check("apply on a part with no material slot leaves it with none (Blender's Boolean shows it with one empty slot)", receipt["status"] == "accepted" - and shown_slots == [None] and len(plate.data.materials) == 0 and len(plate.material_slots) == 0 and baked["cutters"] == ["Slot", "Hole"] - and {k: baked[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown, [shown_slots, len(plate.data.materials), len(plate.material_slots), baked]) - send("assignMaterial", targetObjectName="Plate", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) - send("createObject", objectType="MESH", name="Boss", location=[0.0, -3.0, 0.1], size=0.06) - send("assignMaterial", targetObjectName="Boss", materialName="Boss Brass", color=[0.6, 0.5, 0.2]) - send("setObjectTransform", targetObjectName="Boss", location=[0.0, -3.0, 0.02]) - receipt, third = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Boss", operation="UNION") - shown, shown_slots = evaluated(plate) - receipt, baked = send("brokkr_kitbash.apply", object_name="Plate") - used = np.zeros(len(plate.data.polygons), dtype=np.int32) - plate.data.polygons.foreach_get("material_index", used) - check("a baked part is cut and baked again; a cutter that has a material brings it after the part's own slots, on the faces it made", - receipt["status"] == "accepted" and third["booleans"] == [{"cutter": "Boss", "operation": "UNION"}] and third["baked"] is True - and third["evaluated"]["volume"] > R["plate"]["slotAndHole"]["volume"] and shown_slots == ["Plate Paint", "Boss Brass"] - and [m and m.name for m in plate.data.materials] == ["Plate Paint", "Boss Brass"] and sorted(set(used.tolist())) == [0, 1] - and len(plate.modifiers) == 0, [third and third["evaluated"], shown_slots, [m and m.name for m in plate.data.materials], sorted(set(used.tolist()))]) vent = place("Vent", "vent", "width=0.2; height=0.15") receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Plate", parent_socket="front") - check("a vent that fits attaches to the baked plate's front", receipt["status"] == "accepted" and held(report) + check("a vent that fits attaches to the cut plate's front", receipt["status"] == "accepted" and held(report) and reading("seated", seated(vent, "back", plate, "front", 0.0)) < SEATED, receipt["message"]) refused("a loop of two", "brokkr_kitbash.attach", {"object_name": "Plate", "socket": "back", "parent_name": "Vent", "parent_socket": "back"}, "'Vent' is below 'Plate'") @@ -686,36 +631,6 @@ try: check("a tee with a box cut from it has no non-manifold edge: its branch hub is narrower than its run hub", receipt["status"] == "accepted" and cut and cut["evaluated"]["nonManifoldEdges"] == 0 and 0.004 < cut["evaluated"]["volume"] < 0.008, [receipt["message"], cut and cut["evaluated"]]) - # --- apply and empty material slots ----------------------------------------------------------------------------------------------- - keeper = place("Keeper", "plate", location=[0.0, -9.0, 0.0]) - send("assignMaterial", targetObjectName="Keeper", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) - keeper.data.materials.append(None) # an empty last slot the part was given - send("createObject", objectType="MESH", name="Bare", location=[0.1, -9.0, 0.0], size=0.1) - send("brokkr_kitbash.boolean", object_name="Keeper", cutter="Bare") - receipt, baked = send("brokkr_kitbash.apply", object_name="Keeper") - check("apply keeps a part's own empty last slot when the cutter has no material", receipt["status"] == "accepted" - and [m and m.name for m in keeper.data.materials] == ["Plate Paint", None] and len(keeper.material_slots) == 2, - [receipt["message"], [m and m.name for m in keeper.data.materials]]) - gapped = place("Gapped", "plate", location=[0.0, -12.0, 0.0]) - send("assignMaterial", targetObjectName="Gapped", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) - send("createObject", objectType="MESH", name="Gap", location=[0.1, -12.0, 0.0], size=0.1) - gap = bpy.data.objects["Gap"] - gap.data.materials.append(None) # the cutter's faces are in an empty first slot - gap.data.materials.append(bpy.data.materials["Boss Brass"]) - gap.data.polygons[0].material_index = gap.data.polygons[1].material_index = 1 # two of its faces are brass; the rest stay in the empty slot - send("brokkr_kitbash.boolean", object_name="Gapped", cutter="Gap") - receipt, baked = send("brokkr_kitbash.apply", object_name="Gapped") - used = np.zeros(len(gapped.data.polygons), dtype=np.int32) - gapped.data.polygons.foreach_get("material_index", used) - check("apply leaves no face outside the material slots when a cutter's first slot is empty", receipt["status"] == "accepted" and len(used) > 44 - and used.min() >= 0 and used.max() < len(gapped.data.materials) and not gapped.data.validate_material_indices() and not gapped.data.validate(verbose=False), - [receipt["message"], int(used.min()), int(used.max()), [m and m.name for m in gapped.data.materials]]) - names = [m and m.name for m in gapped.data.materials] - brass = [p.index for p in gapped.data.polygons if "Boss Brass" in names and p.material_index == names.index("Boss Brass")] - far = [p.index for p in gapped.data.polygons if (gapped.matrix_world @ p.center).x < -0.05] # the plate's half the cutter does not reach - check("and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", - names[0] == "Plate Paint" and 0 < len(brass) < len(used) and far and all(used[i] == 0 for i in far) - and all(abs((gapped.matrix_world @ gapped.data.polygons[i].center).x - 0.1) < 0.051 for i in brass), [names, len(brass), len(far), sorted(set(used.tolist()))]) except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) diff --git a/surfaces/blender/tests/live/kitbash_shell.py b/surfaces/blender/tests/live/kitbash_shell.py index d5f8e20..02f2c66 100644 --- a/surfaces/blender/tests/live/kitbash_shell.py +++ b/surfaces/blender/tests/live/kitbash_shell.py @@ -259,7 +259,7 @@ try: 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"]]) + and all(p["connection"] is None for p in report["parts"]), report and [p["object"] for p in report["parts"]]) # --- cut-casts-the-uncut-surface -------------------------------------------------------------------------------------------- section('cut-casts-the-uncut-surface') @@ -398,23 +398,6 @@ try: 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") - twin = place("Twin", "plate", location=[0.0, -15.0, 0.0]) - send("createObject", objectType="MESH", name="TwinHole", location=[0.0, -15.0, 0.0], size=0.05) - send("brokkr_kitbash.boolean", object_name="Twin", cutter="TwinHole") - copied = twin.copy() # a copied part: its own mesh, and a Kit Difference modifier that reads the same collection - copied.data = twin.data.copy() - bpy.context.scene.collection.objects.link(copied) - receipt, baked = send("brokkr_kitbash.apply", object_name="Twin") - kept = bpy.data.collections.get("Twin difference") - check("M6: apply keeps a collection a copied part's modifier still reads", receipt["status"] == "accepted" and len(twin.modifiers) == 0 and kept is not None - and copied.modifiers["Kit Difference"].collection == kept and [o.name for o in kept.objects] == ["TwinHole"], [receipt["message"], [c.name for c in bpy.data.collections]]) - # --- cut-refusals ----------------------------------------------------------------------------------------------------------- section('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} @@ -471,8 +454,6 @@ try: refused(f"cut_many on a target {why}", "brokkr_kitbash.cut_many", {"object_name": name, "cuts": json.dumps([{"name": "Unseen", "part": "box", "origin": [0.1, 0.1, 3.0], "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]}])}, NOT) refused(f"boolean on a target {why}", "brokkr_kitbash.boolean", {"object_name": name, "cutter": "Sheet"}, NOT) - refused("apply on a part disabled in viewports", "brokkr_kitbash.apply", {"object_name": "Plate"}, "Blender does not evaluate 'Plate' in this view layer") - refused("apply on a part in a collection outside the view layer", "brokkr_kitbash.apply", {"object_name": "Loose"}, "Blender does not evaluate 'Loose' in this view layer") veil.hide_viewport = plate.hide_viewport = False bpy.context.view_layer.update() diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 6b5da5f..0ade179 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1812,7 +1812,7 @@ class SheetTests(unittest.TestCase): ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", - "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs", + "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.ribs", "brokkr_kitbash.shell", "brokkr_kitbash.hose"] @@ -1859,7 +1859,7 @@ class HostFileTests(unittest.TestCase): self.assertEqual(at.validate(boolean, host)["operation"], "DIFFERENCE") for bad in ({**attach, "roll": 360.5}, {**attach, "socket": "a b"}, {**attach, "parent_socket": ""}, {**attach, "matrix": [1, 0, 0]}, {**boolean, "operation": "SLICE"}, {**boolean, "solver": "EXACT"}, {**boolean, "cutter": ""}, - {**envelope, "action": "brokkr_kitbash.apply"}, {**envelope, "action": "brokkr_kitbash.detach", "object_name": "x" * 64}, + {**envelope, "action": "brokkr_kitbash.detach", "object_name": "x" * 64}, {**close, "socket": "end b"}, {**close, "other_socket": "x" * 33}, {**close, "other_name": ""}, {**close, "roll": 10}, {k: v for k, v in close.items() if k != "other_socket"}): with self.assertRaises(at.IntentInvalid, msg=str(bad)): @@ -1958,25 +1958,25 @@ 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_cut_boolean_and_apply_evaluate_a_modifier_stack(self): + def test_only_cut_boolean_and_ribs_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]) bodies = {body.split("(")[0]: body.split("\n\n\n")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:]} - self.assertEqual([name for name, body in bodies.items() if "evaluated_of(" in body], ["boolean", "apply", "ribs"]) - self.assertEqual(source.count("evaluated_of("), 7) # its def, evaluable, boolean, apply, and ribs for the designed surface, for the plate's two faces and for its holes + self.assertEqual([name for name, body in bodies.items() if "evaluated_of(" in body], ["boolean", "ribs"]) + self.assertEqual(source.count("evaluated_of("), 6) # its def, evaluable, boolean, and ribs for the designed surface, for the plate's two faces and for its holes self.assertIn("evaluated_of(", source.split("def evaluable(")[1].split("\n\n\n")[0]) place = source.split("def place_cutters(")[1].split("\n\n\n")[0] # cut and cut_many place through it: one evaluation, with the Booleans off self.assertEqual((place.count("evaluable("), place.count("evaluated_of(")), (1, 0)) self.assertLess(place.index("modifier.show_viewport = False"), place.index("evaluable(")) self.assertLess(place.index("evaluable("), place.index("modifier.show_viewport = True")) # unevaluable-target: every action that evaluates refuses an object Blender does not evaluate before its first write - for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["apply"], "bpy.data.meshes.new_from_object("), + for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()")): self.assertLess(body.index("evaluable("), body.index(first_write)) - self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs", "shell", "hose"]) + self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "ribs", "shell", "hose"]) ribs = bodies["ribs"] # every refusal before the ribs object is written, and the cage's modifiers shown again whatever happened self.assertLess(ribs.rindex("raise Refused("), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)")) self.assertLess(ribs.index("finally:"), ribs.index("modifier.show_viewport = True")) From 6ea92025553d8ba65d526a479785313c20886bec Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:33:29 +0100 Subject: [PATCH 145/223] brokkr_kitbash.freeze and thaw: a cut object carries its evaluated mesh, its live mesh held in kit_frozen, its stack kept and off (cut kit-freeze, 2 of 2) Blender re-evaluates every live collection Boolean after any datablock removal, hide or mesh read in the scene. freeze swaps in the evaluated mesh and turns every modifier off; thaw is its one undo. live() refuses a frozen object in set_params, boolean, cut, cut_many, ribs, a shell or hose rebuild and freeze. Live: three cut tanks frozen cost 0.0022 of what they cost live when an orphan mesh is removed (mutant F1, modifiers left on: 1.5; bound 0.057). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 96 ++++++++- .../brokkr_kitbash/brokkr_actions.json | 36 +++- .../blender/tests/live/kitbash.result.json | 3 +- .../blender/tests/live/kitbash_assembly.py | 182 +++++++++++++++++- .../tests/live/kitbash_assembly.result.json | 143 ++++++++++++-- surfaces/blender/tests/live/kitbash_shell.py | 53 +++++ .../tests/live/kitbash_shell.result.json | 55 +++++- surfaces/blender/tests/test_kitbash.py | 19 +- 8 files changed, 546 insertions(+), 41 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 3616982..3ff8135 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1,5 +1,5 @@ """Kitbash parts: place parametric machine parts from a kit, mate them socket to socket, cut them and any other -mesh, and bake them. +mesh, and freeze 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 @@ -17,7 +17,9 @@ A connection belongs to the child: its parent pointer (under an identity parent properties, kit_socket, kit_parent_socket and kit_roll. Its matrix_basis is derived from them and both parts' params by core.mate; attach and set_params write it, and a report says how far the child stands from it. write_connection is the one writer of a connection. roll, aim and reach rewrite an attached part's roll through it, -in place: roll states the roll, aim and reach solve it in closed form (core.aim_roll, core.reach_roll). Placing a +in place: roll states the roll, aim and reach solve it in closed form (core.aim_roll, core.reach_roll). kit_frozen +is the frozen state: freeze holds the live mesh there while the object carries its evaluated one with every modifier +off, and thaw is its one undo. Placing a loose part, hiding a cutter, materials and export are Brokkr's own rows (setObjectTransform, setObjectVisibility, assignMaterial, exportGltf). @@ -32,7 +34,7 @@ identity parent inverse: its matrix_basis is the recess frame and its params the the cutter object moves the cut and its floor socket together, and nothing else stores either. Machinery attaches to a floor socket with the ordinary attach. Blender evaluates a changed target after every action, so each cut costs one Boolean evaluation; cut_many places many cutters for one. Every action that evaluates an object (boolean, cut, -cut_many) first refuses one Blender does not evaluate (evaluable). A report's list that would not fit a +cut_many, freeze) first refuses one Blender does not evaluate (evaluable). A report's list that would not fit a receipt is trimmed by fitted, the rows left off counted beside it: the scene keeps what they would have said. ribs derives the frame under an armor cage from the cage: ribs behind the plate along plane sections, stopped where @@ -86,6 +88,7 @@ from . import core, route KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" SOCKET, PARENT_SOCKET, ROLL = "kit_socket", "kit_parent_socket", "kit_roll" +FROZEN = "kit_frozen" # on a frozen object: an ID pointer to its live mesh; its presence is the frozen state, freeze sets it and thaw deletes it 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" @@ -352,7 +355,15 @@ def part_report(obj, part, built) -> dict: return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, "faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world)), - "connection": connection_report(obj, part, built), "closure": closure_report(obj, part, built)} + "connection": connection_report(obj, part, built), "closure": closure_report(obj, part, built), + "frozen": FROZEN in obj} + + +def live(obj, doing: str) -> None: + """Refuses a frozen object: its mesh is its frozen evaluation and its modifiers are off, so a write would land on + a mesh thaw discards, or under a stack nothing evaluates.""" + if FROZEN in obj: + raise Refused(f"{obj.name!r} is frozen, and {doing} it needs its live mesh and modifiers: thaw it first; nothing changed.") def own_mesh(obj, doing: str) -> None: @@ -400,14 +411,14 @@ def uncut(target, cutter) -> None: def evaluated_of(context, obj): """(depsgraph, obj with its modifier stack evaluated). An Exact Boolean costs from a few tenths of a second (a - kit part) to a few seconds (a subdivided shell), so only boolean and ribs call this; no report does.""" + kit part) to a few seconds (a subdivided shell), so only boolean, freeze (through evaluable) and ribs call this; no report does.""" depsgraph = context.evaluated_depsgraph_get() return depsgraph, obj.evaluated_get(depsgraph) def evaluable(context, obj): """evaluated_of, for an object Blender evaluates: refuses one the evaluated depsgraph does not hold, which has no - evaluated mesh to cast at or cut. Membership of the depsgraph is the test, whatever keeps the object out + evaluated mesh to cast at, cut or freeze. Membership of the depsgraph is the test, whatever keeps the object out of it. Every action that evaluates calls this before its first write.""" depsgraph, evaluated = evaluated_of(context, obj) if not evaluated.is_evaluated: @@ -470,6 +481,7 @@ def place_cutters(context, target, specs) -> list: first did, and no Boolean is evaluated here. Blender evaluates the changed target once after the action, however many cutters it placed.""" rigid(target) + live(target, "cutting") kit, made, names = core.load_kit(CUTTERS), [], set() for spec in specs: name = spec["name"] @@ -556,6 +568,7 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): def work(self, context): obj = mesh_object(self.object_name) part, stored = kit_part_of(obj) + live(obj, "setting params of") own_mesh(obj, "rebuilding") built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored)) closing = closure(obj) # a closure this part is an end of must still be one its new sockets may make; where they stand is only reported @@ -792,6 +805,7 @@ class BROKKR_KITBASH_OT_boolean(PolishOperator): raise Refused(f"{obj.name!r} cannot cut itself; nothing changed.") report = part_report(obj, *built_part(obj)) if PART in obj else {"object": obj.name} rigid(obj) + live(obj, "cutting") uncut(obj, cutter) evaluable(context, obj) operation_collection(obj, self.operation, True).objects.link(cutter) @@ -874,6 +888,68 @@ class BROKKR_KITBASH_OT_cut_many(PolishOperator): return report +class BROKKR_KITBASH_OT_freeze(PolishOperator): + """Freeze a mesh object that has modifiers, a kit part or any other: its mesh becomes its evaluated mesh, its live + mesh is held by its kit_frozen property, and every modifier stays in the stack, off in viewports and renders, with + its collections; Blender then evaluates no Boolean for it until thaw""" + bl_idname = "brokkr_kitbash.freeze" + bl_label = "Freeze Cut Object" + object_name: bpy.props.StringProperty(name="Object", description="A mesh with modifiers: a kit part, a shell or any mesh") + + @kit_work + def work(self, context): + obj = mesh_object(self.object_name) + live(obj, "freezing") + if not obj.modifiers: + raise Refused(f"{obj.name!r} has no modifiers to freeze; nothing changed.") + off = [modifier.name for modifier in obj.modifiers if not (modifier.show_viewport and modifier.show_render)] + if off: + raise Refused(f"{obj.name!r} has {', '.join(off)} off in viewports or renders, and thaw turns every modifier on: " + "it would not give this stack back. Show them, or remove them; nothing changed.") + report = part_report(obj, *built_part(obj)) if PART in obj else {"object": obj.name} + depsgraph, evaluated = evaluable(context, obj) + slots = len(obj.data.materials) + frozen = bpy.data.meshes.new_from_object(evaluated, preserve_all_data_layers=True, depsgraph=depsgraph) + while len(frozen.materials) > slots and frozen.materials[len(frozen.materials) - 1] is None: + frozen.materials.pop() # a Boolean gives a part that had no material slot one empty slot + index = np.zeros(len(frozen.polygons), dtype=np.int32) + frozen.polygons.foreach_get("material_index", index) + if (index < 0).any(): # faces from a cutter's empty slot: slot 0, as faces from a cutter with no material + frozen.polygons.foreach_set("material_index", np.maximum(index, 0)) + frozen.name = f"{obj.name} frozen" + obj[FROZEN] = obj.data + obj.data = frozen + for modifier in obj.modifiers: + modifier.show_viewport = modifier.show_render = False + report.update(frozen=True, **measured(frozen), modifiers=[modifier.name for modifier in obj.modifiers]) + report["booleans"] = fitted(report, "booleans", booleans(obj)) + return report + + +class BROKKR_KITBASH_OT_thaw(PolishOperator): + """Thaw a frozen object: its live mesh comes back from kit_frozen, every modifier is turned on, and the frozen mesh + goes; evaluates nothing itself (Blender evaluates the object once afterwards)""" + bl_idname = "brokkr_kitbash.thaw" + bl_label = "Thaw Frozen Object" + object_name: bpy.props.StringProperty(name="Object", description="A frozen mesh object") + + @kit_work + def work(self, context): + obj = mesh_object(self.object_name) + if FROZEN not in obj: + raise Refused(f"{obj.name!r} is not frozen; nothing changed.") + held, frozen = obj[FROZEN], obj.data + if not isinstance(held, bpy.types.Mesh): + raise Refused(f"{obj.name!r} is frozen and the live mesh its {FROZEN} held is gone: there is nothing to thaw to; nothing changed.") + obj.data = held + del obj[FROZEN] + for modifier in obj.modifiers: + modifier.show_viewport = modifier.show_render = True + if frozen.users == 0: + bpy.data.meshes.remove(frozen) + return {"object": obj.name, "frozen": False, "modifiers": [modifier.name for modifier in obj.modifiers], "faces": len(held.polygons)} + + RIBS = "kit_ribs" # on a ribs object: the request that derived it, as JSON; nothing reads it to decide geometry SAMPLES_LIMIT = 20000 # section points in one ribs: every chain's length over step, summed SHELL_MODIFIERS = ("SOLIDIFY", "BEVEL", "BOOLEAN") # what makes a designed surface a cut plate: off, the cage shows the surface @@ -985,6 +1061,7 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): def work(self, context): cage = mesh_object(self.object_name) rigid(cage) + live(cage, "deriving ribs from") depsgraph, _ = evaluable(context, cage) if not 1 <= len(self.ribs_name) <= 63 or self.ribs_name in bpy.data.objects: raise Refused(f"ribs_name {self.ribs_name!r} must be 1 to 63 characters and no object's name; nothing changed.") @@ -1292,6 +1369,7 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): if obj.type != "MESH" or SHELL not in obj: raise Refused(f"An object named {obj.name!r} exists and is no shell (it carries no {SHELL}): shell rebuilds only what shell made; nothing changed.") rigid(obj) + live(obj, "rebuilding") own_mesh(obj, "rebuilding") if self.count_folds: unseen = [modifier.name for modifier in obj.modifiers if modifier.name in (SUBSURF, SOLIDIFY) and not modifier.show_viewport] @@ -1408,6 +1486,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): if hose is not None: if hose.type != "MESH" or HOSE not in hose: raise Refused(f"An object named {hose.name!r} exists and is no hose (it carries no {HOSE}): hose rebuilds only what hose made; nothing changed.") + live(hose, "rebuilding") own_mesh(hose, "rebuilding") sizes = route.bundle(self.count, self.radius, self.spread, self.clearance, self.bend) r, need, floor, lead, half_width = self.radius, sizes["need"], sizes["floor"], sizes["lead"], sizes["envelope"] - self.radius @@ -1789,7 +1868,7 @@ class BROKKR_KITBASH_OT_describe(PolishOperator): class BROKKR_KITBASH_OT_report(PolishOperator): """Report placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world frame, - the connection and the closure and whether each holds""" + the connection and the closure and whether each holds, and whether the part is frozen""" bl_idname = "brokkr_kitbash.report" bl_label = "Report Kit Parts" bl_options = {"REGISTER"} @@ -1804,7 +1883,8 @@ class BROKKR_KITBASH_OT_report(PolishOperator): classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report, BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach, - BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_ribs, + BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_freeze, BROKKR_KITBASH_OT_thaw, + BROKKR_KITBASH_OT_ribs, BROKKR_KITBASH_OT_shell, BROKKR_KITBASH_OT_hose) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 2fc918f..17a3d57 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -45,7 +45,7 @@ }, { "name": "brokkr_kitbash.set_params", - "doc": "Change params of a placed kit part and rebuild its mesh in place; modifiers and materials stay, and its connection and the parts attached to it are seated again. Refuses a change that breaks a connection, a mesh another object shares and a scaled part. Reports as place_part.", + "doc": "Change params of a placed kit part and rebuild its mesh in place; modifiers and materials stay, and its connection and the parts attached to it are seated again. Refuses a change that breaks a connection, a frozen part, a mesh another object shares and a scaled part. Reports as place_part.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -93,7 +93,7 @@ }, { "name": "brokkr_kitbash.report", - "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds). Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.", + "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds) and frozen. Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", @@ -551,6 +551,38 @@ } ] }, + { + "name": "brokkr_kitbash.freeze", + "doc": "Freeze a mesh object that has modifiers (a kit part, a shell or any mesh) when its cuts are settled: its mesh becomes its evaluated mesh, its live mesh is held by its kit_frozen property, and every modifier stays in the stack, turned off, with its collections and cutters. Blender re-evaluates a live collection Boolean after any removal, hide or mesh read anywhere in the scene; a frozen object costs nothing there. Sockets, connections and report rows stay. set_params, boolean, cut, cut_many, ribs and a shell or hose rebuild refuse a frozen object: thaw it first. Refuses a frozen object, one with no modifiers, one with a modifier already off (named) and one Blender does not evaluate. Reports object (or the part), frozen, faces, volume, nonManifoldEdges, modifiers and booleans.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + } + ] + }, + { + "name": "brokkr_kitbash.thaw", + "doc": "Thaw a frozen object: its live mesh comes back, every modifier is turned on, and the frozen mesh is removed. Evaluates nothing; Blender evaluates the object once afterwards. Refuses an object that is not frozen or whose held mesh is gone. Reports object, frozen false, modifiers and the live mesh's faces.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + } + ] + }, { "name": "brokkr_kitbash.ribs", "doc": "Derive the frame under an armor cage from the cage itself, so it fits the armor by construction: a rib along each plane's section of the cage's surface, set the standoff behind the plate's inner face (along the plate's normal, at any tilt of the plane and any curvature of the wall: its edge is cut from the inner face offset inward, then measured against the plate) and reaching depth inward, clipped inside a crease tighter than that; lightening holes through the ribs; posts that stand the plate off them; longerons through the ribs. The plate's two faces are read from the cage's one Solidify as it evaluates, whatever its thickness mode. A rib stops where the plate is open (a port cut through it), runs behind an opening shorter than bridge (a panel break) and under a recess: openings are read from the cage as it is cut, so cut first. Inward is the side the cage's normals face away from. Makes one mesh object, a child of the cage, baked at this call: after the cage or its cuts change, delete it and run ribs again (its kit_ribs property keeps the request). Every plane and longeron is checked before anything is written. Reports ribs, thickness, sections [{plane, chains, pieces, length, open}], posts, holes, longerons [{index, stations}], faces, volume and nonManifoldEdges.", diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 9a852d1..1f4ba39 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -479,7 +479,8 @@ "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", - "brokkr_kitbash.apply", + "brokkr_kitbash.freeze", + "brokkr_kitbash.thaw", "brokkr_kitbash.ribs", "brokkr_kitbash.shell", "brokkr_kitbash.hose" diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 4371f5f..d0b66c4 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -1,6 +1,6 @@ """Live proof, in a background Blender, of brokkr_kitbash assembly through run_intent: attach and its refusals, set_params seating a part and the parts attached to it again, a braced leg closed by close and what set_params, -attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (one Exact Boolean modifier per operation over a collection of cutters, self-intersection on, above the Bevel). Not part +attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (one Exact Boolean modifier per operation over a collection of cutters, self-intersection on, above the Bevel), and freeze and thaw: the frozen shape, the round trip, the refusals, and what a frozen part costs. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_assembly.py -- @@ -21,6 +21,7 @@ import math import os import re import sys +import time import traceback import tempfile import types @@ -85,6 +86,12 @@ KEPT = 2.1e-4 # intersection off: overlapping shells cancel); separation 6.5 each side. A box through the barrel alone no longer # tells the two apart: the barrel is one shell. CUT = 0.039 +# Seconds the scene's update takes after an orphan mesh is removed with three cut tanks frozen, over the same with them +# live (medians of three, interleaved; every other Boolean in the scene frozen first). Shipped 0.0022 (0.0023 s over 1.05 s); least +# claimed mutant 1.5 (F1, freeze leaves the modifiers on: the Booleans run again, on the frozen mesh); the +# geometric mean, separation 26 each side. A ratio of two times read in one process: what other work +# on the machine does to it is far under the separation. +FROZEN_COST = 0.057 # Metres an attached child is moved to read holds false. HELD is a rule, 1e-5; least claimed mutant 1e-2 (K12); # the geometric mean of the two, separation 32 each side. NUDGE = 3.2e-4 @@ -178,6 +185,10 @@ def measure(mesh): return row +def stack(obj): + return [m.name for m in obj.modifiers] + + 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()) @@ -598,6 +609,71 @@ try: and len(tank.data.polygons) == len(core.build(kit["parts"]["tank"], report["params"]).counts) != raw["faces"] and CUT < resized["volume"] < measure(tank.data)["volume"] - 0.005 and holds("Tee", "Tank", "b", "port_a", 180.0)[0], [receipt["message"], resized]) + # --- freeze and thaw ---------------------------------------------------------------------------------------------------------- + THAW = "thaw it first" + refused("freeze on a mesh with no modifiers", "brokkr_kitbash.freeze", {"object_name": "Plain"}, "'Plain' has no modifiers to freeze") + refused("thaw on a live part", "brokkr_kitbash.thaw", {"object_name": "Tank"}, "'Tank' is not frozen") + tank.modifiers["Kit Bevel"].show_render = False + refused("freeze on a part with a modifier already off names it", "brokkr_kitbash.freeze", {"object_name": "Tank"}, "'Tank' has Kit Bevel off in viewports or renders") + tank.modifiers["Kit Bevel"].show_render = True + slots = [s.material and s.material.name for s in tank.material_slots] + shown, shown_slots = evaluated(tank) + index = np.zeros(len(tank.data.polygons), dtype=np.int32) + tank.data.polygons.foreach_get("material_index", index) + mesh_name, live_faces, meshes, collections = tank.data.name, len(tank.data.polygons), len(bpy.data.meshes), len(bpy.data.collections) + sockets_before = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["sockets"] + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Tank") + after = np.zeros(len(tank.data.polygons), dtype=np.int32) + tank.data.polygons.foreach_get("material_index", after) + facts = frozen and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} + check("freeze makes the evaluated mesh the tank's mesh: the same faces, volume and non-manifold edges, and the tank still evaluates to them", + receipt["status"] == "accepted" and facts == shown == measure(tank.data) == evaluated(tank)[0] and tank.data.name == "Tank frozen" + and len(bpy.data.meshes) == meshes + 1, [receipt["message"], facts, shown]) + check("freeze holds the live mesh in kit_frozen and keeps the stack, off, with its collection and cutter", frozen and frozen["frozen"] is True + and tank["kit_frozen"].name == mesh_name and len(tank["kit_frozen"].polygons) == live_faces and stack(tank) == frozen["modifiers"] == ["Kit Difference", "Kit Bevel"] + and not any(m.show_viewport or m.show_render for m in tank.modifiers) and tank.modifiers["Kit Difference"].collection.objects[:] == [box] + and frozen["booleans"] == [{"cutter": "Box", "operation": "DIFFERENCE"}] and len(bpy.data.collections) == collections and "Box" in bpy.context.scene.objects, + [frozen, [(m.name, m.show_viewport, m.show_render) for m in tank.modifiers]]) + check("freeze keeps the material slots exactly, and faces of both materials", slots == shown_slots == ["Tank Paint", "Strap Steel"] + and [s.material and s.material.name for s in tank.material_slots] == slots and [m and m.name for m in tank.data.materials] == slots + and index.max() == 1 and sorted(set(after.tolist())) == [0, 1], [slots, [m and m.name for m in tank.data.materials], sorted(set(after.tolist()))]) + check("a frozen part keeps what it is", frozen and tank["kit_part"] == "tank" and json.loads(tank["kit_params"])["segments"] == 16 and frozen["part"] == "tank", dict(tank.items())) + RAY = {"origin": [0.0, 0.0, 3.0], "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]} + refused("set_params on a frozen part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, THAW) + refused("boolean on a frozen part", "brokkr_kitbash.boolean", {"object_name": "Tank", "cutter": "Plain"}, THAW) + refused("cut on a frozen part", "brokkr_kitbash.cut", {"object_name": "Tank", "cutter_name": "Late", "part": "box", "origin_x": 0.0, "origin_y": 0.0, "origin_z": 3.0, + "direction_x": 0.0, "direction_y": 0.0, "direction_z": -1.0, "up_y": 1.0, "up_z": 0.0}, THAW) + refused("cut_many on a frozen part", "brokkr_kitbash.cut_many", {"object_name": "Tank", "cuts": json.dumps([{"name": "Late", "part": "box", **RAY}])}, THAW) + refused("freeze on a frozen part", "brokkr_kitbash.freeze", {"object_name": "Tank"}, THAW) + receipt, report = send("brokkr_kitbash.report", object_name="Tank") + check("a frozen part still reports its sockets where its params put them, and what is attached to it still holds", report and report["parts"][0]["frozen"] is True + and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == frozen["faces"] and holds("Tee", "Tank", "b", "port_a", 180.0)[0] + and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], report) + receipt, report = send("brokkr_kitbash.attach", object_name="Radiator", socket="base", parent_name="Tank", parent_socket="saddle") + check("a new part attaches to a frozen one", receipt["status"] == "accepted" and held(report) + and reading("seated", seated(radiator, "base", tank, "saddle", 0.0)) < SEATED, receipt["message"]) + receipt, chilled = send("brokkr_kitbash.freeze", object_name="Tee") + receipt, report = send("brokkr_kitbash.roll", object_name="Tee", roll=90.0) + check("a frozen child rolls where it hangs on a frozen parent, and what hangs on it follows", receipt["status"] == "accepted" and chilled and chilled["frozen"] is True + and holds("Tee", "Tank", "b", "port_a", 90.0)[0] and reading("seated", seated(tee, "b", tank, "port_a", 90.0)) < SEATED + and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], [receipt["message"], connection("Tee")]) + send("brokkr_kitbash.roll", object_name="Tee", roll=180.0) + bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True) + check("the held live mesh survives a purge of orphans", bpy.data.meshes.get(mesh_name) is not None and tank["kit_frozen"] == bpy.data.meshes[mesh_name] + and len(tank["kit_frozen"].polygons) == live_faces, sorted(m.name for m in bpy.data.meshes)) + for name in ("Tee", "Tank"): + receipt, thawed = send("brokkr_kitbash.thaw", object_name=name) + check("thaw puts the live mesh back, turns every modifier on and removes the frozen mesh", receipt["status"] == "accepted" and tank.data.name == mesh_name and "kit_frozen" not in tank + and thawed == {"object": "Tank", "frozen": False, "modifiers": ["Kit Difference", "Kit Bevel"], "faces": live_faces} and stack(tank) == ["Kit Difference", "Kit Bevel"] + and all(m.show_viewport and m.show_render for m in tank.modifiers) and "Tank frozen" not in bpy.data.meshes and "kit_frozen" not in tee + and len(bpy.data.collections) == collections, [receipt["message"], thawed, sorted(m.name for m in bpy.data.meshes)]) + check("the thawed tank evaluates to what it did before freeze, and reports frozen false", evaluated(tank)[0] == shown + and send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["frozen"] is False, [evaluated(tank)[0], shown]) + lost = place("Lost", "plate", location=[0.0, -24.0, 0.0]) + send("brokkr_kitbash.freeze", object_name="Lost") + bpy.data.meshes.remove(lost["kit_frozen"]) + refused("thaw on a frozen part whose held mesh was removed", "brokkr_kitbash.thaw", {"object_name": "Lost"}, "the live mesh its kit_frozen held is gone") + # --- the second target: a plate with no material slot, cut twice ---------------------------------------------------------------------- plate = place("Plate", "plate", location=[0.0, -3.0, 0.0]) send("createObject", objectType="MESH", name="Slot", location=[0.1, -3.0, 0.0], size=0.1) @@ -612,9 +688,35 @@ try: and all(m.use_self and m.solver == "EXACT" for m in plate.modifiers if m.type == "BOOLEAN"), [[m.name for m in plate.modifiers], first and first["evaluated"], second and second["evaluated"]]) R["plate"] = {"raw": measure(plate.data), "slot": first and first["evaluated"], "slotAndHole": second and second["evaluated"]} + twin = plate.copy() # a linked duplicate: it shares the live mesh, and keeps it + twin.name = "Plate_twin" + bpy.context.scene.collection.objects.link(twin) + shown, shown_slots = evaluated(plate) + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Plate") + check("freeze on a part with no material slot leaves the frozen mesh with none (Blender's Boolean shows it with one empty slot); a linked duplicate keeps the live mesh", + receipt["status"] == "accepted" and shown_slots == [None] and len(plate.data.materials) == 0 and len(plate.material_slots) == 0 + and frozen["booleans"] == second["booleans"] and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown + and twin.data.name == "Plate" and plate["kit_frozen"] == twin.data and all(m.show_viewport for m in twin.modifiers), + [shown_slots, len(plate.data.materials), len(plate.material_slots), frozen]) + bpy.data.objects.remove(twin) + send("brokkr_kitbash.thaw", object_name="Plate") + send("assignMaterial", targetObjectName="Plate", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) + send("createObject", objectType="MESH", name="Boss", location=[0.0, -3.0, 0.1], size=0.06) + send("assignMaterial", targetObjectName="Boss", materialName="Boss Brass", color=[0.6, 0.5, 0.2]) + send("setObjectTransform", targetObjectName="Boss", location=[0.0, -3.0, 0.02]) + receipt, third = send("brokkr_kitbash.boolean", object_name="Plate", cutter="Boss", operation="UNION") + shown, shown_slots = evaluated(plate) + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Plate") + used = np.zeros(len(plate.data.polygons), dtype=np.int32) + plate.data.polygons.foreach_get("material_index", used) + check("a thawed part is cut and frozen again; a cutter that has a material brings it after the part's own slots, on the faces it made", + receipt["status"] == "accepted" and third["booleans"][-1] == {"cutter": "Boss", "operation": "UNION"} and third["frozen"] is False and frozen["frozen"] is True + and third["evaluated"]["volume"] > R["plate"]["slotAndHole"]["volume"] and shown_slots == ["Plate Paint", "Boss Brass"] + and [m and m.name for m in plate.data.materials] == ["Plate Paint", "Boss Brass"] and sorted(set(used.tolist())) == [0, 1] + and stack(plate) == ["Kit Difference", "Kit Union", "Kit Bevel"], [third and third["evaluated"], shown_slots, [m and m.name for m in plate.data.materials], sorted(set(used.tolist()))]) vent = place("Vent", "vent", "width=0.2; height=0.15") receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Plate", parent_socket="front") - check("a vent that fits attaches to the cut plate's front", receipt["status"] == "accepted" and held(report) + check("a vent that fits attaches to the frozen plate's front", receipt["status"] == "accepted" and held(report) and reading("seated", seated(vent, "back", plate, "front", 0.0)) < SEATED, receipt["message"]) refused("a loop of two", "brokkr_kitbash.attach", {"object_name": "Plate", "socket": "back", "parent_name": "Vent", "parent_socket": "back"}, "'Vent' is below 'Plate'") @@ -631,6 +733,82 @@ try: check("a tee with a box cut from it has no non-manifold edge: its branch hub is narrower than its run hub", receipt["status"] == "accepted" and cut and cut["evaluated"]["nonManifoldEdges"] == 0 and 0.004 < cut["evaluated"]["volume"] < 0.008, [receipt["message"], cut and cut["evaluated"]]) + # --- freeze and empty material slots ---------------------------------------------------------------------------------------------- + keeper = place("Keeper", "plate", location=[0.0, -9.0, 0.0]) + send("assignMaterial", targetObjectName="Keeper", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) + keeper.data.materials.append(None) # an empty last slot the part was given + send("createObject", objectType="MESH", name="Bare", location=[0.1, -9.0, 0.0], size=0.1) + send("brokkr_kitbash.boolean", object_name="Keeper", cutter="Bare") + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Keeper") + check("freeze keeps a part's own empty last slot when the cutter has no material", receipt["status"] == "accepted" and keeper.data.name == "Keeper frozen" + and [m and m.name for m in keeper.data.materials] == ["Plate Paint", None] and len(keeper.material_slots) == 2, + [receipt["message"], [m and m.name for m in keeper.data.materials]]) + gapped = place("Gapped", "plate", location=[0.0, -12.0, 0.0]) + send("assignMaterial", targetObjectName="Gapped", materialName="Plate Paint", color=[0.35, 0.35, 0.35]) + send("createObject", objectType="MESH", name="Gap", location=[0.1, -12.0, 0.0], size=0.1) + gap = bpy.data.objects["Gap"] + gap.data.materials.append(None) # the cutter's faces are in an empty first slot + gap.data.materials.append(bpy.data.materials["Boss Brass"]) + gap.data.polygons[0].material_index = gap.data.polygons[1].material_index = 1 # two of its faces are brass; the rest stay in the empty slot + send("brokkr_kitbash.boolean", object_name="Gapped", cutter="Gap") + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Gapped") + used = np.zeros(len(gapped.data.polygons), dtype=np.int32) + gapped.data.polygons.foreach_get("material_index", used) + check("freeze leaves no face outside the material slots when a cutter's first slot is empty", receipt["status"] == "accepted" and len(used) > 44 + and used.min() >= 0 and used.max() < len(gapped.data.materials) and not gapped.data.validate_material_indices() and not gapped.data.validate(verbose=False), + [receipt["message"], int(used.min()), int(used.max()), [m and m.name for m in gapped.data.materials]]) + names = [m and m.name for m in gapped.data.materials] + brass = [p.index for p in gapped.data.polygons if "Boss Brass" in names and p.material_index == names.index("Boss Brass")] + far = [p.index for p in gapped.data.polygons if (gapped.matrix_world @ p.center).x < -0.05] # the plate's half the cutter does not reach + check("and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", + names[0] == "Plate Paint" and 0 < len(brass) < len(used) and far and all(used[i] == 0 for i in far) + and all(abs((gapped.matrix_world @ gapped.data.polygons[i].center).x - 0.1) < 0.051 for i in brass), [names, len(brass), len(far), sorted(set(used.tolist()))]) + + # --- a frozen part is cheap ------------------------------------------------------------------------------------------------------- + # Blender re-evaluates every live collection Boolean in the scene after any datablock is removed (docs/kitbash.md). Every + # other cut object is frozen first, so the update timed here evaluates the three tanks' Booleans or none. + for obj in [o for o in bpy.context.scene.objects if o.type == "MESH" and any(m.type == "BOOLEAN" and m.show_viewport for m in o.modifiers)]: + send("brokkr_kitbash.freeze", object_name=obj.name) + tanks = [] + for n in range(3): + tanks.append(place(f"Cold{n}", "tank", location=[6.0, 3.0 * n, 0.0])) + send("createObject", objectType="MESH", name=f"ColdBox{n}", location=[6.3, 3.0 * n, 0.0], size=0.3) + send("brokkr_kitbash.boolean", object_name=f"Cold{n}", cutter=f"ColdBox{n}") + SEEN = [] + + def seen(scene, depsgraph): + SEEN.extend(u.id.original.name for u in depsgraph.updates if isinstance(u.id, bpy.types.Object) and u.is_updated_geometry + and u.id.original.type == "MESH" and any(m.type == "BOOLEAN" and m.show_viewport for m in u.id.original.modifiers)) + + def orphan_removed(): + """(seconds the scene's update takes after an orphan mesh is removed, the objects with a shown Boolean it re-evaluated)""" + mesh = bpy.data.meshes.new("Orphan") + bpy.context.view_layer.update() + SEEN.clear() + start = time.perf_counter() + bpy.data.meshes.remove(mesh) + bpy.context.view_layer.update() + return time.perf_counter() - start, sorted(set(SEEN)) + + bpy.app.handlers.depsgraph_update_post.append(seen) + costs = {"live": [], "frozen": []} + for _ in range(3): + bpy.context.view_layer.update() + costs["live"].append(orphan_removed()) + for obj in tanks: + send("brokkr_kitbash.freeze", object_name=obj.name) + bpy.context.view_layer.update() + costs["frozen"].append(orphan_removed()) + for obj in tanks: + send("brokkr_kitbash.thaw", object_name=obj.name) + bpy.app.handlers.depsgraph_update_post.remove(seen) + medians = {state: sorted(seconds for seconds, _ in rows)[1] for state, rows in costs.items()} + R["frozenCost"] = {"liveSeconds": round(medians["live"], 4), "frozenSeconds": round(medians["frozen"], 5), + "live": [[round(s, 4), names] for s, names in costs["live"]], "frozen": [[round(s, 5), names] for s, names in costs["frozen"]]} + check("removing an orphan mesh re-evaluates the three live cut tanks, and none of them frozen", all(names == ["Cold0", "Cold1", "Cold2"] for _, names in costs["live"]) + and all(names == [] for _, names in costs["frozen"]), R["frozenCost"]) + check("and the update with them frozen costs under the bound of what it costs with them live", + reading("frozenCost", medians["frozen"] / medians["live"]) < FROZEN_COST, R["frozenCost"]) except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index f7be6b4..db1ffde 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -7,7 +7,7 @@ "detail": null }, { - "name": "a part nobody attached reports connection null and baked false", + "name": "a part nobody attached reports connection null", "ok": true, "detail": null }, @@ -497,42 +497,97 @@ "detail": null }, { - "name": "refused, scene unchanged: apply on a mesh that is not a kit part", + "name": "refused, scene unchanged: freeze on a mesh with no modifiers", "ok": true, "detail": null }, { - "name": "apply makes the evaluated mesh the tank's mesh: the same faces and volume, no modifiers, one mesh datablock of the old name", + "name": "refused, scene unchanged: thaw on a live part", "ok": true, "detail": null }, { - "name": "apply keeps the material slots exactly, and faces of both materials", + "name": "refused, scene unchanged: freeze on a part with a modifier already off names it", "ok": true, "detail": null }, { - "name": "apply marks the part baked and keeps what it is", + "name": "freeze makes the evaluated mesh the tank's mesh: the same faces, volume and non-manifold edges, and the tank still evaluates to them", "ok": true, "detail": null }, { - "name": "refused, scene unchanged: set_params on a baked part", + "name": "freeze holds the live mesh in kit_frozen and keeps the stack, off, with its collection and cutter", "ok": true, "detail": null }, { - "name": "refused, scene unchanged: apply on a baked part with no modifiers left", + "name": "freeze keeps the material slots exactly, and faces of both materials", "ok": true, "detail": null }, { - "name": "a baked part still reports its sockets where its params put them, and what is attached to it still holds", + "name": "a frozen part keeps what it is", "ok": true, "detail": null }, { - "name": "a new part attaches to a baked one", + "name": "refused, scene unchanged: set_params on a frozen part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean on a frozen part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut on a frozen part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many on a frozen part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: freeze on a frozen part", + "ok": true, + "detail": null + }, + { + "name": "a frozen part still reports its sockets where its params put them, and what is attached to it still holds", + "ok": true, + "detail": null + }, + { + "name": "a new part attaches to a frozen one", + "ok": true, + "detail": null + }, + { + "name": "a frozen child rolls where it hangs on a frozen parent, and what hangs on it follows", + "ok": true, + "detail": null + }, + { + "name": "the held live mesh survives a purge of orphans", + "ok": true, + "detail": null + }, + { + "name": "thaw puts the live mesh back, turns every modifier on and removes the frozen mesh", + "ok": true, + "detail": null + }, + { + "name": "the thawed tank evaluates to what it did before freeze, and reports frozen false", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: thaw on a frozen part whose held mesh was removed", "ok": true, "detail": null }, @@ -542,22 +597,17 @@ "detail": null }, { - "name": "refused, scene unchanged: apply on a mesh a linked duplicate shares", + "name": "freeze on a part with no material slot leaves the frozen mesh with none (Blender's Boolean shows it with one empty slot); a linked duplicate keeps the live mesh", "ok": true, "detail": null }, { - "name": "apply on a part with no material slot leaves it with none (Blender's Boolean shows it with one empty slot)", + "name": "a thawed part is cut and frozen again; a cutter that has a material brings it after the part's own slots, on the faces it made", "ok": true, "detail": null }, { - "name": "a baked part is cut and baked again; a cutter that has a material brings it after the part's own slots, on the faces it made", - "ok": true, - "detail": null - }, - { - "name": "a vent that fits attaches to the baked plate's front", + "name": "a vent that fits attaches to the frozen plate's front", "ok": true, "detail": null }, @@ -577,12 +627,12 @@ "detail": null }, { - "name": "apply keeps a part's own empty last slot when the cutter has no material", + "name": "freeze keeps a part's own empty last slot when the cutter has no material", "ok": true, "detail": null }, { - "name": "apply leaves no face outside the material slots when a cutter's first slot is empty", + "name": "freeze leaves no face outside the material slots when a cutter's first slot is empty", "ok": true, "detail": null }, @@ -590,6 +640,16 @@ "name": "and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", "ok": true, "detail": null + }, + { + "name": "removing an orphan mesh re-evaluates the three live cut tanks, and none of them frozen", + "ok": true, + "detail": null + }, + { + "name": "and the update with them frozen costs under the bound of what it costs with them live", + "ok": true, + "detail": null } ], "hostErrors": [], @@ -598,6 +658,7 @@ "close nudged": 0.00032, "closed": 3.9e-07, "cut": 0.25, + "frozenCost": 0.0016, "kept": 6e-08, "nudged": 0.00032, "roll": 6.6e-06, @@ -637,5 +698,49 @@ "volume": 0.006031088, "nonManifoldEdges": 0 }, + "frozenCost": { + "liveSeconds": 1.0356, + "frozenSeconds": 0.00168, + "live": [ + [ + 1.0412, + [ + "Cold0", + "Cold1", + "Cold2" + ] + ], + [ + 1.0356, + [ + "Cold0", + "Cold1", + "Cold2" + ] + ], + [ + 0.9348, + [ + "Cold0", + "Cold1", + "Cold2" + ] + ] + ], + "frozen": [ + [ + 0.00168, + [] + ], + [ + 0.00264, + [] + ], + [ + 0.00165, + [] + ] + ] + }, "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/live/kitbash_shell.py b/surfaces/blender/tests/live/kitbash_shell.py index 02f2c66..c5eed48 100644 --- a/surfaces/blender/tests/live/kitbash_shell.py +++ b/surfaces/blender/tests/live/kitbash_shell.py @@ -398,6 +398,57 @@ try: 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"]]) + THAW = "thaw it first" + shown, cage_shown, collections = evaluated(plate)[0], evaluated(cage)[0], len(bpy.data.collections) + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Plate") + check("freeze keeps the three modifiers, off, the three collections they read and every cutter in the scene", receipt["status"] == "accepted" + and frozen["booleans"] == report["booleans"] and len(bpy.data.collections) == collections and frozen["modifiers"] == stack(plate) == ["Kit Difference", "Kit Union", "Kit Intersect", "Kit Bevel"] + and not any(m.show_viewport or m.show_render for m in plate.modifiers) and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown == evaluated(plate)[0] + and all(name in bpy.context.scene.objects for name in ("Hole", "Boss", "Keep")), [receipt["message"], frozen, shown]) + cage_stack, cage_mesh = stack(cage), cage.data.name + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Cage") + check("freeze takes the cage, which is not a kit part: its evaluated wall, its stack off, its cutters still its children", receipt["status"] == "accepted" and frozen["object"] == "Cage" + and "kit" not in frozen and frozen["frozen"] is True and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == cage_shown == evaluated(cage)[0] + and frozen["modifiers"] == stack(cage) == cage_stack and not any(m.show_viewport or m.show_render for m in cage.modifiers) and cage.data.name == "Cage frozen" + and bpy.data.objects["Bay"].parent == cage and len(bpy.data.collections) == collections, [receipt["message"], frozen and frozen["modifiers"], cage_shown]) + refused("ribs from a frozen cage", "brokkr_kitbash.ribs", {"object_name": "Cage", "ribs_name": "ColdRibs", "planes": json.dumps([{"origin": [0.0, 0.0, 0.5], "normal": [0.0, 0.0, 1.0]}])}, THAW) + refused("cut on a frozen cage", "brokkr_kitbash.cut", {"object_name": "Cage", "cutter_name": "Late", "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}, THAW) + refused("cut_many on a frozen cage", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{"name": "Late", "part": "box", "origin": [3.0, 0.0, 0.1], "direction": [-1.0, 0.0, 0.0]}])}, THAW) + refused("boolean on a frozen cage", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Hole"}, THAW) + for name in ("Plate", "Cage"): + receipt, thawed = send("brokkr_kitbash.thaw", object_name=name) + check("thaw gives both back: the live meshes, every modifier on, the frozen meshes gone, and the same evaluated shapes", receipt["status"] == "accepted" + and thawed == {"object": "Cage", "frozen": False, "modifiers": cage_stack, "faces": len(cage.data.polygons)} and cage.data.name == cage_mesh + and all(m.show_viewport and m.show_render for o in (plate, cage) for m in o.modifiers) and not any(n in bpy.data.meshes for n in ("Cage frozen", "Plate frozen")) + and "kit_frozen" not in cage and "kit_frozen" not in plate and evaluated(plate)[0] == shown and evaluated(cage)[0] == cage_shown, + [receipt["message"], thawed, sorted(m.name for m in bpy.data.meshes)]) + twin = place("Twin", "plate", location=[0.0, -15.0, 0.0]) + send("createObject", objectType="MESH", name="TwinHole", location=[0.0, -15.0, 0.0], size=0.05) + send("brokkr_kitbash.boolean", object_name="Twin", cutter="TwinHole") + copied = twin.copy() # a copied part: its own mesh, and a Kit Difference modifier that reads the same collection + copied.data = twin.data.copy() + bpy.context.scene.collection.objects.link(copied) + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Twin") + kept = bpy.data.collections.get("Twin difference") + check("M6: a frozen part and its copy still read the one collection, and the copy stays live", receipt["status"] == "accepted" and kept is not None + and twin.modifiers["Kit Difference"].collection == kept == copied.modifiers["Kit Difference"].collection and [o.name for o in kept.objects] == ["TwinHole"] + and "kit_frozen" in twin and all(m.show_viewport for m in copied.modifiers), [receipt["message"], [c.name for c in bpy.data.collections]]) + send("brokkr_kitbash.thaw", object_name="Twin") + RINGS = [[[x, y, 0.1 - x * x] for x in (-0.3, -0.1, 0.1, 0.3)] for y in (0.0, 0.2, 0.4)] + lid = {"object_name": "Lid", "sheet": json.dumps({"rings": RINGS}), "thickness": 0.02, "levels": 2} + send("brokkr_kitbash.shell", **lid) + send("setObjectTransform", targetObjectName="Lid", location=[0.0, -30.0, 0.0]) + wall = evaluated(bpy.data.objects["Lid"])[0] + receipt, frozen = send("brokkr_kitbash.freeze", object_name="Lid") + check("freeze takes a shell: the wall its Kit Subsurf and Kit Solidify make", receipt["status"] == "accepted" and frozen["modifiers"] == ["Kit Subsurf", "Kit Solidify"] + and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == wall and wall["faces"] > 2 * 6 * 16, [receipt["message"], frozen, wall]) + refused("a rebuild of a frozen shell", "brokkr_kitbash.shell", lid, THAW) + refused("a rebuild of a frozen shell that counts folds", "brokkr_kitbash.shell", {**lid, "count_folds": True}, THAW) + send("brokkr_kitbash.thaw", object_name="Lid") + receipt, rebuilt = send("brokkr_kitbash.shell", **lid) + check("and thawed, the shell rebuilds", receipt["status"] == "accepted" and rebuilt["rebuilt"] is True and evaluated(bpy.data.objects["Lid"])[0] == wall, [receipt["message"], rebuilt]) + # --- cut-refusals ----------------------------------------------------------------------------------------------------------- section('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} @@ -454,6 +505,8 @@ try: refused(f"cut_many on a target {why}", "brokkr_kitbash.cut_many", {"object_name": name, "cuts": json.dumps([{"name": "Unseen", "part": "box", "origin": [0.1, 0.1, 3.0], "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]}])}, NOT) refused(f"boolean on a target {why}", "brokkr_kitbash.boolean", {"object_name": name, "cutter": "Sheet"}, NOT) + refused("freeze on a part disabled in viewports", "brokkr_kitbash.freeze", {"object_name": "Plate"}, "Blender does not evaluate 'Plate' in this view layer") + refused("freeze on a part in a collection outside the view layer", "brokkr_kitbash.freeze", {"object_name": "Loose"}, "Blender does not evaluate 'Loose' in this view layer") veil.hide_viewport = plate.hide_viewport = False bpy.context.view_layer.update() diff --git a/surfaces/blender/tests/live/kitbash_shell.result.json b/surfaces/blender/tests/live/kitbash_shell.result.json index 3b6c679..603575a 100644 --- a/surfaces/blender/tests/live/kitbash_shell.result.json +++ b/surfaces/blender/tests/live/kitbash_shell.result.json @@ -222,17 +222,62 @@ "detail": null }, { - "name": "apply removes the three collections its modifiers held and leaves every cutter in the scene", + "name": "freeze keeps the three modifiers, off, the three collections they read and every cutter in the scene", "ok": true, "detail": null }, { - "name": "refused, scene unchanged: apply on the cage, which is not a kit part", + "name": "freeze takes the cage, which is not a kit part: its evaluated wall, its stack off, its cutters still its children", "ok": true, "detail": null }, { - "name": "M6: apply keeps a collection a copied part's modifier still reads", + "name": "refused, scene unchanged: ribs from a frozen cage", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut on a frozen cage", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: cut_many on a frozen cage", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: boolean on a frozen cage", + "ok": true, + "detail": null + }, + { + "name": "thaw gives both back: the live meshes, every modifier on, the frozen meshes gone, and the same evaluated shapes", + "ok": true, + "detail": null + }, + { + "name": "M6: a frozen part and its copy still read the one collection, and the copy stays live", + "ok": true, + "detail": null + }, + { + "name": "freeze takes a shell: the wall its Kit Subsurf and Kit Solidify make", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a rebuild of a frozen shell", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a rebuild of a frozen shell that counts folds", + "ok": true, + "detail": null + }, + { + "name": "and thawed, the shell rebuilds", "ok": true, "detail": null }, @@ -327,12 +372,12 @@ "detail": null }, { - "name": "refused, scene unchanged: apply on a part disabled in viewports", + "name": "refused, scene unchanged: freeze on a part disabled in viewports", "ok": true, "detail": null }, { - "name": "refused, scene unchanged: apply on a part in a collection outside the view layer", + "name": "refused, scene unchanged: freeze on a part in a collection outside the view layer", "ok": true, "detail": null }, diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 0ade179..c253c90 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1812,7 +1812,7 @@ class SheetTests(unittest.TestCase): ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", - "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.ribs", + "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.freeze", "brokkr_kitbash.thaw", "brokkr_kitbash.ribs", "brokkr_kitbash.shell", "brokkr_kitbash.hose"] @@ -1859,6 +1859,7 @@ class HostFileTests(unittest.TestCase): self.assertEqual(at.validate(boolean, host)["operation"], "DIFFERENCE") for bad in ({**attach, "roll": 360.5}, {**attach, "socket": "a b"}, {**attach, "parent_socket": ""}, {**attach, "matrix": [1, 0, 0]}, {**boolean, "operation": "SLICE"}, {**boolean, "solver": "EXACT"}, {**boolean, "cutter": ""}, + {**envelope, "action": "brokkr_kitbash.freeze"}, {**envelope, "action": "brokkr_kitbash.thaw", "object_name": ""}, {**envelope, "action": "brokkr_kitbash.detach", "object_name": "x" * 64}, {**close, "socket": "end b"}, {**close, "other_socket": "x" * 33}, {**close, "other_name": ""}, {**close, "roll": 10}, {k: v for k, v in close.items() if k != "other_socket"}): @@ -1973,10 +1974,20 @@ class OwnershipTests(unittest.TestCase): self.assertLess(place.index("modifier.show_viewport = False"), place.index("evaluable(")) self.assertLess(place.index("evaluable("), place.index("modifier.show_viewport = True")) # unevaluable-target: every action that evaluates refuses an object Blender does not evaluate before its first write - for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), + for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["freeze"], "bpy.data.meshes.new_from_object("), (bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()")): self.assertLess(body.index("evaluable("), body.index(first_write)) - self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "ribs", "shell", "hose"]) + self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "freeze", "ribs", "shell", "hose"]) + # frozen: thaw evaluates nothing, and every action that writes a mesh or a modifier stack refuses a frozen object before its first write + for call in ("evaluable(", "evaluated_of(", "to_mesh(", "depsgraph", "view_layer.update"): + self.assertNotIn(call, bodies["thaw"]) + for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["freeze"], "bpy.data.meshes.new_from_object("), + (bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()"), (bodies["set_params"], "write_mesh("), + (bodies["hose"], "write_mesh(")): + self.assertLess(body.index("live("), body.index(first_write)) + self.assertEqual((source.count("obj[FROZEN] ="), source.count("del obj[FROZEN]"), source.count("live(")), (1, 1, 8)) # its def and the seven callers above + self.assertIn("obj[FROZEN] =", bodies["freeze"]) + self.assertIn("del obj[FROZEN]", bodies["thaw"]) ribs = bodies["ribs"] # every refusal before the ribs object is written, and the cage's modifiers shown again whatever happened self.assertLess(ribs.rindex("raise Refused("), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)")) self.assertLess(ribs.index("finally:"), ribs.index("modifier.show_viewport = True")) @@ -2100,7 +2111,7 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(assigned, [" obj[CLOSE], obj[CLOSE_TO], obj[CLOSE_TO_SOCKET] = self.socket, other, self.other_socket"]) self.assertIn(assigned[0], bodies["close"]) deleted = re.findall(r"[^\n]*\(SOCKET, PARENT_SOCKET, ROLL, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET\)[^\n]*\n[^\n]*\n\s*del obj\[key\]", source) - self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 1, True)) + self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and thaw's kit_frozen self.assertEqual(source.count("CLOSE_TO]"), 1) # the one subscript write above; every read goes through .get placing = r"matrix_basis|matrix_world\s*=(?!=)|matrix_parent_inverse|\.parent\s*=(?!=)|\bseat\(|\.location|\.rotation" self.assertIsNone(re.search(placing, bodies["close"])) From a69bb89374bf7f384320a76c3efc0a72a4dbc7a1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:48:35 +0100 Subject: [PATCH 146/223] docs/kitbash.md: freezing, what triggers a live collection Boolean, and what freeze buys on KESTREL (cut kit-freeze) Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 63 ++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 7 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 8e789ba..7cc37a6 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1,7 +1,7 @@ # Kitbash parts: machinery from kits `surfaces/blender/brokkr_kitbash` is a Blender add-on that places parametric machine parts from a **kit**, mates -them **socket** to socket, cuts them with booleans and bakes them, and makes the faceted armor **shell** they sit under. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks, +them **socket** to socket, cuts them with booleans and freezes them, and makes the faceted armor **shell** they sit under. It is the machinery vocabulary of a ship's fixed chassis: the frame, tanks, actuators, housings and plumbing an agent assembles offline under a hand-fit armor cage, baked once. It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish` and `brokkr_rig`: it imports the polish package's operator base, `Refused` and `mesh_object`, and nothing from `brokkr_bridge`. @@ -31,6 +31,8 @@ Who owns what: and `kit_close_to_socket` properties. Only `close` writes them and only `detach` clears them. A closure places nothing: whether it holds is derived at each report. - A boolean belongs to its Boolean modifier on the part that is cut. +- Whether a cut object is live or frozen belongs to its `kit_frozen` property, which holds the live mesh while + the object carries its evaluated one. Only `freeze` sets it, and `thaw`, which deletes it, is its one undo. ## A part, end to end @@ -317,12 +319,56 @@ took 1.89 s through the collection modifier, 12.6 s with a Boolean modifier for 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. `boolean` +evaluated, and Blender evaluates it after every action that changes it or a cutter, and after much that changes +neither ("Freezing", below): `freeze` an object when its cuts are settled. `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. +### Freezing + +A live Boolean over a collection is paid for far more often than its target changes. In Blender 5.3 every such +Boolean in the scene is evaluated again, whatever it cuts, after any datablock is removed (an orphan mesh +included), after any object's `hide_viewport` changes, and after any evaluated mesh is copied out +(`new_from_object`). Adding objects, collections or modifiers does not do it. Nearly every action here does one of +the three (`cut_many` hides its target's Booleans to cast, `ribs` makes and removes working objects), so each +finished cut object is paid for again at each later action. Hiding the finished object does not help while its +cutters show, and the hide is itself one more trigger. On a replica of six cut plates (a subdivided, solidified +sphere under one Exact Boolean of four cutters each), each trigger on an unrelated datablock cost 19 to 23 s; with +the plates frozen, 0.004 to 0.014 s (three interleaved repetitions, Blender 5.3 on Starfire). + +**`freeze`** takes any mesh object that has modifiers, a kit part, a shell or a plain mesh. Its mesh becomes its +evaluated mesh (named ` frozen`), its live mesh is held by an ID-pointer property, `kit_frozen`, so it +survives a purge of orphans, and every modifier stays in the stack with its collections, turned off in viewports +and renders. Nothing is removed: the cutter objects stay, a cutter placed by `cut` keeps its floor socket and what +is attached to it, and `booleans` still lists what cuts the object. The frozen mesh's material slots are the +object'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 first slot. A frozen kit part keeps `kit_kit`, `kit_part`, `kit_params` and its +connections: its sockets are still derived from the params, so `attach`, `detach`, `roll`, `aim`, `reach` and +`close` work on it and on what hangs from it. `freeze` reports the part (or `object`), `frozen`, `faces`, +`volume`, `nonManifoldEdges`, `modifiers` and `booleans`. + +**`thaw`** puts the live mesh back, deletes `kit_frozen`, turns every modifier on and removes the frozen mesh. It +evaluates nothing itself; Blender evaluates the object once afterwards, and the thawed object evaluates to the +faces and volume it had. + +A frozen object's mesh is not its design, so every action that would write its live mesh or its stack refuses it +with "thaw it first": `set_params`, `boolean`, `cut`, `cut_many`, `ribs` from it, a `shell` or `hose` rebuild of +it, and `freeze`. Derive ribs before freezing a cage. `freeze` also refuses an object with no modifiers, one with a +modifier already off in viewports or renders (it names them: `thaw` turns every modifier on, and would not give +that stack back), and one Blender does not evaluate. `thaw` refuses an object that is not frozen, and one whose +held mesh was removed. What nothing detects: a modifier of a frozen object turned on by hand, and a material +assigned to a frozen object, which lands on the frozen mesh and goes at `thaw`. `exportGltf` with `applyModifiers` +exports a frozen object's frozen mesh, since its modifiers are off. + +What it buys on an assembly: KESTREL, an experiment mech of 22 cut shells and blocks, evaluated 1035 Booleans +where its cuts need 139 when each finished component was only hidden, and 139 when each was frozen as it was +finished; the whole build took 4.5 times as long hidden as frozen (medians of three interleaved pairs, 3.4 to 5.7 +within a pair, Blender 5.3 on Starfire under other load; an earlier series on a quieter machine read 251.7 s +against 51.2 s). In `tests/live/kitbash_assembly.py`, removing an orphan mesh beside three cut tanks costs 1.05 s +with them live and 0.0023 s with them frozen. + ## Making a shell `shell` makes an armor plate the way one is modelled by hand: fit a sparse subdivision cage, crease the edges that @@ -419,7 +465,7 @@ medians of three interleaved calls in the live suite (Blender 5.3 on Starfire). are twisted, and the Boolean, which cuts quads into triangles, can read the wall as passing through itself and leave edges with four faces. On the Seraph's cap that began at 0.91 of the thickness at which the first face folds (0.0301 against 0.033), on the left cap and not on its mirror, the right; on its breast plate at 0.91 as -well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, or a count on the evaluated +well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, `freeze`, or a count on the evaluated mesh), and keep `thickness` clear of the first folding one with a thinner wall, fewer `levels` or wider facets at the corner. @@ -493,7 +539,7 @@ attaching a part to a floor) costs an evaluation again while the target is visib more cutters than fit (about 150 of long names), the rows left off the end are counted in `booleansOmitted`. The scene keeps every cutter; the target's `Kit` modifier collections list them. -`cut`, `cut_many` and `boolean` evaluate their object, and refuse one Blender does not evaluate in the +`cut`, `cut_many`, `boolean` and `freeze` evaluate their object, and refuse one Blender does not evaluate in the view layer: an object disabled in viewports that nothing evaluated depends on, or one whose collections no view layer shows. A disabled object that an evaluated object needs (a parent of one, a cutter of one) is evaluated all the same, and is cut. @@ -920,8 +966,8 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se | --- | --- | --- | | `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | | `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. 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` and `closure`. Changes nothing and evaluates no modifier. | +| `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 frozen 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 `frozen`. 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; 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.roll` | `object_name`, `roll` (degrees, -360 to 360) | Turns an attached part to that roll where it hangs. Refuses a part that is not attached. Reports the part and `closures` as `set_params` does. | @@ -931,6 +977,8 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se | `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; `booleansOmitted` counts rows a receipt had no room for) 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), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | +| `brokkr_kitbash.freeze` | `object_name` (any mesh with modifiers) | Makes the evaluated mesh the object's mesh, holds the live mesh in `kit_frozen` and turns every modifier off, keeping the stack, its collections and the cutters. Refuses a frozen object, one with no modifiers, one with a modifier already off and one Blender does not evaluate. Reports the part (or `object`), `frozen`, `faces`, `volume`, `nonManifoldEdges`, `modifiers` and `booleans`. | +| `brokkr_kitbash.thaw` | `object_name` | Puts the live mesh back, turns every modifier on and removes the frozen mesh; evaluates nothing. Refuses an object that is not frozen or whose held mesh is gone. Reports `object`, `frozen`, `modifiers` and the live mesh's `faces`. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | | `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | | `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff, range}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `seed`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. | @@ -967,6 +1015,7 @@ assembly by its root: an attached part is placed by its connection. {"action": "createObject", "objectType": "MESH", "name": "Cutter", "location": [0.3, 0.6, 0], "size": 0.2}, {"action": "brokkr_kitbash.boolean", "object_name": "Tank", "cutter": "Cutter"}, {"action": "setObjectVisibility", "targetObjectName": "Cutter", "visible": false}, + {"action": "brokkr_kitbash.freeze", "object_name": "Tank"}, {"action": "brokkr_kitbash.report", "object_name": "Nozzle"}, {"action": "exportGltf", "filepath": "engine.glb", "selection": ["Tank", "Tee", "Nozzle"]} ]} @@ -1057,6 +1106,6 @@ frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may `PoseTests` the closed-form rolls. The operators are exercised in a real Blender by `tests/live/kitbash.py` (placing and re-parameterising, and the frame kit: its nine parts placed, the truss re-parameterised, a beam seated on a bracket), `tests/live/kitbash_assembly.py` (attach, detach, -`set_params` on assemblies, a braced leg closed by `close` and boolean), `tests/live/kitbash_shell.py` +`set_params` on assemblies, a braced leg closed by `close`, boolean, and freeze and thaw with what a frozen part costs), `tests/live/kitbash_shell.py` (`cut` and `cut_many` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no collection) and `tests/live/kitbash_pose.py` (roll, aim and reach). From 6743e5680b1e79073f2680c88720320b85d8652d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 21:58:03 +0100 Subject: [PATCH 147/223] brokkr_kitbash freeze: kit_* refused by the bridge's property setter, the held live mesh kept by a fake user, a dirty frozen part reported and refused at export (cut kit-freeze, fix batch h2) Answers verdict aetheria-release:verdict:cut-kit-freeze.s1. - setObjectCustomProperty refuses any name starting with kit_: those properties are brokkr_kitbash's state, so kit_frozen keeps freeze and thaw as its only writers. - freeze gives the held live mesh a fake user (marked kit_kept, taken back by the last thaw), so a purge cannot delete it when kit_frozen is overwritten by hand; thaw's refusal then names the kept meshes no frozen object holds. - part_report: faces is the live mesh's count, frozen or not; a frozen part adds evaluated {faces}; a frozen part with a modifier shown again reports dirty (the modifiers) and frozen false. freeze reports faces (live) and evaluated {faces, volume, nonManifoldEdges}. - exportGltf with applyModifiers refuses an export that includes a frozen object with a modifier shown. - Live pins: kitbash_hose freezes a hose and its rebuild is refused; kitbash_assembly pins the setter refusal, the purge with an overwritten kit_frozen, the dirty report and the export refusal. - kitbash_assembly and kitbash_faceted print their wall times and keep them out of the result files. - docs/kitbash.md: the KESTREL wall-time ratio as a range (about 2.7 to 5.7), the Boolean evaluation counts (1035 against 139) as the stable measure. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_bridge/actions.json | 2 +- .../blender/brokkr_bridge/blender_target.py | 12 ++ surfaces/blender/brokkr_kitbash/__init__.py | 38 +++++-- .../brokkr_kitbash/brokkr_actions.json | 4 +- surfaces/blender/docs/kitbash.md | 39 ++++--- .../blender/tests/live/kitbash_assembly.py | 46 ++++++-- .../tests/live/kitbash_assembly.result.json | 105 ++++++++++++------ .../blender/tests/live/kitbash_faceted.py | 4 +- .../tests/live/kitbash_faceted.result.json | 8 -- surfaces/blender/tests/live/kitbash_hose.py | 8 ++ .../tests/live/kitbash_hose.result.json | 15 +++ surfaces/blender/tests/live/kitbash_shell.py | 6 +- surfaces/blender/tests/test_node_actions.py | 10 ++ surfaces/blender/tests/test_scene_actions.py | 16 +++ 14 files changed, 235 insertions(+), 78 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/actions.json b/surfaces/blender/brokkr_bridge/actions.json index a605e01..3f6a8b9 100644 --- a/surfaces/blender/brokkr_bridge/actions.json +++ b/surfaces/blender/brokkr_bridge/actions.json @@ -33,7 +33,7 @@ {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, {"name": "parentObjectName", "type": "string", "doc": "empty or absent clears the parent"} ]}, - {"name": "setObjectCustomProperty", "doc": "Set one custom property on an object.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "setObjectCustomProperty", "doc": "Set one custom property on an object. Refuses a name starting with kit_: those are brokkr_kitbash's own state, written by its actions.", "changesScene": true, "editModeSafe": false, "fields": [ {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, {"name": "propertyName", "type": "string", "default": "brokkrValue"}, {"name": "value", "type": "any", "required": true, "doc": "any JSON value Blender accepts as a property"} diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index db3a939..a24f09b 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -46,6 +46,8 @@ DEFAULT_DEBUG_MIRROR_ROOT = "//.brokkr/blender-editor-debug" HOST_SNAPSHOT_SCHEMA = "brokkr.blender.host_snapshot.v0" HOST_ACTIONS_FILE = "brokkr_actions.json" HOST_RESULT_LIMIT = 16000 # characters of a host operator's result copied into a receipt +KIT_RESERVED = "kit_" # brokkr_kitbash owns every custom property so named: setObjectCustomProperty refuses them +KIT_FROZEN = "kit_frozen" # brokkr_kitbash's frozen state (its FROZEN): read here only, to refuse an export that would apply a stack twice COMMAND_INTENT_SCHEMA = "brokkr.blender.command_intent.v0" COMMAND_RECEIPT_SCHEMA = "brokkr.blender.command_receipt.v0" SYNC_SESSION_SCHEMA = "brokkr.sync.session.v0" @@ -944,6 +946,9 @@ class BrokkrBlenderTarget: property_name = command["propertyName"] if property_name.startswith("customProperties."): property_name = property_name[len("customProperties."):] + if property_name.startswith(KIT_RESERVED): + raise sa.ActionRefused(f"{property_name!r} is brokkr_kitbash's own state ({KIT_RESERVED}*): its actions write it, and a value set " + "here would leave the object and the property disagreeing. Use the brokkr_kitbash action; nothing changed.") modifier_name = na.drives_modifier_input(obj, property_name) if modifier_name: return self._receipt(command, "failed", f"{property_name!r} is an input of Geometry Nodes modifier {modifier_name!r}; " @@ -1027,6 +1032,13 @@ class BrokkrBlenderTarget: off_layer = [o.name for o in chosen if o.name not in context.view_layer.objects] if off_layer: raise sa.ActionRefused(f"Selection object is not in the active view layer: {off_layer[0]}") + if command["applyModifiers"]: + # A frozen object's mesh is already its stack's result: a modifier shown on it again would be applied twice. + dirty = sorted(o.name for o in (chosen or context.view_layer.objects.values()) + if o.get(KIT_FROZEN) is not None and any(m.show_viewport for m in o.modifiers)) + if dirty: + raise sa.ActionRefused(f"{', '.join(dirty)}: frozen (brokkr_kitbash.freeze) with a modifier shown again, so the export would apply " + "the stack on top of its own result. Thaw it (brokkr_kitbash.thaw), or hide its modifiers; nothing written.") # The exporter writes into a fresh staging folder beside the target, never onto the output # directory: it may also write a .bin and texture files whose names Brokkr does not choose. Only # after it finishes does every file move into place, each refused if its name is taken, so no diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 3ff8135..26e50e6 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -89,6 +89,7 @@ from . import core, route KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" SOCKET, PARENT_SOCKET, ROLL = "kit_socket", "kit_parent_socket", "kit_roll" FROZEN = "kit_frozen" # on a frozen object: an ID pointer to its live mesh; its presence is the frozen state, freeze sets it and thaw deletes it +KEPT = "kit_kept" # on a live mesh a frozen object holds: freeze gave it the fake user that keeps it through a purge, and the last thaw takes it back 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" @@ -351,12 +352,26 @@ def scene_closures(context, report: dict, ends=()) -> list: def part_report(obj, part, built) -> dict: - """A part as the scene has it. Reads stored properties and matrices only: no modifier is evaluated.""" - return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, - "faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), - "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world)), - "connection": connection_report(obj, part, built), "closure": closure_report(obj, part, built), - "frozen": FROZEN in obj} + """A part as the scene has it. Reads stored properties and matrices only: no modifier is evaluated. `faces` is the + live mesh's count, frozen or not; a frozen part adds `evaluated`, the count of the frozen mesh it carries. A frozen + part with a modifier shown again (by hand: no action does it) is `dirty`, the modifiers named, and not `frozen`: + Blender applies them on top of the frozen mesh, so what it shows and exports is not what was frozen.""" + held = obj.get(FROZEN) + report = {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, + "faces": len((held if isinstance(held, bpy.types.Mesh) else obj.data).polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), + "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world)), + "connection": connection_report(obj, part, built), "closure": closure_report(obj, part, built), + "frozen": FROZEN in obj and not shown(obj)} + if FROZEN in obj: + report["evaluated"] = {"faces": len(obj.data.polygons)} + if shown(obj): + report["dirty"] = shown(obj) + return report + + +def shown(obj) -> list: + """The modifiers Blender evaluates for the object, in a viewport or a render, by name.""" + return [modifier.name for modifier in obj.modifiers if modifier.show_viewport or modifier.show_render] def live(obj, doing: str) -> None: @@ -917,11 +932,13 @@ class BROKKR_KITBASH_OT_freeze(PolishOperator): if (index < 0).any(): # faces from a cutter's empty slot: slot 0, as faces from a cutter with no material frozen.polygons.foreach_set("material_index", np.maximum(index, 0)) frozen.name = f"{obj.name} frozen" + if not obj.data.use_fake_user: # the pointer below is a user too, but a property can be overwritten: the mesh outlives that + obj.data.use_fake_user = obj.data[KEPT] = True obj[FROZEN] = obj.data obj.data = frozen for modifier in obj.modifiers: modifier.show_viewport = modifier.show_render = False - report.update(frozen=True, **measured(frozen), modifiers=[modifier.name for modifier in obj.modifiers]) + report.update(frozen=True, faces=len(obj[FROZEN].polygons), evaluated=measured(frozen), modifiers=[modifier.name for modifier in obj.modifiers]) report["booleans"] = fitted(report, "booleans", booleans(obj)) return report @@ -940,9 +957,14 @@ class BROKKR_KITBASH_OT_thaw(PolishOperator): raise Refused(f"{obj.name!r} is not frozen; nothing changed.") held, frozen = obj[FROZEN], obj.data if not isinstance(held, bpy.types.Mesh): - raise Refused(f"{obj.name!r} is frozen and the live mesh its {FROZEN} held is gone: there is nothing to thaw to; nothing changed.") + kept = sorted(mesh.name for mesh in bpy.data.meshes if KEPT in mesh and not any(other.get(FROZEN) == mesh for other in bpy.data.objects)) + raise Refused(f"{obj.name!r} is frozen and the live mesh its {FROZEN} held is gone: there is nothing to thaw to" + + (f". Live meshes freeze kept that no frozen object holds: {', '.join(kept)}" if kept else "") + "; nothing changed.") obj.data = held del obj[FROZEN] + if KEPT in held and not any(other.get(FROZEN) == held for other in bpy.data.objects): + del held[KEPT] + held.use_fake_user = False for modifier in obj.modifiers: modifier.show_viewport = modifier.show_render = True if frozen.users == 0: diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 17a3d57..4ea390e 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -93,7 +93,7 @@ }, { "name": "brokkr_kitbash.report", - "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds) and frozen. Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.", + "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds) and frozen. faces counts the live mesh; a frozen part adds evaluated {faces}, and dirty (the modifiers shown again by hand, with frozen false). Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", @@ -553,7 +553,7 @@ }, { "name": "brokkr_kitbash.freeze", - "doc": "Freeze a mesh object that has modifiers (a kit part, a shell or any mesh) when its cuts are settled: its mesh becomes its evaluated mesh, its live mesh is held by its kit_frozen property, and every modifier stays in the stack, turned off, with its collections and cutters. Blender re-evaluates a live collection Boolean after any removal, hide or mesh read anywhere in the scene; a frozen object costs nothing there. Sockets, connections and report rows stay. set_params, boolean, cut, cut_many, ribs and a shell or hose rebuild refuse a frozen object: thaw it first. Refuses a frozen object, one with no modifiers, one with a modifier already off (named) and one Blender does not evaluate. Reports object (or the part), frozen, faces, volume, nonManifoldEdges, modifiers and booleans.", + "doc": "Freeze a mesh object that has modifiers (a kit part, a shell or any mesh) when its cuts are settled: its mesh becomes its evaluated mesh, its live mesh is held by its kit_frozen property, and every modifier stays in the stack, turned off, with its collections and cutters. Blender re-evaluates a live collection Boolean after any removal, hide or mesh read anywhere in the scene; a frozen object costs nothing there. Sockets, connections and report rows stay. set_params, boolean, cut, cut_many, ribs and a shell or hose rebuild refuse a frozen object: thaw it first. Refuses a frozen object, one with no modifiers, one with a modifier already off (named) and one Blender does not evaluate. Reports object (or the part), frozen, faces (the live mesh's), evaluated {faces, volume, nonManifoldEdges}, modifiers and booleans.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 7cc37a6..ed81032 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -33,6 +33,8 @@ Who owns what: - A boolean belongs to its Boolean modifier on the part that is cut. - Whether a cut object is live or frozen belongs to its `kit_frozen` property, which holds the live mesh while the object carries its evaluated one. Only `freeze` sets it, and `thaw`, which deletes it, is its one undo. +- Every `kit_*` custom property is the kit's: Brokkr's `setObjectCustomProperty` refuses a name that starts with + `kit_`, so each has only the writers named here. ## A part, end to end @@ -339,15 +341,18 @@ sphere under one Exact Boolean of four cutters each), each trigger on an unrelat the plates frozen, 0.004 to 0.014 s (three interleaved repetitions, Blender 5.3 on Starfire). **`freeze`** takes any mesh object that has modifiers, a kit part, a shell or a plain mesh. Its mesh becomes its -evaluated mesh (named ` frozen`), its live mesh is held by an ID-pointer property, `kit_frozen`, so it -survives a purge of orphans, and every modifier stays in the stack with its collections, turned off in viewports -and renders. Nothing is removed: the cutter objects stay, a cutter placed by `cut` keeps its floor socket and what +evaluated mesh (named ` frozen`), its live mesh is held by an ID-pointer property, `kit_frozen`, and +given a fake user (marked `kit_kept` on the mesh, and taken back by the last `thaw`), so it survives a purge of +orphans even if `kit_frozen` is edited by hand, and every modifier stays in the stack with its collections, turned +off in viewports and renders. Nothing is removed: the cutter objects stay, a cutter placed by `cut` keeps its floor socket and what is attached to it, and `booleans` still lists what cuts the object. The frozen mesh's material slots are the object'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 first slot. A frozen kit part keeps `kit_kit`, `kit_part`, `kit_params` and its connections: its sockets are still derived from the params, so `attach`, `detach`, `roll`, `aim`, `reach` and -`close` work on it and on what hangs from it. `freeze` reports the part (or `object`), `frozen`, `faces`, -`volume`, `nonManifoldEdges`, `modifiers` and `booleans`. +`close` work on it and on what hangs from it. `freeze` reports the part (or `object`), `frozen`, `faces` (the live +mesh's count, as in every report), `evaluated: {faces, volume, nonManifoldEdges}` (the frozen mesh), `modifiers` +and `booleans`. `report` on a frozen part gives `faces`, still the live mesh's, and `evaluated: {faces}`, the +frozen mesh's. **`thaw`** puts the live mesh back, deletes `kit_frozen`, turns every modifier on and removes the frozen mesh. It evaluates nothing itself; Blender evaluates the object once afterwards, and the thawed object evaluates to the @@ -358,16 +363,22 @@ with "thaw it first": `set_params`, `boolean`, `cut`, `cut_many`, `ribs` from it it, and `freeze`. Derive ribs before freezing a cage. `freeze` also refuses an object with no modifiers, one with a modifier already off in viewports or renders (it names them: `thaw` turns every modifier on, and would not give that stack back), and one Blender does not evaluate. `thaw` refuses an object that is not frozen, and one whose -held mesh was removed. What nothing detects: a modifier of a frozen object turned on by hand, and a material -assigned to a frozen object, which lands on the frozen mesh and goes at `thaw`. `exportGltf` with `applyModifiers` -exports a frozen object's frozen mesh, since its modifiers are off. +`kit_frozen` no longer holds a mesh; if a hand edit overwrote it, the refusal names the live meshes freeze kept +that no frozen object holds, and setting `kit_frozen` back to that mesh by hand lets `thaw` through. + +A modifier of a frozen object turned on by hand is applied on top of the frozen mesh. `report` shows such a part +with `frozen` false and `dirty`, the names of the modifiers shown; it stays refused by the actions above until it +is thawed. `exportGltf` with `applyModifiers` exports a frozen object's frozen mesh, since its modifiers are off, +and refuses an export that includes a frozen object with a modifier shown in viewports. What nothing detects: a +material assigned to a frozen object, which lands on the frozen mesh and goes at `thaw`. What it buys on an assembly: KESTREL, an experiment mech of 22 cut shells and blocks, evaluated 1035 Booleans where its cuts need 139 when each finished component was only hidden, and 139 when each was frozen as it was -finished; the whole build took 4.5 times as long hidden as frozen (medians of three interleaved pairs, 3.4 to 5.7 -within a pair, Blender 5.3 on Starfire under other load; an earlier series on a quieter machine read 251.7 s -against 51.2 s). In `tests/live/kitbash_assembly.py`, removing an orphan mesh beside three cut tanks costs 1.05 s -with them live and 0.0023 s with them frozen. +finished. The evaluation counts are the stable measure: they repeat exactly. Wall time follows the machine's +load: the whole build took about 2.7 to 5.7 times as long hidden as frozen across two series of three interleaved +pairs (Blender 5.3 on Starfire under other load; 133 to 149 s against 32 to 54 s in the later one). In +`tests/live/kitbash_assembly.py`, removing an orphan mesh beside three cut tanks costs about 1 s with them live +and about 0.002 s with them frozen. ## Making a shell @@ -967,7 +978,7 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se | `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | | `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 frozen 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 `frozen`. Changes nothing and evaluates no modifier. | +| `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 `frozen`; a frozen part adds `evaluated: {faces}`, and `dirty` (with `frozen` false) when a modifier of it is shown again. `faces` is the live mesh's count. 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; 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.roll` | `object_name`, `roll` (degrees, -360 to 360) | Turns an attached part to that roll where it hangs. Refuses a part that is not attached. Reports the part and `closures` as `set_params` does. | @@ -977,7 +988,7 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se | `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; `booleansOmitted` counts rows a receipt had no room for) 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), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans` (with `booleansOmitted`, as `boolean`). | | `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). | -| `brokkr_kitbash.freeze` | `object_name` (any mesh with modifiers) | Makes the evaluated mesh the object's mesh, holds the live mesh in `kit_frozen` and turns every modifier off, keeping the stack, its collections and the cutters. Refuses a frozen object, one with no modifiers, one with a modifier already off and one Blender does not evaluate. Reports the part (or `object`), `frozen`, `faces`, `volume`, `nonManifoldEdges`, `modifiers` and `booleans`. | +| `brokkr_kitbash.freeze` | `object_name` (any mesh with modifiers) | Makes the evaluated mesh the object's mesh, holds the live mesh in `kit_frozen` and turns every modifier off, keeping the stack, its collections and the cutters. Refuses a frozen object, one with no modifiers, one with a modifier already off and one Blender does not evaluate. Reports the part (or `object`), `frozen`, `faces` (live), `evaluated: {faces, volume, nonManifoldEdges}`, `modifiers` and `booleans`. | | `brokkr_kitbash.thaw` | `object_name` | Puts the live mesh back, turns every modifier on and removes the frozen mesh; evaluates nothing. Refuses an object that is not frozen or whose held mesh is gone. Reports `object`, `frozen`, `modifiers` and the live mesh's `faces`. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | | `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index d0b66c4..b18a340 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -625,11 +625,11 @@ try: receipt, frozen = send("brokkr_kitbash.freeze", object_name="Tank") after = np.zeros(len(tank.data.polygons), dtype=np.int32) tank.data.polygons.foreach_get("material_index", after) - facts = frozen and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} + facts = frozen and frozen["evaluated"] check("freeze makes the evaluated mesh the tank's mesh: the same faces, volume and non-manifold edges, and the tank still evaluates to them", receipt["status"] == "accepted" and facts == shown == measure(tank.data) == evaluated(tank)[0] and tank.data.name == "Tank frozen" and len(bpy.data.meshes) == meshes + 1, [receipt["message"], facts, shown]) - check("freeze holds the live mesh in kit_frozen and keeps the stack, off, with its collection and cutter", frozen and frozen["frozen"] is True + check("freeze holds the live mesh in kit_frozen and keeps the stack, off, with its collection and cutter", frozen and frozen["frozen"] is True and frozen["faces"] == live_faces and tank["kit_frozen"].name == mesh_name and len(tank["kit_frozen"].polygons) == live_faces and stack(tank) == frozen["modifiers"] == ["Kit Difference", "Kit Bevel"] and not any(m.show_viewport or m.show_render for m in tank.modifiers) and tank.modifiers["Kit Difference"].collection.objects[:] == [box] and frozen["booleans"] == [{"cutter": "Box", "operation": "DIFFERENCE"}] and len(bpy.data.collections) == collections and "Box" in bpy.context.scene.objects, @@ -647,7 +647,8 @@ try: refused("freeze on a frozen part", "brokkr_kitbash.freeze", {"object_name": "Tank"}, THAW) receipt, report = send("brokkr_kitbash.report", object_name="Tank") check("a frozen part still reports its sockets where its params put them, and what is attached to it still holds", report and report["parts"][0]["frozen"] is True - and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == frozen["faces"] and holds("Tee", "Tank", "b", "port_a", 180.0)[0] + and report["parts"][0]["sockets"] == sockets_before and report["parts"][0]["faces"] == live_faces != shown["faces"] and report["parts"][0]["evaluated"] == {"faces": shown["faces"]} + and "dirty" not in report["parts"][0] and holds("Tee", "Tank", "b", "port_a", 180.0)[0] and holds("Nozzle", "Tee", "mount", "c", 37.0)[0], report) receipt, report = send("brokkr_kitbash.attach", object_name="Radiator", socket="base", parent_name="Tank", parent_socket="saddle") check("a new part attaches to a frozen one", receipt["status"] == "accepted" and held(report) @@ -661,15 +662,42 @@ try: bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True) check("the held live mesh survives a purge of orphans", bpy.data.meshes.get(mesh_name) is not None and tank["kit_frozen"] == bpy.data.meshes[mesh_name] and len(tank["kit_frozen"].polygons) == live_faces, sorted(m.name for m in bpy.data.meshes)) + # kit_* belongs to the kit: the bridge's property setter refuses it, so kit_frozen keeps its one writer + for name in ("kit_frozen", "customProperties.kit_frozen", "kit_roll", "kit_anything"): + refused(f"setObjectCustomProperty on {name}", "setObjectCustomProperty", {"targetObjectName": "Tank", "propertyName": name, "value": "oops"}, "is brokkr_kitbash's own state (kit_*)") + # a modifier shown again by hand on a frozen part: the report says dirty, not frozen, and an export that applies modifiers refuses it + tank.modifiers["Kit Bevel"].show_viewport = True + dirty = send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0] + check("a frozen part with a modifier shown again reports dirty with the modifier, and not frozen", dirty["frozen"] is False and dirty["dirty"] == ["Kit Bevel"] + and dirty["faces"] == live_faces, dirty) + for label, fields in (("the scene", {}), ("the part by name", {"selection": ["Tank"]})): + refused(f"exportGltf applying modifiers over a dirty frozen part: {label}", "exportGltf", {"filepath": "dirty.glb", "applyModifiers": True, **fields}, + "Tank: frozen (brokkr_kitbash.freeze) with a modifier shown again") + refused("set_params on a dirty frozen part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, THAW) + tank.modifiers["Kit Bevel"].show_viewport = False + check("with the modifier hidden again the part reports frozen; the refused exports wrote nothing", "dirty" not in send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0] + and send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["frozen"] is True and not (WORK / "dirty.glb").exists(), sorted(p.name for p in WORK.iterdir())) for name in ("Tee", "Tank"): receipt, thawed = send("brokkr_kitbash.thaw", object_name=name) check("thaw puts the live mesh back, turns every modifier on and removes the frozen mesh", receipt["status"] == "accepted" and tank.data.name == mesh_name and "kit_frozen" not in tank and thawed == {"object": "Tank", "frozen": False, "modifiers": ["Kit Difference", "Kit Bevel"], "faces": live_faces} and stack(tank) == ["Kit Difference", "Kit Bevel"] and all(m.show_viewport and m.show_render for m in tank.modifiers) and "Tank frozen" not in bpy.data.meshes and "kit_frozen" not in tee - and len(bpy.data.collections) == collections, [receipt["message"], thawed, sorted(m.name for m in bpy.data.meshes)]) + and len(bpy.data.collections) == collections and not tank.data.use_fake_user and "kit_kept" not in tank.data and tank.data.users == 1, + [receipt["message"], thawed, sorted(m.name for m in bpy.data.meshes), tank.data.users]) check("the thawed tank evaluates to what it did before freeze, and reports frozen false", evaluated(tank)[0] == shown and send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["frozen"] is False, [evaluated(tank)[0], shown]) lost = place("Lost", "plate", location=[0.0, -24.0, 0.0]) + lost_mesh = lost.data.name + send("brokkr_kitbash.freeze", object_name="Lost") + lost["kit_frozen"] = "oops" # by hand: no action writes it. The live mesh has lost its one real user + bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True) + check("a live mesh whose kit_frozen was overwritten by hand survives a purge of orphans", lost_mesh in bpy.data.meshes and bpy.data.meshes[lost_mesh].use_fake_user, + sorted(m.name for m in bpy.data.meshes)) + refused("thaw on a frozen part whose kit_frozen was overwritten names the kept mesh", "brokkr_kitbash.thaw", {"object_name": "Lost"}, + f"Live meshes freeze kept that no frozen object holds: {lost_mesh};") + lost["kit_frozen"] = bpy.data.meshes[lost_mesh] # the way back, by hand, that the refusal names + receipt, _ = send("brokkr_kitbash.thaw", object_name="Lost") + check("and with the kept mesh put back in kit_frozen it thaws", receipt["status"] == "accepted" and lost.data.name == lost_mesh and not lost.data.use_fake_user, receipt["message"]) send("brokkr_kitbash.freeze", object_name="Lost") bpy.data.meshes.remove(lost["kit_frozen"]) refused("thaw on a frozen part whose held mesh was removed", "brokkr_kitbash.thaw", {"object_name": "Lost"}, "the live mesh its kit_frozen held is gone") @@ -695,7 +723,7 @@ try: receipt, frozen = send("brokkr_kitbash.freeze", object_name="Plate") check("freeze on a part with no material slot leaves the frozen mesh with none (Blender's Boolean shows it with one empty slot); a linked duplicate keeps the live mesh", receipt["status"] == "accepted" and shown_slots == [None] and len(plate.data.materials) == 0 and len(plate.material_slots) == 0 - and frozen["booleans"] == second["booleans"] and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown + and frozen["booleans"] == second["booleans"] and frozen["evaluated"] == shown and twin.data.name == "Plate" and plate["kit_frozen"] == twin.data and all(m.show_viewport for m in twin.modifiers), [shown_slots, len(plate.data.materials), len(plate.material_slots), frozen]) bpy.data.objects.remove(twin) @@ -803,12 +831,14 @@ try: send("brokkr_kitbash.thaw", object_name=obj.name) bpy.app.handlers.depsgraph_update_post.remove(seen) medians = {state: sorted(seconds for seconds, _ in rows)[1] for state, rows in costs.items()} - R["frozenCost"] = {"liveSeconds": round(medians["live"], 4), "frozenSeconds": round(medians["frozen"], 5), - "live": [[round(s, 4), names] for s, names in costs["live"]], "frozen": [[round(s, 5), names] for s, names in costs["frozen"]]} + # wall time is this machine's: printed, and kept out of the result file, which carries what was re-evaluated + SECONDS = {"live": [round(s, 4) for s, _ in costs["live"]], "frozen": [round(s, 5) for s, _ in costs["frozen"]], "frozenOverLive": medians["frozen"] / medians["live"]} + print("SECONDS", SECONDS, flush=True) + R["frozenCost"] = {state: [names for _, names in rows] for state, rows in costs.items()} check("removing an orphan mesh re-evaluates the three live cut tanks, and none of them frozen", all(names == ["Cold0", "Cold1", "Cold2"] for _, names in costs["live"]) and all(names == [] for _, names in costs["frozen"]), R["frozenCost"]) check("and the update with them frozen costs under the bound of what it costs with them live", - reading("frozenCost", medians["frozen"] / medians["live"]) < FROZEN_COST, R["frozenCost"]) + SECONDS["frozenOverLive"] < FROZEN_COST, SECONDS) except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index db1ffde..7cc08bf 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -576,6 +576,51 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: setObjectCustomProperty on kit_frozen", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: setObjectCustomProperty on customProperties.kit_frozen", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: setObjectCustomProperty on kit_roll", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: setObjectCustomProperty on kit_anything", + "ok": true, + "detail": null + }, + { + "name": "a frozen part with a modifier shown again reports dirty with the modifier, and not frozen", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: exportGltf applying modifiers over a dirty frozen part: the scene", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: exportGltf applying modifiers over a dirty frozen part: the part by name", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a dirty frozen part", + "ok": true, + "detail": null + }, + { + "name": "with the modifier hidden again the part reports frozen; the refused exports wrote nothing", + "ok": true, + "detail": null + }, { "name": "thaw puts the live mesh back, turns every modifier on and removes the frozen mesh", "ok": true, @@ -586,6 +631,21 @@ "ok": true, "detail": null }, + { + "name": "a live mesh whose kit_frozen was overwritten by hand survives a purge of orphans", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: thaw on a frozen part whose kit_frozen was overwritten names the kept mesh", + "ok": true, + "detail": null + }, + { + "name": "and with the kept mesh put back in kit_frozen it thaws", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: thaw on a frozen part whose held mesh was removed", "ok": true, @@ -658,7 +718,6 @@ "close nudged": 0.00032, "closed": 3.9e-07, "cut": 0.25, - "frozenCost": 0.0016, "kept": 6e-08, "nudged": 0.00032, "roll": 6.6e-06, @@ -699,47 +758,27 @@ "nonManifoldEdges": 0 }, "frozenCost": { - "liveSeconds": 1.0356, - "frozenSeconds": 0.00168, "live": [ [ - 1.0412, - [ - "Cold0", - "Cold1", - "Cold2" - ] + "Cold0", + "Cold1", + "Cold2" ], [ - 1.0356, - [ - "Cold0", - "Cold1", - "Cold2" - ] + "Cold0", + "Cold1", + "Cold2" ], [ - 0.9348, - [ - "Cold0", - "Cold1", - "Cold2" - ] + "Cold0", + "Cold1", + "Cold2" ] ], "frozen": [ - [ - 0.00168, - [] - ], - [ - 0.00264, - [] - ], - [ - 0.00165, - [] - ] + [], + [], + [] ] }, "ok": true diff --git a/surfaces/blender/tests/live/kitbash_faceted.py b/surfaces/blender/tests/live/kitbash_faceted.py index ec02c59..be7a6eb 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.py +++ b/surfaces/blender/tests/live/kitbash_faceted.py @@ -445,8 +445,10 @@ except Exception: # noqa: BLE001 whatever it was, it is a failed check with a finally: R["ok"] = all(c["ok"] for c in R["checks"]) R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} + costs = R.pop("costs", None) # wall time is this machine's: printed, and kept out of the result file Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) - print("READINGS", R["readings"], R["costs"], flush=True) + print("READINGS", R["readings"], flush=True) + print("SECONDS", costs, flush=True) sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_faceted.result.json b/surfaces/blender/tests/live/kitbash_faceted.result.json index 1ec749c..14af0bd 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.result.json +++ b/surfaces/blender/tests/live/kitbash_faceted.result.json @@ -183,14 +183,6 @@ "soft": 5.8, "solid": 0.027 }, - "costs": { - "shell": 0.0059, - "shellCountingFolds": 0.0091, - "evaluation": 0.0022, - "rebuildUnderCuts": 1.7, - "rebuildCall": 1.6, - "rebuildCallCountingFolds": 1.6 - }, "folds": { "seeded": { "5185 offset -1": [ diff --git a/surfaces/blender/tests/live/kitbash_hose.py b/surfaces/blender/tests/live/kitbash_hose.py index 65e76c4..7ca00af 100644 --- a/surfaces/blender/tests/live/kitbash_hose.py +++ b/surfaces/blender/tests/live/kitbash_hose.py @@ -438,6 +438,14 @@ try: refused("nine clamps", {**FEED, "clamps": json.dumps([{"socket": "SeatA:front"}] * 9)}, "clamps must be a JSON array of 0 to 8 objects") refused("a pin crossed with no joint", {k: v for k, v in FEED.items() if k != "joint"}, "The hose crosses the pin of 'Shin' on 'Thigh' (socket 'end_b_back'): give joint") refused("a joint where no pin is crossed", {**LINE, "object_name": "New", "joint": json.dumps(JOINT)}, "joint is given and the hose crosses no pin") + feed.modifiers.new("Smooth", "SUBSURF") # by hand: a hose has no modifiers of its own, and freeze takes any mesh that has one + receipt, chilled = send("brokkr_kitbash.freeze", object_name="Feed") + check("a hose given a modifier freezes", receipt["status"] == "accepted" and chilled and chilled["frozen"] is True and feed.data.name == "Feed frozen", receipt["message"]) + refused("a rebuild of a frozen hose", FEED, "'Feed' is frozen, and rebuilding it needs its live mesh and modifiers: thaw it first") + send("brokkr_kitbash.thaw", object_name="Feed") + feed.modifiers.remove(feed.modifiers["Smooth"]) + receipt, thawed = send("brokkr_kitbash.hose", **FEED) + check("the thawed hose rebuilds", receipt["status"] == "accepted" and "Feed frozen" not in bpy.data.meshes and thawed["nonManifoldEdges"] == 0, receipt["message"]) place("Jack", "actuator", "body_r=0.0534;body_len=0.2;extension=0") send("brokkr_kitbash.attach", object_name="Jack", socket="base", parent_name="Shin", parent_socket="end_b", roll=90.0) bpy.context.view_layer.update() diff --git a/surfaces/blender/tests/live/kitbash_hose.result.json b/surfaces/blender/tests/live/kitbash_hose.result.json index acf4864..49cac92 100644 --- a/surfaces/blender/tests/live/kitbash_hose.result.json +++ b/surfaces/blender/tests/live/kitbash_hose.result.json @@ -301,6 +301,21 @@ "ok": true, "detail": null }, + { + "name": "a hose given a modifier freezes", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a rebuild of a frozen hose", + "ok": true, + "detail": null + }, + { + "name": "the thawed hose rebuilds", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: two pins crossed", "ok": true, diff --git a/surfaces/blender/tests/live/kitbash_shell.py b/surfaces/blender/tests/live/kitbash_shell.py index c5eed48..dc4de39 100644 --- a/surfaces/blender/tests/live/kitbash_shell.py +++ b/surfaces/blender/tests/live/kitbash_shell.py @@ -403,12 +403,12 @@ try: receipt, frozen = send("brokkr_kitbash.freeze", object_name="Plate") check("freeze keeps the three modifiers, off, the three collections they read and every cutter in the scene", receipt["status"] == "accepted" and frozen["booleans"] == report["booleans"] and len(bpy.data.collections) == collections and frozen["modifiers"] == stack(plate) == ["Kit Difference", "Kit Union", "Kit Intersect", "Kit Bevel"] - and not any(m.show_viewport or m.show_render for m in plate.modifiers) and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == shown == evaluated(plate)[0] + and not any(m.show_viewport or m.show_render for m in plate.modifiers) and frozen["evaluated"] == shown == evaluated(plate)[0] and all(name in bpy.context.scene.objects for name in ("Hole", "Boss", "Keep")), [receipt["message"], frozen, shown]) cage_stack, cage_mesh = stack(cage), cage.data.name receipt, frozen = send("brokkr_kitbash.freeze", object_name="Cage") check("freeze takes the cage, which is not a kit part: its evaluated wall, its stack off, its cutters still its children", receipt["status"] == "accepted" and frozen["object"] == "Cage" - and "kit" not in frozen and frozen["frozen"] is True and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == cage_shown == evaluated(cage)[0] + and "kit" not in frozen and frozen["frozen"] is True and frozen["evaluated"] == cage_shown == evaluated(cage)[0] and frozen["modifiers"] == stack(cage) == cage_stack and not any(m.show_viewport or m.show_render for m in cage.modifiers) and cage.data.name == "Cage frozen" and bpy.data.objects["Bay"].parent == cage and len(bpy.data.collections) == collections, [receipt["message"], frozen and frozen["modifiers"], cage_shown]) refused("ribs from a frozen cage", "brokkr_kitbash.ribs", {"object_name": "Cage", "ribs_name": "ColdRibs", "planes": json.dumps([{"origin": [0.0, 0.0, 0.5], "normal": [0.0, 0.0, 1.0]}])}, THAW) @@ -442,7 +442,7 @@ try: wall = evaluated(bpy.data.objects["Lid"])[0] receipt, frozen = send("brokkr_kitbash.freeze", object_name="Lid") check("freeze takes a shell: the wall its Kit Subsurf and Kit Solidify make", receipt["status"] == "accepted" and frozen["modifiers"] == ["Kit Subsurf", "Kit Solidify"] - and {k: frozen[k] for k in ("faces", "volume", "nonManifoldEdges")} == wall and wall["faces"] > 2 * 6 * 16, [receipt["message"], frozen, wall]) + and frozen["evaluated"] == wall and wall["faces"] > 2 * 6 * 16, [receipt["message"], frozen, wall]) refused("a rebuild of a frozen shell", "brokkr_kitbash.shell", lid, THAW) refused("a rebuild of a frozen shell that counts folds", "brokkr_kitbash.shell", {**lid, "count_folds": True}, THAW) send("brokkr_kitbash.thaw", object_name="Lid") diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index 6d4a762..c78056e 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -609,6 +609,16 @@ class NodeActionTests(unittest.TestCase): self.assertIn("setModifierInput", receipt["message"]) self.assertFalse(hasattr(host, "custom")) + def test_custom_property_in_the_kit_namespace_is_refused(self): + self.group() + host = self.bpy.data.objects["Host"] + for name in ("kit_frozen", "customProperties.kit_frozen", "kit_roll", "kit_"): + receipt = self.refused(action="setObjectCustomProperty", targetObjectName="Host", propertyName=name, value=3) + self.assertIn("brokkr_kitbash's own state (kit_*)", receipt["message"]) + self.assertFalse(hasattr(host, "custom")) + self.accepted(action="setObjectCustomProperty", targetObjectName="Host", propertyName="kitchen", value=3) + self.assertEqual(host.custom, ("kitchen", 3)) + def test_custom_property_sharing_only_a_display_name_is_an_ordinary_property(self): self.group() host = self.bpy.data.objects["Host"] diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index ef3ae3b..874d2b6 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -114,6 +114,7 @@ class FakeBpy: for o in self.data.objects.values(): o.selected = o is self.mesh o.select_get = (lambda o=o: o.selected) + o.modifiers, o.get = [], (lambda key, default=None: default) # no modifier, no custom property o.select_set = (lambda state, o=o: setattr(o, "selected", state)) add = lambda kind: (lambda mode, undo, **kw: self.add_object(kind, kw, (mode, undo))) self.ops = NS(import_scene=NS(gltf=self.import_gltf), render=NS(render=self.render_still), @@ -291,6 +292,21 @@ class ActionTests(unittest.TestCase): self.assertEqual(call["selected_at_call"], ["Cam", "Lamp"]) self.assertEqual([o.name for o in self.bpy.data.objects.values() if o.selected], ["Cube"]) + def test_export_applying_modifiers_refuses_a_frozen_object_with_a_modifier_shown(self): + mesh = self.bpy.data.objects["Cube"] + mesh.get = lambda key, default=None: "live mesh" if key == "kit_frozen" else default + mesh.modifiers = [NS(show_viewport=False), NS(show_viewport=True)] + for fields in ({}, {"selection": ["Cube"]}): + receipt = self.run_action(action="exportGltf", filepath="dirty.glb", **fields) + self.assertEqual(receipt["status"], "failed", receipt) + self.assertIn("Cube: frozen (brokkr_kitbash.freeze) with a modifier shown again", receipt["message"]) + self.assertEqual((self.bpy.exported, list((self.root / "out").iterdir())), ([], [])) + for fields in ({"applyModifiers": False}, {"selection": ["Cam"]}): # nothing applied, or the object not exported + receipt = self.run_action(action="exportGltf", filepath=f"ok{len(self.bpy.exported)}.glb", **fields) + self.assertEqual(receipt["status"], "accepted", receipt) + mesh.modifiers[1].show_viewport = False + self.assertEqual(self.run_action(action="exportGltf", filepath="frozen.glb")["status"], "accepted") + def test_export_without_a_selection_never_touches_selection(self): def explode(*a, **k): raise AssertionError("selection touched") From 7845b13ed01770704a6b6998909a1611a68bb7a9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:34:24 +0100 Subject: [PATCH 148/223] brokkr_kitbash freeze: one writer of the frozen state, hold; a deleted frozen object releases its live mesh; importGltf drops kit_* extras (cut kit-freeze, fix batch h3) hold is the only writer of kit_frozen, kit_kept and a held live mesh's fake user, and it swaps the meshes. It settles every live mesh after each depsgraph update and before each save: held meshes are kept, kit_kept pointing at the frozen mesh; a mesh no kit_frozen points at is released unless an object still carries the frozen mesh its kit_kept names. The bridge's kit_owned is the one test for kit_*: setObjectCustomProperty refuses, importGltf drops and reports. thaw removes the frozen mesh by user_map, names the kept mesh when kit_frozen was lost; a dirty part is refused as dirty; the export refusal counts show_render as the report does. Co-Authored-By: Claude Fable 5.2 --- .../blender/brokkr_bridge/blender_target.py | 27 +++++- surfaces/blender/brokkr_kitbash/__init__.py | 92 +++++++++++++++---- surfaces/blender/docs/install.md | 2 + surfaces/blender/docs/kitbash.md | 25 +++-- .../blender/tests/live/kitbash_assembly.py | 81 +++++++++++++++- surfaces/blender/tests/test_kitbash.py | 13 ++- surfaces/blender/tests/test_scene_actions.py | 30 +++++- 7 files changed, 227 insertions(+), 43 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index a24f09b..6e23e8c 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -46,7 +46,7 @@ DEFAULT_DEBUG_MIRROR_ROOT = "//.brokkr/blender-editor-debug" HOST_SNAPSHOT_SCHEMA = "brokkr.blender.host_snapshot.v0" HOST_ACTIONS_FILE = "brokkr_actions.json" HOST_RESULT_LIMIT = 16000 # characters of a host operator's result copied into a receipt -KIT_RESERVED = "kit_" # brokkr_kitbash owns every custom property so named: setObjectCustomProperty refuses them +KIT_RESERVED = "kit_" # brokkr_kitbash owns every custom property so named: kit_owned is the one test, setObjectCustomProperty refuses them and importGltf drops them KIT_FROZEN = "kit_frozen" # brokkr_kitbash's frozen state (its FROZEN): read here only, to refuse an export that would apply a stack twice COMMAND_INTENT_SCHEMA = "brokkr.blender.command_intent.v0" COMMAND_RECEIPT_SCHEMA = "brokkr.blender.command_receipt.v0" @@ -946,7 +946,7 @@ class BrokkrBlenderTarget: property_name = command["propertyName"] if property_name.startswith("customProperties."): property_name = property_name[len("customProperties."):] - if property_name.startswith(KIT_RESERVED): + if kit_owned(property_name): raise sa.ActionRefused(f"{property_name!r} is brokkr_kitbash's own state ({KIT_RESERVED}*): its actions write it, and a value set " "here would leave the object and the property disagreeing. Use the brokkr_kitbash action; nothing changed.") modifier_name = na.drives_modifier_input(obj, property_name) @@ -1008,7 +1008,19 @@ class BrokkrBlenderTarget: before = set(self.bpy.data.objects.keys()) self.bpy.ops.import_scene.gltf("EXEC_DEFAULT", False, filepath=str(path)) added = sorted(set(self.bpy.data.objects.keys()) - before) - return self._receipt(command, "accepted", f"Imported {len(added)} object(s) from {path.name}.", added[0] if added else "") + # A file's extras become custom properties, and kit_* is brokkr_kitbash's own state, as setObjectCustomProperty + # has it: an imported kit_frozen would make a frozen object with no live mesh to thaw to. + dropped = [] + for name in added: + obj = self.bpy.data.objects[name] + for holder in (obj, obj.data): + for key in [key for key in (holder.keys() if holder is not None else ()) if kit_owned(key)]: + del holder[key] + dropped.append(name) + dropped = sorted(set(dropped)) + return self._receipt(command, "accepted", f"Imported {len(added)} object(s) from {path.name}." + ( + f" Dropped the file's {KIT_RESERVED}* properties from {', '.join(dropped)}: they are brokkr_kitbash's own state and its actions write them." if dropped else ""), + added[0] if added else "") def _exportGltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: """Write the scene (or the named objects) as .glb or .gltf under the output directory.""" @@ -1035,10 +1047,10 @@ class BrokkrBlenderTarget: if command["applyModifiers"]: # A frozen object's mesh is already its stack's result: a modifier shown on it again would be applied twice. dirty = sorted(o.name for o in (chosen or context.view_layer.objects.values()) - if o.get(KIT_FROZEN) is not None and any(m.show_viewport for m in o.modifiers)) + if o.get(KIT_FROZEN) is not None and any(m.show_viewport or m.show_render for m in o.modifiers)) if dirty: raise sa.ActionRefused(f"{', '.join(dirty)}: frozen (brokkr_kitbash.freeze) with a modifier shown again, so the export would apply " - "the stack on top of its own result. Thaw it (brokkr_kitbash.thaw), or hide its modifiers; nothing written.") + "the stack on top of its own result. Thaw it (brokkr_kitbash.thaw), or hide its modifiers in viewports and renders; nothing written.") # The exporter writes into a fresh staging folder beside the target, never onto the output # directory: it may also write a .bin and texture files whose names Brokkr does not choose. Only # after it finishes does every file move into place, each refused if its name is taken, so no @@ -1928,6 +1940,11 @@ def _sync_session(session_id: str, display_name: str, updated_at: str) -> dict[s } +def kit_owned(property_name: str) -> bool: + """A custom property brokkr_kitbash owns: no bridge action writes one from outside input.""" + return property_name.startswith(KIT_RESERVED) + + def _unity_custom_property_path(component_type: str, property_path: str) -> str: property_path = (property_path or "value").strip() component_type = (component_type or "").strip() diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 26e50e6..d339078 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -88,8 +88,8 @@ from . import core, route KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" SOCKET, PARENT_SOCKET, ROLL = "kit_socket", "kit_parent_socket", "kit_roll" -FROZEN = "kit_frozen" # on a frozen object: an ID pointer to its live mesh; its presence is the frozen state, freeze sets it and thaw deletes it -KEPT = "kit_kept" # on a live mesh a frozen object holds: freeze gave it the fake user that keeps it through a purge, and the last thaw takes it back +FROZEN = "kit_frozen" # on a frozen object: an ID pointer to its live mesh; its presence is the frozen state. hold writes it and nothing else does +KEPT = "kit_kept" # on a live mesh a frozen object holds: an ID pointer to that object's frozen mesh, beside the fake user that keeps the live mesh through a purge. hold writes both 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" @@ -376,9 +376,59 @@ def shown(obj) -> list: def live(obj, doing: str) -> None: """Refuses a frozen object: its mesh is its frozen evaluation and its modifiers are off, so a write would land on - a mesh thaw discards, or under a stack nothing evaluates.""" + a mesh thaw discards, or under a stack nothing evaluates. A dirty one is named dirty, as its report names it.""" if FROZEN in obj: - raise Refused(f"{obj.name!r} is frozen, and {doing} it needs its live mesh and modifiers: thaw it first; nothing changed.") + dirty = shown(obj) + raise Refused(f"{obj.name!r} is frozen" + (f" and dirty ({', '.join(dirty)} shown again)" if dirty else "") + + f", and {doing} it needs its live mesh and modifiers: thaw it first; nothing changed.") + + +def hold(obj=None, frozen=None) -> None: + """The one writer of the frozen state: kit_frozen on an object, and kit_kept and the fake user on a live mesh. + Given an object and its frozen mesh, the object takes that mesh and its kit_frozen takes the live one; given an + object alone, its live mesh comes back from kit_frozen, which goes. Then, given one or not, every live mesh is + settled against the objects there are. One that a frozen object holds has a fake user and kit_kept, a pointer to + that object's frozen mesh. One that no kit_frozen points at loses both and is Blender's to purge, unless an object + still carries the frozen mesh its kit_kept names: that object's kit_frozen was lost by hand, and thaw names the + mesh. So a deleted frozen object releases its live mesh, by an action or by hand, and a hand edit of either + property is put right or reported. The fake user is this function's alone: one she gave a live mesh herself goes + when the mesh is released. Writes only what differs, so settled() may call it after every depsgraph update.""" + if obj is not None: + hold() # what a hand edit left is settled against the holders as they were, before this write changes them + if frozen is None: + obj.data = obj[FROZEN] + del obj[FROZEN] + else: + obj[FROZEN], obj.data = obj.data, frozen + carried, holders = set(), {} + for other in bpy.data.objects: + if other.type == "MESH": + carried.add(other.data.as_pointer()) + held = other.get(FROZEN) + if isinstance(held, bpy.types.Mesh): + holders.setdefault(held.as_pointer(), []).append(other.data) + for held in bpy.data.meshes: + carrying, kept = holders.get(held.as_pointer()), held.get(KEPT) + if carrying: + if not (isinstance(kept, bpy.types.Mesh) and kept in carrying): + held[KEPT] = carrying[0] + if not held.use_fake_user: + held.use_fake_user = True + elif KEPT in held and not (isinstance(kept, bpy.types.Mesh) and kept.as_pointer() in carried): + del held[KEPT] + held.use_fake_user = False + + +@bpy.app.handlers.persistent +def settled(*_) -> None: + """After a depsgraph update and before a save: hold() with no object. A frozen object deleted by any means, the + bridge's deleteObject or a key press, is seen here.""" + hold() + + +def kept_for(obj) -> list: + """The live meshes whose kit_kept names the mesh this object carries, by name.""" + return sorted(mesh.name for mesh in bpy.data.meshes if isinstance(mesh.get(KEPT), bpy.types.Mesh) and mesh[KEPT] == obj.data) def own_mesh(obj, doing: str) -> None: @@ -932,10 +982,7 @@ class BROKKR_KITBASH_OT_freeze(PolishOperator): if (index < 0).any(): # faces from a cutter's empty slot: slot 0, as faces from a cutter with no material frozen.polygons.foreach_set("material_index", np.maximum(index, 0)) frozen.name = f"{obj.name} frozen" - if not obj.data.use_fake_user: # the pointer below is a user too, but a property can be overwritten: the mesh outlives that - obj.data.use_fake_user = obj.data[KEPT] = True - obj[FROZEN] = obj.data - obj.data = frozen + hold(obj, frozen) for modifier in obj.modifiers: modifier.show_viewport = modifier.show_render = False report.update(frozen=True, faces=len(obj[FROZEN].polygons), evaluated=measured(frozen), modifiers=[modifier.name for modifier in obj.modifiers]) @@ -953,21 +1000,19 @@ class BROKKR_KITBASH_OT_thaw(PolishOperator): @kit_work def work(self, context): obj = mesh_object(self.object_name) - if FROZEN not in obj: - raise Refused(f"{obj.name!r} is not frozen; nothing changed.") - held, frozen = obj[FROZEN], obj.data + held, frozen = obj.get(FROZEN), obj.data if not isinstance(held, bpy.types.Mesh): - kept = sorted(mesh.name for mesh in bpy.data.meshes if KEPT in mesh and not any(other.get(FROZEN) == mesh for other in bpy.data.objects)) - raise Refused(f"{obj.name!r} is frozen and the live mesh its {FROZEN} held is gone: there is nothing to thaw to" - + (f". Live meshes freeze kept that no frozen object holds: {', '.join(kept)}" if kept else "") + "; nothing changed.") - obj.data = held - del obj[FROZEN] - if KEPT in held and not any(other.get(FROZEN) == held for other in bpy.data.objects): - del held[KEPT] - held.use_fake_user = False + kept = kept_for(obj) + if FROZEN not in obj and not kept: + raise Refused(f"{obj.name!r} is not frozen; nothing changed.") + raise Refused(f"{obj.name!r} carries a frozen mesh and its {FROZEN} " + ("is gone" if FROZEN not in obj else "no longer points at a mesh") + + (f": freeze kept its live mesh {', '.join(repr(name) for name in kept)}. Point {FROZEN} back at it by hand " + f"(object[{FROZEN!r}] = bpy.data.meshes[{kept[0]!r}]) and thaw" if kept else + ", and no kept live mesh names the mesh it carries: there is nothing to thaw to") + "; nothing changed.") + hold(obj) for modifier in obj.modifiers: modifier.show_viewport = modifier.show_render = True - if frozen.users == 0: + if not bpy.data.user_map(subset=[frozen])[frozen]: # users is no test: a glTF export that applied modifiers leaves the count one high bpy.data.meshes.remove(frozen) return {"object": obj.name, "frozen": False, "modifiers": [modifier.name for modifier in obj.modifiers], "faces": len(held.polygons)} @@ -1910,13 +1955,20 @@ classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KI BROKKR_KITBASH_OT_shell, BROKKR_KITBASH_OT_hose) +SETTLED_ON = (bpy.app.handlers.depsgraph_update_post, bpy.app.handlers.save_pre) + + def register(): if MISSING is not None or not hasattr(bpy.types.WindowManager, RESULT): raise RuntimeError(f"brokkr_kitbash needs brokkr_mesh_polish enabled first ({MISSING or 'its result property is not registered'}).") for cls in classes: bpy.utils.register_class(cls) + for handlers in SETTLED_ON: + handlers.append(settled) def unregister(): + for handlers in SETTLED_ON: + handlers.remove(settled) for cls in reversed(classes): bpy.utils.unregister_class(cls) diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 2659f4d..40362d6 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -186,6 +186,8 @@ Behaviour the table does not say, per action: - `importGltf`: `filepath`, `.gltf` or `.glb`, relative to the add-on preference `Import Directory` (absolute paths, `..` and symlinks that resolve outside it are refused). Empty `Import Directory` disables the action. Needs Blender's glTF add-on. + Custom properties named `kit_*` that the file's extras carry are dropped from the imported + objects and their data, and the receipt names the objects: they are brokkr_kitbash's own state. - `exportGltf`: `filepath`, `.glb` (binary) or `.gltf` (separate `.bin`), relative to the add-on preference `Render Output Directory` (the renderStill rules: no `..`, no links, and an existing name is refused; there is no overwrite). diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index ed81032..4096be7 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -33,8 +33,11 @@ Who owns what: - A boolean belongs to its Boolean modifier on the part that is cut. - Whether a cut object is live or frozen belongs to its `kit_frozen` property, which holds the live mesh while the object carries its evaluated one. Only `freeze` sets it, and `thaw`, which deletes it, is its one undo. + Both go through one function, `hold`, which is also the only writer of `kit_kept` and of the fake user on a held + live mesh ("Freezing"). - Every `kit_*` custom property is the kit's: Brokkr's `setObjectCustomProperty` refuses a name that starts with - `kit_`, so each has only the writers named here. + `kit_`, and `importGltf` drops such properties from the objects and meshes it imports and names the objects in + its receipt, so each has only the writers named here. A kit part exported with extras comes back as a plain mesh. ## A part, end to end @@ -342,8 +345,12 @@ the plates frozen, 0.004 to 0.014 s (three interleaved repetitions, Blender 5.3 **`freeze`** takes any mesh object that has modifiers, a kit part, a shell or a plain mesh. Its mesh becomes its evaluated mesh (named ` frozen`), its live mesh is held by an ID-pointer property, `kit_frozen`, and -given a fake user (marked `kit_kept` on the mesh, and taken back by the last `thaw`), so it survives a purge of -orphans even if `kit_frozen` is edited by hand, and every modifier stays in the stack with its collections, turned +given a fake user and `kit_kept`, a pointer to the frozen mesh, so it survives a purge of orphans and a save even +if `kit_frozen` is edited by hand. The kit settles this after every depsgraph update and before every save: a live +mesh that no `kit_frozen` points at loses its fake user and `kit_kept`, unless an object still carries the frozen +mesh its `kit_kept` names. So deleting a frozen object, by `deleteObject` or in Blender, releases its live mesh to +the next purge or save, and a `kit_kept` cleared by hand is written again. The fake user is the kit's: one already +set on a live mesh goes when the mesh is released. Every modifier stays in the stack with its collections, turned off in viewports and renders. Nothing is removed: the cutter objects stay, a cutter placed by `cut` keeps its floor socket and what is attached to it, and `booleans` still lists what cuts the object. The frozen mesh's material slots are the object's own (an empty one it had included), followed by any a cutter brought; faces a cutter made from an empty @@ -363,13 +370,15 @@ with "thaw it first": `set_params`, `boolean`, `cut`, `cut_many`, `ribs` from it it, and `freeze`. Derive ribs before freezing a cage. `freeze` also refuses an object with no modifiers, one with a modifier already off in viewports or renders (it names them: `thaw` turns every modifier on, and would not give that stack back), and one Blender does not evaluate. `thaw` refuses an object that is not frozen, and one whose -`kit_frozen` no longer holds a mesh; if a hand edit overwrote it, the refusal names the live meshes freeze kept -that no frozen object holds, and setting `kit_frozen` back to that mesh by hand lets `thaw` through. +`kit_frozen` no longer holds a mesh; if a hand edit overwrote or deleted it, the refusal names the kept live mesh +whose `kit_kept` points at the mesh the object carries, and setting `kit_frozen` back to that mesh by hand lets +`thaw` through. A modifier of a frozen object turned on by hand is applied on top of the frozen mesh. `report` shows such a part -with `frozen` false and `dirty`, the names of the modifiers shown; it stays refused by the actions above until it -is thawed. `exportGltf` with `applyModifiers` exports a frozen object's frozen mesh, since its modifiers are off, -and refuses an export that includes a frozen object with a modifier shown in viewports. What nothing detects: a +with `frozen` false and `dirty`, the names of the modifiers shown in viewports or renders; it stays refused by the +actions above, as "frozen and dirty", until it is thawed. `exportGltf` with `applyModifiers` exports a frozen +object's frozen mesh, since its modifiers are off, and refuses an export that includes a dirty one, by the same +rule: a modifier shown in viewports or renders. What nothing detects: a material assigned to a frozen object, which lands on the frozen mesh and goes at `thaw`. What it buys on an assembly: KESTREL, an experiment mech of 22 cut shells and blocks, evaluated 1035 Booleans diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index b18a340..48239fa 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -673,8 +673,14 @@ try: for label, fields in (("the scene", {}), ("the part by name", {"selection": ["Tank"]})): refused(f"exportGltf applying modifiers over a dirty frozen part: {label}", "exportGltf", {"filepath": "dirty.glb", "applyModifiers": True, **fields}, "Tank: frozen (brokkr_kitbash.freeze) with a modifier shown again") - refused("set_params on a dirty frozen part", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, THAW) + refused("set_params on a dirty frozen part, named dirty as its report names it", "brokkr_kitbash.set_params", {"object_name": "Tank", "params": "length=1.0"}, + "'Tank' is frozen and dirty (Kit Bevel shown again), and setting params of it needs its live mesh and modifiers: thaw it first") tank.modifiers["Kit Bevel"].show_viewport = False + tank.modifiers["Kit Bevel"].show_render = True # shown in renders only: dirty by the same rule, in the report and at the export + check("a frozen part with a modifier shown in renders only reports dirty", send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0].get("dirty") == ["Kit Bevel"]) + refused("exportGltf applying modifiers over a frozen part dirty in renders only", "exportGltf", {"filepath": "dirty.glb", "applyModifiers": True, "selection": ["Tank"]}, + "Tank: frozen (brokkr_kitbash.freeze) with a modifier shown again") + tank.modifiers["Kit Bevel"].show_render = False check("with the modifier hidden again the part reports frozen; the refused exports wrote nothing", "dirty" not in send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0] and send("brokkr_kitbash.report", object_name="Tank")[1]["parts"][0]["frozen"] is True and not (WORK / "dirty.glb").exists(), sorted(p.name for p in WORK.iterdir())) for name in ("Tee", "Tank"): @@ -694,13 +700,82 @@ try: check("a live mesh whose kit_frozen was overwritten by hand survives a purge of orphans", lost_mesh in bpy.data.meshes and bpy.data.meshes[lost_mesh].use_fake_user, sorted(m.name for m in bpy.data.meshes)) refused("thaw on a frozen part whose kit_frozen was overwritten names the kept mesh", "brokkr_kitbash.thaw", {"object_name": "Lost"}, - f"Live meshes freeze kept that no frozen object holds: {lost_mesh};") + f"its kit_frozen no longer points at a mesh: freeze kept its live mesh {lost_mesh!r}. Point kit_frozen back at it by hand") lost["kit_frozen"] = bpy.data.meshes[lost_mesh] # the way back, by hand, that the refusal names receipt, _ = send("brokkr_kitbash.thaw", object_name="Lost") check("and with the kept mesh put back in kit_frozen it thaws", receipt["status"] == "accepted" and lost.data.name == lost_mesh and not lost.data.use_fake_user, receipt["message"]) send("brokkr_kitbash.freeze", object_name="Lost") bpy.data.meshes.remove(lost["kit_frozen"]) - refused("thaw on a frozen part whose held mesh was removed", "brokkr_kitbash.thaw", {"object_name": "Lost"}, "the live mesh its kit_frozen held is gone") + refused("thaw on a frozen part whose held mesh was removed", "brokkr_kitbash.thaw", {"object_name": "Lost"}, "no kept live mesh names the mesh it carries: there is nothing to thaw to") + + # --- the frozen state has one writer, hold: what it does when the holder goes, by an action or by hand, and what an import may not bring --- + def purge(): + bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True) + + def saved_meshes(name): + """The meshes a save writes, read from the file: a save and reload keeps these and no others.""" + bpy.ops.wm.save_as_mainfile(filepath=str(WORK / name), copy=True) + with bpy.data.libraries.load(str(WORK / name)) as (source, _): + return sorted(source.meshes) + + def kept_state(name): + mesh = bpy.data.meshes.get(name) + return mesh and [mesh.use_fake_user, getattr(mesh.get("kit_kept"), "name", mesh.get("kit_kept"))] + + target.configure_action_dirs(str(WORK), str(WORK)) + gone = place("Gone", "plate", location=[0.0, -27.0, 0.0]) + gone_mesh = gone.data.name + send("brokkr_kitbash.freeze", object_name="Gone") + receipt, _ = send("exportGltf", filepath="gone_applied.glb", applyModifiers=True, selection=["Gone"]) + send("brokkr_kitbash.thaw", object_name="Gone") + check("thaw after an export that applied modifiers leaves no frozen mesh behind", receipt["status"] == "accepted" and "Gone frozen" not in bpy.data.meshes + and gone.data.name == gone_mesh, [receipt["message"], sorted(m.name for m in bpy.data.meshes)]) + send("brokkr_kitbash.freeze", object_name="Gone") + check("freeze gives the live mesh a fake user and kit_kept, a pointer to the frozen mesh; a save writes both", kept_state(gone_mesh) == [True, "Gone frozen"] + and {gone_mesh, "Gone frozen"} <= set(saved_meshes("held.blend")), kept_state(gone_mesh)) + receipt, _ = send("exportGltf", filepath="gone.glb", applyModifiers=False, extras=True, selection=["Gone"]) + exported = receipt["status"] + receipt, _ = send("deleteObject", targetObjectName="Gone") + purge() + check("deleteObject on a frozen object releases its live mesh: a purge takes it and the frozen mesh", receipt["status"] == "accepted" and exported == "accepted" + and gone_mesh not in bpy.data.meshes and "Gone frozen" not in bpy.data.meshes, [kept_state(gone_mesh), sorted(m.name for m in bpy.data.meshes)]) + receipt, _ = send("importGltf", filepath="gone.glb") + back = bpy.data.objects.get("Gone") + check("importGltf drops the kit_* properties a file's extras carry, and says so: the imported object is not frozen and not a part", receipt["status"] == "accepted" + and back is not None and not [key for holder in (back, back.data) for key in holder.keys() if key.startswith("kit_")] + and "Dropped the file's kit_* properties from Gone" in receipt["message"], [receipt["message"], back and dict(back.items())]) + refused("thaw on the imported object", "brokkr_kitbash.thaw", {"object_name": "Gone"}, "'Gone' is not frozen") + send("deleteObject", targetObjectName="Gone") + purge() + plain = place("Plain_gone", "plate", location=[0.0, -30.0, 0.0]) + plain_mesh = plain.data.name + send("brokkr_kitbash.freeze", object_name="Plain_gone") + with bpy.context.temp_override(selected_objects=[plain]): + deleted = bpy.ops.object.delete() + written = saved_meshes("deleted.blend") + purge() + check("a frozen object deleted in Blender, by no action: a save writes neither mesh, and a purge takes both", deleted == {"FINISHED"} and "Plain_gone" not in bpy.data.objects + and plain_mesh not in written and "Plain_gone frozen" not in written and plain_mesh not in bpy.data.meshes and "Plain_gone frozen" not in bpy.data.meshes, + [deleted, written, sorted(m.name for m in bpy.data.meshes)]) + hand = place("Hand", "plate", location=[0.0, -33.0, 0.0]) + hand_mesh = hand.data.name + send("brokkr_kitbash.freeze", object_name="Hand") + del bpy.data.meshes[hand_mesh]["kit_kept"] # by hand + receipt, _ = send("brokkr_kitbash.thaw", object_name="Hand") + check("a kept mesh whose kit_kept was cleared by hand still gives its fake user back at thaw", receipt["status"] == "accepted" and kept_state(hand_mesh) == [False, None] + and hand.data.name == hand_mesh, [receipt["message"], kept_state(hand_mesh)]) + send("brokkr_kitbash.freeze", object_name="Hand") + del hand["kit_frozen"] # by hand: the object still carries the frozen mesh the kept mesh names + purge() + check("a live mesh whose kit_frozen was deleted by hand stays kept through a purge and a save", kept_state(hand_mesh) == [True, "Hand frozen"] + and hand_mesh in saved_meshes("lost.blend"), kept_state(hand_mesh)) + refused("thaw on a frozen part whose kit_frozen was deleted names the kept mesh", "brokkr_kitbash.thaw", {"object_name": "Hand"}, + f"'Hand' carries a frozen mesh and its kit_frozen is gone: freeze kept its live mesh {hand_mesh!r}. Point kit_frozen back at it by hand") + hand["kit_frozen"] = bpy.data.meshes[hand_mesh] + receipt, _ = send("brokkr_kitbash.thaw", object_name="Hand") + check("and with kit_frozen pointed back it thaws and the mesh is released", receipt["status"] == "accepted" and hand.data.name == hand_mesh + and kept_state(hand_mesh) == [False, None] and "Hand frozen" not in bpy.data.meshes, [receipt["message"], kept_state(hand_mesh)]) + target.configure_action_dirs("", str(WORK)) # --- the second target: a plate with no material slot, cut twice ---------------------------------------------------------------------- plate = place("Plate", "plate", location=[0.0, -3.0, 0.0]) diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index c253c90..746ee5a 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1985,9 +1985,14 @@ class OwnershipTests(unittest.TestCase): (bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()"), (bodies["set_params"], "write_mesh("), (bodies["hose"], "write_mesh(")): self.assertLess(body.index("live("), body.index(first_write)) - self.assertEqual((source.count("obj[FROZEN] ="), source.count("del obj[FROZEN]"), source.count("live(")), (1, 1, 8)) # its def and the seven callers above - self.assertIn("obj[FROZEN] =", bodies["freeze"]) - self.assertIn("del obj[FROZEN]", bodies["thaw"]) + self.assertEqual(source.count("live("), 8) # its def and the seven callers above + # the frozen state has one writer: every write of kit_frozen, kit_kept and a fake user is in hold, which swaps the meshes too + hold = source.split("\ndef hold(")[1].split("\n\n\n")[0] + writes = r"\[(?:FROZEN|KEPT)\](?:, obj\.data)? =(?!=)|del \w+\[(?:FROZEN|KEPT)\]|use_fake_user = " + self.assertEqual(re.findall(writes, source), re.findall(writes, hold)) + self.assertEqual(len(re.findall(writes, hold)), 6) + self.assertEqual(("hold(obj, frozen)" in bodies["freeze"], "hold(obj)" in bodies["thaw"], "obj.data =" in bodies["freeze"] + bodies["thaw"]), (True, True, False)) + self.assertEqual(re.findall(r"handlers\.(\w+)", source.split("SETTLED_ON = ")[1].split("\n")[0]),["depsgraph_update_post", "save_pre"]) ribs = bodies["ribs"] # every refusal before the ribs object is written, and the cage's modifiers shown again whatever happened self.assertLess(ribs.rindex("raise Refused("), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)")) self.assertLess(ribs.index("finally:"), ribs.index("modifier.show_viewport = True")) @@ -2111,7 +2116,7 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(assigned, [" obj[CLOSE], obj[CLOSE_TO], obj[CLOSE_TO_SOCKET] = self.socket, other, self.other_socket"]) self.assertIn(assigned[0], bodies["close"]) deleted = re.findall(r"[^\n]*\(SOCKET, PARENT_SOCKET, ROLL, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET\)[^\n]*\n[^\n]*\n\s*del obj\[key\]", source) - self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and thaw's kit_frozen + self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and hold's kit_frozen self.assertEqual(source.count("CLOSE_TO]"), 1) # the one subscript write above; every read goes through .get placing = r"matrix_basis|matrix_world\s*=(?!=)|matrix_parent_inverse|\.parent\s*=(?!=)|\bseat\(|\.location|\.rotation" self.assertIsNone(re.search(placing, bodies["close"])) diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index 874d2b6..8f9de97 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -67,6 +67,15 @@ def fake_render(): return FakeRender() +class Extras(dict): + """An ID with custom properties: a mapping, and the attributes it is given.""" + def __init__(self, properties=(), **attributes): + super().__init__(properties) + self.__dict__.update(attributes) + + __hash__ = object.__hash__ + + class Objects(dict): """bpy.data.objects: a mapping with keys() and get(); like bpy_prop_collection, iterating it yields the objects.""" @@ -89,7 +98,7 @@ class FakeUndo: class FakeBpy: def __init__(self): - self.imported = [] + self.imported, self.import_extras, self.import_mesh_extras = [], {}, {} self.rendered = [] self.scene = NS(name="Scene", camera=None, world=None, render=fake_render()) self.camera_data = NS(lens=50.0, type="PERSP", ortho_scale=6.0, clip_start=0.1, clip_end=100.0, @@ -141,7 +150,7 @@ class FakeBpy: def import_gltf(self, mode, undo, filepath): assert (mode, undo) == ("EXEC_DEFAULT", False) self.imported.append(filepath) - self.data.objects["Imported"] = NS(name="Imported", type="MESH", data=None) + self.data.objects["Imported"] = Extras(self.import_extras, name="Imported", type="MESH", data=Extras(self.import_mesh_extras)) def export_gltf(self, mode, undo, **kwargs): assert (mode, undo) == ("EXEC_DEFAULT", False) @@ -193,6 +202,18 @@ class ActionTests(unittest.TestCase): self.assertEqual(receipt["status"], "accepted") self.assertEqual(self.bpy.imported, [str(self.root / "in" / "model.glb")]) self.assertEqual(receipt["objectName"], "Imported") + self.assertEqual(receipt["message"], "Imported 1 object(s) from model.glb.") + + def test_import_drops_the_kit_properties_a_file_carries(self): + """kit_* is brokkr_kitbash's own state: what setObjectCustomProperty refuses, importGltf does not bring in from extras.""" + self.bpy.import_extras = {"kit_frozen": None, "kit_part": "tank", "kit_params": "{}", "note": "kept", "kitchen": 1} + self.bpy.import_mesh_extras = {"kit_kept": True, "source": "scan"} + receipt = self.run_action(action="importGltf", filepath="model.glb") + imported = self.bpy.data.objects["Imported"] + self.assertEqual((receipt["status"], dict(imported), dict(imported.data)), ("accepted", {"note": "kept", "kitchen": 1}, {"source": "scan"})) + self.assertIn("Dropped the file's kit_* properties from Imported", receipt["message"]) + self.assertEqual(bt.kit_owned("kit_frozen") and bt.kit_owned("kit_anything"), True) + self.assertEqual(bt.kit_owned("kitchen") or bt.kit_owned("akit_x"), False) def test_import_outside_the_import_dir_is_refused_before_bpy(self): for path in ("../secret.glb", str(self.root / "secret.glb"), "/etc/passwd.glb", "sub/../../secret.glb"): @@ -295,7 +316,7 @@ class ActionTests(unittest.TestCase): def test_export_applying_modifiers_refuses_a_frozen_object_with_a_modifier_shown(self): mesh = self.bpy.data.objects["Cube"] mesh.get = lambda key, default=None: "live mesh" if key == "kit_frozen" else default - mesh.modifiers = [NS(show_viewport=False), NS(show_viewport=True)] + mesh.modifiers = [NS(show_viewport=False, show_render=False), NS(show_viewport=True, show_render=False)] for fields in ({}, {"selection": ["Cube"]}): receipt = self.run_action(action="exportGltf", filepath="dirty.glb", **fields) self.assertEqual(receipt["status"], "failed", receipt) @@ -305,6 +326,9 @@ class ActionTests(unittest.TestCase): receipt = self.run_action(action="exportGltf", filepath=f"ok{len(self.bpy.exported)}.glb", **fields) self.assertEqual(receipt["status"], "accepted", receipt) mesh.modifiers[1].show_viewport = False + mesh.modifiers[0].show_render = True # shown in renders only: dirty by the rule brokkr_kitbash's report uses + self.assertIn("with a modifier shown again", self.run_action(action="exportGltf", filepath="render.glb")["message"]) + mesh.modifiers[0].show_render = False self.assertEqual(self.run_action(action="exportGltf", filepath="frozen.glb")["status"], "accepted") def test_export_without_a_selection_never_touches_selection(self): From 2439b23af8bcbafa4a2691d2038950ac30a925f8 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:33:01 +0100 Subject: [PATCH 149/223] kitbash core: a socket type states its dof; mate and residual take a slide; within; aim_roll and reach_roll inside limits check_kit admits socketTypes[..].dof (revolute | prismatic; absent is rigid). mate is S_parent @ T(0, 0, slide) @ Rz(roll) @ FLIP @ inv(S_child). within() is the one rule for a value inside its limits. Two kits mate a type only when match and dof agree. Cut aetheria-release:cut_spec:cut-kit-joint-records.r1. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/core.py | 75 ++++++++++++++++++++----- 1 file changed, 61 insertions(+), 14 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index c298351..345a6ee 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -303,10 +303,12 @@ def check_kit(document: Any) -> dict: for name, entry in document["socketTypes"].items(): where = f"{here} socket type {name!r}" _name(name, where, set()) - _keys(entry, where, ("match", "doc")) + _keys(entry, where, ("match", "doc"), ("dof",)) if entry["match"] not in ("equal", "fits"): raise KitError(f"{where}: match must be 'equal' or 'fits'") - types[name] = {"match": entry["match"], "doc": _text(entry["doc"], f"{where} doc")} + if "dof" in entry and entry["dof"] not in DOFS: + raise KitError(f"{where}: dof must be 'revolute' or 'prismatic' (a type that states none is rigid)") + types[name] = {"match": entry["match"], "doc": _text(entry["doc"], f"{where} doc"), **({"dof": entry["dof"]} if "dof" in entry else {})} parts, part_names = {}, set() for index, part in enumerate(document["parts"]): name = _name(part.get("name") if isinstance(part, dict) else None, f"{here} part {index}", part_names) @@ -1219,19 +1221,44 @@ def surface_frame(point, normal, up, roll_degrees: float = 0.0) -> np.ndarray: 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).""" - return parent_socket["matrix"] @ _roll(roll_degrees) @ FLIP @ np.linalg.inv(child_socket["matrix"]) +def _slid(metres: float) -> np.ndarray: + move = np.eye(4) + move[2, 3] = metres + return move -def residual(parent_world, parent_socket: dict, child_world, child_socket: dict, roll_degrees: float) -> float: +def mate(parent_socket: dict, child_socket: dict, roll_degrees: float = 0.0, slide: float = 0.0) -> np.ndarray: + """The child's 4x4 in its parent's frame that seats child_socket on parent_socket: normals opposed, the child + turned roll_degrees about the parent socket's z (right-handed; at 0 the two ys line up) and its socket's origin + `slide` metres along that z from the parent socket's (0: origins together). A turn about z and a move along it + commute, so one connection carries both.""" + return parent_socket["matrix"] @ _slid(slide) @ _roll(roll_degrees) @ FLIP @ np.linalg.inv(child_socket["matrix"]) + + +def residual(parent_world, parent_socket: dict, child_world, child_socket: dict, roll_degrees: float, slide: float = 0.0) -> float: """How far a child stands from where mate puts it: the largest absolute entry of the difference between the frame its socket should have in the world and the frame it has.""" - wanted = np.asarray(parent_world, dtype=np.float64) @ parent_socket["matrix"] @ _roll(roll_degrees) @ FLIP + wanted = np.asarray(parent_world, dtype=np.float64) @ parent_socket["matrix"] @ _slid(slide) @ _roll(roll_degrees) @ FLIP return float(np.abs(wanted - np.asarray(child_world, dtype=np.float64) @ child_socket["matrix"]).max()) +DOFS = ("revolute", "prismatic") # what a socket type's dof may state: the child turns about the parent socket's z, or slides along it +# How far past an end of its limits a joint's value may stand and still be inside them, as a fraction of the larger +# of 1 and the ends' sizes. A rule: an action's roll and slide are float32 fields and limits are JSON doubles, so a +# value typed as an end of its own limits stands up to 6e-08 of itself off that end; 1e-06 is 17 of those. +LIMIT_SLACK = 1e-6 + + +def within(value: float, lo: float, hi: float, revolute: bool) -> float | None: + """The representative of a joint's value inside its limits [lo, hi], or None when it has none: the value itself + on a prismatic joint; on a revolute one the value itself when it is inside, else value + 360 k, the least at or + above lo. A value within LIMIT_SLACK of an end is that end.""" + slack = LIMIT_SLACK * max(1.0, abs(lo), abs(hi)) + if revolute and not lo - slack <= value <= hi + slack: + value += 360.0 * math.ceil((lo - slack - value) / 360.0) + return min(max(value, lo), hi) if lo - slack <= value <= hi + slack else None + + def roll_terms(parent_world, parent_socket: dict, child_socket: dict, local, w: float, direction) -> tuple[float, float, float]: """(A, B, C) with direction . (the child's `local`, in the world) = A cos(roll) + B sin(roll) + C when the child is mated on parent_socket at that roll. `local` is in the child's own frame: a point with w 1, an axis with w 0. @@ -1263,26 +1290,36 @@ def _wrapped(degrees: float) -> float: return 180.0 - (180.0 - degrees) % 360.0 -def aim_roll(parent_world, parent_socket: dict, child_socket: dict, axis, direction) -> tuple[float, float]: +def aim_roll(parent_world, parent_socket: dict, child_socket: dict, axis, direction, limits=None) -> tuple[float, float]: """(roll in degrees in (-180, 180], the dot it achieves) that turns the child's own `axis` as far toward the world `direction` as its pin lets it: roll = atan2(B, A), dot = C + hypot(A, B), for unit vectors. Refuses an - axis or a direction along the pin (hypot(A, B) at most AIM_FLOOR), which no roll turns.""" + axis or a direction along the pin (hypot(A, B) at most AIM_FLOOR), which no roll turns. With `limits` (lo, hi) + the roll is its representative inside them (within); when the free roll has none, the end of the limits whose + dot is the larger (the dot is a sinusoid of the roll: over an interval of at most a turn it peaks at its + optimum or at an end; a tie takes lo), and the dot is that end's.""" direction = np.asarray(direction, dtype=np.float64) direction = direction / np.linalg.norm(direction) A, B, C = roll_terms(parent_world, parent_socket, child_socket, axis, 0.0, direction) if math.hypot(A, B) <= AIM_FLOOR: raise KitError(f"socket {child_socket['name']!r} on parent socket {parent_socket['name']!r}: the axis {tuple(float(v) for v in axis)} of the part " f"or the direction {tuple(round(float(v), 6) for v in direction)} lies along the pin, so no roll turns one toward the other") - return _wrapped(math.degrees(math.atan2(B, A))), C + math.hypot(A, B) + roll = _wrapped(math.degrees(math.atan2(B, A))) + if limits is None: + return roll, C + math.hypot(A, B) + inside = within(roll, *limits, True) + if inside is not None: + return inside, C + math.hypot(A, B) + return max(((end, A * math.cos(math.radians(end)) + B * math.sin(math.radians(end)) + C) for end in limits), key=lambda found: found[1]) -def reach_roll(parent_world, parent_socket: dict, child_socket: dict, point, direction, height: float, current_roll: float) -> tuple[float, float]: +def reach_roll(parent_world, parent_socket: dict, child_socket: dict, point, direction, height: float, current_roll: float, limits=None) -> tuple[float, float]: """(roll in degrees in (-180, 180], residual |direction . p - height| in metres) that brings the child's own `point` to the plane direction . x = height, for a unit direction: atan2(B, A) +- acos((height - C) / hypot(A, B)), of the two the one nearer current_roll round the circle (a tie takes the smaller roll). A height up to REACH_EDGE past the top or bottom of the circle is taken as the top or bottom. Refuses a height farther out, naming the range the point reaches, and a point no roll moves along the direction (it lies on the pin, or the direction - does).""" + does). With `limits` (lo, hi) only a root with a representative inside them (within) is taken, as that + representative; with none inside it refuses, naming both roots and the limits.""" direction = np.asarray(direction, dtype=np.float64) direction = direction / np.linalg.norm(direction) A, B, C = roll_terms(parent_world, parent_socket, child_socket, point, 1.0, direction) @@ -1295,6 +1332,12 @@ def reach_roll(parent_world, parent_socket: dict, child_socket: dict, point, dir f"it reaches {C - swing:.6f} m to {C + swing:.6f} m") middle, spread = math.degrees(math.atan2(B, A)), math.degrees(math.acos(max(-1.0, min(1.0, (height - C) / swing)))) roots = sorted({_wrapped(middle - spread), _wrapped(middle + spread)}) + if limits is not None: + inside = [found for found in (within(root, *limits, True) for root in roots) if found is not None] + if not inside: + raise KitError(f"{here}: the rolls that bring the point to {height:.6f} m, {' and '.join(f'{root:.6g}' for root in roots)}, are outside " + f"the joint's limits {limits[0]:.6g} to {limits[1]:.6g}") + roots = inside roll = min(roots, key=lambda root: (round(abs(_wrapped(root - current_roll)), 9), root)) return roll, abs(A * math.cos(math.radians(roll)) + B * math.sin(math.radians(roll)) + C - height) @@ -1316,7 +1359,7 @@ def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict, child agree as that type's match says ('equal': within 1 percent of the larger; 'fits': the child at most the parent). kit_types is the socketTypes of the parent's kit. For parts of two kits, child_types is the socketTypes of the child's and `kits` the two kits' names: socket types are a vocabulary kits share, and the two sockets mate only - when the child's kit declares the type with the same match.""" + when the child's kit declares the type with the same match and the same dof.""" p, c = parent_socket, child_socket both = f"socket {c['name']!r} ({c['type']}, size {c['size']:.6g}) and parent socket {p['name']!r} ({p['type']}, size {p['size']:.6g})" if p["type"] != c["type"]: @@ -1325,6 +1368,10 @@ def mate_refusal(kit_types: dict, parent_socket: dict, child_socket: dict, child theirs = child_types.get(c["type"], {}).get("match") return (f"{both}: kit {kits[0]!r} declares socket type {p['type']!r} with match {kit_types[p['type']]['match']!r} and kit {kits[1]!r} " f"{'with match ' + repr(theirs) if theirs else 'does not declare it'}; parts of two kits mate by socket types both declare alike") + if child_types is not None and child_types[c["type"]].get("dof") != kit_types[p["type"]].get("dof"): + ours, theirs = (types[p["type"]].get("dof", "none (rigid)") for types in (kit_types, child_types)) + return (f"{both}: kit {kits[0]!r} declares socket type {p['type']!r} with dof {ours} and kit {kits[1]!r} with dof {theirs}; " + "parts of two kits mate by socket types both declare alike") if kit_types[p["type"]]["match"] == "equal": if abs(p["size"] - c["size"]) > EQUAL * max(p["size"], c["size"]) * (1 + SLACK): return f"{both} are {p['type']} sockets, which mate at equal sizes (within 1 percent)" From ed4d7729eb6aefb1de2fbfcf6c9e2eb33a9a9f9f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:33:01 +0100 Subject: [PATCH 150/223] kits: pivot is revolute; a prismatic slide type; ram_barrel and ram_rod cut from the actuator at its gland Slide 0 is closed and the slide is the extension: a rod of length body_len + 1.1 body_r in its barrel stands as the actuator does. JointRecordTests: slide, within, limits on aim and reach, dof across kits; mutants J1 J2 J3 J4 J6 each die there. Co-Authored-By: Claude Fable 5.2 --- .../blender/brokkr_kitbash/kits/frame.v0.json | 2 +- .../brokkr_kitbash/kits/mechanical.v0.json | 56 ++++- surfaces/blender/tests/test_kitbash.py | 192 +++++++++++++++++- 3 files changed, 245 insertions(+), 5 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/kits/frame.v0.json b/surfaces/blender/brokkr_kitbash/kits/frame.v0.json index e25c7fe..f4848aa 100644 --- a/surfaces/blender/brokkr_kitbash/kits/frame.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/frame.v0.json @@ -4,7 +4,7 @@ "doc": "Chassis structure: sectioned beams, a truss, a portal, a gusset and a wedge, each a section swept along a path. Metres.", "socketTypes": { "mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"}, - "pivot": {"match": "equal", "doc": "pin joint; size is the pin diameter"} + "pivot": {"match": "equal", "dof": "revolute", "doc": "pin joint; size is the pin diameter"} }, "parts": [ { diff --git a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json index 027e85a..325773c 100644 --- a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json @@ -5,7 +5,8 @@ "socketTypes": { "flange": {"match": "equal", "doc": "bolted pipe or duct face; size is the bore diameter"}, "mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"}, - "pivot": {"match": "equal", "doc": "pin joint; size is the pin diameter"}, + "pivot": {"match": "equal", "dof": "revolute", "doc": "pin joint; size is the pin diameter"}, + "slide": {"match": "equal", "dof": "prismatic", "doc": "telescoping bore; size is the bore diameter; the child slides along the socket's z"}, "hose": {"match": "fits", "doc": "hose port; size is the widest bundle it takes"} }, "parts": [ @@ -179,6 +180,59 @@ {"name": "port_rod", "type": "hose", "size": "0.4*body_r", "at": ["1.45*body_r", 0, "2.25*body_r+body_len"], "z": "+x", "y": "+z"} ] }, + { + "name": "ram_barrel", + "doc": "The barrel of a tie-rod hydraulic cylinder, the actuator's up to its gland: base eye on a cross pin with a socket on each end face, square caps, barrel, ports, and a bore a ram_rod slides in.", + "params": [ + {"name": "body_r", "type": "number", "min": 0.05, "max": 0.12, "default": 0.06, "doc": "barrel radius"}, + {"name": "body_len", "type": "number", "min": 0.2, "max": 1.0, "default": 0.4, "doc": "barrel length between caps"}, + {"name": "rod_r", "type": "number", "min": 0.01, "max": 0.02, "default": 0.018, "doc": "radius of the rod its gland takes"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"} + ], + "bevel": "0.04*body_r", + "shapes": [ + {"shape": "box", "size": ["1.2*body_r", "0.9*body_r", "1.6*body_r"], "at": [0, 0, "0.8*body_r"]}, + {"shape": "tube", "r0": "0.45*body_r", "r1": "0.45*body_r", "length": "1.3*body_r", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.65*body_r", "0.8*body_r"]}, + {"shape": "box", "size": ["2.4*body_r", "2.4*body_r", "0.5*body_r"], "at": [0, 0, "1.75*body_r"]}, + {"shape": "tube", "r0": "body_r", "r1": "body_r", "length": "body_len+0.2*body_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.9*body_r"]}, + {"shape": "box", "size": ["2.4*body_r", "2.4*body_r", "0.5*body_r"], "at": [0, 0, "2.25*body_r+body_len"]}, + {"shape": "repeat", "count": 2, "step": ["1.9*body_r", 0, 0], "of": + {"shape": "tube", "r0": "0.12*body_r", "r1": "0.12*body_r", "length": "body_len+1.3*body_r", "segments": 6, "at": ["-0.95*body_r", "-0.95*body_r", "1.35*body_r"]}}, + {"shape": "repeat", "count": 2, "step": ["1.9*body_r", 0, 0], "of": + {"shape": "tube", "r0": "0.12*body_r", "r1": "0.12*body_r", "length": "body_len+1.3*body_r", "segments": 6, "at": ["-0.95*body_r", "0.95*body_r", "1.35*body_r"]}}, + {"shape": "repeat", "count": 2, "step": [0, 0, "body_len+0.5*body_r"], "of": + {"shape": "tube", "r0": "0.2*body_r", "r1": "0.2*body_r", "length": "0.45*body_r", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": ["body_r", 0, "1.75*body_r"]}}, + {"shape": "tube", "r0": "rod_r+0.25*body_r", "r1": "rod_r+0.25*body_r", "length": "0.4*body_r", "segments": "segments", "smooth": true, "at": [0, 0, "2.4*body_r+body_len"]} + ], + "sockets": [ + {"name": "base", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "0.8*body_r"], "z": "+y", "y": "+z"}, + {"name": "base_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "0.8*body_r"], "z": "-y", "y": "+z"}, + {"name": "bore", "type": "slide", "size": "2*rod_r", "at": [0, 0, "2*body_r"], "z": "+z", "y": "+y"}, + {"name": "port_cap", "type": "hose", "size": "0.4*body_r", "at": ["1.45*body_r", 0, "1.75*body_r"], "z": "+x", "y": "+z"}, + {"name": "port_rod", "type": "hose", "size": "0.4*body_r", "at": ["1.45*body_r", 0, "2.25*body_r+body_len"], "z": "+x", "y": "+z"} + ] + }, + { + "name": "ram_rod", + "doc": "The rod of a hydraulic cylinder, the actuator's from its gland: a rod from its piston face to a rod eye on a cross pin with a socket on each end face. Its piston slides in a ram_barrel's bore: slide 0 is closed, the slide is the extension.", + "params": [ + {"name": "body_r", "type": "number", "min": 0.05, "max": 0.12, "default": 0.06, "doc": "its barrel's radius: sizes the rod eye"}, + {"name": "rod_r", "type": "number", "min": 0.01, "max": 0.02, "default": 0.018, "doc": "rod radius"}, + {"name": "length", "type": "number", "min": 0.2, "max": 2.0, "default": 0.466, "doc": "piston face to the rod eye's block; its barrel's body_len + 1.1*body_r stands as the actuator does at extension 0"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"} + ], + "bevel": "0.04*body_r", + "shapes": [ + {"shape": "tube", "r0": "rod_r", "r1": "rod_r", "length": "length+0.2*body_r", "segments": "segments", "smooth": true, "at": [0, 0, 0]}, + {"shape": "box", "size": ["1.2*body_r", "0.9*body_r", "1.4*body_r"], "at": [0, 0, "length+0.7*body_r"]}, + {"shape": "tube", "r0": "0.45*body_r", "r1": "0.45*body_r", "length": "1.3*body_r", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.65*body_r", "length+0.7*body_r"]} + ], + "sockets": [ + {"name": "piston", "type": "slide", "size": "2*rod_r", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "rod_end", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "length+0.7*body_r"], "z": "+y", "y": "+z"}, + {"name": "rod_end_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "length+0.7*body_r"], "z": "-y", "y": "+z"} + ] + }, { "name": "pipe_fitting", "doc": "Flanged tee: a run along +z with a branch along +x at its middle, a reinforced hub and bolted flanges.", diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 746ee5a..626f77a 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -559,21 +559,24 @@ class ParamTests(unittest.TestCase): @unittest.skipIf(np is None, "numpy is not installed") class MechanicalKitTests(unittest.TestCase): - PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "pipe_fitting", "radiator_stack", "vent", "plate", "reducer", "bracket"] + PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "ram_barrel", "ram_rod", "pipe_fitting", "radiator_stack", "vent", "plate", "reducer", "bracket"] @classmethod def setUpClass(cls): cls.kit = core.load_kit("mechanical") - def test_the_kit_is_the_eleven_parts_and_four_socket_types(self): + def test_the_kit_is_the_thirteen_parts_and_five_socket_types(self): self.assertEqual(list(self.kit["parts"]), self.PARTS) - self.assertEqual({k: v["match"] for k, v in self.kit["socketTypes"].items()}, {"flange": "equal", "mount": "fits", "pivot": "equal", "hose": "fits"}) + self.assertEqual({k: (v["match"], v.get("dof")) for k, v in self.kit["socketTypes"].items()}, + {"flange": ("equal", None), "mount": ("fits", None), "pivot": ("equal", "revolute"), "slide": ("equal", "prismatic"), "hose": ("fits", None)}) self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, { "nozzle": [("mount", "flange")], "tank": [("port_a", "flange"), ("port_b", "flange"), ("saddle", "mount"), ("lug_a", "mount"), ("lug_b", "mount"), ("lug_a_back", "mount"), ("lug_b_back", "mount")], "ribbed_cylinder": [("end_a", "flange"), ("end_b", "flange")], "strut": [("end_a", "pivot"), ("end_a_back", "pivot"), ("end_b", "pivot"), ("end_b_back", "pivot")], "actuator": [("base", "pivot"), ("base_back", "pivot"), ("rod_end", "pivot"), ("rod_end_back", "pivot"), ("port_cap", "hose"), ("port_rod", "hose")], + "ram_barrel": [("base", "pivot"), ("base_back", "pivot"), ("bore", "slide"), ("port_cap", "hose"), ("port_rod", "hose")], + "ram_rod": [("piston", "slide"), ("rod_end", "pivot"), ("rod_end_back", "pivot")], "pipe_fitting": [("a", "flange"), ("b", "flange"), ("c", "flange")], "radiator_stack": [("base", "mount")], "vent": [("back", "mount")], "plate": [("back", "mount"), ("front", "mount")], "reducer": [("big", "flange"), ("small", "flange")], "bracket": [("mount", "mount"), ("pivot", "pivot"), ("pivot_back", "pivot")]}) @@ -1409,6 +1412,189 @@ class PoseTests(unittest.TestCase): core.reach_roll(world, sp, sc, [rng.uniform(-1, 1) for _ in range(3)], (world @ sp["matrix"])[:3, 2], 0.0, 0.0) +@unittest.skipIf(np is None, "numpy is not installed") +class JointRecordTests(unittest.TestCase): + """What a connection's joint record rests on in core: the socket type's dof, mate and residual with a slide, + within, and aim_roll and reach_roll inside limits. Bounds sit at the geometric mean of the shipped worst reading + and the least claimed mutant's (lodur:ruling:deterministic-bound-margin); a reading that is exact is asserted + equal.""" + PAIRS = MateTests.PAIRS + SLIDES = (-0.04, 0.025, 0.3) + SLID = 2.4e-8 # metres from the point `slide` along the parent socket's z. shipped 9.7e-16; least mutant 0.6 (J1); separation 6.2e14 + RAM = 1.9e-8 # a socket of barrel and rod against the actuator's. shipped 0, taken as one float step; least mutant 1.6 (J1); separation 7.2e15 + BEATEN = 1.2e-8 # how far a roll inside the limits may pass the dot aim reports. shipped 1.1e-16; least mutant 1.26 (J2), J3 reads 1.99; separation 1.1e16 + + @classmethod + def setUpClass(cls): + cls.kit = core.load_kit("mechanical") + + def slide_readings(self): + """Read from the two world frames, not through core.residual: how far the child socket's origin stands from + the point `slide` along the parent socket's z, the normals, and the residual at the stated slide.""" + rng, parts, worst = random.Random("slide"), self.kit["parts"], {"slid": 0.0, "normal": 0.0, "residual": 0.0} + for parent, parent_params, parent_socket, child, child_params, child_socket in self.PAIRS: + sp, sc = core.joint(parts[parent], core.build(parts[parent], parent_params), parent_socket, + parts[child], core.build(parts[child], child_params), child_socket) + world = np.eye(4) + world[:3, :3] = core._rotation([rng.uniform(-180, 180) for _ in range(3)]) + world[:3, 3] = [rng.uniform(-5, 5) for _ in range(3)] + for roll in (0.0, 30.0, -115.0): + self.assertEqual(core.mate(sp, sc, roll, 0.0).tolist(), core.mate(sp, sc, roll).tolist()) # slide 0 is the mate there was + for slide in self.SLIDES: + placed = world @ core.mate(sp, sc, roll, slide) + a, b = world @ sp["matrix"], placed @ sc["matrix"] + worst["slid"] = max(worst["slid"], float(np.linalg.norm(b[:3, 3] - a[:3, 3] - slide * a[:3, 2]))) + worst["normal"] = max(worst["normal"], float(np.abs(a[:3, 2] + b[:3, 2]).max())) + worst["residual"] = max(worst["residual"], core.residual(world, sp, placed, sc, roll, slide)) + self.assertAlmostEqual(core.residual(world, sp, placed, sc, roll, 0.0), abs(slide) * float(np.abs(a[:3, 2]).max()), places=12) # read at another slide it stands that far off + return worst + + def test_a_slide_stands_the_child_along_the_parent_socket_z(self): + """slide-mates. Mutant J1 (the slide applied after FLIP, so along the child's side of the joint: the child + stands -slide along the parent socket's z).""" + worst = self.slide_readings() + self.assertLess(worst["slid"], self.SLID) + self.assertLess(worst["normal"], MateTests.NORMAL) + self.assertLess(worst["residual"], MateTests.RESIDUAL) + + def ram_reading(self): + parts, worst = self.kit["parts"], 0.0 + for body_r, body_len, extension in ((0.06, 0.4, 0.0), (0.05, 0.2, 0.15), (0.12, 1.0, 0.8), (0.09, 0.55, 0.31)): + barrel = core.build(parts["ram_barrel"], {"body_r": body_r, "body_len": body_len}) + rod = core.build(parts["ram_rod"], {"body_r": body_r, "length": body_len + 1.1 * body_r}) + whole = {s["name"]: s["matrix"] for s in core.build(parts["actuator"], {"body_r": body_r, "body_len": body_len, "extension": extension}).sockets} + sp, sc = core.joint(parts["ram_barrel"], barrel, "bore", parts["ram_rod"], rod, "piston") + self.assertIsNone(core.mate_refusal(self.kit["socketTypes"], sp, sc)) + placed = core.mate(sp, sc, 0.0, extension) + for socket in barrel.sockets: + if socket["name"] != "bore": + worst = max(worst, float(np.abs(socket["matrix"] - whole[socket["name"]]).max())) + for socket in rod.sockets[1:]: + worst = max(worst, float(np.abs(placed @ socket["matrix"] - whole[socket["name"]]).max())) + return worst + + def test_a_rod_in_its_barrel_is_the_actuator_at_that_extension(self): + """slide-mates, on the kit: ram_rod's piston on ram_barrel's bore at slide e puts every socket where the + actuator has it at extension e. Slide 0 is closed. Mutant J1.""" + self.assertEqual([(s["name"], s["type"]) for s in core.build(self.kit["parts"]["ram_barrel"]).sockets], + [("base", "pivot"), ("base_back", "pivot"), ("bore", "slide"), ("port_cap", "hose"), ("port_rod", "hose")]) + self.assertEqual([(s["name"], s["type"]) for s in core.build(self.kit["parts"]["ram_rod"]).sockets], + [("piston", "slide"), ("rod_end", "pivot"), ("rod_end_back", "pivot")]) + self.assertLess(self.ram_reading(), self.RAM) + + def test_a_socket_type_states_its_dof(self): + """dof-by-type, the format. A type states revolute or prismatic or nothing (rigid); anything else is refused + naming the type.""" + doc = document() + doc["socketTypes"] = {"mount": {"match": "fits", "doc": ""}, "pin": {"match": "equal", "doc": "", "dof": "revolute"}, "bore": {"match": "equal", "dof": "prismatic", "doc": ""}} + self.assertEqual({name: entry.get("dof") for name, entry in core.check_kit(doc)["socketTypes"].items()}, {"mount": None, "pin": "revolute", "bore": "prismatic"}) + self.assertNotIn("dof", core.check_kit(doc)["socketTypes"]["mount"]) + for odd in ("hinge", "", None, ["revolute"], "rigid"): + doc["socketTypes"]["pin"]["dof"] = odd + with self.assertRaisesRegex(core.KitError, r"kit 't' socket type 'pin': dof must be 'revolute' or 'prismatic'"): + core.check_kit(doc) + doc["socketTypes"]["pin"] = {"match": "equal", "doc": "", "axis": "z"} + with self.assertRaisesRegex(core.KitError, r"socket type 'pin' has no key 'axis'"): + core.check_kit(doc) + types = {kit: core.load_kit(kit)["socketTypes"] for kit in ("mechanical", "frame", "cutters")} + self.assertEqual({(kit, name): entry["dof"] for kit, found in types.items() for name, entry in found.items() if "dof" in entry}, + {("mechanical", "pivot"): "revolute", ("mechanical", "slide"): "prismatic", ("frame", "pivot"): "revolute"}) + self.assertEqual(core.describe(self.kit, "ram_rod")["socketTypes"]["slide"]["dof"], "prismatic") + + def test_two_kits_mate_a_type_only_when_its_dof_agrees(self): + """dof-by-type, across kits. Mutant J6 (mate_refusal ignores dof across kits): a pivot another kit declares + without dof mates.""" + types, frame = self.kit["socketTypes"], core.load_kit("frame")["socketTypes"] + socket = lambda name, kind, size: {"name": name, "type": kind, "size": size, "matrix": np.eye(4)} # noqa: E731 + self.assertIsNone(core.mate_refusal(frame, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), types, ("frame", "mechanical"))) + self.assertIsNone(core.mate_refusal(types, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), frame, ("mechanical", "frame"))) + rigid = {**types, "pivot": {"match": "equal", "doc": ""}} + self.assertRegex(core.mate_refusal(types, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), rigid, ("mechanical", "odd")), + r"kit 'mechanical' declares socket type 'pivot' with dof revolute and kit 'odd' with dof none \(rigid\); parts of two kits mate by socket types both declare alike") + self.assertRegex(core.mate_refusal(rigid, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), types, ("odd", "mechanical")), + r"kit 'odd' declares socket type 'pivot' with dof none \(rigid\) and kit 'mechanical' with dof revolute") + sliding = {**types, "pivot": {"match": "equal", "doc": "", "dof": "prismatic"}} + self.assertIn("with dof revolute and kit 'odd' with dof prismatic", core.mate_refusal(types, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), sliding, ("mechanical", "odd"))) + self.assertIsNone(core.mate_refusal(rigid, socket("p", "pivot", 0.05), socket("c", "pivot", 0.05), None)) # one kit: its own type + + def test_within_is_the_value_s_representative_inside_the_limits(self): + """limits-everywhere, the one rule. Mutant J2 (within without the 360 k shift): -170 has no representative in + 150..210.""" + self.assertEqual(core.within(190.0, 150.0, 210.0, True), 190.0) + self.assertEqual(core.within(-170.0, 150.0, 210.0, True), 190.0) + self.assertEqual(core.within(550.0, 150.0, 210.0, True), 190.0) + self.assertIsNone(core.within(-170.0, 150.0, 210.0, False)) + self.assertIsNone(core.within(100.0, 150.0, 210.0, True)) + self.assertIsNone(core.within(-100.0, 150.0, 210.0, True)) + self.assertEqual(core.within(180.0, -180.0, 180.0, True), 180.0) # a value inside is itself + self.assertEqual(core.within(-180.0, -180.0, 180.0, True), -180.0) + self.assertEqual(core.within(270.0, -180.0, 180.0, True), -90.0) + self.assertEqual(core.within(-350.0, 0.0, 20.0, True), 10.0) + self.assertEqual(core.within(0.12, 0.0, 0.3, False), 0.12) + self.assertIsNone(core.within(0.31, 0.0, 0.3, False)) + self.assertIsNone(core.within(-0.001, 0.0, 0.3, False)) + self.assertEqual(core.within(float(np.float32(0.3)), 0.0, 0.3, False), 0.3) # a float32 field's 0.3 is 1.2e-08 over: the end + self.assertEqual(core.within(float(np.float32(-20.1)), -20.1, 90.0, True), -20.1) + self.assertEqual(core.within(-1e-7, 0.0, 0.3, False), 0.0) + self.assertIsNone(core.within(0.3 + 3e-6, 0.0, 0.3, False)) # 3 slacks over + + def aim_readings(self): + """Over PoseTests' joints, each under limits drawn about it: how far a roll on a quarter-degree grid inside + the limits passes the dot aim_roll reports there, and how far the reported dot is from the one read back.""" + worst, pose = {"beaten": -math.inf, "read": 0.0, "ends": 0, "cases": 0}, PoseTests() + pose.kit = self.kit + for world, sp, sc, rng in pose.joints("aim-limits"): + for name, axis in core.AXES.items(): + if abs(np.array(axis) @ sc["matrix"][:3, 2]) == 1.0: + continue + d, lo = pose.direction(rng), rng.uniform(-360.0, 300.0) + hi = lo + rng.uniform(5.0, min(360.0, 360.0 - lo)) + roll, dot = core.aim_roll(world, sp, sc, axis, d, (lo, hi)) + turned = lambda r: float(d @ (world @ core.mate(sp, sc, r))[:3, :3] @ np.array(axis)) # noqa: E731 + self.assertTrue(lo <= roll <= hi, (roll, lo, hi)) + worst["read"] = max(worst["read"], abs(dot - turned(roll))) + worst["beaten"] = max(worst["beaten"], max(turned(float(r)) for r in np.arange(lo, hi, 0.25)) - dot) + worst["ends"] += roll in (lo, hi) + worst["cases"] += 1 + return worst + + def test_aim_inside_limits_takes_the_best_roll_they_hold(self): + """limits-everywhere, aim. The free roll's representative when the limits hold one (150..210 and a free roll + of -170: 190), else the end with the larger dot. Mutant J3 (the end nearer the free roll by angle, read along + the line and not round the circle: 100..185 and a free roll of -170 takes 100).""" + ident = {"name": "s", "matrix": np.eye(4)} + toward = lambda roll: (-math.sin(math.radians(roll)), math.cos(math.radians(roll)), 0.0) # noqa: E731 the child's y stands there at that roll + aim = lambda free, limits: tuple(round(v, 9) for v in core.aim_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), toward(free), limits)) # noqa: E731 + self.assertEqual(aim(-170.0, None), (-170.0, 1.0)) + self.assertEqual(aim(-170.0, (150.0, 210.0)), (190.0, 1.0)) + self.assertEqual(aim(-170.0, (100.0, 185.0)), (185.0, round(math.cos(math.radians(5.0)), 9))) + self.assertEqual(aim(-170.0, (-90.0, 20.0)), (-90.0, round(math.cos(math.radians(80.0)), 9))) + self.assertEqual(aim(90.0, (-20.0, 200.0)), (90.0, 1.0)) + self.assertEqual(aim(0.0, (170.0, 190.0)), (170.0, round(math.cos(math.radians(170.0)), 9))) # a tie takes lo + with self.assertRaisesRegex(core.KitError, "lies along the pin"): + core.aim_roll(np.eye(4), ident, ident, (0.0, 0.0, 1.0), (1.0, 0.0, 0.0), (0.0, 90.0)) + worst = self.aim_readings() + self.assertEqual(worst["cases"], 80) + self.assertGreater(worst["ends"], 20) # the limits bind in a share of the cases + self.assertLess(worst["read"], PoseTests.AIMED) + self.assertLess(worst["beaten"], self.BEATEN) + + def test_reach_inside_limits_takes_a_root_they_hold(self): + """limits-everywhere, reach. Mutant J4 (the nearer root whatever the limits).""" + ident = {"name": "s", "matrix": np.eye(4)} + reach = lambda current, limits: tuple(round(v, 9) for v in core.reach_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (1.0, 0.0, 0.0), 0.5, current, limits)) # noqa: E731 + self.assertEqual(reach(0.0, None), (-30.0, 0.0)) # the roots are -30 and -150 + self.assertEqual(reach(0.0, (-160.0, -100.0)), (-150.0, 0.0)) # the nearer root is outside + self.assertEqual(reach(0.0, (200.0, 220.0)), (210.0, 0.0)) # as its representative + self.assertEqual(reach(0.0, (-180.0, 180.0)), (-30.0, 0.0)) # both inside: the nearer + self.assertEqual(reach(-170.0, (-180.0, 180.0)), (-150.0, 0.0)) + self.assertEqual(reach(300.0, (180.0, 360.0)), (330.0, 0.0)) + with self.assertRaisesRegex(core.KitError, r"socket 's' on parent socket 's': the rolls that bring the point to 0\.500000 m, -150 and -30, are outside the joint's limits 0 to 90$"): + reach(0.0, (0.0, 90.0)) + with self.assertRaisesRegex(core.KitError, "it reaches -1.000000 m to 1.000000 m"): + core.reach_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (1.0, 0.0, 0.0), 1.5, 0.0, (0.0, 90.0)) + + @unittest.skipIf(np is None, "numpy is not installed") class StructureTests(unittest.TestCase): """core's sweep, band, crossings, resample and spans: what brokkr_kitbash.ribs builds a frame from. Every reading is From 12e73c9dc3f7911d8b54158d8fb2c1dc113f205d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:41:06 +0100 Subject: [PATCH 151/223] kitbash: joint records on the connection; joint, slide and joints actions; the hose reads its range from the pin's limits A connection's DOF kind is its parent socket's type's. write_connection, the one writer, states kit_slide, kit_min, kit_max, kit_mechanism and kit_compliance, refusing before it writes a record the DOF may not carry and a value with no representative inside the limits. roll, aim and reach stay inside a revolute joint's limits; slide poses a prismatic one; joint states the record; joints reports the tree as brokkr.joints v1 rows with axis and order derived. detach clears the record. Deleted with it: the hose's joint.range key, its shape check and its current-roll refusal. A crossed pin is a revolute connection and its range is that connection's limits; a pin without limits and a slide between the ends are refused. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 307 ++++++++++++++---- .../brokkr_kitbash/brokkr_actions.json | 81 ++++- surfaces/blender/tests/test_kitbash.py | 35 +- 3 files changed, 344 insertions(+), 79 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index d339078..96aeb51 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -71,6 +71,7 @@ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), import contextlib import json import math +import re import bmesh import bpy @@ -88,6 +89,10 @@ from . import core, route KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" SOCKET, PARENT_SOCKET, ROLL = "kit_socket", "kit_parent_socket", "kit_roll" +SLIDE, LIMIT_MIN, LIMIT_MAX, MECHANISM, COMPLIANCE = "kit_slide", "kit_min", "kit_max", "kit_mechanism", "kit_compliance" # a connection's joint record; write_connection is its one writer +RECORD = (SLIDE, LIMIT_MIN, LIMIT_MAX, MECHANISM, COMPLIANCE) +LABEL = r"[a-z0-9_]{1,32}" # a mechanism label +TURN, TRAVEL, HERTZ, DAMPING = 360.0, 10.0, 30.0, 2.0 # what a joint record may state: degrees a revolute joint's limits span and stand from 0, metres a prismatic one's stand from 0, a compliance's hertz and damping ratio FROZEN = "kit_frozen" # on a frozen object: an ID pointer to its live mesh; its presence is the frozen state. hold writes it and nothing else does KEPT = "kit_kept" # on a live mesh a frozen object holds: an ID pointer to that object's frozen mesh, beside the fake user that keeps the live mesh through a purge. hold writes both CLOSE, CLOSE_TO, CLOSE_TO_SOCKET = "kit_close_socket", "kit_close_to", "kit_close_to_socket" @@ -190,13 +195,51 @@ def built_part(obj, kits=None): def link(obj): - """The connection a child states, (its socket, the parent's socket, roll in degrees), or None. The parent is - obj.parent and is stored nowhere else. attach, set_params, detach and every report read it here. A kit_roll - that is not a finite number (written by hand) is roll None: the connection is stated and cannot hold.""" + """The connection a child states, (its socket, the parent's socket, roll in degrees, slide in metres), or None. + The parent is obj.parent and is stored nowhere else. attach, set_params, detach and every report read it here. + A kit_roll or kit_slide that is not a finite number (written by hand) is None: the connection is stated and + cannot hold. An absent kit_slide is 0.""" if SOCKET not in obj: return None - roll = obj.get(ROLL, 0.0) - return str(obj[SOCKET]), str(obj.get(PARENT_SOCKET, "")), float(roll) if core.finite(roll) else None + roll, slide = obj.get(ROLL, 0.0), obj.get(SLIDE, 0.0) + return str(obj[SOCKET]), str(obj.get(PARENT_SOCKET, "")), float(roll) if core.finite(roll) else None, float(slide) if core.finite(slide) else None + + +def dof(parent, parent_socket: dict): + """The DOF kind of a connection on a socket of a part, 'revolute', 'prismatic' or None (rigid): what the + socket's type states in the parent's kit. Nothing else decides it: no part, socket or object name is read.""" + return core.load_kit(str(parent.get(KIT, "")))["socketTypes"][parent_socket["type"]].get("dof") + + +def joint_record(obj) -> dict: + """The joint record a child's connection states, {limits: (lo, hi) or None, mechanism, compliance}: degrees of + its roll on a revolute joint, metres of its slide on a prismatic one. Every report, the joints report, the + poses and hose read it here. A value written by hand that write_connection would not have written reads None.""" + lo, hi, label, spring = obj.get(LIMIT_MIN), obj.get(LIMIT_MAX), obj.get(MECHANISM), None + with contextlib.suppress(ValueError, TypeError): + spring = json.loads(obj.get(COMPLIANCE, "null")) + return {"limits": (float(lo), float(hi)) if core.finite(lo) and core.finite(hi) and lo <= hi else None, + "mechanism": label if isinstance(label, str) and re.fullmatch(LABEL, label) else None, + "compliance": spring if isinstance(spring, dict) and set(spring) == {"hertz", "damping_ratio"} and all(core.finite(v) for v in spring.values()) else None} + + +def record_refusal(kind, socket_type: str, record: dict) -> str | None: + """None when a connection of this DOF kind may carry the record, else why not.""" + limits, spring = record["limits"], record["compliance"] + if kind is None: + return (f"socket type {socket_type!r} states no dof: the connection is rigid and carries no limits, mechanism or compliance" + if any(value is not None for value in record.values()) else None) + if limits is not None and kind == "revolute" and (limits[1] - limits[0] > TURN or max(abs(limits[0]), abs(limits[1])) > TURN): + return f"limits {limits[0]:.6g} to {limits[1]:.6g}: a revolute joint's span at most {TURN:g} degrees, each end within {TURN:g} of 0" + if limits is not None and kind == "prismatic" and max(abs(limits[0]), abs(limits[1])) > TRAVEL: + return f"limits {limits[0]:.6g} to {limits[1]:.6g}: a prismatic joint's stand within {TRAVEL:g} m of 0" + if spring is not None and kind != "prismatic": + return f"compliance is a prismatic joint's (a slide that settles under load): socket type {socket_type!r} is {kind}" + if spring is not None and limits is None: + return "compliance needs limits: the travel the slide settles within" + if spring is not None and not (0.0 < spring["hertz"] <= HERTZ and 0.0 <= spring["damping_ratio"] <= DAMPING): + return f"compliance {spring}: hertz is over 0 and at most {HERTZ:g}, damping_ratio 0 to {DAMPING:g}" + return None def attached(obj) -> list: @@ -256,8 +299,8 @@ def mated(parent, parent_part, parent_built, child, child_part, child_built, sta it: a roll that is not a number, a socket name a part does not have, or sockets core.mate_refusal will not mate. The parts may be of two kits: they mate when both kits declare the socket's type alike. A closure is checked here too (how "closing on"), the part it names as the parent.""" - if stated[2] is None: - raise Refused(f"{child.name!r} on {parent.name!r}: its {ROLL} is not a number: detach it and attach it again; nothing changed.") + if stated[2] is None or stated[3] is None: + raise Refused(f"{child.name!r} on {parent.name!r}: its {ROLL if stated[2] is None else SLIDE} is not a number: detach it and attach it again; nothing changed.") try: sockets = core.joint(parent_part, parent_built, stated[1], child_part, child_built, stated[0]) kits = (parent_part["kit"], child_part["kit"]) @@ -276,33 +319,66 @@ def seat(child, basis) -> None: child.matrix_basis = Matrix(np.asarray(basis).tolist()) -def write_connection(child, parent, sockets, stated) -> None: - """State a connection and seat it: the child's parent, its derived matrix_basis and its three properties. - `sockets` is mated()'s answer for `stated`. attach, roll, aim and reach write a connection here and nowhere - else.""" +def write_connection(child, parent, sockets, stated, record=None) -> None: + """State a connection and seat it: the child's parent, its derived matrix_basis, its three properties and its + joint record. `sockets` is mated()'s answer for `stated`; `record` is the joint record to state (joint_record's + shape), None to keep the one the child states. attach, roll, aim, reach, slide and joint write a connection + here and nowhere else, so what a joint record may be is decided here: before anything is written it refuses a + record its DOF kind may not carry (record_refusal), a slide on a connection that is not prismatic, and a value + with no representative inside the limits (core.within), naming value and limits; the value written is that + representative.""" + kind, (socket, parent_socket, roll, slide) = dof(parent, sockets[0]), stated + record, here = joint_record(child) if record is None else record, f"{child.name!r} on {parent.name!r}" + refusal = record_refusal(kind, sockets[0]["type"], record) + if refusal is None and kind != "prismatic" and slide != 0.0: + refusal = f"socket type {sockets[0]['type']!r} is {kind or 'rigid'}: only a prismatic connection slides" + if refusal is None and record["limits"] is not None: + value = roll if kind == "revolute" else slide + inside = core.within(value, *record["limits"], kind == "revolute") + if inside is None: + refusal = (f"its {'roll' if kind == 'revolute' else 'slide'} {value:.6g} is outside the joint's limits " + f"{record['limits'][0]:.6g} to {record['limits'][1]:.6g}") + roll, slide = (inside, slide) if kind == "revolute" else (roll, inside) + if refusal: + raise Refused(f"{here}: {refusal}; nothing changed.") child.parent = parent - seat(child, core.mate(*sockets, stated[2])) - child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated + seat(child, core.mate(*sockets, roll, slide)) + child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll + lo, hi = record["limits"] or (None, None) + for key, value in ((SLIDE, slide if kind == "prismatic" else None), (LIMIT_MIN, lo), (LIMIT_MAX, hi), (MECHANISM, record["mechanism"]), + (COMPLIANCE, record["compliance"] and json.dumps(record["compliance"], sort_keys=True))): + if value is not None: + child[key] = value + elif key in child: + del child[key] def connection_report(obj, part, built): """None for a part that states no connection, else what it states and whether it holds: the parent is a kit part, both sockets exist, the roll is a number, the parent inverse is the identity and the child stands within HELD of core.mate. A child moved or re-parented by another action reads holds false until - set_params seats it again.""" + set_params seats it again. With it the joint record: dof (the parent socket's type's: revolute, prismatic or + null for rigid), slide, limits, mechanism, compliance, and within, false only for a value written by hand + outside its limits.""" stated = link(obj) if stated is None: return None + record = joint_record(obj) row = {"parent": obj.parent.name if obj.parent else None, "socket": stated[0], "parentSocket": stated[1], - "roll": None if stated[2] is None else round(stated[2], 6), "residual": None, "holds": False} + "roll": None if stated[2] is None else round(stated[2], 6), "residual": None, "holds": False, + "dof": None, "slide": None if stated[3] is None else round(stated[3], 6), "limits": record["limits"] and [round(v, 6) for v in record["limits"]], + "mechanism": record["mechanism"], "compliance": record["compliance"], "within": True} try: - if obj.parent is None or stated[2] is None: + if obj.parent is None or stated[2] is None or stated[3] is None: return row parent_part, parent_built = built_part(obj.parent) parent_socket, socket = core.joint(parent_part, parent_built, stated[1], part, built, stated[0]) + row["dof"] = dof(obj.parent, parent_socket) except (Refused, core.KitError): return row - row["residual"] = round(core.residual(obj.parent.matrix_world, parent_socket, obj.matrix_world, socket, stated[2]), 9) + if record["limits"] is not None and row["dof"] is not None: + row["within"] = core.within(stated[2] if row["dof"] == "revolute" else stated[3], *record["limits"], row["dof"] == "revolute") is not None + row["residual"] = round(core.residual(obj.parent.matrix_world, parent_socket, obj.matrix_world, socket, stated[2], stated[3]), 9) row["holds"] = bool(np.abs(np.array(obj.matrix_parent_inverse) - np.eye(4)).max() <= HELD and row["residual"] <= HELD) return row @@ -638,18 +714,18 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored)) closing = closure(obj) # a closure this part is an end of must still be one its new sockets may make; where they stand is only reported if closing is not None and closing[1] is not None: - mated(closing[1], *built_part(closing[1]), obj, part, built, (closing[0], closing[2], 0.0), "closing on") + mated(closing[1], *built_part(closing[1]), obj, part, built, (closing[0], closing[2], 0.0, 0.0), "closing on") for other in closing_on(obj): - mated(obj, part, built, other, *built_part(other), (closure(other)[0], closure(other)[2], 0.0), "closing on") + mated(obj, part, built, other, *built_part(other), (closure(other)[0], closure(other)[2], 0.0, 0.0), "closing on") seats, stated = [], link(obj) # every connection this part is an end of, checked against its new sockets before anything is written if stated is not None: if obj.parent is None: raise Refused(f"{obj.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.") parent_part, parent_built = built_part(obj.parent) - seats.append((obj, core.mate(*mated(obj.parent, parent_part, parent_built, obj, part, built, stated), stated[2]))) + seats.append((obj, core.mate(*mated(obj.parent, parent_part, parent_built, obj, part, built, stated), *stated[2:]))) for child in attached(obj): child_part, child_built = built_part(child) - seats.append((child, core.mate(*mated(obj, part, built, child, child_part, child_built, link(child)), link(child)[2]))) + seats.append((child, core.mate(*mated(obj, part, built, child, child_part, child_built, link(child)), *link(child)[2:]))) try: old = core.build(part, stored) except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by @@ -698,11 +774,11 @@ class BROKKR_KITBASH_OT_attach(PolishOperator): if ancestor == child: raise Refused(f"{parent.name!r} is below {child.name!r}: attaching {child.name!r} to it would close a loop; nothing changed.") ancestor = ancestor.parent - stated = (self.socket, self.parent_socket, float(self.roll)) + stated = (self.socket, self.parent_socket, float(self.roll), 0.0) sockets = mated(parent, parent_part, parent_built, child, part, built, stated) free(parent, self.parent_socket) free(child, self.socket) - write_connection(child, parent, sockets, stated) + write_connection(child, parent, sockets, stated, {"limits": None, "mechanism": None, "compliance": None}) # a new connection states no joint record: brokkr_kitbash.joint gives it one context.view_layer.update() return part_report(child, part, built) @@ -724,18 +800,20 @@ class BROKKR_KITBASH_OT_detach(PolishOperator): world = obj.matrix_world.copy() obj.parent = None obj.matrix_world = world - for key in (SOCKET, PARENT_SOCKET, ROLL, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET): + for key in (SOCKET, PARENT_SOCKET, ROLL, *RECORD, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET): if key in obj: del obj[key] return part_report(obj, part, built) def pose(context, name: str, solve) -> dict: - """Give an attached part a new roll where it hangs: its parent and both sockets stay, and what is attached to - it follows. `solve(child, built, sockets, stated)` answers (the roll, what to add to the report), or refuses. - Refuses a part that states no connection or has no parent, and what mated() refuses. The report is the part's - and, as set_params', every closure in the scene with the part's own first: a roll can open one, and never - seats one.""" + """Give an attached part a new roll, slide or joint record where it hangs: its parent and both sockets stay, and + what is attached to it follows. `solve(child, built, sockets, stated, joint)` answers (the roll, the slide, what + to add to the report, the joint record to state or None to keep it), or refuses; `joint` is the record the + connection states with its `dof` and the parent socket's `type`. Refuses a part that states no connection or + has no parent, what mated() refuses and what write_connection does: a value outside the joint's limits. The + report is the part's and, as set_params', every closure in the scene with the part's own first: a pose can open + one, and never seats one.""" child = mesh_object(name) part, built = built_part(child) stated = link(child) @@ -745,10 +823,10 @@ def pose(context, name: str, solve) -> dict: raise Refused(f"{child.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.") sockets = mated(child.parent, *built_part(child.parent), child, part, built, stated) try: - roll, solved = solve(child, built, sockets, stated) + roll, slide, solved, record = solve(child, built, sockets, stated, {**joint_record(child), "dof": dof(child.parent, sockets[0]), "type": sockets[0]["type"]}) except core.KitError as error: raise Refused(f"{child.name!r} on {child.parent.name!r}: {error}; nothing changed.") from None - write_connection(child, child.parent, sockets, (stated[0], stated[1], float(roll))) + write_connection(child, child.parent, sockets, (stated[0], stated[1], float(roll), float(slide)), record) context.view_layer.update() report = {**part_report(child, part, built), **solved} report["closures"] = scene_closures(context, report, (child,)) @@ -774,7 +852,7 @@ class BROKKR_KITBASH_OT_roll(PolishOperator): @kit_work def work(self, context): - return pose(context, self.object_name, lambda child, built, sockets, stated: (self.roll, {})) + return pose(context, self.object_name, lambda child, built, sockets, stated, joint: (self.roll, stated[3], {}, None)) class BROKKR_KITBASH_OT_aim(PolishOperator): @@ -791,9 +869,9 @@ class BROKKR_KITBASH_OT_aim(PolishOperator): @kit_work def work(self, context): - def solve(child, built, sockets, stated): - roll, dot = core.aim_roll(child.parent.matrix_world, *sockets, core.AXES[self.axis], unit(self)) - return roll, {"aimed": {"roll": round(roll, 6), "dot": round(dot, 9)}} + def solve(child, built, sockets, stated, joint): + roll, dot = core.aim_roll(child.parent.matrix_world, *sockets, core.AXES[self.axis], unit(self), joint["limits"] if joint["dof"] == "revolute" else None) + return roll, stated[3], {"aimed": {"roll": round(roll, 6), "dot": round(dot, 9)}}, None return pose(context, self.object_name, solve) @@ -812,15 +890,109 @@ class BROKKR_KITBASH_OT_reach(PolishOperator): @kit_work def work(self, context): - def solve(child, built, sockets, stated): + def solve(child, built, sockets, stated, joint): found = [s for s in built.sockets if s["name"] == self.socket] if not found: raise Refused(f"{child.name!r} has no socket {self.socket!r}; its sockets: {', '.join(s['name'] for s in built.sockets)}; nothing changed.") - roll, residual = core.reach_roll(child.parent.matrix_world, *sockets, found[0]["matrix"][:3, 3], unit(self), self.height, stated[2]) - return roll, {"reached": {"roll": round(roll, 6), "residual": round(residual, 9)}} + roll, residual = core.reach_roll(child.parent.matrix_world, *sockets, found[0]["matrix"][:3, 3], unit(self), self.height, stated[2], + joint["limits"] if joint["dof"] == "revolute" else None) + return roll, stated[3], {"reached": {"roll": round(roll, 6), "residual": round(residual, 9)}}, None return pose(context, self.object_name, solve) +class BROKKR_KITBASH_OT_joint(PolishOperator): + """State the joint record of an attached kit part's connection: its limits, a mechanism label and, on a slide, + its compliance""" + bl_idname = "brokkr_kitbash.joint" + bl_label = "State Kit Joint" + object_name: bpy.props.StringProperty(name="Object", description="An attached part on a revolute or prismatic socket") + record: bpy.props.StringProperty(name="Record", default="{}", description="A JSON object of any of limits ([lo, hi] or null), mechanism (a label or null), " + "compliance ({hertz, damping_ratio} or null); a key left out keeps what is stated, null clears it") + + @kit_work + def work(self, context): + try: + given = json.loads(self.record) + except ValueError as error: + raise Refused(f"record must be JSON ({error}); nothing changed.") from None + limits, label, spring = (given.get(key) for key in ("limits", "mechanism", "compliance")) if isinstance(given, dict) else (None, None, None) + if (not isinstance(given, dict) or not set(given) <= {"limits", "mechanism", "compliance"} + or not (limits is None or isinstance(limits, list) and len(limits) == 2 and all(core.finite(v) for v in limits) and limits[0] <= limits[1]) + or not (label is None or isinstance(label, str) and re.fullmatch(LABEL, label)) + or not (spring is None or isinstance(spring, dict) and set(spring) == {"hertz", "damping_ratio"} and all(core.finite(v) for v in spring.values()))): + raise Refused("record must be a JSON object of any of limits ([lo, hi], lo at most hi, or null), mechanism (1 to 32 of a-z, 0-9 and _, or null) and " + "compliance ({hertz, damping_ratio} or null); nothing changed.") + + def solve(child, built, sockets, stated, joint): + if joint["dof"] is None: + raise Refused(f"{child.name!r} on {child.parent.name!r}: socket type {joint['type']!r} states no dof: the connection is rigid and carries no joint record; nothing changed.") + record = {key: joint[key] for key in ("limits", "mechanism", "compliance")} + if "limits" in given: + record["limits"] = limits and (float(limits[0]), float(limits[1])) + if "mechanism" in given: + record["mechanism"] = label + if "compliance" in given: + record["compliance"] = spring and {key: float(spring[key]) for key in ("hertz", "damping_ratio")} + return stated[2], stated[3], {}, record + return pose(context, self.object_name, solve) + + +class BROKKR_KITBASH_OT_slide(PolishOperator): + """Slide an attached kit part along its parent socket's normal, in place, on a prismatic connection: its parent + and sockets stay and what hangs from it follows""" + bl_idname = "brokkr_kitbash.slide" + bl_label = "Slide Kit Part" + object_name: bpy.props.StringProperty(name="Object", description="A part attached on a prismatic socket") + slide: bpy.props.FloatProperty(name="Slide", default=0.0, min=-10.0, max=10.0, precision=4, + description="Metres along the parent socket's normal from where the two sockets' origins meet") + + @kit_work + def work(self, context): + def solve(child, built, sockets, stated, joint): + if joint["dof"] != "prismatic": + raise Refused(f"{child.name!r} on {child.parent.name!r}: socket type {joint['type']!r} is {joint['dof'] or 'rigid'}: slide poses a prismatic connection" + f"{' (roll, aim and reach turn this one)' if joint['dof'] else ''}; nothing changed.") + return stated[2], self.slide, {}, None + return pose(context, self.object_name, solve) + + +class BROKKR_KITBASH_OT_joints(PolishOperator): + """Report the joints of the tree of kit parts under a root: each revolute or prismatic connection with its + parent joint, axis, value, limits, mechanism and compliance, in the root's frame""" + bl_idname = "brokkr_kitbash.joints" + bl_label = "Report Kit Joints" + bl_options = {"REGISTER"} + object_name: bpy.props.StringProperty(name="Object", description="The root: a kit part; the report is of what is attached below it") + + @kit_work + def work(self, context): + root, kits, rows, rigid_count = mesh_object(self.object_name), {}, [], 0 + built_part(root, kits) + frame = np.linalg.inv(np.array(root.matrix_world, dtype=np.float64)) + todo = [(child, None) for child in sorted(attached(root), key=lambda o: o.name, reverse=True)] + while todo: # depth first, children by name: a joint's parent joint is the nearest DOF connection above it, and rigid connections fold into it + child, above = todo.pop() + part, built = built_part(child, kits) + stated = link(child) + parent_socket, _ = mated(child.parent, *built_part(child.parent, kits), child, part, built, stated) + kind = dof(child.parent, parent_socket) + if kind is None: + rigid_count += 1 + else: + record, value = joint_record(child), stated[2] if kind == "revolute" else stated[3] + at = frame @ np.array(child.parent.matrix_world, dtype=np.float64) @ parent_socket["matrix"] + limits = record["limits"] and [round(v, 6) for v in record["limits"]] + rows.append({"id": child.name, "parent": above, "part": part["name"], "socket": f"{child.parent.name}:{stated[1]}", "kind": kind, + "axis": [round(float(v), 6) for v in at[:3, 2]], "origin": [round(float(v), 6) for v in at[:3, 3]], "value": round(value, 6), + "limits": limits, "min": limits and round(record["limits"][0] - value, 6), "max": limits and round(record["limits"][1] - value, 6), + "mechanism": record["mechanism"], "compliance": record["compliance"]}) + above = child.name + todo += [(below, above) for below in sorted(attached(child), key=lambda o: o.name, reverse=True)] + report = {"schema": "brokkr.joints", "version": 1, "root": root.name, "frame": "the root object's: Blender axes (+Z up), metres", "rigid": rigid_count} + report["joints"] = fitted(report, "joints", rows) + return report + + class BROKKR_KITBASH_OT_close(PolishOperator): """State that a socket of a kit part meets a socket of another part, of its kit or of any kit whose socket types agree, closing a loop the tree of connections cannot: accepted only when the two already meet, origins together and normals opposed, and it @@ -841,7 +1013,7 @@ class BROKKR_KITBASH_OT_close(PolishOperator): raise Refused(f"{obj.name!r} cannot close on itself; nothing changed.") if closure(obj) is not None: raise Refused(f"{obj.name!r} already states a closure (its socket {closure(obj)[0]!r}): a part states one, and detach clears it; nothing changed.") - there, here = mated(other, other_part, other_built, obj, part, built, (self.socket, self.other_socket, 0.0), "closing on") + there, here = mated(other, other_part, other_built, obj, part, built, (self.socket, self.other_socket, 0.0, 0.0), "closing on") free(other, self.other_socket) free(obj, self.socket) apart = core.closure_residual(other.matrix_world, there, obj.matrix_world, here) @@ -1542,7 +1714,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): step: bpy.props.FloatProperty(name="Step", default=0.02, min=0.0049, max=0.2, description="Voxel size of the search") sag: bpy.props.FloatProperty(name="Sag", default=1.0, min=0.0, max=8.0, description="How far the middle of each free span hangs, in outside diameters; 0: taut") clamps: bpy.props.StringProperty(name="Clamps", default="[]", description="A JSON array of up to 8 {socket: 'Object:socket'}, mount sockets, in order along the hose") - joint: bpy.props.StringProperty(name="Joint", default="", description="Empty, or a JSON object {socket, standoff, range: [lo, hi]}: the pin the hose crosses") + joint: bpy.props.StringProperty(name="Joint", default="", description="Empty, or a JSON object {socket, standoff}: the pin the hose crosses; its roll range is that connection's limits") # the action table states radius from 0.003 and step from 0.005: a float property rounds those up, so its bounds stand just under @kit_work @@ -1565,10 +1737,13 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): "use fewer or thinner hoses, a smaller spread, or a larger port; nothing changed.") clamp_rows, joint = self.rows() clamps = [self.frame(context, row, f"clamps[{index}]", ("mount",), kits) for index, row in enumerate(clamp_rows)] - pins, pin = self.crossed(start["object"], end["object"], kits), None + (pins, slides), pin = self.crossed(start["object"], end["object"], kits), None + if slides: + raise Refused(f"The hose crosses the slide of {slides[0][0].name!r} on {slides[0][0].parent.name!r} (socket {slides[0][1]['name']!r}): a hose across a prismatic " + "connection is not routed; end it on a part on this side of the slide; nothing changed.") if joint is None and pins: - raise Refused(f"The hose crosses the pin of {pins[0][0].name!r} on {pins[0][0].parent.name!r} (socket {pins[0][1]['name']!r}): give joint, a socket on that pin's axis, " - "a standoff and the roll range; nothing changed.") + raise Refused(f"The hose crosses the pin of {pins[0][0].name!r} on {pins[0][0].parent.name!r} (socket {pins[0][1]['name']!r}): give joint, a socket on that pin's axis " + "and a standoff; nothing changed.") if joint is not None and len(pins) != 1: raise Refused(("joint is given and the hose crosses no pin: its ends are on parts no pivot connection stands between" if not pins else f"The hose crosses {len(pins)} pins ({', '.join(repr(child.name) + ' on ' + repr(child.parent.name) for child, _, _ in pins)}): a hose crosses one; " @@ -1584,13 +1759,19 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): if off > 1e-6 or lean > 1e-6: raise Refused(f"joint.socket {on['name']!r} is not on the axis of the pin the hose crosses ({child.name!r} on {child.parent.name!r}, socket {socket['name']!r}): " f"its origin stands {off:.6g} m off the axis and its z leans {math.degrees(math.asin(min(1.0, lean))):.6g} degrees from it; nothing changed.") - if not joint["range"][0] - 1e-9 <= current <= joint["range"][1] + 1e-9: - raise Refused(f"{child.name!r} stands at roll {current:.6g}, outside joint.range {joint['range']}: the range holds the pose the hose is routed at; nothing changed.") + limits = joint_record(child)["limits"] # the roll range the hose is proven over is the pin's own: its connection's limits + if limits is None: + raise Refused(f"{child.name!r} on {child.parent.name!r}: the pin the hose crosses states no limits: brokkr_kitbash.joint gives it the roll range " + "the hose is proven over; nothing changed.") + if core.within(current, *limits, True) is None: + raise Refused(f"{child.name!r} stands at roll {current:.6g}, outside its joint's limits {limits[0]:.6g} to {limits[1]:.6g}: roll it inside them, or state " + "limits that hold it (brokkr_kitbash.joint); nothing changed.") + current = core.within(current, *limits, True) sides = [child in self.chain(stop["object"]) for stop in (start, *clamps, end)] changes = [index for index in range(len(sides) - 1) if sides[index] != sides[index + 1]] if len(changes) != 1: raise Refused(f"clamps cross the pin of {child.name!r} {len(changes)} times: list them in order along the hose, those on the start's side of the pin first; nothing changed.") - pin = {"origin": axis[:3, 3], "axis": axis[:3, 2], "current": current, "before": changes[0], "child": child, "child_first": sides[0], + pin = {"origin": axis[:3, 3], "axis": axis[:3, 2], "current": current, "limits": limits, "before": changes[0], "child": child, "child_first": sides[0], "point": on["matrix"][:3, 3] + on["matrix"][:3, 2] * joint["standoff"]} rest, moved, through = self.trees(start["depsgraph"], hose, pin and pin["child"], kits) reach = need + 2.0 * floor + self.step @@ -1700,7 +1881,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): "depsgraph": evaluable(context, obj)[0]} def rows(self): - """(the clamps' 'Object:socket' texts, the joint as {socket, standoff, range} or None), each refused by shape.""" + """(the clamps' 'Object:socket' texts, the joint as {socket, standoff} or None), each refused by shape.""" try: clamps, joint = json.loads(self.clamps or "[]"), json.loads(self.joint) if self.joint else None except ValueError as error: @@ -1711,29 +1892,28 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): if not isinstance(row, dict) or set(row) != {"socket"} or not isinstance(row["socket"], str): raise Refused(f"clamps[{index}] must be an object of socket, an 'Object:socket' text; nothing changed.") if joint is not None: - span = joint.get("range") if isinstance(joint, dict) else None - if (not isinstance(joint, dict) or set(joint) != {"socket", "standoff", "range"} or not isinstance(joint["socket"], str) - or not (core.finite(joint["standoff"]) and 0.0 <= joint["standoff"] <= 10.0) - or not (isinstance(span, list) and len(span) == 2 and all(core.finite(v) and -360.0 <= v <= 360.0 for v in span) and 0.0 <= span[1] - span[0] <= 360.0)): - raise Refused("joint must be an object of socket (an 'Object:socket' text), standoff (0 to 10) and range ([lo, hi] in degrees, lo to hi at most 360, each within 360 of 0); nothing changed.") + if (not isinstance(joint, dict) or set(joint) != {"socket", "standoff"} or not isinstance(joint["socket"], str) + or not (core.finite(joint["standoff"]) and 0.0 <= joint["standoff"] <= 10.0)): + raise Refused("joint must be an object of socket (an 'Object:socket' text) and standoff (0 to 10): the pin's roll range is its connection's limits " + "(brokkr_kitbash.joint); nothing changed.") return [row["socket"] for row in clamps], joint - def crossed(self, start, end, kits) -> list: - """The pins between two objects, [(child, the parent's pivot socket, roll)]: a connection is a child's parent - pointer and its kit_parent_socket (link), and it is a pin when that socket is a pivot. Read along both parent - chains up to the first object they share; with none shared, along both whole chains.""" + def crossed(self, start, end, kits) -> tuple: + """(the pins, the slides) between two objects, each [(child, the parent's socket, roll)]: a connection is a + child's parent pointer and its kit_parent_socket (link); it is a pin when that socket's type states dof + revolute in the parent's kit and a slide when it states prismatic. Read along both parent chains up to the + first object they share; with none shared, along both whole chains.""" up, down = self.chain(start), self.chain(end) shared = [obj for obj in up if obj in down] between = up[:up.index(shared[0])] + down[:down.index(shared[0])] if shared else up + down - pins = [] + found = {"revolute": [], "prismatic": [], None: []} for child in between: stated = link(child) if stated is None or child.parent is None or PART not in child.parent: continue - socket = [s for s in built_part(child.parent, kits)[1].sockets if s["name"] == stated[1] and s["type"] == "pivot"] - if socket: - pins.append((child, socket[0], stated[2])) - return pins + for socket in (s for s in built_part(child.parent, kits)[1].sockets if s["name"] == stated[1]): + found[dof(child.parent, socket)].append((child, socket, stated[2])) + return found["revolute"], found["prismatic"] def trees(self, depsgraph, hose, child, kits): """(a tree of every mesh the depsgraph evaluates but this hose, the pin's child side and the hoses through @@ -1829,7 +2009,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): before, after = before / np.linalg.norm(before), after / np.linalg.norm(after) if pin["child_first"]: # read from the parent's side, as route.passes turns it before, after = -after, -before - low, high = (v - pin["current"] for v in sized["joint"]["range"]) + low, high = (v - pin["current"] for v in pin["limits"]) least[j - 1] = sized["floor"] * math.tan(min(route.sharpest_turn(before, after, pin["axis"], low, high), route.STIFF) / 2.0) return np.where(clamped, sized["kept"], 0.0), clamped, least @@ -1879,7 +2059,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): if pin is not None: j, order = tags.index("J"), slice(None, None, -1) if pin["child_first"] else slice(None) # passes reads a polyline from the parent's side swing = route.passes(points[order], made.t[order], (len(points) - 1 - j) if pin["child_first"] else j, pin["origin"], pin["axis"], - route.rolls_of(sized["joint"]["range"][0], sized["joint"]["range"][1], ROLL_STEP), ROLL_FINEST, pin["current"], sized["far_rest"], sized["far_moved"], + route.rolls_of(pin["limits"][0], pin["limits"][1], ROLL_STEP), ROLL_FINEST, pin["current"], sized["far_rest"], sized["far_moved"], sized["need"], sized["floor"], sized["exempt"], keep=keep[order]) return made.curve, made, sagged, clearance, swing @@ -1950,6 +2130,7 @@ class BROKKR_KITBASH_OT_report(PolishOperator): classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report, BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach, + BROKKR_KITBASH_OT_joint, BROKKR_KITBASH_OT_slide, BROKKR_KITBASH_OT_joints, BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_freeze, BROKKR_KITBASH_OT_thaw, BROKKR_KITBASH_OT_ribs, BROKKR_KITBASH_OT_shell, BROKKR_KITBASH_OT_hose) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 4ea390e..e0d6282 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -93,7 +93,7 @@ }, { "name": "brokkr_kitbash.report", - "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds) and frozen. faces counts the live mesh; a frozen part adds evaluated {faces}, and dirty (the modifiers shown again by hand, with frozen false). Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.", + "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world 4x4, the connection (parent, sockets, roll, residual, holds, and its joint record: dof, slide, limits, mechanism, compliance, within) and frozen. faces counts the live mesh; a frozen part adds evaluated {faces}, and dirty (the modifiers shown again by hand, with frozen false). Evaluates no modifier. Refuses a part scaled in the world: resize with set_params.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", @@ -109,7 +109,7 @@ }, { "name": "brokkr_kitbash.attach", - "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.", + "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. The connection's DOF is its parent socket's type's (revolute, prismatic or rigid); it starts with no joint record: brokkr_kitbash.joint states one. Reports the child with its connection.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -176,7 +176,7 @@ }, { "name": "brokkr_kitbash.roll", - "doc": "Turn an attached kit part to a roll about its parent socket's normal, in place: its parent and both sockets stay, and what is attached to it follows. Refuses a part that is not attached. Reports the part and closures, every closure in the scene as {part, to, holds}, its own first: a roll can open one and never seats one.", + "doc": "Turn an attached kit part to a roll about its parent socket's normal, in place: its parent and both sockets stay, and what is attached to it follows. Refuses a part that is not attached and, on a revolute joint with limits, a roll with no turn of itself inside them (the roll written is the one inside). Reports the part and closures, every closure in the scene as {part, to, holds}, its own first: a roll can open one and never seats one.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -201,7 +201,7 @@ }, { "name": "brokkr_kitbash.aim", - "doc": "Turn an attached kit part about its pin until one of its own axes points as near a world direction as the pin lets it. The roll is solved exactly, not searched. Refuses an axis or a direction that lies along the pin (within about 0.06 degrees), and a zero direction. Reports the part, aimed: {roll, dot} (dot 1 when the axis reaches the direction) and closures as roll does.", + "doc": "Turn an attached kit part about its pin until one of its own axes points as near a world direction as the pin lets it. The roll is solved exactly, not searched. On a revolute joint with limits the roll stays inside them: where the free roll is outside, the end of the limits that points the axis nearer. Refuses an axis or a direction that lies along the pin (within about 0.06 degrees), and a zero direction. Reports the part, aimed: {roll, dot} (dot 1 when the axis reaches the direction) and closures as roll does.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -254,7 +254,7 @@ }, { "name": "brokkr_kitbash.reach", - "doc": "Turn an attached kit part about its pin until one of its sockets' origins stands at a height along a world direction (by default world z): of the two rolls that do it, the one nearer the roll it has. Solved exactly. Refuses a height the socket cannot reach, naming the range it can (either end of the range is taken), and a socket that lies on the pin. Reports the part, reached: {roll, residual} and closures as roll does.", + "doc": "Turn an attached kit part about its pin until one of its sockets' origins stands at a height along a world direction (by default world z): of the two rolls that do it, the one nearer the roll it has. Solved exactly. On a revolute joint with limits only a roll inside them is taken; with neither inside it refuses, naming both rolls and the limits. Refuses a height the socket cannot reach, naming the range it can (either end of the range is taken), and a socket that lies on the pin. Reports the part, reached: {roll, residual} and closures as roll does.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -308,6 +308,73 @@ } ] }, + { + "name": "brokkr_kitbash.joint", + "doc": "State the joint record of an attached kit part's connection. The connection's DOF is its parent socket's type's: revolute (its value is the roll, degrees) or prismatic (the slide, metres). record is a JSON object of any of limits ([lo, hi] or null), mechanism (a label of 1 to 32 a-z, 0-9 and _, or null) and compliance ({\"hertz\": over 0 to 30, \"damping_ratio\": 0 to 2} or null: a slide in the load path that settles under load, a record for a runtime, solved by nothing here); a key left out keeps what is stated and null clears it. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits spanning over 360 degrees or with an end past 360, prismatic limits with an end past 10 m, and compliance on a revolute joint or without limits. Moves nothing but a roll to its turn inside the limits. Reports the part and closures as roll does.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "a part attached on a revolute or prismatic socket" + }, + { + "name": "record", + "type": "string", + "required": true, + "minLength": 2, + "maxLength": 400, + "doc": "a JSON object of any of limits, mechanism, compliance" + } + ] + }, + { + "name": "brokkr_kitbash.slide", + "doc": "Slide an attached kit part along its parent socket's normal, in place, on a prismatic connection (a ram_rod in a ram_barrel's bore: slide 0 is closed, the slide is the extension): its parent and both sockets stay, and what is attached to it follows. Refuses a revolute or rigid connection naming its socket type, and a slide outside the joint's limits. Reports the part and closures as roll does.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "a part attached on a prismatic socket" + }, + { + "name": "slide", + "type": "number", + "required": true, + "minimum": -10, + "maximum": 10, + "doc": "metres along the parent socket's normal from where the two sockets' origins meet" + } + ] + }, + { + "name": "brokkr_kitbash.joints", + "doc": "The joints of the tree of kit parts attached under a root part, as {schema: brokkr.joints, version: 1, root, frame, rigid, joints}. A row per revolute or prismatic connection, depth first with children by name, so a joint's parent row comes before it: id (the child object), parent (the id of the nearest joint above, or null: rigid connections fold into it and are counted in rigid), part, socket ('Object:socket', the parent socket), kind, axis and origin (that socket's z and origin in the root object's frame: Blender axes, +Z up, metres), value (the roll in degrees or the slide in metres now), limits ([lo, hi] or null), min and max (the limits less the value: the travel either way from this pose), mechanism and compliance. Axis, origin and order are derived at each report from the kits and the parent tree; nothing stores them. Rows a receipt cannot carry are counted in jointsOmitted. Refuses a connection that cannot be read. Evaluates no modifier.", + "changesScene": false, + "editModeSafe": true, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the root: a kit part" + } + ] + }, { "name": "brokkr_kitbash.close", "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.", @@ -800,7 +867,7 @@ }, { "name": "brokkr_kitbash.hose", - "doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut with room for its bends where a way has it, and the whole polyline is rounded, each corner by the largest arc its measured room allows. That polyline is a seed: one refused for want of straight between its corners is refined in continuous space (vertices dropped, moved and added, each change proven clear), and before a route is refused the legs are searched again on two more grid origins and at half the step. The refusal then names the steps and origins tried and the first seed's refusal, and says this shows no route was found, not that none exists; it says the bundle is too stiff only where that is proven at a port. The innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a pivot connection between its ends' parts): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres, \"range\": [lo, hi]}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. The whole range from lo to hi is measured without posing anything, each side against the other side's parts: a roll every 5 degrees answers for the rolls about it by what a point can move within them, and more are measured between where that falls short; another hose through the same pin is kept clear of where it stands, not across the rolls (follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes that check). Every line is measured so that nothing thinner than a spacing can stand between two readings, whatever the step. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, seed {step, offset, refined} (the grid that gave the route, and whether its polyline was refined), sag per leg in metres, rolls (how many were measured), worstRoll, worstClearance (least over the range, each reading less what its point can move within its roll's bin), faces, volume, nonManifoldEdges and radii {least, corners}.", + "doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut with room for its bends where a way has it, and the whole polyline is rounded, each corner by the largest arc its measured room allows. That polyline is a seed: one refused for want of straight between its corners is refined in continuous space (vertices dropped, moved and added, each change proven clear), and before a route is refused the legs are searched again on two more grid origins and at half the step. The refusal then names the steps and origins tried and the first seed's refusal, and says this shows no route was found, not that none exists; it says the bundle is too stiff only where that is proven at a port. The innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a revolute connection between its ends' parts, with limits stated by brokkr_kitbash.joint: they are the roll range lo to hi; a pin without limits and a prismatic connection between the ends are refused): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. The whole range from lo to hi is measured without posing anything, each side against the other side's parts: a roll every 5 degrees answers for the rolls about it by what a point can move within them, and more are measured between where that falls short; another hose through the same pin is kept clear of where it stands, not across the rolls (follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes that check). Every line is measured so that nothing thinner than a spacing can stand between two readings, whatever the step. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, seed {step, offset, refined} (the grid that gave the route, and whether its polyline was refined), sag per leg in metres, rolls (how many were measured), worstRoll, worstClearance (least over the range, each reading less what its point can move within its roll's bin), faces, volume, nonManifoldEdges and radii {least, corners}.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -898,7 +965,7 @@ "type": "string", "minLength": 0, "maxLength": 4000, - "doc": "empty, or a JSON object {\"socket\": \"Object:socket\", \"standoff\": 0 to 10, \"range\": [lo, hi]}: the pin the hose crosses", + "doc": "empty, or a JSON object {\"socket\": \"Object:socket\", \"standoff\": 0 to 10}: the pin the hose crosses; its roll range is that connection's limits", "default": "" } ] diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 626f77a..82e4d10 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1997,7 +1997,8 @@ class SheetTests(unittest.TestCase): ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", - "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close", + "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", + "brokkr_kitbash.joint", "brokkr_kitbash.slide", "brokkr_kitbash.joints", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.freeze", "brokkr_kitbash.thaw", "brokkr_kitbash.ribs", "brokkr_kitbash.shell", "brokkr_kitbash.hose"] @@ -2120,7 +2121,8 @@ class OwnershipTests(unittest.TestCase): r"hide_render|hide_viewport|display_type", # a cutter's visibility is setObjectVisibility's r"kit_parent_name|kit_parent\b|matrix_world_stored", # obj.parent has no second owner r"SCREW|\"ARRAY\"|spin\(", # core makes every vertex: no modifier or bmesh op makes kit geometry - r"Kit Boolean |operand_type\s*=\s*[\"']OBJECT") # cutters cut through one collection Boolean per operation, never a modifier each + r"Kit Boolean |operand_type\s*=\s*[\"']OBJECT", # cutters cut through one collection Boolean per operation, never a modifier each + r"kit_axis|kit_order|kit_parent_joint") # a joint's axis is its parent socket's z and its order the parent tree: neither is stored CORE = r"^import bpy|^from bpy|^import bmesh" SCHEMAS = r"brokkr\.kit\.v0" @@ -2273,16 +2275,31 @@ class OwnershipTests(unittest.TestCase): def test_only_write_connection_writes_the_roll(self): """one-writer. kit_roll is the one statement of a connection's roll, and write_connection its one writer: attach - and pose (roll, aim and reach) call it; set_params and the reports read the roll and never write it back. - Mutant R7 (attach keeps its own inline write beside write_connection).""" + and pose (roll, aim, reach, slide and joint) call it; set_params and the reports read the roll and never write + it back. Mutant R7 (attach keeps its own inline write beside write_connection). The joint record (kit_slide, + kit_min, kit_max, kit_mechanism, kit_compliance) is written there too and nowhere else: its names are read by + link and joint_record, cleared by detach, and no other function names them; the hose keeps no roll range of + its own, and no DOF kind is read from a socket type's name.""" source = self.sources()["__init__.py"] writes = re.findall(r'[^\n]*(?:\[ROLL\]|\["kit_roll"\])\s*=(?!=)[^\n]*', source) - self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated"]) - self.assertIn(writes[0], source.split("def write_connection(")[1].split("\n\n\n")[0]) + self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll"]) + writer = source.split("def write_connection(")[1].split("\n\n\n")[0] + self.assertIn(writes[0], writer) + record = r"SLIDE|LIMIT_MIN|LIMIT_MAX|MECHANISM|COMPLIANCE|RECORD" + written = rf'\[(?:{record})\](?:, \w+\[\w+\])*\s*=(?!=)|\["kit_(?:slide|min|max|mechanism|compliance)"\]' + self.assertIsNone(re.search(written, source)) + self.assertEqual(re.findall(r"[^\n]*\[key\] = [^\n]*", source), [" child[key] = value"]) + self.assertIn(" child[key] = value", writer) + named = [body.split("(")[0] for body in re.split(r"\n(?:def|class) ", source)[1:] if re.search(rf"\b(?:{record})\b", body)] + self.assertEqual(named, ["link", "joint_record", "mated", "write_connection", "BROKKR_KITBASH_OT_detach"]) + for text in ("child[SLIDE] = slide", "obj[LIMIT_MIN], obj[LIMIT_MAX] = limits", 'obj["kit_compliance"] = text'): + self.assertIsNotNone(re.search(written, text)) + self.assertNotIn('"range"', source) + self.assertNotIn('"pivot"', source) bodies = {body.split("(")[0]: body.split("\n\n\n")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:]} callers = [name for name, body in bodies.items() if "write_connection(" in body] self.assertEqual((callers, source.count("write_connection("), source.split("def pose(")[1].split("\n\n\n")[0].count("write_connection(")), (["attach"], 3, 1)) - for name in ("roll", "aim", "reach"): + for name in ("roll", "aim", "reach", "slide", "joint"): self.assertEqual((bodies[name].count("pose(context, self.object_name, "), bool(re.search(r"\.parent\s*=(?!=)|\bseat\(|matrix_basis", bodies[name]))), (1, False), name) self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|matrix_basis", bodies["attach"])) @@ -2301,7 +2318,7 @@ class OwnershipTests(unittest.TestCase): assigned = re.findall(rf"[^\n]*\[{keys}\][^\n=]*=(?!=)[^\n]*", source) self.assertEqual(assigned, [" obj[CLOSE], obj[CLOSE_TO], obj[CLOSE_TO_SOCKET] = self.socket, other, self.other_socket"]) self.assertIn(assigned[0], bodies["close"]) - deleted = re.findall(r"[^\n]*\(SOCKET, PARENT_SOCKET, ROLL, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET\)[^\n]*\n[^\n]*\n\s*del obj\[key\]", source) + deleted = re.findall(r"[^\n]*\(SOCKET, PARENT_SOCKET, ROLL, \*RECORD, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET\)[^\n]*\n[^\n]*\n\s*del obj\[key\]", source) self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and hold's kit_frozen self.assertEqual(source.count("CLOSE_TO]"), 1) # the one subscript write above; every read goes through .get placing = r"matrix_basis|matrix_world\s*=(?!=)|matrix_parent_inverse|\.parent\s*=(?!=)|\bseat\(|\.location|\.rotation" @@ -2312,7 +2329,7 @@ class OwnershipTests(unittest.TestCase): def test_the_patterns_bite(self): planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name', - 'obj.modifiers.new("Turn", "SCREW")', 'modifier.operand_type = "OBJECT"') + 'obj.modifiers.new("Turn", "SCREW")', 'modifier.operand_type = "OBJECT"', 'child["kit_axis"] = list(axis)') self.assertIsNotNone(re.search(self.PACKAGE[6], 'obj.modifiers.new("Kit Boolean " + cutter.name, "BOOLEAN")')) for text in ('obj.modifiers.new("Bolts", "ARRAY")', "bmesh.ops.spin(bm, geom=geom)"): self.assertIsNotNone(re.search(self.PACKAGE[5], text)) From 5475a763afcfc99b226c999d4f238d0e2c12e74a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:50:40 +0100 Subject: [PATCH 152/223] live: joint records on the pose scene, the knee's limits before each hose; close and the hose's second reader take the new shapes kitbash_pose: a rod in its barrel, limits on a pin for roll, aim and reach, the record's refusals, the joints report under the tank (a toe below a rigid foot reads the hinge as its parent joint), detach clears the eight keys. kitbash_hose: JOINT drops range; the -20..90 and -10..20 cases are the knee's limits, 30..60 and -200..200 are the joint action's refusals; a pin without limits and a hose across a slide are refused. Fixes two callers the last commit missed: close's mated() tuple and hose.through's crossed(). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 2 +- surfaces/blender/tests/live/kitbash_hose.py | 43 +++++- surfaces/blender/tests/live/kitbash_pose.py | 163 ++++++++++++++++++++ 3 files changed, 201 insertions(+), 7 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 96aeb51..45e6807 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1949,7 +1949,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): ends = [bpy.data.objects.get(text if text in bpy.data.objects else text.rsplit(":", 1)[0]) for text in (stated["start"], stated["end"])] except (ValueError, TypeError, KeyError, AttributeError): return False - return None not in ends and any(found[0] == child for found in self.crossed(ends[0], ends[1], kits)) + return None not in ends and any(found[0] == child for found in self.crossed(ends[0], ends[1], kits)[0]) @staticmethod def reader(trees, cap: float): diff --git a/surfaces/blender/tests/live/kitbash_hose.py b/surfaces/blender/tests/live/kitbash_hose.py index 7ca00af..5cf35c2 100644 --- a/surfaces/blender/tests/live/kitbash_hose.py +++ b/surfaces/blender/tests/live/kitbash_hose.py @@ -229,7 +229,16 @@ try: ports = [frame(upper, "port_cap")[:3, 3], frame(lower, "port_cap")[:3, 3]] check("the actuator's ports sit on its boss faces, facing out", np.allclose(ports[0], [-0.5, -0.2, 0.01], atol=1e-6) and np.allclose(frame(upper, "port_cap")[:3, 2], [1, 0, 0], atol=1e-6) and others(None).find_nearest(Vector(ports[0]))[3] < 1e-6 and np.allclose(frame(upper, "port_rod")[:3, 3], [-0.5, -0.2, 0.27], atol=1e-6), ports[0].tolist()) - JOINT = {"socket": "Shin:end_a_back", "standoff": 0.08, "range": [-20, 20]} + JOINT = {"socket": "Shin:end_a_back", "standoff": 0.08} + + def limits(lo, hi): + """State the knee's limits: the roll range a hose across it is proven over is the pin's own.""" + receipt, _ = send("brokkr_kitbash.joint", object_name="Shin", record=json.dumps({"limits": None if lo is None else [lo, hi]})) + return receipt + + refused("hose-range-from-pin: a pin with no limits, naming the action that states them", {"object_name": "Feed", "start": "ActT:port_cap", "end": "ActS:port_cap", **BUNDLE, "joint": json.dumps(JOINT)}, + "'Shin' on 'Thigh': the pin the hose crosses states no limits: brokkr_kitbash.joint gives it the roll range the hose is proven over") + check("the knee takes its limits", limits(-20, 20)["status"] == "accepted" and (shin["kit_min"], shin["kit_max"]) == (-20.0, 20.0), dict(shin.items())) FEED = {"object_name": "Feed", "start": "ActT:port_cap", "end": "ActS:port_cap", **BUNDLE, "joint": json.dumps(JOINT)} state = scene_state() receipt, report = send("brokkr_kitbash.hose", **FEED) @@ -260,12 +269,14 @@ try: _, again = send("brokkr_kitbash.hose", **FEED) check("a rebuild at the same pose reports what the first call did", {**again, "rebuilt": False} == report and len(bpy.data.meshes) == len(state[1]) + 1, again) check("hose-through-range: the range passes and reports the length's change", report["lengthChange"] is not None and report["lengthChange"] >= 0 and report["worstRoll"] is not None, report) - refused("a range that swings the shin's hose into the thigh's parts, naming the sagged attempt and the taut one", {**FEED, "joint": json.dumps({**JOINT, "range": [-20, 90]})}, + limits(-20, 90) + refused("a range that swings the shin's hose into the thigh's parts, naming the sagged attempt and the taut one", FEED, "sagged: roll 48.59: the hose's child's side reads 0.0269 m from the parts about the pin at [-0.2144, -0.2042, 0.7271], counting the 0.0005933 m it can move against the other side's " "through the 0.156 degrees either side of it: too near the 0.0266 m the bundle needs to prove it of what stands between two readings; taut: roll 50.78: the hose's child's side reads 0.0264 m") - receipt, _ = send("brokkr_kitbash.hose", **{**FEED, "joint": json.dumps({**JOINT, "range": [-20, 90]})}) + receipt, _ = send("brokkr_kitbash.hose", **FEED) check("the refusal names both attempts, each by its roll and its side", "sagged: roll " in str(receipt["message"]) and "; taut: roll " in str(receipt["message"]) and str(receipt["message"]).count("the hose's child's side reads") == 2, receipt["message"]) + limits(-20, 20) section("thin plate") # A plate 1 mm thick, 4 cm square, on the thigh, where a point of the shin's side of a single hose stands at roll # -17.5: between two of the rolls 5 degrees apart. At -20 and at -15 the hose keeps its need from it. @@ -295,8 +306,10 @@ try: receipt, _ = send("brokkr_kitbash.hose", **SINGLE) named = [float(part.split(":")[0]) for part in str(receipt["message"]).split("roll ")[1:]] check("the refusal names a roll between -20 and -15 for each attempt", len(named) >= 1 and all(-20.0 < roll < -15.0 for roll in named), receipt["message"]) - receipt, narrow = send("brokkr_kitbash.hose", **{**SINGLE, "joint": json.dumps({**JOINT, "standoff": 0.24, "range": [-10, 20]})}) + limits(-10, 20) + receipt, narrow = send("brokkr_kitbash.hose", **SINGLE) check("short of the plate the same hose passes its range", receipt["status"] == "accepted" and narrow["rolls"] >= 7, receipt["message"]) + limits(-20, 20) for name in ("Thin", "Single"): gone = bpy.data.objects[name] mesh = gone.data @@ -451,8 +464,26 @@ try: bpy.context.view_layer.update() refused("two pins crossed", {**FEED, "object_name": "New", "end": "Jack:port_cap", "count": 1, "radius": 0.004}, "The hose crosses 2 pins ('Jack' on 'Shin', 'Shin' on 'Thigh'): a hose crosses one") refused("a joint socket off the crossed pin's axis", {**FEED, "joint": json.dumps({**JOINT, "socket": "Shin:end_b_back"})}, "joint.socket 'Shin:end_b_back' is not on the axis of the pin the hose crosses ('Shin' on 'Thigh', socket 'end_b_back')") - refused("the current roll outside the range", {**FEED, "joint": json.dumps({**JOINT, "range": [30, 60]})}, "'Shin' stands at roll 10, outside joint.range [30, 60]") - refused("a range over a full turn", {**FEED, "joint": json.dumps({**JOINT, "range": [-200, 200]})}, "joint must be an object of socket") + state = scene_state() + receipt = limits(30, 60) + check("limits that exclude the roll the knee stands at are the joint action's to refuse", receipt["status"] != "accepted" and "'Shin' on 'Thigh': its roll 10 is outside the joint's limits 30 to 60" in str(receipt["message"]) + and scene_state() == state, receipt["message"]) + receipt = limits(-200, 200) + check("and limits over a full turn", receipt["status"] != "accepted" and "a revolute joint's span at most 360 degrees" in str(receipt["message"]) and scene_state() == state, receipt["message"]) + shin["kit_min"], shin["kit_max"] = 30.0, 60.0 # by hand: the hose reads the pin's limits and finds the roll outside them + refused("the current roll outside limits written by hand", FEED, "'Shin' stands at roll 10, outside its joint's limits 30 to 60") + shin["kit_min"], shin["kit_max"] = -20.0, 20.0 + refused("a joint that states a range of its own", {**FEED, "joint": json.dumps({**JOINT, "range": [-20, 20]})}, "joint must be an object of socket (an 'Object:socket' text) and standoff (0 to 10)") + place("Barrel", "ram_barrel", "body_r=0.0534") + place("Rod", "ram_rod", "body_r=0.0534") + send("brokkr_kitbash.attach", object_name="Barrel", socket="base", parent_name="Shin", parent_socket="end_b_back", roll=90.0) + send("brokkr_kitbash.attach", object_name="Rod", socket="piston", parent_name="Barrel", parent_socket="bore") + rod_tip = bpy.data.objects.new("RodTip", None) + bpy.context.scene.collection.objects.link(rod_tip) + rod_tip.parent = bpy.data.objects["Rod"] + bpy.context.view_layer.update() + refused("hose-range-from-pin: a hose across a slide", {**FEED, "object_name": "New", "start": "Barrel:port_cap", "end": "RodTip", "count": 1, "radius": 0.004, "joint": ""}, + "The hose crosses the slide of 'Rod' on 'Barrel' (socket 'bore'): a hose across a prismatic connection is not routed") refused("a grid past the voxel limit", {**FEED, "step": 0.005}, "voxels at step 0.005, over 524288: a step of ") lower.scale = (1.0, 1.0, 1.01) bpy.context.view_layer.update() diff --git a/surfaces/blender/tests/live/kitbash_pose.py b/surfaces/blender/tests/live/kitbash_pose.py index cfce1ad..75254d7 100644 --- a/surfaces/blender/tests/live/kitbash_pose.py +++ b/surfaces/blender/tests/live/kitbash_pose.py @@ -84,6 +84,9 @@ NEARER = 0.0 # Metres past the top of its circle a reach may ask (core.REACH_EDGE, a rule: HELD). A height typed back from a # refusal's range overshoots by at most 3.2e-07 here and is taken; PAST is refused. The two sit sqrt(10) either side. EDGE, PAST = 1e-5, 3.2e-5 +# The largest difference between a joints row's axis or origin and the parent socket's z or origin read from the scene +# in the root's frame. Set below. +JOINT_FRAME = 1.0 def check(name, ok, detail=None): @@ -309,6 +312,166 @@ try: refused("reach along no direction", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": 0.0, "direction_z": 0.0}, "The direction is zero") refused("a roll past a turn, by the action table", "brokkr_kitbash.roll", {"object_name": "Strut", "roll": 361.0}, "roll") refused("an axis that is not one of the six, by the action table", "brokkr_kitbash.aim", {"object_name": "Strut", "axis": "x", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "axis") + + # --- joint records ------------------------------------------------------------------------------------------------------ + # Below the strut: a barrel on its other pin with a rod in its bore, and a bracket hung by its own pin that carries a + # second bracket rigidly, which carries a strut on its pin. Tank > Mount (rigid) > Strut > {Barrel > Rod, Hinge > Foot (rigid) > Toe, Ram}. + rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] + check("joint, slide and joints load as host actions after reach", rows[rows.index("brokkr_kitbash.reach") + 1:][:3] == ["brokkr_kitbash.joint", "brokkr_kitbash.slide", "brokkr_kitbash.joints"], rows) + barrel, rod = place("Barrel", "ram_barrel"), place("Rod", "ram_rod") + hinge, foot, toe = place("Hinge", "bracket"), place("Foot", "bracket"), place("Toe", "strut", "width=0.09") + send("brokkr_kitbash.attach", object_name="Barrel", socket="base", parent_name="Strut", parent_socket="end_b_back", roll=25.0) + receipt, report = send("brokkr_kitbash.attach", object_name="Rod", socket="piston", parent_name="Barrel", parent_socket="bore") + send("brokkr_kitbash.attach", object_name="Hinge", socket="pivot", parent_name="Strut", parent_socket="end_a_back", roll=-15.0) + send("brokkr_kitbash.attach", object_name="Foot", socket="mount", parent_name="Hinge", parent_socket="mount", roll=90.0) + send("brokkr_kitbash.attach", object_name="Toe", socket="end_a", parent_name="Foot", parent_socket="pivot", roll=40.0) + found = report and report["connection"] + check("a rod attaches in its barrel's bore: a prismatic connection at slide 0 with no joint record, and no record key written", + receipt["status"] == "accepted" and holds(found, "Barrel", "piston", "bore", 0.0) and found == {**found, "dof": "prismatic", "slide": 0.0, "limits": None, "mechanism": None, "compliance": None, "within": True} + and sorted(k for k in rod.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_parent_socket", "kit_part", "kit_roll", "kit_slide", "kit_socket"] + and connection("Strut")["dof"] == "revolute" and connection("Mount")["dof"] is None and "kit_slide" not in strut.keys() and "kit_slide" not in mount.keys(), + [receipt["message"], found, sorted(rod.keys()), connection("Strut"), connection("Mount")]) + + def slid(amount): + """How far the rod's piston stands from the point `amount` along the bore's z, and how far its normal is from opposed.""" + a, b = frame(barrel, "bore"), frame(rod, "piston") + return max(float(np.linalg.norm(b[:3, 3] - a[:3, 3] - amount * a[:3, 2])), float(np.abs(a[:3, 2] + b[:3, 2]).max())) + + # the record: stated by joint, kept key by key + spring = {"hertz": 4.0, "damping_ratio": 0.7} + receipt, report = send("brokkr_kitbash.joint", object_name="Rod", record=json.dumps({"limits": [0.0, 0.3], "mechanism": "shock", "compliance": spring})) + found = report and report["connection"] + check("joint states a slide's limits, mechanism and compliance, and moves nothing", receipt["status"] == "accepted" and found == {**found, "dof": "prismatic", "slide": 0.0, "limits": [0.0, 0.3], + "mechanism": "shock", "compliance": spring, "within": True, "holds": True} and (rod["kit_min"], rod["kit_max"], rod["kit_mechanism"], json.loads(rod["kit_compliance"])) == (0.0, 0.3, "shock", spring) + and reading("slid", slid(0.0)) < SEATED, [receipt["message"], found, dict(rod.items())]) + receipt, report = send("brokkr_kitbash.joint", object_name="Rod", record=json.dumps({"mechanism": None})) + found = report and report["connection"] + check("a key left out keeps what is stated and null clears it", receipt["status"] == "accepted" and found == {**found, "limits": [0.0, 0.3], "mechanism": None, "compliance": spring} + and "kit_mechanism" not in rod.keys(), [receipt["message"], found]) + send("brokkr_kitbash.joint", object_name="Rod", record=json.dumps({"mechanism": "shock"})) + + # slide + for amount in (0.12, 0.3, 0.0, 0.12): + was, pin = stated(rod), frame(rod, "rod_end")[:3, 3].copy() + receipt, report = send("brokkr_kitbash.slide", object_name="Rod", slide=amount) + off, moved = reading("slid", slid(amount)), float(np.linalg.norm(frame(rod, "rod_end")[:3, 3] - pin)) + found = report and report["connection"] + check(f"slide {amount:g} moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated", + receipt["status"] == "accepted" and off < SEATED and abs(rod["kit_slide"] - amount) < 1e-6 and found["holds"] is True and found["slide"] == round(rod["kit_slide"], 6) + and {k: v for k, v in stated(rod)[1].items() if k != "kit_slide"} == {k: v for k, v in was[1].items() if k != "kit_slide"} and stated(rod)[0] == "Barrel" + and abs(moved - abs(amount - was[1]["kit_slide"])) < SEATED, [receipt["message"], found, off, moved, dict(rod.items())]) + receipt, report = send("brokkr_kitbash.roll", object_name="Rod", roll=90.0) + check("a roll on a prismatic connection is a build angle: it turns the rod in the bore and the slide stays", receipt["status"] == "accepted" and rod["kit_roll"] == 90.0 + and abs(rod["kit_slide"] - 0.12) < 1e-6 and reading("slid", slid(0.12)) < SEATED and holds(report["connection"], "Barrel", "piston", "bore", 90.0), [receipt["message"], report and report["connection"]]) + receipt, report = send("brokkr_kitbash.set_params", object_name="Barrel", params="body_len=0.5") + check("set_params of the barrel moves its bore and reseats the rod at its slide", receipt["status"] == "accepted" and reading("slid", slid(0.12)) < SEATED + and connection("Rod") == {**connection("Rod"), "holds": True, "slide": 0.12}, [receipt["message"], connection("Rod")]) + refused("a slide past the joint's limits, naming value and limits", "brokkr_kitbash.slide", {"object_name": "Rod", "slide": 0.31}, "'Rod' on 'Barrel': its slide 0.31 is outside the joint's limits 0 to 0.3") + refused("a slide under them", "brokkr_kitbash.slide", {"object_name": "Rod", "slide": -0.01}, "its slide -0.01 is outside the joint's limits 0 to 0.3") + refused("a slide of a pin, naming its type", "brokkr_kitbash.slide", {"object_name": "Strut", "slide": 0.1}, "'Strut' on 'Mount': socket type 'pivot' is revolute: slide poses a prismatic connection") + refused("a slide of a rigid connection, naming its type", "brokkr_kitbash.slide", {"object_name": "Mount", "slide": 0.1}, "'Mount' on 'Tank': socket type 'mount' is rigid: slide poses a prismatic connection") + refused("a joint record on a rigid connection, naming its type", "brokkr_kitbash.joint", {"object_name": "Mount", "record": '{"limits": [0, 10]}'}, + "'Mount' on 'Tank': socket type 'mount' states no dof: the connection is rigid") + refused("limits that exclude the slide the joint has", "brokkr_kitbash.joint", {"object_name": "Rod", "record": '{"limits": [0.2, 0.3]}'}, "its slide 0.12 is outside the joint's limits 0.2 to 0.3") + refused("prismatic limits past 10 m", "brokkr_kitbash.joint", {"object_name": "Rod", "record": '{"limits": [0, 11]}'}, "a prismatic joint's stand within 10 m of 0") + refused("limits cleared under a compliance", "brokkr_kitbash.joint", {"object_name": "Rod", "record": '{"limits": null}'}, "compliance needs limits") + refused("a compliance out of range", "brokkr_kitbash.joint", {"object_name": "Rod", "record": '{"compliance": {"hertz": 0, "damping_ratio": 0.7}}'}, "hertz is over 0 and at most 30") + refused("a compliance on a pin", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [-180, 180], "compliance": {"hertz": 4, "damping_ratio": 0.7}}'}, + "compliance is a prismatic joint's (a slide that settles under load): socket type 'pivot' is revolute") + refused("revolute limits spanning over a turn", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [-200, 200]}'}, "a revolute joint's span at most 360 degrees") + refused("a revolute limit past 360", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [300, 400]}'}, "each end within 360 of 0") + refused("a record that is not the shape", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [10, -10]}'}, "record must be a JSON object of any of limits") + refused("a record with a key it does not have", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"axis": [0, 0, 1]}'}, "record must be a JSON object of any of limits") + refused("a mechanism that is no label", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"mechanism": "Knee Ram"}'}, "record must be a JSON object of any of limits") + refused("a record that is not JSON", "brokkr_kitbash.joint", {"object_name": "Strut", "record": "{limits}"}, "record must be JSON") + refused("a joint record on a part nobody attached", "brokkr_kitbash.joint", {"object_name": "Spare", "record": "{}"}, "'Spare' is not attached") + + # limits on a pin: roll, aim and reach stay inside them + world, z = np.array(mount.matrix_world, dtype=np.float64), np.array([0.0, 0.0, 1.0]) + pointing = lambda roll: (world @ core.mate(socket(mount, "pivot"), socket(strut, "end_a"), roll))[:3, :3] @ z # noqa: E731 where the strut's z points at a roll + send("brokkr_kitbash.roll", object_name="Strut", roll=180.0) + refused("limits that exclude the roll the joint has", "brokkr_kitbash.joint", {"object_name": "Strut", "record": '{"limits": [190, 210]}'}, "'Strut' on 'Mount': its roll 180 is outside the joint's limits 190 to 210") + receipt, report = send("brokkr_kitbash.joint", object_name="Strut", record='{"limits": [150, 210], "mechanism": "knee"}') + check("joint states a pin's limits about the roll it has", receipt["status"] == "accepted" and report["connection"] == {**report["connection"], "roll": 180.0, "limits": [150.0, 210.0], "mechanism": "knee", "within": True} + and (strut["kit_min"], strut["kit_max"]) == (150.0, 210.0) and "kit_slide" not in strut.keys(), [receipt["message"], report and report["connection"]]) + refused("a roll with no turn of itself inside the limits, naming value and limits", "brokkr_kitbash.roll", {"object_name": "Strut", "roll": 100.0}, "'Strut' on 'Mount': its roll 100 is outside the joint's limits 150 to 210") + receipt, report = send("brokkr_kitbash.roll", object_name="Strut", roll=-170.0) + check("a roll a turn away from the limits is written as its representative inside them: -170 as 190", receipt["status"] == "accepted" and strut["kit_roll"] == 190.0 + and holds(report["connection"], "Mount", "end_a", "pivot", 190.0) and reading("seated", seated(strut, "end_a", mount, "pivot", 190.0)) < SEATED, [receipt["message"], report and report["connection"]]) + send("brokkr_kitbash.roll", object_name="Strut", roll=160.0) + d = pointing(-170.0) + receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis="+z", direction_x=float(d[0]), direction_y=float(d[1]), direction_z=float(d[2])) + aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9} + check("aim solving -170 inside limits 150..210 writes 190", receipt["status"] == "accepted" and reading("limit roll", abs(aimed["roll"] - 190.0)) < ROLL and abs(strut["kit_roll"] - 190.0) < ROLL + and reading("aimed", abs(aimed["dot"] - 1.0)) < AIMED and holds(report["connection"], "Mount", "end_a", "pivot", aimed["roll"]), [receipt["message"], aimed, strut["kit_roll"]]) + for free, end in ((100.0, 150.0), (-110.0, 210.0), (127.0, 150.0)): + d = pointing(free) + receipt, report = send("brokkr_kitbash.aim", object_name="Strut", axis="+z", direction_x=float(d[0]), direction_y=float(d[1]), direction_z=float(d[2])) + aimed = (report or {}).get("aimed") or {"roll": 1e9, "dot": 1e9} + read = float(np.array(strut.matrix_world, dtype=np.float64)[:3, :3] @ z @ d) + grid = max(float(pointing(float(r)) @ d) for r in np.arange(150.0, 210.25, 0.25)) + check(f"aim at where roll {free:g} points, outside the limits, takes the end that points nearer ({end:g}): no roll inside the limits passes it", + receipt["status"] == "accepted" and aimed["roll"] == end and strut["kit_roll"] == end and reading("aimed", abs(aimed["dot"] - read)) < AIMED + and reading("aimed short", max(grid - read, 0.0)) < AIMED and reading("aimed", abs(read - math.cos(math.radians(free - end)))) < AIMED, [receipt["message"], aimed, read, grid]) + A, B, C = core.roll_terms(world, socket(mount, "pivot"), socket(strut, "end_a"), socket(strut, "end_b")["matrix"][:3, 3], 1.0, z) + middle, swing = math.degrees(math.atan2(B, A)), math.hypot(A, B) + near, far, height = middle - 40.0, middle + 40.0, C + math.cos(math.radians(40.0)) * swing # the two rolls that reach this height + send("brokkr_kitbash.joint", object_name="Strut", record='{"limits": null}') + send("brokkr_kitbash.roll", object_name="Strut", roll=round(near + 5.0, 3)) + send("brokkr_kitbash.joint", object_name="Strut", record=json.dumps({"limits": [round(near + 2.0, 3), round(far + 10.0, 3)]})) + receipt, report = send("brokkr_kitbash.reach", object_name="Strut", socket="end_b", height=height) + reached = (report or {}).get("reached") or {"roll": 1e9, "residual": 1e9} + check("reach inside limits that hold only the farther of its two rolls takes that one", receipt["status"] == "accepted" and reading("limit roll", abs(reached["roll"] - far)) < ROLL + and reading("reached", abs(float(frame(strut, "end_b")[:3, 3] @ z) - height)) < REACHED and report["connection"]["within"] is True, [receipt["message"], reached, near, far]) + send("brokkr_kitbash.roll", object_name="Strut", roll=round(near + 5.0, 3)) + send("brokkr_kitbash.joint", object_name="Strut", record=json.dumps({"limits": [round(near + 2.0, 3), round(far - 2.0, 3)]})) + refused("reach with neither roll inside the limits, naming both and the limits", "brokkr_kitbash.reach", {"object_name": "Strut", "socket": "end_b", "height": height}, + f"are outside the joint's limits {round(near + 2.0, 3):.6g} to {round(far - 2.0, 3):.6g}") + rod["kit_slide"] = 0.5 # by hand, past the limits: every report says so and the next pose is refused + found = connection("Rod") + check("a slide written by hand outside the limits reads within false and does not hold", found == {**found, "slide": 0.5, "within": False, "holds": False}, found) + refused("and a roll of it is refused by the limits", "brokkr_kitbash.roll", {"object_name": "Rod", "roll": 0.0}, "its slide 0.5 is outside the joint's limits 0 to 0.3") + rod["kit_slide"] = 0.12 + check("put back, it holds", connection("Rod") == {**connection("Rod"), "slide": 0.12, "within": True, "holds": True}, connection("Rod")) + + # --- the joints report -------------------------------------------------------------------------------------------------- + send("brokkr_kitbash.joint", object_name="Hinge", record='{"limits": [-90, 20], "mechanism": "ankle"}') + receipt, joints = send("brokkr_kitbash.joints", object_name="Tank") + R["joints"] = joints + table = {row["id"]: row for row in (joints or {}).get("joints", [])} + check("joints reports the tree under the tank: schema, the root's frame, a row per DOF connection depth first with children by name, parents first, rigid ones counted", + receipt["status"] == "accepted" and {k: v for k, v in joints.items() if k != "joints"} == {"schema": "brokkr.joints", "version": 1, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres", "rigid": 2} + and [row["id"] for row in joints["joints"]] == ["Strut", "Barrel", "Rod", "Hinge", "Toe", "Ram"], [receipt["message"], joints]) + check("a joint's parent is the nearest DOF connection above it, not the object it hangs from: the toe's is the hinge, through the rigid foot; the rod's is the barrel", + {name: row["parent"] for name, row in table.items()} == {"Strut": None, "Barrel": "Strut", "Rod": "Barrel", "Hinge": "Strut", "Toe": "Hinge", "Ram": "Strut"} and toe.parent == foot, + {name: row["parent"] for name, row in table.items()}) + check("each row names its part, its parent socket and its kind", {name: (row["part"], row["socket"], row["kind"]) for name, row in table.items()} == { + "Strut": ("strut", "Mount:pivot", "revolute"), "Barrel": ("ram_barrel", "Strut:end_b_back", "revolute"), "Rod": ("ram_rod", "Barrel:bore", "prismatic"), + "Hinge": ("bracket", "Strut:end_a_back", "revolute"), "Toe": ("strut", "Foot:pivot", "revolute"), "Ram": ("actuator", "Strut:end_b", "revolute")}, table) + inverse = np.linalg.inv(np.array(tank.matrix_world, dtype=np.float64)) + for name, row in table.items(): + owner, _, parent_socket = row["socket"].partition(":") + at = inverse @ frame(bpy.data.objects[owner], parent_socket) + reading("joint frame", max(float(np.abs(at[:3, 2] - row["axis"]).max()), float(np.abs(at[:3, 3] - row["origin"]).max()))) + check("axis and origin are the parent socket's z and origin in the root's frame, read from the scene", len(table) == 6 and R["readings"]["joint frame"] < JOINT_FRAME, R["readings"]) + value = strut["kit_roll"] + check("value is the roll or slide now, limits are as stated, and min and max are the limits less the value: the travel either way", + table["Rod"] == {**table["Rod"], "value": 0.12, "limits": [0.0, 0.3], "min": -0.12, "max": 0.18, "mechanism": "shock", "compliance": spring} + and table["Hinge"] == {**table["Hinge"], "value": -15.0, "limits": [-90.0, 20.0], "min": -75.0, "max": 35.0, "mechanism": "ankle", "compliance": None} + and table["Strut"] == {**table["Strut"], "value": round(value, 6), "min": round(round(near + 2.0, 3) - value, 6), "max": round(round(far - 2.0, 3) - value, 6), "mechanism": "knee"} + and table["Ram"] == {**table["Ram"], "value": -36.0, "limits": None, "min": None, "max": None, "mechanism": None, "compliance": None}, table) + receipt, below = send("brokkr_kitbash.joints", object_name="Hinge") + check("under another root the rows are in its frame and begin below it", receipt["status"] == "accepted" and [(row["id"], row["parent"]) for row in below["joints"]] == [("Toe", None)] and below["rigid"] == 1 + and float(np.abs((np.linalg.inv(np.array(hinge.matrix_world, dtype=np.float64)) @ frame(foot, "pivot"))[:3, 3] - below["joints"][0]["origin"]).max()) < JOINT_FRAME, below) + refused("joints of a mesh that is not a kit part", "brokkr_kitbash.joints", {"object_name": "Plain"}, "'Plain' is not a kit part") + + # --- detach clears the record ------------------------------------------------------------------------------------------- + receipt, report = send("brokkr_kitbash.detach", object_name="Rod") + check("detach leaves none of the eight connection keys", receipt["status"] == "accepted" and report["connection"] is None and rod.parent is None + and sorted(k for k in rod.keys() if k.startswith("kit_")) == ["kit_kit", "kit_params", "kit_part"], [receipt["message"], sorted(rod.keys())]) + receipt, report = send("brokkr_kitbash.attach", object_name="Rod", socket="piston", parent_name="Barrel", parent_socket="bore") + check("and attached again it states no record", receipt["status"] == "accepted" and report["connection"] == {**report["connection"], "slide": 0.0, "limits": None, "mechanism": None, "compliance": None}, + [receipt["message"], report and report["connection"]]) except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) From 66fd7bb6446c994202220c86489c46b3c242b361 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:57:08 +0100 Subject: [PATCH 153/223] live: thirteen parts in kitbash.py; the joint frame bound from its mutant; result files of the four kitbash runs Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/kitbash.py | 10 +- .../blender/tests/live/kitbash.result.json | 71 ++- .../tests/live/kitbash_hose.result.json | 29 +- surfaces/blender/tests/live/kitbash_pose.py | 9 +- .../tests/live/kitbash_pose.result.json | 409 +++++++++++++++++- 5 files changed, 515 insertions(+), 13 deletions(-) diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index ef5abc9..35ec6bd 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -1,5 +1,5 @@ """Live proof, in a background Blender, that the brokkr_kitbash rows are admitted by Brokkr as host actions and that -the mechanical kit goes through run_intent: describe, place_part for all eleven parts, setObjectTransform, +the mechanical kit goes through run_intent: describe, place_part for all thirteen parts, setObjectTransform, assignMaterial, set_params, report, the refusals, the frame kit's nine parts (placed, a truss re-parameterised, a beam seated on a mechanical bracket), and exportGltf. Not part of the unittest run: it needs Blender. @@ -93,7 +93,7 @@ try: kit = core.load_kit("mechanical") receipt, described = send("brokkr_kitbash.describe") names = [p["name"] for p in described["parts"]] if described else [] - check("describe lists eleven parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 11 + check("describe lists thirteen parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 13 and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")]) receipt, one = send("brokkr_kitbash.describe", part="actuator") check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"] @@ -133,7 +133,7 @@ try: check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"] and report["sockets"] == core.socket_rows(reference.sockets), report) - check("eleven parts are eleven mesh objects", len(bpy.data.objects) == 11 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) + check("thirteen parts are thirteen mesh objects", len(bpy.data.objects) == 13 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) # --- set_params keeps what is not derived -------------------------------------------------------------------------------- reducer = bpy.data.objects["P_reducer"] @@ -252,7 +252,7 @@ try: check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"]) receipt, whole = send("brokkr_kitbash.report") - check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 11, receipt["message"]) + check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 13, receipt["message"]) # --- the frame kit: every shell an extrude, a section swept along a path -------------------------------------------------- frame = core.load_kit("frame") @@ -301,7 +301,7 @@ try: if glb.is_file(): blob = glb.read_bytes() meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", [])) - check("exportGltf of all eleven parts succeeds", receipt["status"] == "accepted" and meshes == 11, [receipt["message"], meshes]) + check("exportGltf of all thirteen parts succeeds", receipt["status"] == "accepted" and meshes == 13, [receipt["message"], meshes]) R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]} for name, report in placed.items() if report} diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 1f4ba39..d468d78 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -7,7 +7,7 @@ "detail": null }, { - "name": "describe lists eleven parts, whole, inside a receipt", + "name": "describe lists thirteen parts, whole, inside a receipt", "ok": true, "detail": null }, @@ -121,6 +121,46 @@ "ok": true, "detail": null }, + { + "name": "place_part ram_barrel: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, + { + "name": "place_part ram_barrel: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part ram_barrel: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part ram_barrel: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "place_part ram_rod: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, + { + "name": "place_part ram_rod: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part ram_rod: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part ram_rod: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, { "name": "place_part pipe_fitting: sharp_edge is true on exactly core's sharp edges (0)", "ok": true, @@ -242,7 +282,7 @@ "detail": null }, { - "name": "eleven parts are eleven mesh objects", + "name": "thirteen parts are thirteen mesh objects", "ok": true, "detail": null }, @@ -452,7 +492,7 @@ "detail": null }, { - "name": "exportGltf of all eleven parts succeeds", + "name": "exportGltf of all thirteen parts succeeds", "ok": true, "detail": null } @@ -475,6 +515,9 @@ "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", + "brokkr_kitbash.joint", + "brokkr_kitbash.slide", + "brokkr_kitbash.joints", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", @@ -615,6 +658,28 @@ "port_rod" ] }, + "ram_barrel": { + "faces": 180, + "shells": 12, + "bevel": 0.0024, + "sockets": [ + "base", + "base_back", + "bore", + "port_cap", + "port_rod" + ] + }, + "ram_rod": { + "faces": 58, + "shells": 3, + "bevel": 0.0024, + "sockets": [ + "piston", + "rod_end", + "rod_end_back" + ] + }, "pipe_fitting": { "faces": 436, "shells": 14, diff --git a/surfaces/blender/tests/live/kitbash_hose.result.json b/surfaces/blender/tests/live/kitbash_hose.result.json index 49cac92..e86c30d 100644 --- a/surfaces/blender/tests/live/kitbash_hose.result.json +++ b/surfaces/blender/tests/live/kitbash_hose.result.json @@ -6,6 +6,16 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: hose-range-from-pin: a pin with no limits, naming the action that states them", + "ok": true, + "detail": null + }, + { + "name": "the knee takes its limits", + "ok": true, + "detail": null + }, { "name": "hose-behind-armour: three hoses route from the thigh's ram to the shin's, round the plate and through the pin point", "ok": true, @@ -327,12 +337,27 @@ "detail": null }, { - "name": "refused, scene unchanged: the current roll outside the range", + "name": "limits that exclude the roll the knee stands at are the joint action's to refuse", "ok": true, "detail": null }, { - "name": "refused, scene unchanged: a range over a full turn", + "name": "and limits over a full turn", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: the current roll outside limits written by hand", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a joint that states a range of its own", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: hose-range-from-pin: a hose across a slide", "ok": true, "detail": null }, diff --git a/surfaces/blender/tests/live/kitbash_pose.py b/surfaces/blender/tests/live/kitbash_pose.py index 75254d7..8ff9464 100644 --- a/surfaces/blender/tests/live/kitbash_pose.py +++ b/surfaces/blender/tests/live/kitbash_pose.py @@ -85,8 +85,13 @@ NEARER = 0.0 # refusal's range overshoots by at most 3.2e-07 here and is taken; PAST is refused. The two sit sqrt(10) either side. EDGE, PAST = 1e-5, 3.2e-5 # The largest difference between a joints row's axis or origin and the parent socket's z or origin read from the scene -# in the root's frame. Set below. -JOINT_FRAME = 1.0 +# in the root's frame. Shipped worst 4.9e-07 (rows carry 6 decimals); least claimed mutant 3.1 (J11, the rows in the +# world's frame); separation 6.3e6. +JOINT_FRAME = 1.2e-3 +# The joint-record readings below use the bounds above: "slid", metres between the rod's piston and the point its slide +# states along the bore's z, against SEATED (shipped 1.4e-07; least claimed mutant J1, the slide applied after FLIP, reads 0.6); +# "limit roll", degrees between a roll solved inside limits and the one expected, against ROLL (shipped +# 2e-05; its mutants J2, J3 and J4 die in test_kitbash's JointRecordTests, where their readings are). def check(name, ok, detail=None): diff --git a/surfaces/blender/tests/live/kitbash_pose.result.json b/surfaces/blender/tests/live/kitbash_pose.result.json index ea72302..9773931 100644 --- a/surfaces/blender/tests/live/kitbash_pose.result.json +++ b/surfaces/blender/tests/live/kitbash_pose.result.json @@ -230,6 +230,251 @@ "name": "refused, scene unchanged: an axis that is not one of the six, by the action table", "ok": true, "detail": null + }, + { + "name": "joint, slide and joints load as host actions after reach", + "ok": true, + "detail": null + }, + { + "name": "a rod attaches in its barrel's bore: a prismatic connection at slide 0 with no joint record, and no record key written", + "ok": true, + "detail": null + }, + { + "name": "joint states a slide's limits, mechanism and compliance, and moves nothing", + "ok": true, + "detail": null + }, + { + "name": "a key left out keeps what is stated and null clears it", + "ok": true, + "detail": null + }, + { + "name": "slide 0.12 moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated", + "ok": true, + "detail": null + }, + { + "name": "slide 0.3 moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated", + "ok": true, + "detail": null + }, + { + "name": "slide 0 moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated", + "ok": true, + "detail": null + }, + { + "name": "slide 0.12 moves the rod along the bore's z where it hangs: its parent, sockets, roll and record as they were, the slide stated and seated", + "ok": true, + "detail": null + }, + { + "name": "a roll on a prismatic connection is a build angle: it turns the rod in the bore and the slide stays", + "ok": true, + "detail": null + }, + { + "name": "set_params of the barrel moves its bore and reseats the rod at its slide", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a slide past the joint's limits, naming value and limits", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a slide under them", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a slide of a pin, naming its type", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a slide of a rigid connection, naming its type", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a joint record on a rigid connection, naming its type", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: limits that exclude the slide the joint has", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: prismatic limits past 10 m", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: limits cleared under a compliance", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a compliance out of range", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a compliance on a pin", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: revolute limits spanning over a turn", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a revolute limit past 360", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a record that is not the shape", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a record with a key it does not have", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a mechanism that is no label", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a record that is not JSON", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a joint record on a part nobody attached", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: limits that exclude the roll the joint has", + "ok": true, + "detail": null + }, + { + "name": "joint states a pin's limits about the roll it has", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a roll with no turn of itself inside the limits, naming value and limits", + "ok": true, + "detail": null + }, + { + "name": "a roll a turn away from the limits is written as its representative inside them: -170 as 190", + "ok": true, + "detail": null + }, + { + "name": "aim solving -170 inside limits 150..210 writes 190", + "ok": true, + "detail": null + }, + { + "name": "aim at where roll 100 points, outside the limits, takes the end that points nearer (150): no roll inside the limits passes it", + "ok": true, + "detail": null + }, + { + "name": "aim at where roll -110 points, outside the limits, takes the end that points nearer (210): no roll inside the limits passes it", + "ok": true, + "detail": null + }, + { + "name": "aim at where roll 127 points, outside the limits, takes the end that points nearer (150): no roll inside the limits passes it", + "ok": true, + "detail": null + }, + { + "name": "reach inside limits that hold only the farther of its two rolls takes that one", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: reach with neither roll inside the limits, naming both and the limits", + "ok": true, + "detail": null + }, + { + "name": "a slide written by hand outside the limits reads within false and does not hold", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: and a roll of it is refused by the limits", + "ok": true, + "detail": null + }, + { + "name": "put back, it holds", + "ok": true, + "detail": null + }, + { + "name": "joints reports the tree under the tank: schema, the root's frame, a row per DOF connection depth first with children by name, parents first, rigid ones counted", + "ok": true, + "detail": null + }, + { + "name": "a joint's parent is the nearest DOF connection above it, not the object it hangs from: the toe's is the hinge, through the rigid foot; the rod's is the barrel", + "ok": true, + "detail": null + }, + { + "name": "each row names its part, its parent socket and its kind", + "ok": true, + "detail": null + }, + { + "name": "axis and origin are the parent socket's z and origin in the root's frame, read from the scene", + "ok": true, + "detail": null + }, + { + "name": "value is the roll or slide now, limits are as stated, and min and max are the limits less the value: the travel either way", + "ok": true, + "detail": null + }, + { + "name": "under another root the rows are in its frame and begin below it", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: joints of a mesh that is not a kit part", + "ok": true, + "detail": null + }, + { + "name": "detach leaves none of the eight connection keys", + "ok": true, + "detail": null + }, + { + "name": "and attached again it states no record", + "ok": true, + "detail": null } ], "hostErrors": [], @@ -238,11 +483,173 @@ "aimed short": 0.0, "edge reached": 2.6e-08, "edge typed past": 3.2e-07, + "joint frame": 4e-07, + "limit roll": 2e-05, "reach other root": 74.0, - "reached": 2.1e-07, + "reached": 2.4e-07, "roll": 8.4e-06, "seated": 1.1e-06, + "slid": 1.4e-07, "turned": 0.55 }, + "joints": { + "schema": "brokkr.joints", + "version": 1, + "root": "Tank", + "frame": "the root object's: Blender axes (+Z up), metres", + "rigid": 2, + "joints": [ + { + "id": "Strut", + "parent": null, + "part": "strut", + "socket": "Mount:pivot", + "kind": "revolute", + "axis": [ + -0.0, + 1.0, + 0.0 + ], + "origin": [ + 0.436, + 0.0, + 0.85368 + ], + "value": -113.019997, + "limits": [ + -116.02, + -40.02 + ], + "min": -3.000003, + "max": 72.999997, + "mechanism": "knee", + "compliance": null + }, + { + "id": "Barrel", + "parent": "Strut", + "part": "ram_barrel", + "socket": "Strut:end_b_back", + "kind": "revolute", + "axis": [ + -0.0, + 1.0, + 0.0 + ], + "origin": [ + 0.154833, + 0.085, + 1.515425 + ], + "value": 25.0, + "limits": null, + "min": null, + "max": null, + "mechanism": null, + "compliance": null + }, + { + "id": "Rod", + "parent": "Barrel", + "part": "ram_rod", + "socket": "Barrel:bore", + "kind": "prismatic", + "axis": [ + 0.034551, + -0.0, + 0.999403 + ], + "origin": [ + 0.157321, + 0.124, + 1.587382 + ], + "value": 0.12, + "limits": [ + 0.0, + 0.3 + ], + "min": -0.12, + "max": 0.18, + "mechanism": "shock", + "compliance": { + "damping_ratio": 0.7, + "hertz": 4.0 + } + }, + { + "id": "Hinge", + "parent": "Strut", + "part": "bracket", + "socket": "Strut:end_a_back", + "kind": "revolute", + "axis": [ + -0.0, + 1.0, + 0.0 + ], + "origin": [ + 0.436, + 0.085, + 0.85368 + ], + "value": -15.0, + "limits": [ + -90.0, + 20.0 + ], + "min": -75.0, + "max": 35.0, + "mechanism": "ankle", + "compliance": null + }, + { + "id": "Toe", + "parent": "Hinge", + "part": "strut", + "socket": "Foot:pivot", + "kind": "revolute", + "axis": [ + 0.787796, + 0.0, + 0.615936 + ], + "origin": [ + 0.559187, + 0.085, + 0.696121 + ], + "value": 40.0, + "limits": null, + "min": null, + "max": null, + "mechanism": null, + "compliance": null + }, + { + "id": "Ram", + "parent": "Strut", + "part": "actuator", + "socket": "Strut:end_b", + "kind": "revolute", + "axis": [ + 0.0, + -1.0, + -0.0 + ], + "origin": [ + 0.154833, + -0.0, + 1.515425 + ], + "value": -36.0, + "limits": null, + "min": null, + "max": null, + "mechanism": null, + "compliance": null + } + ] + }, "ok": true } \ No newline at end of file From 7bc14ecc8245488842007a23866acfde3cfaae6a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 23:04:16 +0100 Subject: [PATCH 154/223] docs/kitbash.md: joint records, the joints report and what it gives up; a pin's range is its connection's limits; ram_barrel and ram_rod Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 108 ++++++++++++++---- .../tests/live/kitbash_assembly.result.json | 62 +++++++++- 2 files changed, 149 insertions(+), 21 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 4096be7..f82d7c3 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -25,8 +25,10 @@ Who owns what: included: a part's size is its params, and a socket's frame is a rotation and an origin. Set scale to 1 and resize with `set_params`. - A connection between two parts belongs to the child: its parent pointer and its `kit_socket`, - `kit_parent_socket` and `kit_roll` properties. Where the child stands is derived from them - ("Assembling parts"). + `kit_parent_socket` and `kit_roll` properties, and its joint record (`kit_slide`, `kit_min`, `kit_max`, + `kit_mechanism`, `kit_compliance`). Where the child stands is derived from them ("Assembling parts"). The + joint's kind belongs to the kit's socket type and its axis to the parent socket's frame: neither is stored on + the connection. - A closure, the joint that closes a loop, belongs to the closing part: its `kit_close_socket`, `kit_close_to` and `kit_close_to_socket` properties. Only `close` writes them and only `detach` clears them. A closure places nothing: whether it holds is derived at each report. @@ -149,7 +151,8 @@ well under the part's thinnest feature at its smallest params. **Sockets** are frames. `at` is the origin; `z` is the outward normal (a mating socket faces it), `y` is up (the roll reference), and x is y cross z; each is one of `+x -x +y -y +z -z` in the part's frame, on different axes. `size` is a diameter in metres. `type` names one of the kit's `socketTypes`, whose `match` says how sizes are to -be compared when sockets are mated: `equal` (within 1 percent) or `fits` (the child at most the parent). A socket +be compared when sockets are mated: `equal` (within 1 percent) or `fits` (the child at most the parent), and +whose optional `dof` (`revolute` or `prismatic`; absent is rigid) says how a child seated on such a socket moves. A socket sits on a flat face of the part whose normal is its `z`; `test_kitbash` checks this for every part of a shipped kit at its default, smallest and largest params and at seeded draws between. @@ -162,20 +165,75 @@ angle: at 0 the two parts line up, side by side. A pin carries a socket on each **A connection** seats one socket of a child part on one socket of a parent part: the two origins together, the two normals opposed, and the child turned `roll` degrees about the parent socket's normal (right-handed; at 0 the -two sockets' up axes line up). The child owns it. It is the child's parent pointer, under an identity parent -inverse, and three ID properties on the child: `kit_socket` (its own socket), `kit_parent_socket` and `kit_roll`. -Nothing else stores it: no parent name, no world matrix, no empties. The child's `matrix_basis` is derived, +two sockets' up axes line up). On a prismatic socket the child also stands `slide` metres along that normal. The +child owns it. It is the child's parent pointer, under an identity parent inverse, and three ID properties on the +child: `kit_socket` (its own socket), `kit_parent_socket` and `kit_roll`, with its joint record ("Joint records", +below). Nothing else stores it: no parent name, no world matrix, no empties. The child's `matrix_basis` is +derived, ```text -matrix_basis = S_parent @ Rz(roll) @ FLIP @ inverse(S_child) FLIP = half a turn about y +matrix_basis = S_parent @ T(0, 0, slide) @ Rz(roll) @ FLIP @ inverse(S_child) FLIP = half a turn about y ``` -with `S` each socket's frame in its own part at that part's stored params (`core.mate`). `attach`, `set_params`, -`roll`, `aim` and `reach` write it; nothing else should. +with `S` each socket's frame in its own part at that part's stored params (`core.mate`); a turn about z and a move +along it commute, so one connection carries both. `attach`, `set_params`, `roll`, `aim`, `reach`, `slide` and +`joint` write it; nothing else should. + +**Joint records.** A connection's degree of freedom is its parent socket's type's: a socket type states +`"dof": "revolute"` (the child turns about the socket's z: `pivot`), `"dof": "prismatic"` (it slides along it: +`slide`) or nothing, and is then rigid (`flange`, `mount`, `hose`). No part, socket or object name decides it. A +revolute joint's value is its `kit_roll`, in degrees; a prismatic joint's is its `kit_slide`, in metres, and its +roll is a build angle. Beside the value the child's connection carries a record: + +| Property | States | Stated by | +| --- | --- | --- | +| `kit_slide` | metres along the parent socket's z; prismatic only, 0 where the two origins meet | `slide` | +| `kit_min`, `kit_max` | the limits of the value, both or neither: degrees on a revolute joint (a span of at most 360, each end within 360 of 0), metres on a prismatic one (each end within 10 m of 0) | `joint` | +| `kit_mechanism` | a label of 1 to 32 `a-z`, `0-9` and `_`: which mechanism the joint is (`knee`, `shock`) | `joint` | +| `kit_compliance` | `{"hertz", "damping_ratio"}` (hertz over 0 to 30, damping ratio 0 to 2): a slide in the load path that settles and rebounds under load. Prismatic only, and it needs limits, the travel it settles within | `joint` | + +Every one of them is written by one function, `write_connection`, which `attach`, `roll`, `aim`, `reach`, `slide` +and `joint` all seat through; `detach` clears them with the connection. So the limits have one check: a value with +no representative inside them is refused before anything is written, naming value and limits, and a roll a turn +away from its limits is written as the roll inside them (limits 150 to 210 and a roll of -170: 190). `aim` inside +limits takes the free roll when the limits hold it and otherwise the end that points the axis nearer; `reach` +takes only a root inside them. A new connection states no record. A value written by hand outside its limits +reads `within: false` in every report and the next pose of that part is refused. + +Limits and springs follow Box2D v3's `b2PrismaticJointDef` and Jolt's `SliderConstraintSettings`: the slide's +limits and a spring as a frequency in hertz and a damping ratio sit on the joint itself. Frequency and damping +ratio describe how the strut feels whatever mass it carries; a stiffness in N/m would need the mass the kit does +not know. `kit_compliance` is a record for a runtime: nothing in Brokkr solves it. + +Two things a rig needs are not stored, because each is already stated once. The axis is the parent socket's z in +the kit at the parent's stored params: a copy on the connection would go stale at the next `set_params`. The order +is the parent tree. `brokkr_kitbash.joints` derives both at each call and emits them, so a consumer derives +nothing: + +```json +{"schema": "brokkr.joints", "version": 1, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres", + "rigid": 2, "joints": [ + {"id": "Strut", "parent": null, "part": "strut", "socket": "Mount:pivot", "kind": "revolute", + "axis": [0.0, 1.0, 0.0], "origin": [0.436, 0.0, 0.85368], "value": -113.019997, "limits": [-116.02, -40.02], + "min": -3.000003, "max": 72.999997, "mechanism": "knee", "compliance": null}, + {"id": "Rod", "parent": "Barrel", "part": "ram_rod", "socket": "Barrel:bore", "kind": "prismatic", + "axis": [0.97429, 0.0, 0.225296], "origin": [1.072572, 0.124, 1.312762], "value": 0.12, "limits": [0.0, 0.3], + "min": -0.12, "max": 0.18, "mechanism": "shock", "compliance": {"damping_ratio": 0.7, "hertz": 4.0}}]} +``` + +A row per revolute or prismatic connection under the root, depth first with children by name, so a row's parent +comes before it. `parent` is the nearest joint above, not the object the part hangs from: rigid connections fold +into it and are counted in `rigid`. `axis` and `origin` are the parent socket's z and origin in the root object's +frame. `min` and `max` are the limits less the value, the travel either way from the pose the report was taken at, +which is the shape of Aetheria's `ShipJoint` (`Min` and `Max` about rest). What the report gives up: it is the +pose at the call, so rest is whatever the assembly stood at; it carries no meshes or bone names, so a consumer +joins rows to the exported objects by `id`; and `ShipJoint` has no slide and no spring yet +(aetheria-release:question:shipjoint-prismatic-dof), so a prismatic row has no Aetheria reader today. **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` +vocabulary kits share: parts of two kits mate when both kits declare the socket's type with the same `match` and +the same `dof` (`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 @@ -666,7 +724,7 @@ evaluation once for every `ribs` call; iterate planes on the cage before it is c ```json {"action": "brokkr_kitbash.hose", "object_name": "Feed", "start": "ThighRam:port_cap", "end": "ShinRam:port_cap", "count": 3, "radius": 0.006, "clearance": 0.005, - "joint": "{\"socket\": \"Shin:end_a_back\", \"standoff\": 0.08, \"range\": [-120, 20]}"} + "joint": "{\"socket\": \"Shin:end_a_back\", \"standoff\": 0.08}"} ``` **Ends.** `start` and `end` are `Object:socket` on a kit part, a `hose` socket (an actuator's `port_cap` and @@ -751,9 +809,12 @@ radius above the face, for 2 outside diameters each side, and gets a pad on the bundle lies flat on the first clamp; its ups are rotation minimising (Wang et al. 2008), so it does not twist between clamps, and a later clamp's strap follows the bundle as it arrives. -**A pin.** A hose may cross one pin: a pivot connection between its ends' parts, found from their parent chains. -`joint` names a socket on that pin's axis whose z runs along it (the free end face of the pin: a strut's -`end_a_back`), a `standoff` and the pin's roll `range`. The hose passes through the point `standoff` beyond that +**A pin.** A hose may cross one pin: a revolute connection between its ends' parts, found from their parent +chains. `joint` names a socket on that pin's axis whose z runs along it (the free end face of the pin: a strut's +`end_a_back`) and a `standoff`. The roll range the hose is proven over is the pin's own: its connection's limits, +stated once with `brokkr_kitbash.joint` (`{"limits": [-120, 20]}`) and read by every hose across it. A pin with no +limits is refused, naming that action, and so is a prismatic connection between the ends: a hose across a slide +is not routed. The hose passes through the point `standoff` beyond that socket, on the axis, as a robot's dress pack does: the straights on each side then move with their own part and only the bend at that point changes with the roll. The whole range is measured without posing anything, not a list of rolls in it. Each roll from `lo` to `hi` in steps of 5 degrees answers for the rolls nearer it than any @@ -792,7 +853,8 @@ skin weights are `brokkr_rig`'s. **Refusals**, each before anything is written: a name taken by an object that is no hose; an end or clamp that names no object, no such socket, or a socket of the wrong type; a bundle wider than a port, naming both sizes; a part that is scaled or that Blender does not evaluate; a pin crossed with no `joint`, a `joint` with no pin, two -pins, a `joint` socket off the pin's axis, the current roll outside `range`; a search box over 524288 voxels, +pins, a `joint` socket off the pin's axis, a pin with no limits or standing outside them, a slide between the +ends; a search box over 524288 voxels, naming a step that fits; an end nearer an obstacle than the bundle needs; a bundle proven too stiff to leave a port; and, once every seed has been tried, no route found, with the first seed's refusal: no way through, a corner under the floor by what its polyline lacked, a curve not proven to keep the clearance at a named point, or a roll @@ -993,6 +1055,9 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se | `brokkr_kitbash.roll` | `object_name`, `roll` (degrees, -360 to 360) | Turns an attached part to that roll where it hangs. Refuses a part that is not attached. Reports the part and `closures` as `set_params` does. | | `brokkr_kitbash.aim` | `object_name`, `axis` (`+x`, `-x`, `+y`, `-y`, `+z` or `-z`, the part's own), `direction_x`, `direction_y`, `direction_z` (world, any length) | Solves the roll that turns the axis as far toward the direction as the pin lets it, and turns the part to it. Refuses an axis or direction along the pin. Reports the part, `aimed: {roll, dot}` and `closures`. | | `brokkr_kitbash.reach` | `object_name`, `socket` (one of the part's), `height` (metres, -1000 to 1000), `direction_x`, `direction_y`, `direction_z` (world; default 0, 0, 1) | Solves the roll that brings the socket's origin to `height` along the direction, the nearer of the two, and turns the part to it. Refuses a height out of reach, naming the range. Reports the part, `reached: {roll, residual}` and `closures`. | +| `brokkr_kitbash.joint` | `object_name`, `record` (a JSON object of any of `limits`: `[lo, hi]` or null; `mechanism`: a label or null; `compliance`: `{hertz, damping_ratio}` or null) | States the joint record of an attached part's connection; a key left out keeps what is stated and null clears it. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits over a turn or past 360, prismatic limits past 10 m, and compliance on a revolute joint or without limits. Reports the part and `closures` as `roll` does | +| `brokkr_kitbash.slide` | `object_name`, `slide` (metres, -10 to 10) | Slides an attached part along its parent socket's normal on a prismatic connection, where it hangs. Refuses a revolute or rigid connection naming its socket type, and a slide outside the joint's limits. Reports the part and `closures` as `roll` does | +| `brokkr_kitbash.joints` | `object_name` (the root, a kit part) | Reports the joints of the tree attached under the root as `brokkr.joints` version 1: a row per revolute or prismatic connection, parents first, with `id`, `parent`, `part`, `socket`, `kind`, `axis`, `origin`, `value`, `limits`, `min`, `max`, `mechanism` and `compliance`, in the root's frame ("Joint records"). Changes nothing | | `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. | | `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added; `booleansOmitted` counts rows a receipt had no room for) 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), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans` (with `booleansOmitted`, as `boolean`). | @@ -1001,7 +1066,7 @@ Python loop of BVH queries with three rays a sample, and the 13,824-candidate se | `brokkr_kitbash.thaw` | `object_name` | Puts the live mesh back, turns every modifier on and removes the frozen mesh; evaluates nothing. Refuses an object that is not frozen or whose held mesh is gone. Reports `object`, `frozen`, `modifiers` and the live mesh's `faces`. | | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | | `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | -| `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff, range}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `seed`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. | +| `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `seed`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. | `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. @@ -1047,8 +1112,9 @@ file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the ## The mechanical kit -`kits/mechanical.v0.json`: eleven parts, each along +z, with socket types `flange` (equal), `mount` (fits), -`pivot` (equal) and `hose` (fits: a port takes a bundle no wider than its size). +`kits/mechanical.v0.json`: thirteen parts, each along +z, with socket types `flange` (equal), `mount` (fits), +`pivot` (equal, revolute), `slide` (equal, prismatic: a telescoping bore, sized by its diameter) and `hose` (fits: +a port takes a bundle no wider than its size). | part | params | sockets | | --- | --- | --- | @@ -1057,6 +1123,8 @@ file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the | `ribbed_cylinder` | `radius`, `length`, `ribs`, `rib_depth`, `rib_width`, `segments` | `end_a`, `end_b` (flange) | | `strut` | `length`, `width`, `thickness`, `segments` | `end_a`, `end_a_back`, `end_b`, `end_b_back` (pivot): the two end faces of the pin at each end | | `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `base_back`, `rod_end`, `rod_end_back` (pivot); the rod end's two move with `extension`; `port_cap`, `port_rod` (hose, `0.4*body_r` wide) on the end faces of its two port bosses | +| `ram_barrel` | `body_r`, `body_len`, `rod_r`, `segments` | the actuator up to its gland: `base`, `base_back` (pivot); `bore` (slide, `2*rod_r`) at the closed piston face, its z along the barrel; `port_cap`, `port_rod` (hose) | +| `ram_rod` | `body_r`, `rod_r`, `length`, `segments` | the actuator from its gland: `piston` (slide, `2*rod_r`); `rod_end`, `rod_end_back` (pivot). In a barrel's bore slide 0 is closed and the slide is the extension; a rod of `length` `body_len + 1.1*body_r` stands as the actuator does | | `pipe_fitting` | `pipe_r`, `run`, `branch`, `flange_r`, `flange_t`, `segments` | `a`, `b`, `c` (flange) | | `radiator_stack` | `fins`, `fin_w`, `fin_h`, `fin_t`, `pitch`, `segments` | `base` (mount) | | `vent` | `width`, `height`, `depth`, `slats`, `slat_t`, `tilt` | `back` (mount) | @@ -1088,7 +1156,7 @@ on the other then lie in one plane and can meet at a pin: a braced leg. ## The frame kit `kits/frame.v0.json`: nine parts of chassis structure, every shell an extrude. Its socket types are `mount` (fits) -and `pivot` (equal), the same two lines as `mechanical`'s, so a frame part seats on a mechanical one and the other +and `pivot` (equal, revolute), the same two lines as `mechanical`'s, so a frame part seats on a mechanical one and the other way round (`place_part` and `describe` take `kit: "frame"`). | part | params | what it is | sockets | @@ -1117,7 +1185,7 @@ python -m unittest discover -s surfaces/blender/tests -p "test_kitbash.py" -v 16 seeded draws, and checks that every shell is closed and wound outward, every socket frame is right-handed and 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`. +part of `mechanical` also joins the part and socket list in `test_the_kit_is_the_thirteen_parts_and_five_socket_types`. `FrameKitTests` holds `frame` to the same (the seat check reads a cap that is not convex, an I section's, as it reads a convex one), with the truss's shells and chords, the portal's mitres, its web in the frame's plane and its feet apart, each beam's `w` across x and `h` along y, and a beam seated on a mechanical diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index 7cc08bf..8448f5d 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -612,7 +612,17 @@ "detail": null }, { - "name": "refused, scene unchanged: set_params on a dirty frozen part", + "name": "refused, scene unchanged: set_params on a dirty frozen part, named dirty as its report names it", + "ok": true, + "detail": null + }, + { + "name": "a frozen part with a modifier shown in renders only reports dirty", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: exportGltf applying modifiers over a frozen part dirty in renders only", "ok": true, "detail": null }, @@ -651,6 +661,56 @@ "ok": true, "detail": null }, + { + "name": "thaw after an export that applied modifiers leaves no frozen mesh behind", + "ok": true, + "detail": null + }, + { + "name": "freeze gives the live mesh a fake user and kit_kept, a pointer to the frozen mesh; a save writes both", + "ok": true, + "detail": null + }, + { + "name": "deleteObject on a frozen object releases its live mesh: a purge takes it and the frozen mesh", + "ok": true, + "detail": null + }, + { + "name": "importGltf drops the kit_* properties a file's extras carry, and says so: the imported object is not frozen and not a part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: thaw on the imported object", + "ok": true, + "detail": null + }, + { + "name": "a frozen object deleted in Blender, by no action: a save writes neither mesh, and a purge takes both", + "ok": true, + "detail": null + }, + { + "name": "a kept mesh whose kit_kept was cleared by hand still gives its fake user back at thaw", + "ok": true, + "detail": null + }, + { + "name": "a live mesh whose kit_frozen was deleted by hand stays kept through a purge and a save", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: thaw on a frozen part whose kit_frozen was deleted names the kept mesh", + "ok": true, + "detail": null + }, + { + "name": "and with kit_frozen pointed back it thaws and the mesh is released", + "ok": true, + "detail": null + }, { "name": "two cutters share one Boolean modifier above the Bevel, in its collection in the order they came", "ok": true, From fa64f43a35caf3bdac3726cfcbf16a7d98016991 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:28:21 +0100 Subject: [PATCH 155/223] brokkr_kitbash.ram: a zone names a part of a body its pin joins (JOINS), or the record is refused Soul s4 (zone-spans-the-member-and-hides-an-overlap): two zones of 0.51 of its length cover a member, so no radius bound stops a foreign part being let. The record can say which bodies a pin joins: a the parent, the rocker's pivot the parent and rocker, p the rocker and coupler, c the coupler and child, b the child, d the rocker. Mechanism refuses any other zone before measuring it; from_record and a search world's answer pass the same loop. Tests: every (kind, member, pin, body) admitted or refused by a hand table; Soul's parent capsule under the coupler refused three ways; the wall, bead, lug and world cases restated on bodies their pins join. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/ram.py | 9 ++ surfaces/blender/tests/test_ram.py | 116 +++++++++++++++++++------ 2 files changed, 99 insertions(+), 26 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py index d7cb60f..1383b5e 100644 --- a/surfaces/blender/brokkr_kitbash/ram.py +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -31,6 +31,9 @@ it turns with: a thigh's core, the bracket that carries the rocker's pivot, a li for each member of MEMBERS[kind], zones (part, pin, radius, depth). Every member meets every part. A zone lowers what the member's samples keep from one part, and only within `radius` of the axis of `pin`, one of the member's own (RIDES), measured across the hinge axis: there a sample may come as near the part as -depth and no nearer. +The part is one of a body that pin joins (JOINS: a the parent; the rocker's pivot the parent and the rocker; p the +rocker and the coupler; c the coupler and the child; b the child; d the rocker), or the record is refused: what a +member meets at a pin is of the bodies pinned there, and a part of any other body is never let near it. depth is 0 for what is stacked beside the member on the pin (a plate, the bracket or horn the pin stands in: the member's axis stays outside it, so a pin whose place along the axis is inside the part it claims to stand beside is refused), the pin's radius for the pin through the member's eye, half the thickness for the member's own plate @@ -68,6 +71,9 @@ MEMBERS = {"direct": ("barrel", "rod"), "four_bar": ("barrel", "rod", "rocker", EYE = {"direct": "b", "four_bar": "d", "bell_crank": "d"} # the pin the rod's eye rides RIDES = {kind: {"barrel": ("a", EYE[kind]), "rod": ("a", EYE[kind]), "rocker": ("rocker", "p"), "coupler": ("p", "c"), "rocker arm": ("rocker", "d")} for kind in KINDS} # member -> the pins at its start and its end +JOINS = {kind: {"a": ("parent",), "b": ("child",)} if kind == "direct" else + {"a": ("parent",), "rocker": ("parent", "rocker"), "p": ("rocker", "coupler"), "c": ("coupler", "child"), "d": ("rocker",)} + for kind in KINDS} # pin -> the bodies it joins: only their parts are zoned about it GATES = ("assembly", "stroke", "toggle", "arm", "load", "clash") SCHEMA, VERSION = "brokkr.ram", 1 ZONE = ("part", "pin", "radius", "depth") # a zone of `touch`, as the record writes it @@ -216,6 +222,9 @@ class Mechanism: radius, depth = _number(self.kind, f"{member} {part} radius", radius, 0.0), _number(self.kind, f"{member} {part} depth", depth) if depth < 0.0: raise RamError(self.kind, "record", f"a depth of 0 or more, got {depth!r}", pin=f"{member} {part} depth") + if self.parts[part] not in JOINS[self.kind][pin]: + raise RamError(self.kind, "record", f"{member} may touch about {pin} a part of a body the pin joins ({', '.join(JOINS[self.kind][pin])}); " + f"{part!r} turns with {self.parts[part]}", pin=f"{member} {part} pin") span = _span(self, member) for name, value in (("radius", radius), ("depth", depth)): if value > span: diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py index 1fbe829..8a8c12d 100644 --- a/surfaces/blender/tests/test_ram.py +++ b/surfaces/blender/tests/test_ram.py @@ -562,8 +562,9 @@ class DeepKnee(unittest.TestCase): def test_a_part_in_the_rams_way_on_each_link(self): # a lug on the rocker, then on the coupler, on the rod's axis 0.12 from the eye at -60: refused naming the part - # and its body. A zone about the eye lets the rod and the barrel by it only if it reaches the lug and is as - # deep as the lug; a zone of another member's changes nothing + # and its body. A zone about the eye lets the rod and the barrel by the rocker's only if it reaches the lug and + # is as deep as the lug; a zone of another member's changes nothing. The coupler's lug is let by no zone of + # the ram's: the eye's pin does not join the coupler m, ram = r3("bell_crank", CRANK), R.Ram(BORE) at = R.pose(m, -60.0) on_rod = (at.eye - 0.12 * at.u)[:, None, :] @@ -574,13 +575,20 @@ class DeepKnee(unittest.TestCase): def zones(radius, depth, members=("rod", "barrel")): return {**touch, **{member: touch[member] + [("lug", "d" if member != "coupler" else "p", radius, depth)] for member in members}} - for label, given in (("nothing let", touch), ("the coupler's zone", zones(0.4, 0.02, ("coupler",))), ("a zone short of the lug", zones(0.1, 0.02)), - ("a zone too shallow", zones(0.4, 0.01))): + if body == "coupler": # d joins the rocker alone: no zone of the ram's names a part of the coupler + with self.assertRaises(R.RamError) as caught: + dressed(m, bodies, zones(0.4, 0.02)) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", "barrel lug pin")) + self.assertIn("a body the pin joins (rocker); 'lug' turns with coupler", str(caught.exception)) + for label, given in (("nothing let", touch), ("the coupler's zone", zones(0.4, 0.02, ("coupler",))), + *((("a zone short of the lug", zones(0.1, 0.02)), ("a zone too shallow", zones(0.4, 0.01))) if body == "rocker" else ())): with self.assertRaises(R.RamError) as caught: R.fit(dressed(m, bodies, given), ram, steps=49, distance=bodies) self.assertEqual((caught.exception.gate, caught.exception.fit.clear_at[2]), ("clash", "lug"), (body, label)) self.assertIn(caught.exception.fit.clear_at[1], ("rod[0]", "barrel[0]")) self.assertIn(f"part 'lug' ({body})", str(caught.exception)) + if body == "coupler": + continue f = R.fit(dressed(m, bodies, zones(0.4, 0.02)), ram, steps=49, distance=bodies) self.assertIn(("rod[0]", "lug"), f.allowed) self.assertNotIn(("rocker arm", "lug"), f.allowed) @@ -645,16 +653,16 @@ class DeepKnee(unittest.TestCase): self.assertAlmostEqual(R._span(m, "rocker arm"), 0.24, places=9) self.assertGreaterEqual(R._span(m, "rod"), float(R.pose(m, np.linspace(-125.0, 0.0, 126)).L.max())) self.assertEqual([ram.eye(*of) for of in (("barrel", "a"), ("rod", "a"), ("rod", "d"), ("coupler", "c"))], [ram.e_a, ram.e_a, ram.e_b, ram.link_r]) - for member, pin in (("barrel", "a"), ("rod", "d"), ("rocker", "p"), ("coupler", "c"), ("rocker arm", "rocker")): + for member, pin, part in (("barrel", "a", "thigh"), ("rod", "d", "pin d"), ("rocker", "p", "coupler plates"), ("coupler", "c", "horn"), ("rocker arm", "rocker", "bracket")): span, eye = R._span(m, member), ram.eye(member, pin) def zoned(radius, depth): - return dressed(m, bodies, {member: [("thigh", pin, radius, depth)]}) + return dressed(m, bodies, {member: [(part, pin, radius, depth)]}) zoned(span, 0.0) for radius, depth, field in ((1.2 * span, 0.0, "radius"), (1e308, 0.0, "radius"), (1e9, 1e9, "radius"), (0.1, 1.2 * span, "depth"), (0.1, 1e308, "depth")): with self.assertRaises(R.RamError) as caught: zoned(radius, depth) - self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} thigh {field}")) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} {part} {field}")) self.assertIn(f"{member} is at most {span:.4f} from pin to pin", str(caught.exception)) R.clearance(zoned(0.1, eye), ram, [-60.0], bodies) wrote = R.record(zoned(0.1, eye), ram) @@ -664,19 +672,66 @@ class DeepKnee(unittest.TestCase): lambda: R.from_record(wrote)): with self.assertRaises(R.RamError) as caught: read() - self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} thigh depth")) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} {part} depth")) self.assertIn(f"{member}'s on {pin} is {eye:.4f}", str(caught.exception)) + def test_a_zone_names_a_part_of_a_body_its_pin_joins(self): + # Soul's whole-member zones: two of 0.51 of its length about p and c covered the coupler and let its axis + # 0.0294 into a capsule of the thigh. No bound on a radius stops that; the record says which bodies a pin + # joins, and a part of any other is zoned about it by no member, whatever the radius and depth + joins = {"a": ("parent",), "b": ("child",), "rocker": ("parent", "rocker"), "p": ("rocker", "coupler"), "c": ("coupler", "child"), "d": ("rocker",)} + for m in (R.Mechanism("direct", O, X, -62, 0, a=(0.05, -0.3, 0.8), b=(0.05, -0.3, -0.6)), r3("four_bar", DEEP), r3("bell_crank", CRANK)): + parts = {"of " + body: body for body in R.BODIES[m.kind]} + for member in R.MEMBERS[m.kind]: + for pin in R.RIDES[m.kind][member]: + for part, body in parts.items(): + zone = {member: [(part, pin, 0.01, 0.0)]} + if body in joins[pin]: + self.assertEqual(replace(m, parts=parts, touch=zone).touch[member], ((part, pin, 0.01, 0.0),)) + continue + with self.assertRaises(R.RamError) as caught: + replace(m, parts=parts, touch=zone) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} {part} pin"), (m.kind, member, pin, body)) + self.assertIn(f"{member} may touch about {pin} a part of a body the pin joins ({', '.join(joins[pin])}); " + f"'{part}' turns with {body}", str(caught.exception)) + # Soul's capsule of the parent under the coupler, zoned as the probe zoned it: refused by the record, by + # from_record and as a world's answer; the shipped zones, each a part of a body its pin joins, are read + m, ram = r3("bell_crank", CRANK), R.Ram(BORE) + bodies, touch = r3_bodies(m, ram) + wire = json.loads(json.dumps(R.record(dressed(m, bodies, touch), ram))) + self.assertEqual(R.from_record(wire)[0].touch, dressed(m, bodies, touch).touch) + bodies.parts["under"], bodies.shapes["under"] = "parent", [("capsule", (X_COUPLER, 0.5, 0.2), (X_COUPLER, 0.6, 0.3), 0.08)] + halves = [("under", "p", 0.51 * m.lc, ram.link_r), ("under", "c", 0.51 * m.lc, ram.link_r)] + wire["parts"]["under"] = "parent" + for k, zone in enumerate(halves): + given = {**touch, "coupler": touch["coupler"] + halves[k:]} + wrote = {**wire, "touch": {**wire["touch"], "coupler": wire["touch"]["coupler"] + [dict(zip(R.ZONE, zone))]}} + hinge, seat = {"pivot": O, "axis": X, "lo": -125, "hi": 0}, {name: [getattr(m, name)] for name in ("a", "rocker", "c")} + for read in (lambda: dressed(m, bodies, given), lambda: R.from_record(wrote), + lambda: R.search("bell_crank", hinge, ram, {**seat, "link": (m.lr, m.lr, 1), "d": (0.24, 0.24, 1)}, world=lambda made: (bodies.parts, given, bodies))): + with self.assertRaises(R.RamError) as caught: + read() + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", "coupler under pin")) + self.assertIn(f"about {zone[1]} a part of a body the pin joins", str(caught.exception)) + # the body is refused before the zone is measured: a zone both foreign and wider than its member names the pin + with self.assertRaises(R.RamError) as caught: + dressed(m, bodies, {"coupler": [("under", "p", 1e9, 0.0)]}) + self.assertEqual(caught.exception.pin, "coupler under pin") + def test_a_wall_the_axis_crosses_in_a_zone_is_read_whatever_its_thickness(self): - # Soul's tunnel: a wall of the thigh across the coupler, midway between two of its samples, inside a zone - # about p of depth 0. Every sample stands outside it; the segment between them is what crosses + # Soul's tunnel: a wall of the rocker across the coupler, midway between two of its samples, inside a zone + # about p of depth 0. Every sample stands outside it; the segment between them is what crosses. The wall is + # the rocker's, which p joins, and stands in the rocker's frame, where the coupler's samples at -60 are `samples` m, ram = r3("bell_crank", CRANK), R.Ram(BORE) at = R.pose(m, -60.0) start = at.P[0] - np.array(X) * ((at.P[0] - at.C[0]) @ np.array(X)) count = int(math.ceil(m.lc / ram.spacing())) + 1 - samples = start + (at.C[0] - start) * np.linspace(0.0, 1.0, count)[:, None] + + def seen(n): + return R._into(m, at, "rocker", (start + (at.C[0] - start) * np.linspace(0.0, 1.0, n)[:, None])[None])[0] + samples = seen(count) spot = 0.5 * (samples[2] + samples[3]) - along = (at.C[0] - start) / m.lc + along = (samples[-1] - samples[0]) / m.lc k = 1 if abs(along[1]) > abs(along[2]) else 2 def reading(half, shift=0.0): @@ -684,7 +739,7 @@ class DeepKnee(unittest.TestCase): lo[k], hi[k] = spot[k] - half, spot[k] + half lo[0], hi[0] = X_COUPLER - 0.05 + shift, X_COUPLER + 0.05 + shift bodies = r3_parts(m, ram) - bodies.parts["wall"], bodies.shapes["wall"] = "parent", [("box", lo, hi)] + bodies.parts["wall"], bodies.shapes["wall"] = "rocker", [("box", lo, hi)] self.assertGreater(float(bodies("wall", samples).min()), 0.0) return R.clearance(dressed(m, bodies, {"coupler": [("wall", "p", 0.28, 0.0)]}), ram, [-60.0], bodies).pairs[("coupler", "wall")][0] for half in (0.01, 0.003, 1e-4, 1e-7, 1e-10): @@ -697,9 +752,9 @@ class DeepKnee(unittest.TestCase): self.assertGreaterEqual(reading(0.01, 0.05 + 1.2 * ram.spacing() / R.FINE), 0.0) # a segment with one end in the zone is proved as well. Sampled 0.3 apart, the sample beyond the zone keeps its # 0.186 from a bead on the axis 0.008 past the last sample in the zone; the bead is read all the same - wide = start + (at.C[0] - start) * np.linspace(0.0, 1.0, 3)[:, None] + wide = seen(3) bodies, spot = r3_parts(m, ram), wide[1] + 0.012 * along - bodies.parts["bead"], bodies.shapes["bead"] = "parent", [("capsule", spot, spot, 0.004)] + bodies.parts["bead"], bodies.shapes["bead"] = "rocker", [("capsule", spot, spot, 0.004)] self.assertGreater(float(bodies("bead", wide[:2]).min()), 0.0) self.assertGreaterEqual(float(bodies("bead", wide[2:])[0]), near(ram, "coupler", 0.3)) got = R.clearance(dressed(m, bodies, {"coupler": [("bead", "p", 0.25, 0.0)]}), ram, [-60.0], bodies, spacing=0.3) @@ -843,8 +898,13 @@ class OracleRule(unittest.TestCase): lugged = two(a=seats.shapes["a"] and ("parent", seats.shapes["a"]), b=("child", seats.shapes["b"]), **{"b.lug": ("child", seats.shapes["b"])}) got = R.clearance(dressed(m, lugged, zones), ram, 0.0, lugged) self.assertEqual({pair: round(reading[0], 9) for pair, reading in got.pairs.items() if reading[0] < 0.0}, {("rod[0]", "b.lug"): round(-0.03 - near(ram, "rod"), 9)}) - for crossed in ({"barrel": [("b", "b", 0.2, 0.03)], "rod": [("a", "a", 0.2, 0.03)]}, {"barrel": [("a", "b", 0.2, 0.03)], "rod": [("b", "a", 0.2, 0.03)]}): - self.assertLess(float(R.clearance(dressed(m, seats, crossed), ram, 0.0, seats).margin[0]), 0.0) + crossed = {"barrel": [("b", "b", 0.2, 0.03)], "rod": [("a", "a", 0.2, 0.03)]} + self.assertLess(float(R.clearance(dressed(m, seats, crossed), ram, 0.0, seats).margin[0]), 0.0) + # and a part zoned about the pin at the member's other end, which does not join its body, is no zone at all + for crossed, pin in (({"barrel": [("a", "b", 0.2, 0.03)]}, "barrel a pin"), ({"rod": [("b", "a", 0.2, 0.03)]}, "rod b pin")): + with self.assertRaises(R.RamError) as caught: + dressed(m, seats, crossed) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", pin)) def test_every_body_owns_a_part(self): ball = Bodies({"ball": ("parent", [("capsule", (0, 0, 0), (0, 0, 0), 0.1)])}) @@ -942,19 +1002,20 @@ class SearchBestFirst(unittest.TestCase): ((ball.parts, {}, None), "search", "world(m) returns"), ((ball.parts, {"rod": ["parent"]}, ball), "record", "zone is (part, pin, radius, depth)"), ((ball.parts, {"rod": [("parent", "c", 1.0, 0.0)]}, ball), "record", "a pin it rides (a, b)"), ((ball.parts, {"rod": [("thigh", "b", 1.0, 0.0)]}, ball), "record", "no part of the record"), - ((ball.parts, {"rod": [("parent", "b", 1e308, 0.0)]}, ball), "record", "rod is at most"), - ((ball.parts, {"rod": [("parent", "b", 0.5, 1e308)]}, ball), "record", "rod is at most"), - ((ball.parts, {"rod": [("parent", "b", 1e9, 1e9)]}, ball), "record", "rod is at most"), - ((ball.parts, {"rod": [("parent", "b", float("inf"), 0.0)]}, ball), "record", "a finite number"), - ((ball.parts, {"rod": [("parent", "b", 0.5, float("nan"))]}, ball), "record", "a finite number"), - ((ball.parts, {"rod": [("parent", "b", 0.5, 1.2 * ram.e_b)]}, ball), "record", "rod's on b is 0.0850"), + ((ball.parts, {"rod": [("child", "b", 1e308, 0.0)]}, ball), "record", "rod is at most"), + ((ball.parts, {"rod": [("parent", "b", 0.5, 0.0)]}, ball), "record", "a body the pin joins (child); 'parent' turns with parent"), + ((ball.parts, {"rod": [("child", "b", 0.5, 1e308)]}, ball), "record", "rod is at most"), + ((ball.parts, {"rod": [("child", "b", 1e9, 1e9)]}, ball), "record", "rod is at most"), + ((ball.parts, {"rod": [("child", "b", float("inf"), 0.0)]}, ball), "record", "a finite number"), + ((ball.parts, {"rod": [("child", "b", 0.5, float("nan"))]}, ball), "record", "a finite number"), + ((ball.parts, {"rod": [("child", "b", 0.5, 1.2 * ram.e_b)]}, ball), "record", "rod's on b is 0.0850"), (({"ball": "rocker"}, {}, ball), "record", "turns with 'rocker'"), (({"ball": "parent"}, {}, ball), "record", "no part turns with body child")): with self.assertRaises(R.RamError) as caught: R.search("direct", self.HINGE, ram, seats, world=lambda m: made) self.assertEqual(caught.exception.gate, gate, said) self.assertIn(said, str(caught.exception)) self.assertTrue(R.search("direct", self.HINGE, ram, seats, world=lambda m: (ball.parts, {}, ball)).found) - self.assertTrue(R.search("direct", self.HINGE, ram, seats, world=lambda m: (ball.parts, {"rod": [("parent", "b", 0.5, ram.e_b)]}, ball)).found) + self.assertTrue(R.search("direct", self.HINGE, ram, seats, world=lambda m: (ball.parts, {"rod": [("child", "b", 0.5, ram.e_b)]}, ball)).found) def test_the_limit_is_refused_naming_the_count(self): seats = {"a": grid((0, -0.5, 0.4), (0, -0.2, 1.2), (1, 3, 5)), "b": grid((0, -0.5, -1.2), (0, -0.2, -0.4), (1, 3, 5))} @@ -1082,7 +1143,8 @@ class RecordDrives(unittest.TestCase): ({"parts": {"knee": "parent"}, "touch": {"rod": "knee"}}, "rod's zones are a list"), ({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1}]}}, "missing ['depth']"), ({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0.0, "whole": True}]}}, "unknown ['whole']"), - ({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": None, "depth": 0.0}]}}, "(pin rod knee radius)")): + ({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": None, "depth": 0.0}]}}, "(pin rod knee radius)"), + ({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0.0}]}}, "(pin rod knee pin): rod may touch about b a part of a body the pin joins (child)")): with self.assertRaises(R.RamError) as caught: R.from_record({**data, **change}) self.assertEqual(caught.exception.gate, "record", change) @@ -1090,7 +1152,7 @@ class RecordDrives(unittest.TestCase): with self.assertRaises(R.RamError) as caught: R.from_record([data]) self.assertIn("a record is an object, got list", str(caught.exception)) - zoned = R.from_record({**data, "parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0}]}})[0] + zoned = R.from_record({**data, "parts": {"knee": "child"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0}]}})[0] self.assertEqual(zoned.touch, {"rod": (("knee", "b", 0.1, 0.0),)}) # a ram refuses the same numbers when built by hand for bad in ({"bore": -0.05}, {"bore": 0.0}, {"bore": None}, {"bore": True}, {"bore": 0.05, "gap": float("nan")}, {"bore": 0.05, "tail": float("inf")}, {"bore": 0.05, "rod": "0.02"}): @@ -1144,6 +1206,8 @@ class Refusals(unittest.TestCase): self.refused("record", "rod knee radius", **knee, touch={"rod": [("knee", "d", "0.1", 0.0)]}) self.refused("record", "rod knee depth", **knee, touch={"rod": [("knee", "d", 0.1, -0.01)]}) self.refused("record", "rod knee depth", **knee, touch={"rod": [("knee", "d", 0.1, float("nan"))]}) + self.assertIn("a body the pin joins (rocker); 'knee' turns with parent", str(self.refused("record", "rod knee pin", **knee, touch={"rod": [("knee", "d", 0.1, 0.0)]}))) + self.assertEqual(R.Mechanism("four_bar", O, X, -125, 0, **{name: yz(DEEP[name]) for name in DEEP}, **knee, touch={"rod": [("knee", "a", 0.1, 0.0)]}).touch["rod"], (("knee", "a", 0.1, 0.0),)) self.refused("record", "a", a=(0, 1)) self.refused("record", "c", c=(0, float("nan"), 1)) self.refused("record", "b", b=(0, 0, -1)) # a four-bar has no b From 60348312885555b99eb1c9075fdaa0850c8f401b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:39:32 +0100 Subject: [PATCH 156/223] test_ram: Soul s4's surviving mutants die; the two off-margin bounds restated by the margin ruling FINE is read as 64 and the floor's crossover (0.451 of spacing/64) is bounded at 0.319 and 0.638: FINE 128 (0.2255) and FINE 32 (0.902) each fail, as do 8 and 4096. A bead of the shin before the first sample of a zone about c kills the left-only pair. A base 0.1 from the rocker's pivot kills the ram's span taken about the knee's pivot (0.539 against 1.335, bound 0.848). The -0.9 link_r bounds become deviations from hand values (ZONED), the >= 0.02 bound a deviation from the nearest sample's reading (BESIDE, against B1: the proof by the nearer end less the span). Each constant states shipped, mutant and separation. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/test_ram.py | 59 ++++++++++++++++++++++++------ 1 file changed, 48 insertions(+), 11 deletions(-) diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py index 8a8c12d..1d43a83 100644 --- a/surfaces/blender/tests/test_ram.py +++ b/surfaces/blender/tests/test_ram.py @@ -499,6 +499,15 @@ SWING_BOUND = 0.81 TOGGLE_ARM = 0.0386 +# The clearance gate's zones on the R-3 bell crank. A reading a hand value states is bounded by its deviation from it; +# a shipped deviation of 0 counts as half an ulp of the value (lodur:ruling:deterministic-bound-zero-reading). +ZONED = 2.2e-10 # a rocker sample against its own plates: shipped 0 (half an ulp of link_r, 1.7e-18), W1..W3 (a zone's edge strict, the first zone only, the last zone overriding) 0.0294 and 0.0914 off, separation 1.3e8 each side +BESIDE = 1.2e-10 # a wall 0.02 beside the coupler, read at the nearest sample: shipped 0 (half an ulp of 0.0242, 1.7e-18), B1 (the proof by the nearer end's reading less the span, which halves and reads beside the wall) 0.00423 off, separation 4.9e7 each side +FLOOR_UNDER = 0.319 # how near the axis a wall held outside reads as touched, in spacing / 64: shipped under 0.451, FINE 128 under 0.2255, separation 1.41 each side +FLOOR_OVER = 0.638 # shipped under 0.451, FINE 32 under 0.902, separation 1.41 each side +SPAN_RAM = 0.848 # the ram's span with its base 0.1 from the rocker's pivot: shipped 0.5390 (about that pivot), the span about the knee's pivot 1.3347, separation 1.57 each side + + @unittest.skipIf(np is None, "numpy is not installed") class DeepKnee(unittest.TestCase): """The R-3 knee over 0..-125 (probes P1 to P3).""" @@ -653,6 +662,16 @@ class DeepKnee(unittest.TestCase): self.assertAlmostEqual(R._span(m, "rocker arm"), 0.24, places=9) self.assertGreaterEqual(R._span(m, "rod"), float(R.pose(m, np.linspace(-125.0, 0.0, 126)).L.max())) self.assertEqual([ram.eye(*of) for of in (("barrel", "a"), ("rod", "a"), ("rod", "d"), ("coupler", "c"))], [ram.e_a, ram.e_a, ram.e_b, ram.link_r]) + # a linkage's ram spans from the rocker's pivot, which its eye turns about, not the knee's: a base seated 0.1 + # from the rocker's pivot makes a ram of 0.539 at the most, and a zone between that and the 1.335 the knee's + # pivot would give is refused + seated = replace(m, a=m.rocker + (0.0, 0.0, 0.1), parts=bodies.parts) + self.assertAlmostEqual(R._span(seated, "rod"), 0.1 + math.hypot(X_ROCKER, 0.24), places=12) + for member in ("barrel", "rod"): + replace(seated, touch={member: [("thigh", "a", 0.53, 0.0)]}) + with self.assertRaises(R.RamError) as caught: + replace(seated, touch={member: [("thigh", "a", SPAN_RAM, 0.0)]}) + self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} thigh radius")) for member, pin, part in (("barrel", "a", "thigh"), ("rod", "d", "pin d"), ("rocker", "p", "coupler plates"), ("coupler", "c", "horn"), ("rocker arm", "rocker", "bracket")): span, eye = R._span(m, member), ram.eye(member, pin) @@ -727,8 +746,8 @@ class DeepKnee(unittest.TestCase): start = at.P[0] - np.array(X) * ((at.P[0] - at.C[0]) @ np.array(X)) count = int(math.ceil(m.lc / ram.spacing())) + 1 - def seen(n): - return R._into(m, at, "rocker", (start + (at.C[0] - start) * np.linspace(0.0, 1.0, n)[:, None])[None])[0] + def seen(n, body="rocker"): + return R._into(m, at, body, (start + (at.C[0] - start) * np.linspace(0.0, 1.0, n)[:, None])[None])[0] samples = seen(count) spot = 0.5 * (samples[2] + samples[3]) along = (samples[-1] - samples[0]) / m.lc @@ -740,16 +759,22 @@ class DeepKnee(unittest.TestCase): lo[0], hi[0] = X_COUPLER - 0.05 + shift, X_COUPLER + 0.05 + shift bodies = r3_parts(m, ram) bodies.parts["wall"], bodies.shapes["wall"] = "rocker", [("box", lo, hi)] - self.assertGreater(float(bodies("wall", samples).min()), 0.0) + reading.sampled = float(bodies("wall", samples).min()) + self.assertGreater(reading.sampled, 0.0) return R.clearance(dressed(m, bodies, {"coupler": [("wall", "p", 0.28, 0.0)]}), ram, [-60.0], bodies).pairs[("coupler", "wall")][0] for half in (0.01, 0.003, 1e-4, 1e-7, 1e-10): self.assertLess(reading(half), 0.0, half) - # the same walls beside the axis, 0.02 off along the hinge axis: held outside, and let + # the same walls beside the axis, 0.02 off along the hinge axis: held outside, and let. The samples either + # side prove the segment, so the reading is the nearer sample's (0.0242: 0.02 across, 0.0137 along), not the + # 0.02 a point between them would read for half in (0.01, 1e-7): - self.assertGreaterEqual(reading(half, 0.07), 0.02) - # nearer the axis than the floor of the halving, a part the axis is held outside reads as touched - self.assertLess(reading(0.01, 0.05 + 0.2 * ram.spacing() / R.FINE), 0.0) - self.assertGreaterEqual(reading(0.01, 0.05 + 1.2 * ram.spacing() / R.FINE), 0.0) + self.assertLess(abs(reading(half, 0.07) - reading.sampled), BESIDE, half) + self.assertGreater(reading.sampled, 0.024) + # nearer the axis than the floor of the halving, a part the axis is held outside reads as touched. The floor is + # the spacing over 64, written here as the number: the doc's, and what the gate's cost was measured at + self.assertEqual(R.FINE, 64) + self.assertLess(reading(0.01, 0.05 + FLOOR_UNDER * ram.spacing() / 64), 0.0) + self.assertGreaterEqual(reading(0.01, 0.05 + FLOOR_OVER * ram.spacing() / 64), 0.0) # a segment with one end in the zone is proved as well. Sampled 0.3 apart, the sample beyond the zone keeps its # 0.186 from a bead on the axis 0.008 past the last sample in the zone; the bead is read all the same wide = seen(3) @@ -759,6 +784,15 @@ class DeepKnee(unittest.TestCase): self.assertGreaterEqual(float(bodies("bead", wide[2:])[0]), near(ram, "coupler", 0.3)) got = R.clearance(dressed(m, bodies, {"coupler": [("bead", "p", 0.25, 0.0)]}), ram, [-60.0], bodies, spacing=0.3) self.assertLess(got.pairs[("coupler", "bead")][0], 0.0) + # and so is the segment whose far end alone is in the zone: a bead of the shin 0.008 short of the first sample + # in a zone about c, the sample before it out of the zone and keeping its 0.186 + wide = seen(3, "child") + bodies, spot = r3_parts(m, ram), wide[1] - 0.012 * (wide[2] - wide[0]) / m.lc + bodies.parts["bead"], bodies.shapes["bead"] = "child", [("capsule", spot, spot, 0.004)] + self.assertGreater(float(bodies("bead", wide[1:]).min()), 0.0) + self.assertGreaterEqual(float(bodies("bead", wide[:1])[0]), near(ram, "coupler", 0.3)) + got = R.clearance(dressed(m, bodies, {"coupler": [("bead", "c", 0.25, 0.0)]}), ram, [-60.0], bodies, spacing=0.3) + self.assertLess(got.pairs[("coupler", "bead")][0], 0.0) def test_two_zones_of_one_pair_and_a_sample_at_a_zones_radius(self): # Soul's W1..W3. A pair zoned twice: a sample both reach is let the deeper, in either order, and each zone @@ -773,8 +807,11 @@ class DeepKnee(unittest.TestCase): self.assertAlmostEqual(reading(deep, beside, far), 0.0, places=12) self.assertAlmostEqual(reading(beside, deep, far), 0.0, places=12) self.assertAlmostEqual(reading(far, beside, deep), 0.0, places=12) - for short in ((beside, beside, far), (deep, beside), (far, deep[:2] + (0.3 * m.lr, ram.link_r))): - self.assertLess(reading(*short), -0.9 * ram.link_r, short) + # short of that the sample reads what it is: link_r inside its own plate where the zone holds it outside, and + # where no zone reaches it link_r inside and all it keeps short + own = ram.link_r + near(ram, "rocker") + for short, reads in (((beside, beside, far), -ram.link_r), ((deep, beside), -own), ((far, deep[:2] + (0.3 * m.lr, ram.link_r)), -own)): + self.assertLess(abs(reading(*short) - reads), ZONED, short) at = R.pose(m, [-60.0]) end = at.P - np.array(X) * ((at.P - m.rocker) @ np.array(X))[:, None] count = int(math.ceil(m.lr / ram.spacing())) + 1 @@ -782,7 +819,7 @@ class DeepKnee(unittest.TestCase): across = np.linalg.norm(R._flat(pts - m.rocker, np.array(X)), axis=2)[0] edge, beyond = float(across[3]), m.lr - 0.5 * float(across[3] + across[4]) self.assertAlmostEqual(reading(("rocker plates", "rocker", edge, ram.link_r), ("rocker plates", "p", beyond, ram.link_r), degrees=[-60.0]), 0.0, places=12) - self.assertLess(reading(("rocker plates", "rocker", float(np.nextafter(edge, 0.0)), ram.link_r), ("rocker plates", "p", beyond, ram.link_r), degrees=[-60.0]), -0.9 * ram.link_r) + self.assertLess(abs(reading(("rocker plates", "rocker", float(np.nextafter(edge, 0.0)), ram.link_r), ("rocker plates", "p", beyond, ram.link_r), degrees=[-60.0]) + own), ZONED) def test_a_pin_stood_inside_what_it_stands_beside_is_refused(self): # Soul's moved-x probes: the rocker's x moved from its plate's place (0.3675) into the bracket's 0.13..0.35, From 2be27f0c0c34407454de7953ca23c0582f4d8d90 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:40:57 +0100 Subject: [PATCH 157/223] live ram_knee: the oracle's rays held from inside: 29 points inside the jointlib rocker plates Soul s4 (ray-fixture-pins-above-one-not-three, crossing-proof-needs-a-sign- true-oracle): the fixture held only points outside the plates, which two rays or an axis-aligned pair read as three do. ram_rays.json gains `inside`: points 0.001 or more inside one of the shell's four convex pieces, nine aimed along a ray, x or y, twenty where a side's two bars overlap. The oracle as made reads 0 outside; two rays 16, one ray 10, the second ray the first 10, the second and third along x and y 6. The check asks 0 and at least 2. The fixture's `about` says what this does not show: fed as one shell the overlap is signed by parity, and three rays read 1,906 of 38,448 inside grid points outside; with each piece its own shell, none. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/fixtures/ram_rays.json | 2 +- surfaces/blender/tests/live/ram_knee.py | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/tests/fixtures/ram_rays.json b/surfaces/blender/tests/fixtures/ram_rays.json index 788d9ee..37c414c 100644 --- a/surfaces/blender/tests/fixtures/ram_rays.json +++ b/surfaces/blender/tests/fixtures/ram_rays.json @@ -1 +1 @@ -{"about":"The rocker's twin plates of the R-3 bell crank as Imagination's jointlib builds them (one shell, triangulated, at rest), and points between the plates (|x| under 0.349, the plates begin at 0.35): each stands on the oracle's first ray 0.004 to 0.02 short of a vertex or an edge of the shell. Every point is outside.","verts":[[-0.349999994,0.740011215,0.389170021],[-0.349999994,0.752862871,0.394919485],[-0.349999994,0.763308823,0.404358923],[-0.349999994,0.770326555,0.416564375],[-0.349999994,0.773229182,0.430341005],[-0.349999994,0.77173245,0.444340348],[-0.349999994,0.765982985,0.457191974],[-0.349999994,0.756543517,0.467637926],[-0.349999994,0.744338095,0.474655658],[-0.349999994,0.730561495,0.477558255],[-0.349999994,0.716562152,0.476061553],[-0.349999994,0.305388123,0.365099549],[-0.349999994,0.292536497,0.359350085],[-0.349999994,0.282090545,0.349910617],[-0.349999994,0.275072783,0.337705195],[-0.349999994,0.272170216,0.323928565],[-0.349999994,0.273666918,0.309929222],[-0.349999994,0.279416382,0.297077596],[-0.349999994,0.288855821,0.286631644],[-0.349999994,0.301061243,0.279613912],[-0.349999994,0.314837903,0.276711315],[-0.349999994,0.328837216,0.278208017],[-0.38499999,0.740011215,0.389170021],[-0.38499999,0.752862871,0.394919485],[-0.38499999,0.763308823,0.404358923],[-0.38499999,0.770326555,0.416564375],[-0.38499999,0.773229182,0.430341005],[-0.38499999,0.77173245,0.444340348],[-0.38499999,0.765982985,0.457191974],[-0.38499999,0.756543517,0.467637926],[-0.38499999,0.744338095,0.474655658],[-0.38499999,0.730561495,0.477558255],[-0.38499999,0.716562152,0.476061553],[-0.38499999,0.305388123,0.365099549],[-0.38499999,0.292536497,0.359350085],[-0.38499999,0.282090545,0.349910617],[-0.38499999,0.275072783,0.337705195],[-0.38499999,0.272170216,0.323928565],[-0.38499999,0.273666918,0.309929222],[-0.38499999,0.279416382,0.297077596],[-0.38499999,0.288855821,0.286631644],[-0.38499999,0.301061243,0.279613912],[-0.38499999,0.314837903,0.276711315],[-0.38499999,0.328837216,0.278208017],[-0.349999994,0.514849424,0.463428885],[-0.349999994,0.522187293,0.473566681],[-0.349999994,0.526033282,0.485475808],[-0.349999994,0.526010931,0.497990549],[-0.349999994,0.522122383,0.509885848],[-0.349999994,0.514748275,0.519997358],[-0.349999994,0.504610479,0.527335227],[-0.349999994,0.492701381,0.531181216],[-0.349999994,0.480186641,0.531158805],[-0.349999994,0.468291312,0.527270257],[-0.349999994,0.458179832,0.519896209],[-0.349999994,0.288777888,0.349887431],[-0.349999994,0.28144002,0.339749664],[-0.349999994,0.27759403,0.327840507],[-0.349999994,0.277616382,0.315325767],[-0.349999994,0.281504929,0.303430468],[-0.349999994,0.288879007,0.293318987],[-0.349999994,0.299016804,0.285981119],[-0.349999994,0.310925931,0.282135129],[-0.349999994,0.323440671,0.282157511],[-0.349999994,0.335336,0.286046058],[-0.349999994,0.345447481,0.293420136],[-0.38499999,0.514849424,0.463428885],[-0.38499999,0.522187293,0.473566681],[-0.38499999,0.526033282,0.485475808],[-0.38499999,0.526010931,0.497990549],[-0.38499999,0.522122383,0.509885848],[-0.38499999,0.514748275,0.519997358],[-0.38499999,0.504610479,0.527335227],[-0.38499999,0.492701381,0.531181216],[-0.38499999,0.480186641,0.531158805],[-0.38499999,0.468291312,0.527270257],[-0.38499999,0.458179832,0.519896209],[-0.38499999,0.288777888,0.349887431],[-0.38499999,0.28144002,0.339749664],[-0.38499999,0.27759403,0.327840507],[-0.38499999,0.277616382,0.315325767],[-0.38499999,0.281504929,0.303430468],[-0.38499999,0.288879007,0.293318987],[-0.38499999,0.299016804,0.285981119],[-0.38499999,0.310925931,0.282135129],[-0.38499999,0.323440671,0.282157511],[-0.38499999,0.335336,0.286046058],[-0.38499999,0.345447481,0.293420136],[0.349999994,0.740011215,0.389170021],[0.349999994,0.752862871,0.394919485],[0.349999994,0.763308823,0.404358923],[0.349999994,0.770326555,0.416564375],[0.349999994,0.773229182,0.430341005],[0.349999994,0.77173245,0.444340348],[0.349999994,0.765982985,0.457191974],[0.349999994,0.756543517,0.467637926],[0.349999994,0.744338095,0.474655658],[0.349999994,0.730561495,0.477558255],[0.349999994,0.716562152,0.476061553],[0.349999994,0.305388123,0.365099549],[0.349999994,0.292536497,0.359350085],[0.349999994,0.282090545,0.349910617],[0.349999994,0.275072783,0.337705195],[0.349999994,0.272170216,0.323928565],[0.349999994,0.273666918,0.309929222],[0.349999994,0.279416382,0.297077596],[0.349999994,0.288855821,0.286631644],[0.349999994,0.301061243,0.279613912],[0.349999994,0.314837903,0.276711315],[0.349999994,0.328837216,0.278208017],[0.38499999,0.740011215,0.389170021],[0.38499999,0.752862871,0.394919485],[0.38499999,0.763308823,0.404358923],[0.38499999,0.770326555,0.416564375],[0.38499999,0.773229182,0.430341005],[0.38499999,0.77173245,0.444340348],[0.38499999,0.765982985,0.457191974],[0.38499999,0.756543517,0.467637926],[0.38499999,0.744338095,0.474655658],[0.38499999,0.730561495,0.477558255],[0.38499999,0.716562152,0.476061553],[0.38499999,0.305388123,0.365099549],[0.38499999,0.292536497,0.359350085],[0.38499999,0.282090545,0.349910617],[0.38499999,0.275072783,0.337705195],[0.38499999,0.272170216,0.323928565],[0.38499999,0.273666918,0.309929222],[0.38499999,0.279416382,0.297077596],[0.38499999,0.288855821,0.286631644],[0.38499999,0.301061243,0.279613912],[0.38499999,0.314837903,0.276711315],[0.38499999,0.328837216,0.278208017],[0.349999994,0.514849424,0.463428885],[0.349999994,0.522187293,0.473566681],[0.349999994,0.526033282,0.485475808],[0.349999994,0.526010931,0.497990549],[0.349999994,0.522122383,0.509885848],[0.349999994,0.514748275,0.519997358],[0.349999994,0.504610479,0.527335227],[0.349999994,0.492701381,0.531181216],[0.349999994,0.480186641,0.531158805],[0.349999994,0.468291312,0.527270257],[0.349999994,0.458179832,0.519896209],[0.349999994,0.288777888,0.349887431],[0.349999994,0.28144002,0.339749664],[0.349999994,0.27759403,0.327840507],[0.349999994,0.277616382,0.315325767],[0.349999994,0.281504929,0.303430468],[0.349999994,0.288879007,0.293318987],[0.349999994,0.299016804,0.285981119],[0.349999994,0.310925931,0.282135129],[0.349999994,0.323440671,0.282157511],[0.349999994,0.335336,0.286046058],[0.349999994,0.345447481,0.293420136],[0.38499999,0.514849424,0.463428885],[0.38499999,0.522187293,0.473566681],[0.38499999,0.526033282,0.485475808],[0.38499999,0.526010931,0.497990549],[0.38499999,0.522122383,0.509885848],[0.38499999,0.514748275,0.519997358],[0.38499999,0.504610479,0.527335227],[0.38499999,0.492701381,0.531181216],[0.38499999,0.480186641,0.531158805],[0.38499999,0.468291312,0.527270257],[0.38499999,0.458179832,0.519896209],[0.38499999,0.288777888,0.349887431],[0.38499999,0.28144002,0.339749664],[0.38499999,0.27759403,0.327840507],[0.38499999,0.277616382,0.315325767],[0.38499999,0.281504929,0.303430468],[0.38499999,0.288879007,0.293318987],[0.38499999,0.299016804,0.285981119],[0.38499999,0.310925931,0.282135129],[0.38499999,0.323440671,0.282157511],[0.38499999,0.335336,0.286046058],[0.38499999,0.345447481,0.293420136]],"faces":[[19,21,11],[24,22,32],[22,1,0],[23,2,1],[24,3,2],[25,4,3],[26,5,4],[27,6,5],[28,7,6],[29,8,7],[30,9,8],[31,10,9],[32,11,10],[33,12,11],[34,13,12],[35,14,13],[36,15,14],[37,16,15],[38,17,16],[39,18,17],[40,19,18],[41,20,19],[42,21,20],[43,0,21],[63,65,55],[68,66,76],[66,45,44],[67,46,45],[68,47,46],[69,48,47],[70,49,48],[71,50,49],[72,51,50],[73,52,51],[74,53,52],[75,54,53],[76,55,54],[77,56,55],[78,57,56],[79,58,57],[80,59,58],[81,60,59],[82,61,60],[83,62,61],[84,63,62],[85,64,63],[86,65,64],[87,44,65],[95,93,91],[122,124,128],[89,110,88],[90,111,89],[91,112,90],[92,113,91],[93,114,92],[94,115,93],[95,116,94],[96,117,95],[97,118,96],[98,119,97],[99,120,98],[100,121,99],[101,122,100],[102,123,101],[103,124,102],[104,125,103],[105,126,104],[106,127,105],[107,128,106],[108,129,107],[109,130,108],[88,131,109],[141,139,135],[166,168,172],[133,154,132],[134,155,133],[135,156,134],[136,157,135],[137,158,136],[138,159,137],[139,160,138],[140,161,139],[141,162,140],[142,163,141],[143,164,142],[144,165,143],[145,166,144],[146,167,145],[147,168,146],[148,169,147],[149,170,148],[150,171,149],[151,172,150],[152,173,151],[153,174,152],[132,175,153],[21,0,10],[0,1,10],[1,2,3],[3,4,5],[5,6,7],[7,8,9],[9,10,3],[10,11,21],[3,10,1],[11,12,13],[13,14,15],[15,16,19],[16,17,19],[17,18,19],[19,20,21],[3,5,7],[7,9,3],[11,13,19],[13,15,19],[22,43,33],[43,42,33],[42,41,40],[40,39,38],[38,37,40],[37,36,40],[36,35,34],[34,33,40],[33,32,22],[40,33,42],[32,31,30],[30,29,28],[28,27,26],[26,25,28],[25,24,28],[24,23,22],[36,34,40],[32,30,24],[30,28,24],[22,23,1],[23,24,2],[24,25,3],[25,26,4],[26,27,5],[27,28,6],[28,29,7],[29,30,8],[30,31,9],[31,32,10],[32,33,11],[33,34,12],[34,35,13],[35,36,14],[36,37,15],[37,38,16],[38,39,17],[39,40,18],[40,41,19],[41,42,20],[42,43,21],[43,22,0],[65,44,54],[44,45,54],[45,46,47],[47,48,49],[49,50,47],[50,51,47],[51,52,53],[53,54,47],[54,55,65],[47,54,45],[55,56,57],[57,58,59],[59,60,61],[61,62,63],[63,64,65],[51,53,47],[55,57,63],[57,59,63],[59,61,63],[66,87,77],[87,86,77],[86,85,84],[84,83,80],[83,82,80],[82,81,80],[80,79,78],[78,77,84],[77,76,66],[84,77,86],[76,75,74],[74,73,72],[72,71,68],[71,70,68],[70,69,68],[68,67,66],[80,78,84],[76,74,68],[74,72,68],[66,67,45],[67,68,46],[68,69,47],[69,70,48],[70,71,49],[71,72,50],[72,73,51],[73,74,52],[74,75,53],[75,76,54],[76,77,55],[77,78,56],[78,79,57],[79,80,58],[80,81,59],[81,82,60],[82,83,61],[83,84,62],[84,85,63],[85,86,64],[86,87,65],[87,66,44],[89,88,98],[88,109,99],[109,108,107],[107,106,105],[105,104,107],[104,103,107],[103,102,101],[101,100,99],[99,98,88],[98,97,91],[97,96,95],[95,94,93],[93,92,91],[91,90,89],[109,107,99],[103,101,107],[101,99,107],[98,91,89],[97,95,91],[130,131,121],[131,110,120],[110,111,112],[112,113,116],[113,114,116],[114,115,116],[116,117,118],[118,119,120],[120,121,131],[121,122,128],[122,123,124],[124,125,128],[125,126,128],[126,127,128],[128,129,130],[110,112,120],[116,118,112],[118,120,112],[121,128,130],[89,111,110],[90,112,111],[91,113,112],[92,114,113],[93,115,114],[94,116,115],[95,117,116],[96,118,117],[97,119,118],[98,120,119],[99,121,120],[100,122,121],[101,123,122],[102,124,123],[103,125,124],[104,126,125],[105,127,126],[106,128,127],[107,129,128],[108,130,129],[109,131,130],[88,110,131],[133,132,142],[132,153,143],[153,152,151],[151,150,149],[149,148,147],[147,146,145],[145,144,143],[143,142,132],[142,141,135],[141,140,139],[139,138,135],[138,137,135],[137,136,135],[135,134,133],[153,151,143],[151,149,147],[147,145,151],[145,143,151],[142,135,133],[174,175,165],[175,154,164],[154,155,156],[156,157,158],[158,159,156],[159,160,156],[160,161,162],[162,163,164],[164,165,175],[165,166,172],[166,167,168],[168,169,170],[170,171,168],[171,172,168],[172,173,174],[154,156,164],[160,162,156],[162,164,156],[165,172,174],[133,155,154],[134,156,155],[135,157,156],[136,158,157],[137,159,158],[138,160,159],[139,161,160],[140,162,161],[141,163,162],[142,164,163],[143,165,164],[144,166,165],[145,167,166],[146,168,167],[147,169,168],[148,170,169],[149,171,170],[150,172,171],[151,173,172],[152,174,173],[153,175,174],[132,154,175]],"points":[[0.34569818,0.758339776,0.399797897],[0.34569818,0.765357508,0.412003349],[0.33924546,0.757903937,0.405161809],[0.34569818,0.768260135,0.425779979],[0.343547274,0.765775611,0.423499465],[0.33924546,0.760806564,0.418938439],[0.34569818,0.766763402,0.439779322],[0.343547274,0.764278879,0.437498808],[0.33924546,0.759309832,0.432937782],[0.34569818,0.761013938,0.452630947],[0.343547274,0.758529415,0.450350434],[0.33924546,0.753560368,0.445789407],[0.34569818,0.75157447,0.4630769],[0.343547274,0.749089947,0.460796386],[0.33924546,0.744120899,0.45623536],[0.347849087,0.741853572,0.472375145],[0.34569818,0.739369048,0.470094631],[0.343547274,0.736884525,0.467814118],[0.33924546,0.731915478,0.463253092],[0.347849087,0.728076971,0.475277742],[0.34569818,0.725592448,0.472997229],[0.343547274,0.723107924,0.470716715],[0.33924546,0.718138877,0.466155689],[0.347849087,0.714077628,0.473781039]]} \ No newline at end of file +{"about":"The rocker's twin plates of the R-3 bell crank as Imagination's jointlib builds them (one shell, triangulated, at rest), and points between the plates (|x| under 0.349, the plates begin at 0.35): each stands on the oracle's first ray 0.004 to 0.02 short of a vertex or an edge of the shell. Every point is outside. `inside`: points 0.001 or more inside one of the shell's four pieces (each a convex prism; a side's two bars overlap about the pivot and share their faces' planes): nine aimed along a ray of RAYS, x or y at a vertex or an edge, the rest from a grid where the bars overlap. Fed as one shell, as here, the overlap is where a ray's parity fails: the oracle as it is made reads every one of these inside; two rays, one ray, a second ray equal to the first, or the second and third along x and y each read some outside. They hold the rays. They do not show that the oracle signs this shell truly: of 38,448 grid points inside it, three rays read 1,906 outside with the pieces one shell and none with each piece its own shell.","verts":[[-0.349999994,0.740011215,0.389170021],[-0.349999994,0.752862871,0.394919485],[-0.349999994,0.763308823,0.404358923],[-0.349999994,0.770326555,0.416564375],[-0.349999994,0.773229182,0.430341005],[-0.349999994,0.77173245,0.444340348],[-0.349999994,0.765982985,0.457191974],[-0.349999994,0.756543517,0.467637926],[-0.349999994,0.744338095,0.474655658],[-0.349999994,0.730561495,0.477558255],[-0.349999994,0.716562152,0.476061553],[-0.349999994,0.305388123,0.365099549],[-0.349999994,0.292536497,0.359350085],[-0.349999994,0.282090545,0.349910617],[-0.349999994,0.275072783,0.337705195],[-0.349999994,0.272170216,0.323928565],[-0.349999994,0.273666918,0.309929222],[-0.349999994,0.279416382,0.297077596],[-0.349999994,0.288855821,0.286631644],[-0.349999994,0.301061243,0.279613912],[-0.349999994,0.314837903,0.276711315],[-0.349999994,0.328837216,0.278208017],[-0.38499999,0.740011215,0.389170021],[-0.38499999,0.752862871,0.394919485],[-0.38499999,0.763308823,0.404358923],[-0.38499999,0.770326555,0.416564375],[-0.38499999,0.773229182,0.430341005],[-0.38499999,0.77173245,0.444340348],[-0.38499999,0.765982985,0.457191974],[-0.38499999,0.756543517,0.467637926],[-0.38499999,0.744338095,0.474655658],[-0.38499999,0.730561495,0.477558255],[-0.38499999,0.716562152,0.476061553],[-0.38499999,0.305388123,0.365099549],[-0.38499999,0.292536497,0.359350085],[-0.38499999,0.282090545,0.349910617],[-0.38499999,0.275072783,0.337705195],[-0.38499999,0.272170216,0.323928565],[-0.38499999,0.273666918,0.309929222],[-0.38499999,0.279416382,0.297077596],[-0.38499999,0.288855821,0.286631644],[-0.38499999,0.301061243,0.279613912],[-0.38499999,0.314837903,0.276711315],[-0.38499999,0.328837216,0.278208017],[-0.349999994,0.514849424,0.463428885],[-0.349999994,0.522187293,0.473566681],[-0.349999994,0.526033282,0.485475808],[-0.349999994,0.526010931,0.497990549],[-0.349999994,0.522122383,0.509885848],[-0.349999994,0.514748275,0.519997358],[-0.349999994,0.504610479,0.527335227],[-0.349999994,0.492701381,0.531181216],[-0.349999994,0.480186641,0.531158805],[-0.349999994,0.468291312,0.527270257],[-0.349999994,0.458179832,0.519896209],[-0.349999994,0.288777888,0.349887431],[-0.349999994,0.28144002,0.339749664],[-0.349999994,0.27759403,0.327840507],[-0.349999994,0.277616382,0.315325767],[-0.349999994,0.281504929,0.303430468],[-0.349999994,0.288879007,0.293318987],[-0.349999994,0.299016804,0.285981119],[-0.349999994,0.310925931,0.282135129],[-0.349999994,0.323440671,0.282157511],[-0.349999994,0.335336,0.286046058],[-0.349999994,0.345447481,0.293420136],[-0.38499999,0.514849424,0.463428885],[-0.38499999,0.522187293,0.473566681],[-0.38499999,0.526033282,0.485475808],[-0.38499999,0.526010931,0.497990549],[-0.38499999,0.522122383,0.509885848],[-0.38499999,0.514748275,0.519997358],[-0.38499999,0.504610479,0.527335227],[-0.38499999,0.492701381,0.531181216],[-0.38499999,0.480186641,0.531158805],[-0.38499999,0.468291312,0.527270257],[-0.38499999,0.458179832,0.519896209],[-0.38499999,0.288777888,0.349887431],[-0.38499999,0.28144002,0.339749664],[-0.38499999,0.27759403,0.327840507],[-0.38499999,0.277616382,0.315325767],[-0.38499999,0.281504929,0.303430468],[-0.38499999,0.288879007,0.293318987],[-0.38499999,0.299016804,0.285981119],[-0.38499999,0.310925931,0.282135129],[-0.38499999,0.323440671,0.282157511],[-0.38499999,0.335336,0.286046058],[-0.38499999,0.345447481,0.293420136],[0.349999994,0.740011215,0.389170021],[0.349999994,0.752862871,0.394919485],[0.349999994,0.763308823,0.404358923],[0.349999994,0.770326555,0.416564375],[0.349999994,0.773229182,0.430341005],[0.349999994,0.77173245,0.444340348],[0.349999994,0.765982985,0.457191974],[0.349999994,0.756543517,0.467637926],[0.349999994,0.744338095,0.474655658],[0.349999994,0.730561495,0.477558255],[0.349999994,0.716562152,0.476061553],[0.349999994,0.305388123,0.365099549],[0.349999994,0.292536497,0.359350085],[0.349999994,0.282090545,0.349910617],[0.349999994,0.275072783,0.337705195],[0.349999994,0.272170216,0.323928565],[0.349999994,0.273666918,0.309929222],[0.349999994,0.279416382,0.297077596],[0.349999994,0.288855821,0.286631644],[0.349999994,0.301061243,0.279613912],[0.349999994,0.314837903,0.276711315],[0.349999994,0.328837216,0.278208017],[0.38499999,0.740011215,0.389170021],[0.38499999,0.752862871,0.394919485],[0.38499999,0.763308823,0.404358923],[0.38499999,0.770326555,0.416564375],[0.38499999,0.773229182,0.430341005],[0.38499999,0.77173245,0.444340348],[0.38499999,0.765982985,0.457191974],[0.38499999,0.756543517,0.467637926],[0.38499999,0.744338095,0.474655658],[0.38499999,0.730561495,0.477558255],[0.38499999,0.716562152,0.476061553],[0.38499999,0.305388123,0.365099549],[0.38499999,0.292536497,0.359350085],[0.38499999,0.282090545,0.349910617],[0.38499999,0.275072783,0.337705195],[0.38499999,0.272170216,0.323928565],[0.38499999,0.273666918,0.309929222],[0.38499999,0.279416382,0.297077596],[0.38499999,0.288855821,0.286631644],[0.38499999,0.301061243,0.279613912],[0.38499999,0.314837903,0.276711315],[0.38499999,0.328837216,0.278208017],[0.349999994,0.514849424,0.463428885],[0.349999994,0.522187293,0.473566681],[0.349999994,0.526033282,0.485475808],[0.349999994,0.526010931,0.497990549],[0.349999994,0.522122383,0.509885848],[0.349999994,0.514748275,0.519997358],[0.349999994,0.504610479,0.527335227],[0.349999994,0.492701381,0.531181216],[0.349999994,0.480186641,0.531158805],[0.349999994,0.468291312,0.527270257],[0.349999994,0.458179832,0.519896209],[0.349999994,0.288777888,0.349887431],[0.349999994,0.28144002,0.339749664],[0.349999994,0.27759403,0.327840507],[0.349999994,0.277616382,0.315325767],[0.349999994,0.281504929,0.303430468],[0.349999994,0.288879007,0.293318987],[0.349999994,0.299016804,0.285981119],[0.349999994,0.310925931,0.282135129],[0.349999994,0.323440671,0.282157511],[0.349999994,0.335336,0.286046058],[0.349999994,0.345447481,0.293420136],[0.38499999,0.514849424,0.463428885],[0.38499999,0.522187293,0.473566681],[0.38499999,0.526033282,0.485475808],[0.38499999,0.526010931,0.497990549],[0.38499999,0.522122383,0.509885848],[0.38499999,0.514748275,0.519997358],[0.38499999,0.504610479,0.527335227],[0.38499999,0.492701381,0.531181216],[0.38499999,0.480186641,0.531158805],[0.38499999,0.468291312,0.527270257],[0.38499999,0.458179832,0.519896209],[0.38499999,0.288777888,0.349887431],[0.38499999,0.28144002,0.339749664],[0.38499999,0.27759403,0.327840507],[0.38499999,0.277616382,0.315325767],[0.38499999,0.281504929,0.303430468],[0.38499999,0.288879007,0.293318987],[0.38499999,0.299016804,0.285981119],[0.38499999,0.310925931,0.282135129],[0.38499999,0.323440671,0.282157511],[0.38499999,0.335336,0.286046058],[0.38499999,0.345447481,0.293420136]],"faces":[[19,21,11],[24,22,32],[22,1,0],[23,2,1],[24,3,2],[25,4,3],[26,5,4],[27,6,5],[28,7,6],[29,8,7],[30,9,8],[31,10,9],[32,11,10],[33,12,11],[34,13,12],[35,14,13],[36,15,14],[37,16,15],[38,17,16],[39,18,17],[40,19,18],[41,20,19],[42,21,20],[43,0,21],[63,65,55],[68,66,76],[66,45,44],[67,46,45],[68,47,46],[69,48,47],[70,49,48],[71,50,49],[72,51,50],[73,52,51],[74,53,52],[75,54,53],[76,55,54],[77,56,55],[78,57,56],[79,58,57],[80,59,58],[81,60,59],[82,61,60],[83,62,61],[84,63,62],[85,64,63],[86,65,64],[87,44,65],[95,93,91],[122,124,128],[89,110,88],[90,111,89],[91,112,90],[92,113,91],[93,114,92],[94,115,93],[95,116,94],[96,117,95],[97,118,96],[98,119,97],[99,120,98],[100,121,99],[101,122,100],[102,123,101],[103,124,102],[104,125,103],[105,126,104],[106,127,105],[107,128,106],[108,129,107],[109,130,108],[88,131,109],[141,139,135],[166,168,172],[133,154,132],[134,155,133],[135,156,134],[136,157,135],[137,158,136],[138,159,137],[139,160,138],[140,161,139],[141,162,140],[142,163,141],[143,164,142],[144,165,143],[145,166,144],[146,167,145],[147,168,146],[148,169,147],[149,170,148],[150,171,149],[151,172,150],[152,173,151],[153,174,152],[132,175,153],[21,0,10],[0,1,10],[1,2,3],[3,4,5],[5,6,7],[7,8,9],[9,10,3],[10,11,21],[3,10,1],[11,12,13],[13,14,15],[15,16,19],[16,17,19],[17,18,19],[19,20,21],[3,5,7],[7,9,3],[11,13,19],[13,15,19],[22,43,33],[43,42,33],[42,41,40],[40,39,38],[38,37,40],[37,36,40],[36,35,34],[34,33,40],[33,32,22],[40,33,42],[32,31,30],[30,29,28],[28,27,26],[26,25,28],[25,24,28],[24,23,22],[36,34,40],[32,30,24],[30,28,24],[22,23,1],[23,24,2],[24,25,3],[25,26,4],[26,27,5],[27,28,6],[28,29,7],[29,30,8],[30,31,9],[31,32,10],[32,33,11],[33,34,12],[34,35,13],[35,36,14],[36,37,15],[37,38,16],[38,39,17],[39,40,18],[40,41,19],[41,42,20],[42,43,21],[43,22,0],[65,44,54],[44,45,54],[45,46,47],[47,48,49],[49,50,47],[50,51,47],[51,52,53],[53,54,47],[54,55,65],[47,54,45],[55,56,57],[57,58,59],[59,60,61],[61,62,63],[63,64,65],[51,53,47],[55,57,63],[57,59,63],[59,61,63],[66,87,77],[87,86,77],[86,85,84],[84,83,80],[83,82,80],[82,81,80],[80,79,78],[78,77,84],[77,76,66],[84,77,86],[76,75,74],[74,73,72],[72,71,68],[71,70,68],[70,69,68],[68,67,66],[80,78,84],[76,74,68],[74,72,68],[66,67,45],[67,68,46],[68,69,47],[69,70,48],[70,71,49],[71,72,50],[72,73,51],[73,74,52],[74,75,53],[75,76,54],[76,77,55],[77,78,56],[78,79,57],[79,80,58],[80,81,59],[81,82,60],[82,83,61],[83,84,62],[84,85,63],[85,86,64],[86,87,65],[87,66,44],[89,88,98],[88,109,99],[109,108,107],[107,106,105],[105,104,107],[104,103,107],[103,102,101],[101,100,99],[99,98,88],[98,97,91],[97,96,95],[95,94,93],[93,92,91],[91,90,89],[109,107,99],[103,101,107],[101,99,107],[98,91,89],[97,95,91],[130,131,121],[131,110,120],[110,111,112],[112,113,116],[113,114,116],[114,115,116],[116,117,118],[118,119,120],[120,121,131],[121,122,128],[122,123,124],[124,125,128],[125,126,128],[126,127,128],[128,129,130],[110,112,120],[116,118,112],[118,120,112],[121,128,130],[89,111,110],[90,112,111],[91,113,112],[92,114,113],[93,115,114],[94,116,115],[95,117,116],[96,118,117],[97,119,118],[98,120,119],[99,121,120],[100,122,121],[101,123,122],[102,124,123],[103,125,124],[104,126,125],[105,127,126],[106,128,127],[107,129,128],[108,130,129],[109,131,130],[88,110,131],[133,132,142],[132,153,143],[153,152,151],[151,150,149],[149,148,147],[147,146,145],[145,144,143],[143,142,132],[142,141,135],[141,140,139],[139,138,135],[138,137,135],[137,136,135],[135,134,133],[153,151,143],[151,149,147],[147,145,151],[145,143,151],[142,135,133],[174,175,165],[175,154,164],[154,155,156],[156,157,158],[158,159,156],[159,160,156],[160,161,162],[162,163,164],[164,165,175],[165,166,172],[166,167,168],[168,169,170],[170,171,168],[171,172,168],[172,173,174],[154,156,164],[160,162,156],[162,164,156],[165,172,174],[133,155,154],[134,156,155],[135,157,156],[136,158,157],[137,159,158],[138,160,159],[139,161,160],[140,162,161],[141,163,162],[142,164,163],[143,165,164],[144,166,165],[145,167,166],[146,168,167],[147,169,168],[148,170,169],[149,171,170],[150,172,171],[151,173,172],[152,174,173],[153,175,174],[132,154,175]],"points":[[0.34569818,0.758339776,0.399797897],[0.34569818,0.765357508,0.412003349],[0.33924546,0.757903937,0.405161809],[0.34569818,0.768260135,0.425779979],[0.343547274,0.765775611,0.423499465],[0.33924546,0.760806564,0.418938439],[0.34569818,0.766763402,0.439779322],[0.343547274,0.764278879,0.437498808],[0.33924546,0.759309832,0.432937782],[0.34569818,0.761013938,0.452630947],[0.343547274,0.758529415,0.450350434],[0.33924546,0.753560368,0.445789407],[0.34569818,0.75157447,0.4630769],[0.343547274,0.749089947,0.460796386],[0.33924546,0.744120899,0.45623536],[0.347849087,0.741853572,0.472375145],[0.34569818,0.739369048,0.470094631],[0.343547274,0.736884525,0.467814118],[0.33924546,0.731915478,0.463253092],[0.347849087,0.728076971,0.475277742],[0.34569818,0.725592448,0.472997229],[0.343547274,0.723107924,0.470716715],[0.33924546,0.718138877,0.466155689],[0.347849087,0.714077628,0.473781039]],"inside":[[-0.374881795,0.506437858,0.465394675],[-0.366131796,0.753098523,0.427236497],[0.367678355,0.451073686,0.418925236],[0.367678355,0.479256774,0.475544262],[0.36188077,0.558458164,0.350741692],[0.35499999,0.520441353,0.474452346],[-0.365999994,0.497151121,0.512630403],[-0.376249991,0.504683891,0.465963334],[0.367499992,0.497122383,0.509885848],[0.357,0.405670216,0.383211315],[0.357,0.417670216,0.389211315],[0.357,0.426670216,0.392211315],[-0.378,0.405670216,0.386211315],[-0.378,0.420670216,0.371211315],[-0.378,0.429670216,0.380211315],[-0.357,0.279670216,0.335211315],[-0.357,0.294670216,0.356211315],[0.3675,0.276670216,0.329211315],[0.3675,0.276670216,0.335211315],[-0.3675,0.354670216,0.365211315],[-0.357,0.387670216,0.380211315],[0.378,0.351670216,0.359211315],[-0.3675,0.357670216,0.305211315],[-0.357,0.372670216,0.311211315],[0.378,0.351670216,0.299211315],[-0.3675,0.291670216,0.314211315],[0.357,0.303670216,0.317211315],[-0.3675,0.354670216,0.362211315],[-0.357,0.357670216,0.326211315]]} \ No newline at end of file diff --git a/surfaces/blender/tests/live/ram_knee.py b/surfaces/blender/tests/live/ram_knee.py index 33dc608..a2a31f7 100644 --- a/surfaces/blender/tests/live/ram_knee.py +++ b/surfaces/blender/tests/live/ram_knee.py @@ -12,6 +12,8 @@ without them). is an absolute path; writes .result.json and .r3_ The oracle is ram.Signed, three rays by majority. Its ray count is held by tests/fixtures/ram_rays.json: the rocker plates as Imagination's jointlib builds them and points between the plates that stand on the first ray short of an edge or a vertex. One ray reads them inside a plate they stand clear of; the oracle as it is made reads none inside. +Its rays are held by the fixture's points inside the plates, where the plates' two bars overlap: the oracle as it is +made reads each inside, and two rays, one, a repeated ray or rays along x and y read some outside. A clearance verdict is a sign, the gate's own. FLAT follows lodur:ruling:deterministic-bound-margin. The checks run inside one try: an uncaught error is a failed check that names its section, and the result file is always written. @@ -331,6 +333,23 @@ try: check("ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray", (np.abs(aimed[:, 0]) < 0.349).all() and (made > 0).all() and (single < 0).sum() >= 5, [int((made < 0).sum()), int((single < 0).sum())]) + # the other way, which the gate's proof between samples leans on: points inside the same plates. The oracle as it is + # made reads every one inside; each change of its rays reads some outside. Counts of points: shipped 0 (half a + # point, lodur:ruling:deterministic-bound-zero-reading), the least mutant 6 (the second and third rays along x + # and y), geometric mean 1.7: the check asks 2 + within = np.array(fixture["inside"]) + + def outside(count=3, rays=None): + oracle = Signed(plates, rays=count) + if rays is not None: + oracle.rays = [Vector(ray).normalized() for ray in rays] + return int((oracle("plates", within) >= 0).sum()) + read = {"as made": outside(), "two rays": outside(2), "one ray": outside(1), "the second ray the first": outside(rays=(R.RAYS[0], R.RAYS[0], R.RAYS[2])), + "the second and third along x and y": outside(rays=(R.RAYS[0], (1, 0, 0), (0, 1, 0)))} + RES["readings"]["jointlib plates: inside points read outside, of %d" % len(within)] = read + check("rays-inside: points inside the jointlib rocker plates all read inside by the oracle as it is made, and some read outside with two rays, with one, with the second ray the first, " + "and with the second and third along x and y", read["as made"] == 0 and min(count for name, count in read.items() if name != "as made") >= 2, read) + SECTION[0] = "seat" seat = np.concatenate([v for v, _ in shells["parent.seat"]]) deepest = float(Signed(shells)("parent.body", seat).min()) From 3c1344d7762e4d6adfa8557a6c3d4b342bf2d177 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:41:43 +0100 Subject: [PATCH 158/223] brokkr_kitbash.ram: the record is version 2 and holds no settle block The reserved block (stiffness, damping, travel; written null, solved by nothing) leaves the ram record: a load-path cylinder's settle is a slide joint's, in the joint records (cut kit-joint-records). VERSION is 2; a version-1 record is refused as another version's, and the key is refused like any the record does not know. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/ram.py | 20 ++++++++------------ surfaces/blender/tests/test_ram.py | 16 ++++++++-------- 2 files changed, 16 insertions(+), 20 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py index 1383b5e..48875af 100644 --- a/surfaces/blender/brokkr_kitbash/ram.py +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -75,9 +75,8 @@ JOINS = {kind: {"a": ("parent",), "b": ("child",)} if kind == "direct" else {"a": ("parent",), "rocker": ("parent", "rocker"), "p": ("rocker", "coupler"), "c": ("coupler", "child"), "d": ("rocker",)} for kind in KINDS} # pin -> the bodies it joins: only their parts are zoned about it GATES = ("assembly", "stroke", "toggle", "arm", "load", "clash") -SCHEMA, VERSION = "brokkr.ram", 1 +SCHEMA, VERSION = "brokkr.ram", 2 ZONE = ("part", "pin", "radius", "depth") # a zone of `touch`, as the record writes it -COMPLIANCE = ("stiffness", "damping", "travel") # reserved: a load-path ram's settle, solved by a later version BAND = 1e-9 # the loop is refused within this of a dead centre of the rocker and coupler FINE = 64 # in a zone a segment between samples is halved down to spacing / FINE RAYS = ((0.5377, 0.6211, 0.5701), (-0.7071, 0.2903, 0.6447), (0.1873, -0.8011, -0.5684)) # Signed's, in order @@ -670,21 +669,20 @@ def search(kind, hinge, ram, seats, world=None, limit=20000, steps=25, spacing=N def record(m, ram): """The mechanism record: plain JSON types, everything a rig or runtime needs to drive the ram from the hinge angle (from_record, then length or extension). It holds what is authored and nothing derived from it: barrel, - closed length and link lengths come from the pins and the ram. `compliance` is reserved for a load-path ram's - settle (COMPLIANCE: stiffness, damping, travel); version 1 writes it null and solves none.""" + closed length and link lengths come from the pins and the ram.""" return {"schema": SCHEMA, "version": VERSION, "kind": m.kind, "hinge": {"pivot": m.pivot.tolist(), "axis": m.axis.tolist(), "lo": m.lo, "hi": m.hi}, "pins": {name: getattr(m, name).tolist() for name in PINS[m.kind]}, "offsets": list(m.offsets), "ram": {f.name: getattr(ram, f.name) for f in fields(Ram)}, - "parts": dict(m.parts), "compliance": None, + "parts": dict(m.parts), "touch": {member: [dict(zip(ZONE, zone)) for zone in zones] for member, zones in m.touch.items()}} def from_record(data): - """(Mechanism, Ram) of a record. A record of another schema or version (the integer 1: not 1.0, not true), with - a key this version does not know or without one it does, with a compliance block, or with a value that is not - its field's type (a finite number, three of them, a name), or with a zone wider or deeper than its member is - refused whole, as a RamError naming the field: nothing is read past and dropped.""" + """(Mechanism, Ram) of a record. A record of another schema or version (the integer 2: not 2.0, not true), with + a key this version does not know or without one it does, or with a value that is not its field's type (a finite + number, three of them, a name), or with a zone of a body its pin does not join, or wider or deeper than its + member, is refused whole, as a RamError naming the field: nothing is read past and dropped.""" if not isinstance(data, dict): raise RamError("None", "record", f"a record is an object, got {type(data).__name__}") kind, version = str(data.get("kind")), data.get("version") @@ -704,13 +702,11 @@ def from_record(data): raise RamError(kind, "record", f"three finite numbers, got {value!r}", pin=name) return [_number(kind, name, x) for x in value] - keys("record", data, ("schema", "version", "kind", "hinge", "pins", "offsets", "ram", "parts", "touch", "compliance")) + keys("record", data, ("schema", "version", "kind", "hinge", "pins", "offsets", "ram", "parts", "touch")) hinge, pins, ram = data["hinge"], data["pins"], data["ram"] keys("hinge", hinge, ("pivot", "axis", "lo", "hi")) keys("pins", pins, PINS[kind]) keys("ram", ram, [f.name for f in fields(Ram)]) - if data["compliance"] is not None: - raise RamError(kind, "record", f"a compliance block ({', '.join(COMPLIANCE)}) is a later version's: version {VERSION} solves none and will not drop it") for name, value in ram.items(): _number(kind, name, value, 0.0 if name == "bore" else None) if not isinstance(data["offsets"], list): diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py index 1d43a83..3c5af6a 100644 --- a/surfaces/blender/tests/test_ram.py +++ b/surfaces/blender/tests/test_ram.py @@ -1119,8 +1119,8 @@ class RecordDrives(unittest.TestCase): data = R.record(m, ram) wire = json.loads(json.dumps(data)) self.assertEqual(wire, data) - self.assertEqual(sorted(data), ["compliance", "hinge", "kind", "offsets", "parts", "pins", "ram", "schema", "touch", "version"]) - self.assertEqual((data["schema"], data["version"], data["compliance"]), ("brokkr.ram", 1, None)) + self.assertEqual(sorted(data), ["hinge", "kind", "offsets", "parts", "pins", "ram", "schema", "touch", "version"]) + self.assertEqual((data["schema"], data["version"]), ("brokkr.ram", 2)) again, ram2 = R.from_record(wire) self.assertEqual(R.record(again, ram2), data) self.assertEqual((again.parts, again.touch), (m.parts, m.touch)) @@ -1151,18 +1151,18 @@ class RecordDrives(unittest.TestCase): def test_a_record_this_version_cannot_read_is_refused_whole(self): data = R.record(R.Mechanism("direct", O, X, -62, 0, a=(0.05, -0.3, 0.8), b=(0.05, -0.3, -0.6)), R.Ram(BORE)) settle = {"stiffness": 2.0e6, "damping": 4.0e3, "travel": 0.02} - self.assertEqual(tuple(settle), R.COMPLIANCE) ram = dict(data["ram"], stiffness=2.0e6) short = {k: v for k, v in data.items() if k != "touch"} - for change, said in (({"version": 2}, "version 2"), ({"version": 2, "compliance": settle}, "version 2"), ({"compliance": settle}, "compliance block"), + for change, said in (({"version": 1}, "reads brokkr.ram version 2; the record is brokkr.ram version 1"), ({"version": 3}, "version 3"), ({"version": 1, "settle": settle}, "version 1"), ({"schema": "brokkr.kit"}, "brokkr.kit"), ({"settle": settle}, "unknown ['settle']"), ({"ram": ram}, "unknown ['stiffness']"), ({"hinge": dict(data["hinge"], rate=1.0)}, "unknown ['rate']"), - # a block that is falsy is a block (S23); the version is the integer 1 - ({"compliance": {}}, "compliance block"), ({"compliance": 0}, "compliance block"), ({"compliance": False}, "compliance block"), - ({"version": 1.0}, "version 1.0"), ({"version": True}, "version True"), ({"version": "1"}, "version '1'"), + # a key the record does not know is refused whatever it holds, null and falsy included (S23): a ram + # record carries no settle. The version is the integer 2 + ({"settle": None}, "unknown ['settle']"), ({"settle": {}}, "unknown ['settle']"), ({"settle": False}, "unknown ['settle']"), + ({"version": 2.0}, "version 2.0"), ({"version": True}, "version True"), ({"version": "2"}, "version '2'"), ({"kind": "scissor"}, "kind is one of"), # a pin this kind has not, or a key that is no pin, is refused by name; so is one missing - ({"pins": dict(data["pins"], q=[0.0, 0.0, 0.0])}, "the pins's keys are not version 1's: unknown ['q']"), + ({"pins": dict(data["pins"], q=[0.0, 0.0, 0.0])}, "the pins's keys are not version 2's: unknown ['q']"), ({"pins": dict(data["pins"], parts={})}, "unknown ['parts']"), ({"pins": {"a": data["pins"]["a"]}}, "missing ['b']"), ({"pins": [1, 2]}, "(pin pins): an object, got list"), ({"ram": None}, "(pin ram): an object, got NoneType"), # every number is a finite number, the bore over 0; three of them make a point From fd1f4ed2c2e796d3a3036a1f5f47127dd175c3a6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:42:25 +0100 Subject: [PATCH 159/223] docs/kitbash.md: Rams and linkages: a zone's part is of a body its pin joins; the record is version 2; the rays held from inside Clearance states the body rule and what it gives up (among the joined bodies' parts a whole-member zone still lets the axis in; a third body's plate is never zoned; a four-bar's eye is let near no coupler part). The record is version 2 and holds nothing of a cylinder's settle. Readings: the 29 inside points and the mutants' counts, and that overlapping closed pieces given as one shell are mis-signed (1,906 of 38,448) where piece by piece none are. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 42 ++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index f82d7c3..6c720db 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -944,7 +944,10 @@ body whose rest frame it turns with), and `touch`: for each member (`barrel`, `r bell crank's `rocker arm`), zones `(part, pin, radius, depth)`. Every member meets every part. A zone changes what the member's samples keep from one part, and only within `radius` of the axis of `pin`, measured across the hinge axis; the pin is one the member rides (the ram `a` and its eye, the rocker its pivot and `p`, the coupler `p` and -`c`, the arm the pivot and `d`). Inside the zone a sample may come as near the part as `-depth`; beyond it the +`c`, the arm the pivot and `d`), and the part is one of a body that pin joins: `a` the parent; the rocker's pivot +the parent and the rocker; `p` the rocker and the coupler; `c` the coupler and the child; a direct ram's `b` the +child; `d` the rocker (`JOINS`). A zone naming a part of any other body is refused by the record, whatever its +radius and depth. Inside the zone a sample may come as near the part as `-depth`; beyond it the pair is checked like any other. Nothing is exempt by a name, by a length cut from a member's end, or by the member's own body: the barrel runs from its back end, the rod to the eye, a bar from pin to pin. Every body of the kind owns at least one part, or the gate refuses the record. @@ -964,7 +967,9 @@ to pin: a bar's length between its pins, and for the barrel and the rod the base the centre the eye turns about, added. A `Mechanism` refuses a zone past that from its pins alone. Its depth is also no more than the member's eye on that pin (`Ram.eye`: `e_a` at the base, `e_b` at the rod's eye, `link_r` on a bar), which `from_record` and the gate refuse, so a world's answer is held to it as well. The record holds no -plate widths, so the radius has no tighter bound than the length. +plate widths, so the radius has no tighter bound than the length, and two zones of half a member's length about +its two pins cover it whole. What the record does hold is which body a part turns with: a member is let near only +what is pinned where it is pinned. Between two samples of which either is in a zone the gate does not rely on the spacing. A distance changes by no more than the way between two points, so along a segment it is at least (g(a) + g(b) - length) / 2. Where that @@ -975,7 +980,12 @@ samples' readings stand, so a burial is read to spacing / 128. This asks of the than the true distance. What it gives up: inside a zone the gate holds only the member's axis `depth` from the part, not its surface a -gap from it, so a link may graze the plate it scissors with anywhere within the stated radius. The members are +gap from it, so a link may graze the plate it scissors with anywhere within the stated radius. Among the parts of +the bodies a pin joins the gate still cannot tell a member's own plate from another: a zone over the whole member +lets its axis `depth` into any of them. A part of a third body is never zoned, so a plate stacked on a pin from a +body the pin does not join is refused where it stands; it is stated as a part of a body the pin joins. A four-bar's +eye rides `d`, which joins the rocker alone, though it stands on `p`: the ram is let near the coupler's plates +there by no zone. The members are round bars; a plate's flat sides are not modelled, which is why stacked plates need a zone at all. The proof between samples costs oracle calls: a depth stated with no slack over the burial (a bar's own plates at `link_r`) is halved to the floor along the whole zone. And it is along the axis at each checked angle; between two angles @@ -996,20 +1006,20 @@ about R, and `d` about R for a bell crank, the eye standing at `a`'s place along least arm; a miss returns the tally by gate and the nearest miss. Clearance takes `world(m) -> (parts, touch, distance)`: a linkage's brackets and links are the candidate's own, so each candidate that reaches the gate is met with the parts its own pins place. What `world` returns is read as a record's: anything but the three, a part on -no body of the kind, a zone that is not a part, a pin the member rides, a radius and a depth, or a zone wider or -deeper than its member is refused. +no body of the kind, a zone that is not a part, a pin the member rides, a radius and a depth, a zone of a body +its pin does not join, or a zone wider or deeper than its member is refused. `swept` gives the ram's swept surface in any body's frame, for a recess. ### The record -`record` and `from_record` carry a mechanism as JSON: `schema` (`brokkr.ram`), `version` (1), `kind`, `hinge`, -`pins`, `offsets`, `ram`, `parts`, `touch` (member -> zones, each `{part, pin, radius, depth}`), and `compliance`. -It holds what is authored; barrel, closed length and link lengths are derived by the reader. `compliance` is -reserved for a load-path ram's settle (stiffness, damping, travel); version 1 writes it null and solves none. A -record of another schema or version (the integer 1: 1.0 and true are not it), with a key version 1 does not know or -without one it does (at the top, in `ram`, `hinge`, `pins` or a zone), with a compliance block, or with a value -that is not its field's (a finite number, the bore over 0, three numbers for a point), or with a zone wider or -deeper than its member is refused whole, as a +`record` and `from_record` carry a mechanism as JSON: `schema` (`brokkr.ram`), `version` (2), `kind`, `hinge`, +`pins`, `offsets`, `ram`, `parts` and `touch` (member -> zones, each `{part, pin, radius, depth}`). +It holds what is authored; barrel, closed length and link lengths are derived by the reader. It holds nothing of +how a load-path cylinder settles: that is a slide joint's, in the joint's own record. A +record of another schema or version (the integer 2: 2.0 and true are not it), with a key version 2 does not know or +without one it does (at the top, in `ram`, `hinge`, `pins` or a zone), or with a value +that is not its field's (a finite number, the bore over 0, three numbers for a point), or with a zone of a body +its pin does not join, or wider or deeper than its member, is refused whole, as a `RamError` that names the field: a reader never reads past what it cannot solve. A `Ram` built by hand refuses the same numbers. @@ -1025,6 +1035,12 @@ for the side. One ray that runs through an edge or a vertex miscounts and signs clear of. `tests/fixtures/ram_rays.json` holds the ray count: the rocker plates as the joint library builds them and 24 points between the plates, each on the first ray short of an edge or a vertex. One ray signs all 24 inside; three sign none. Three rays are not a proof: of 146 such points one ray missigned, two rays missigned 16. +The same file holds 29 points inside the plates, where the gate's proof between samples needs the sign: the oracle +as it is made reads each inside; two rays read 16 outside, one ray 10, the second ray set to the first 10, the +second and third along x and y 6. Most stand where a side's two bars overlap, and the fixture gives the four bars +as one shell: there the parity of a ray counts two skins, and three rays read 1,906 of 38,448 inside grid points +outside. With each bar its own shell, as `Signed` takes a part's shells and as the live knee builds them, they +read none outside: a part whose closed pieces overlap is given piece by piece. | drive | reading | | --- | --- | From d94dace75f511958636e7a87a505248eca2f6fcc Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:57:47 +0100 Subject: [PATCH 160/223] live ram_knee: the inside check reads the oracle as it is made, by Signed's own ray count The check passed rays=3 itself, so Signed's default at two rays kept it green (the mutant survived its first run). It now builds the oracle with no count. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/ram_knee.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/surfaces/blender/tests/live/ram_knee.py b/surfaces/blender/tests/live/ram_knee.py index a2a31f7..28f182f 100644 --- a/surfaces/blender/tests/live/ram_knee.py +++ b/surfaces/blender/tests/live/ram_knee.py @@ -339,8 +339,8 @@ try: # and y), geometric mean 1.7: the check asks 2 within = np.array(fixture["inside"]) - def outside(count=3, rays=None): - oracle = Signed(plates, rays=count) + def outside(count=None, rays=None): + oracle = Signed(plates) if count is None else Signed(plates, rays=count) # as made: the count is Signed's own if rays is not None: oracle.rays = [Vector(ray).normalized() for ray in rays] return int((oracle("plates", within) >= 0).sum()) From 7282c02d4467561f87daede625f871f4bd16d76a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 23:05:56 +0100 Subject: [PATCH 161/223] brokkr_kitbash.ram: Signed reads a mesh piece by piece: inside the part is inside any piece Self's ruling on the fork cut-kit-ram-lows.h1 reported: callers feed joined meshes such as jointlib's, whose closed pieces overlap. Parity over the whole mesh reads the overlap as outside, the direction the proof between samples cannot bear. _pieces splits a mesh into the pieces its faces join; each gets its own tree and bounding box. Unit test of the split. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/ram.py | 35 ++++++++++++++++++++++---- surfaces/blender/tests/test_ram.py | 13 ++++++++++ 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py index 48875af..7799526 100644 --- a/surfaces/blender/brokkr_kitbash/ram.py +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -24,7 +24,7 @@ the coupler bar at c's, the ram at a's plus each of `offsets`. search(kind, hinge, ram, seats, ...) the best of a seat grid, or the tally and the nearest miss record(m, ram), from_record the JSON record a rig or runtime drives from swept(fit, body, ...) points of the swept ram's surface in a body's rest frame - Signed(shells, cap) the distance oracle over closed meshes, signed by three rays + Signed(shells, cap) the distance oracle over closed meshes, piece by piece, signed by three rays Clearance. The record names the mechanism's `parts`, each a piece of one body (part -> the body whose rest frame it turns with: a thigh's core, the bracket that carries the rocker's pivot, a link's plates, a pin), and `touch`: @@ -749,11 +749,36 @@ def swept(f, body, margin=0.0, steps=13, around=8): return _into(m, p, body, np.concatenate(pts, axis=1)).reshape(-1, 3) +def _pieces(vertices, faces): + """A mesh's pieces, [(vertices, faces)]: each the faces joined to one another through shared vertices.""" + vertices, root = np.asarray(vertices, dtype=float), list(range(len(vertices))) + + def find(i): + while root[i] != i: + root[i] = root[root[i]] + i = root[i] + return i + for face in faces: + for i in face[1:]: + root[find(i)] = find(face[0]) + groups = {} + for face in faces: + groups.setdefault(find(face[0]), []).append(face) + out = [] + for group in groups.values(): + used = sorted({i for face in group for i in face}) + at = {i: k for k, i in enumerate(used)} + out.append((vertices[used], [tuple(at[i] for i in face) for face in group])) + return out + + class Signed: """The distance oracle over closed meshes: distance(part, points) is the nearest face's distance, negative where the point is inside one of the part's shells (its depth below the nearest face), capped at `cap` outside - only. shells: part -> [(vertices (N, 3), faces)], each shell closed, in the rest frame of the part's body. - Inside is the crossing parity of `rays` of RAYS, by majority: one ray that runs through an edge or a vertex + only. shells: part -> [(vertices (N, 3), faces)], in the rest frame of the part's body. A mesh is read piece by + piece (_pieces), each piece closed: a point is inside the part where it is inside any piece, so pieces joined + into one mesh may overlap (parity over the whole mesh would read where two overlap as outside). Inside a + piece is the crossing parity of `rays` of RAYS, by majority: one ray that runs through an edge or a vertex miscounts, and a sample then reads inside a plate it stands clear of. An unknown part raises. Needs Blender's mathutils (BVHTree).""" @@ -762,8 +787,8 @@ class Signed: from mathutils.bvhtree import BVHTree self.cap, self.asked, self.vector = cap, 0, Vector self.rays = [Vector(ray).normalized() for ray in RAYS[:rays]] - self.trees = {part: [(BVHTree.FromPolygons(np.asarray(v, dtype=float).tolist(), [tuple(face) for face in f], epsilon=0.0), - np.min(v, axis=0), np.max(v, axis=0)) for v, f in made] for part, made in shells.items()} + self.trees = {part: [(BVHTree.FromPolygons(v.tolist(), [tuple(face) for face in f], epsilon=0.0), np.min(v, axis=0), np.max(v, axis=0)) + for mesh in made for v, f in _pieces(*mesh)] for part, made in shells.items()} @staticmethod def crossings(tree, v, ray): diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py index 3c5af6a..2a94872 100644 --- a/surfaces/blender/tests/test_ram.py +++ b/surfaces/blender/tests/test_ram.py @@ -1268,6 +1268,19 @@ class Refusals(unittest.TestCase): self.assertEqual((caught.exception.gate, caught.exception.pin), ("arm", "b")) self.assertIn(f"arm at {caught.exception.angle:g} deg (pin b)", str(caught.exception)) + def test_a_mesh_is_read_piece_by_piece(self): + # Signed's split: two tetrahedra in one mesh, the second's vertices listed first and its faces interleaved, + # come back as two closed pieces with their own vertices; a mesh of one piece comes back whole + tet = [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)] + a, b = np.array([(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)], float), np.array([(0.2, 0.2, 0.2), (5, 0, 0), (0, 5, 0), (0, 0, 5)], float) + faces = [face for pair in zip([tuple(i + 4 for i in f) for f in tet], tet) for face in pair] + pieces = R._pieces(np.concatenate([b, a]), faces) + self.assertEqual(len(pieces), 2) + for (verts, got), want in zip(pieces, (a, b)): + self.assertEqual((verts.tolist(), sorted(got)), (want.tolist(), tet)) + whole = R._pieces(a, tet) + self.assertEqual((len(whole), whole[0][0].tolist(), whole[0][1]), (1, a.tolist(), tet)) + def test_no_blender(self): source = (SURFACE / "brokkr_kitbash" / "ram.py").read_text(encoding="utf-8") for word in ("bpy", "np.gradient"): From c4ac06c2dd0025532b29a21aae126ca380e4e5ae Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 23:05:57 +0100 Subject: [PATCH 162/223] live ram_knee: no point inside the jointlib plates reads outside (0 of 38,477); the ray count held beside the bars inside-reads-inside replaces rays-inside: a 0.003 grid inside the four bars (truth by each bar's face planes) and the fixture's 29 points, all read inside. Parity over the whole mesh read 1,906 outside. Read bar by bar, the 24 points between the plates fall outside every bar's box and one ray no longer miscounts them; ram_rays.json's `points` are now 14 beside the bars that one ray reads inside and three read outside. Two rays, or a second and third along x and y, read them as three do. ram_knee.result.json regenerated: 21 checks. docs: the piece-by-piece read. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 14 ++--- surfaces/blender/tests/fixtures/ram_rays.json | 2 +- surfaces/blender/tests/live/ram_knee.py | 54 +++++++++++-------- .../blender/tests/live/ram_knee.result.json | 21 +++++--- 4 files changed, 53 insertions(+), 38 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 6c720db..5bb0ad6 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1033,14 +1033,14 @@ collars at the eye and a base clevis whose foot runs 0.01 into the thigh; 12 par oracle, `ram.Signed(shells, cap)`: the nearest face for the depth, the crossing parity of three rays, by majority, for the side. One ray that runs through an edge or a vertex miscounts and signs a sample inside a plate it stands clear of. `tests/fixtures/ram_rays.json` holds the ray count: the rocker plates as the joint library builds them -and 24 points between the plates, each on the first ray short of an edge or a vertex. One ray signs all 24 +and 14 points beside their bars, each on the first ray short of an edge or a vertex. One ray signs all 14 inside; three sign none. Three rays are not a proof: of 146 such points one ray missigned, two rays missigned 16. -The same file holds 29 points inside the plates, where the gate's proof between samples needs the sign: the oracle -as it is made reads each inside; two rays read 16 outside, one ray 10, the second ray set to the first 10, the -second and third along x and y 6. Most stand where a side's two bars overlap, and the fixture gives the four bars -as one shell: there the parity of a ray counts two skins, and three rays read 1,906 of 38,448 inside grid points -outside. With each bar its own shell, as `Signed` takes a part's shells and as the live knee builds them, they -read none outside: a part whose closed pieces overlap is given piece by piece. +Two rays, or a second and third along x and y, read those 14 as three do: the fixture holds the count above one. +A mesh is read piece by piece: `Signed` splits it into the pieces its faces join, each closed, and a point is +inside the part where it is inside any piece. The joint library's plates are one mesh of four bars, a side's two +overlapping about the pivot; parity over the whole mesh reads the overlap as outside (1,906 of 38,448 grid +points inside the bars, the direction the proof between samples cannot bear), and piece by piece none of them +reads outside, which the live check holds. | drive | reading | | --- | --- | diff --git a/surfaces/blender/tests/fixtures/ram_rays.json b/surfaces/blender/tests/fixtures/ram_rays.json index 37c414c..ab8fd15 100644 --- a/surfaces/blender/tests/fixtures/ram_rays.json +++ b/surfaces/blender/tests/fixtures/ram_rays.json @@ -1 +1 @@ -{"about":"The rocker's twin plates of the R-3 bell crank as Imagination's jointlib builds them (one shell, triangulated, at rest), and points between the plates (|x| under 0.349, the plates begin at 0.35): each stands on the oracle's first ray 0.004 to 0.02 short of a vertex or an edge of the shell. Every point is outside. `inside`: points 0.001 or more inside one of the shell's four pieces (each a convex prism; a side's two bars overlap about the pivot and share their faces' planes): nine aimed along a ray of RAYS, x or y at a vertex or an edge, the rest from a grid where the bars overlap. Fed as one shell, as here, the overlap is where a ray's parity fails: the oracle as it is made reads every one of these inside; two rays, one ray, a second ray equal to the first, or the second and third along x and y each read some outside. They hold the rays. They do not show that the oracle signs this shell truly: of 38,448 grid points inside it, three rays read 1,906 outside with the pieces one shell and none with each piece its own shell.","verts":[[-0.349999994,0.740011215,0.389170021],[-0.349999994,0.752862871,0.394919485],[-0.349999994,0.763308823,0.404358923],[-0.349999994,0.770326555,0.416564375],[-0.349999994,0.773229182,0.430341005],[-0.349999994,0.77173245,0.444340348],[-0.349999994,0.765982985,0.457191974],[-0.349999994,0.756543517,0.467637926],[-0.349999994,0.744338095,0.474655658],[-0.349999994,0.730561495,0.477558255],[-0.349999994,0.716562152,0.476061553],[-0.349999994,0.305388123,0.365099549],[-0.349999994,0.292536497,0.359350085],[-0.349999994,0.282090545,0.349910617],[-0.349999994,0.275072783,0.337705195],[-0.349999994,0.272170216,0.323928565],[-0.349999994,0.273666918,0.309929222],[-0.349999994,0.279416382,0.297077596],[-0.349999994,0.288855821,0.286631644],[-0.349999994,0.301061243,0.279613912],[-0.349999994,0.314837903,0.276711315],[-0.349999994,0.328837216,0.278208017],[-0.38499999,0.740011215,0.389170021],[-0.38499999,0.752862871,0.394919485],[-0.38499999,0.763308823,0.404358923],[-0.38499999,0.770326555,0.416564375],[-0.38499999,0.773229182,0.430341005],[-0.38499999,0.77173245,0.444340348],[-0.38499999,0.765982985,0.457191974],[-0.38499999,0.756543517,0.467637926],[-0.38499999,0.744338095,0.474655658],[-0.38499999,0.730561495,0.477558255],[-0.38499999,0.716562152,0.476061553],[-0.38499999,0.305388123,0.365099549],[-0.38499999,0.292536497,0.359350085],[-0.38499999,0.282090545,0.349910617],[-0.38499999,0.275072783,0.337705195],[-0.38499999,0.272170216,0.323928565],[-0.38499999,0.273666918,0.309929222],[-0.38499999,0.279416382,0.297077596],[-0.38499999,0.288855821,0.286631644],[-0.38499999,0.301061243,0.279613912],[-0.38499999,0.314837903,0.276711315],[-0.38499999,0.328837216,0.278208017],[-0.349999994,0.514849424,0.463428885],[-0.349999994,0.522187293,0.473566681],[-0.349999994,0.526033282,0.485475808],[-0.349999994,0.526010931,0.497990549],[-0.349999994,0.522122383,0.509885848],[-0.349999994,0.514748275,0.519997358],[-0.349999994,0.504610479,0.527335227],[-0.349999994,0.492701381,0.531181216],[-0.349999994,0.480186641,0.531158805],[-0.349999994,0.468291312,0.527270257],[-0.349999994,0.458179832,0.519896209],[-0.349999994,0.288777888,0.349887431],[-0.349999994,0.28144002,0.339749664],[-0.349999994,0.27759403,0.327840507],[-0.349999994,0.277616382,0.315325767],[-0.349999994,0.281504929,0.303430468],[-0.349999994,0.288879007,0.293318987],[-0.349999994,0.299016804,0.285981119],[-0.349999994,0.310925931,0.282135129],[-0.349999994,0.323440671,0.282157511],[-0.349999994,0.335336,0.286046058],[-0.349999994,0.345447481,0.293420136],[-0.38499999,0.514849424,0.463428885],[-0.38499999,0.522187293,0.473566681],[-0.38499999,0.526033282,0.485475808],[-0.38499999,0.526010931,0.497990549],[-0.38499999,0.522122383,0.509885848],[-0.38499999,0.514748275,0.519997358],[-0.38499999,0.504610479,0.527335227],[-0.38499999,0.492701381,0.531181216],[-0.38499999,0.480186641,0.531158805],[-0.38499999,0.468291312,0.527270257],[-0.38499999,0.458179832,0.519896209],[-0.38499999,0.288777888,0.349887431],[-0.38499999,0.28144002,0.339749664],[-0.38499999,0.27759403,0.327840507],[-0.38499999,0.277616382,0.315325767],[-0.38499999,0.281504929,0.303430468],[-0.38499999,0.288879007,0.293318987],[-0.38499999,0.299016804,0.285981119],[-0.38499999,0.310925931,0.282135129],[-0.38499999,0.323440671,0.282157511],[-0.38499999,0.335336,0.286046058],[-0.38499999,0.345447481,0.293420136],[0.349999994,0.740011215,0.389170021],[0.349999994,0.752862871,0.394919485],[0.349999994,0.763308823,0.404358923],[0.349999994,0.770326555,0.416564375],[0.349999994,0.773229182,0.430341005],[0.349999994,0.77173245,0.444340348],[0.349999994,0.765982985,0.457191974],[0.349999994,0.756543517,0.467637926],[0.349999994,0.744338095,0.474655658],[0.349999994,0.730561495,0.477558255],[0.349999994,0.716562152,0.476061553],[0.349999994,0.305388123,0.365099549],[0.349999994,0.292536497,0.359350085],[0.349999994,0.282090545,0.349910617],[0.349999994,0.275072783,0.337705195],[0.349999994,0.272170216,0.323928565],[0.349999994,0.273666918,0.309929222],[0.349999994,0.279416382,0.297077596],[0.349999994,0.288855821,0.286631644],[0.349999994,0.301061243,0.279613912],[0.349999994,0.314837903,0.276711315],[0.349999994,0.328837216,0.278208017],[0.38499999,0.740011215,0.389170021],[0.38499999,0.752862871,0.394919485],[0.38499999,0.763308823,0.404358923],[0.38499999,0.770326555,0.416564375],[0.38499999,0.773229182,0.430341005],[0.38499999,0.77173245,0.444340348],[0.38499999,0.765982985,0.457191974],[0.38499999,0.756543517,0.467637926],[0.38499999,0.744338095,0.474655658],[0.38499999,0.730561495,0.477558255],[0.38499999,0.716562152,0.476061553],[0.38499999,0.305388123,0.365099549],[0.38499999,0.292536497,0.359350085],[0.38499999,0.282090545,0.349910617],[0.38499999,0.275072783,0.337705195],[0.38499999,0.272170216,0.323928565],[0.38499999,0.273666918,0.309929222],[0.38499999,0.279416382,0.297077596],[0.38499999,0.288855821,0.286631644],[0.38499999,0.301061243,0.279613912],[0.38499999,0.314837903,0.276711315],[0.38499999,0.328837216,0.278208017],[0.349999994,0.514849424,0.463428885],[0.349999994,0.522187293,0.473566681],[0.349999994,0.526033282,0.485475808],[0.349999994,0.526010931,0.497990549],[0.349999994,0.522122383,0.509885848],[0.349999994,0.514748275,0.519997358],[0.349999994,0.504610479,0.527335227],[0.349999994,0.492701381,0.531181216],[0.349999994,0.480186641,0.531158805],[0.349999994,0.468291312,0.527270257],[0.349999994,0.458179832,0.519896209],[0.349999994,0.288777888,0.349887431],[0.349999994,0.28144002,0.339749664],[0.349999994,0.27759403,0.327840507],[0.349999994,0.277616382,0.315325767],[0.349999994,0.281504929,0.303430468],[0.349999994,0.288879007,0.293318987],[0.349999994,0.299016804,0.285981119],[0.349999994,0.310925931,0.282135129],[0.349999994,0.323440671,0.282157511],[0.349999994,0.335336,0.286046058],[0.349999994,0.345447481,0.293420136],[0.38499999,0.514849424,0.463428885],[0.38499999,0.522187293,0.473566681],[0.38499999,0.526033282,0.485475808],[0.38499999,0.526010931,0.497990549],[0.38499999,0.522122383,0.509885848],[0.38499999,0.514748275,0.519997358],[0.38499999,0.504610479,0.527335227],[0.38499999,0.492701381,0.531181216],[0.38499999,0.480186641,0.531158805],[0.38499999,0.468291312,0.527270257],[0.38499999,0.458179832,0.519896209],[0.38499999,0.288777888,0.349887431],[0.38499999,0.28144002,0.339749664],[0.38499999,0.27759403,0.327840507],[0.38499999,0.277616382,0.315325767],[0.38499999,0.281504929,0.303430468],[0.38499999,0.288879007,0.293318987],[0.38499999,0.299016804,0.285981119],[0.38499999,0.310925931,0.282135129],[0.38499999,0.323440671,0.282157511],[0.38499999,0.335336,0.286046058],[0.38499999,0.345447481,0.293420136]],"faces":[[19,21,11],[24,22,32],[22,1,0],[23,2,1],[24,3,2],[25,4,3],[26,5,4],[27,6,5],[28,7,6],[29,8,7],[30,9,8],[31,10,9],[32,11,10],[33,12,11],[34,13,12],[35,14,13],[36,15,14],[37,16,15],[38,17,16],[39,18,17],[40,19,18],[41,20,19],[42,21,20],[43,0,21],[63,65,55],[68,66,76],[66,45,44],[67,46,45],[68,47,46],[69,48,47],[70,49,48],[71,50,49],[72,51,50],[73,52,51],[74,53,52],[75,54,53],[76,55,54],[77,56,55],[78,57,56],[79,58,57],[80,59,58],[81,60,59],[82,61,60],[83,62,61],[84,63,62],[85,64,63],[86,65,64],[87,44,65],[95,93,91],[122,124,128],[89,110,88],[90,111,89],[91,112,90],[92,113,91],[93,114,92],[94,115,93],[95,116,94],[96,117,95],[97,118,96],[98,119,97],[99,120,98],[100,121,99],[101,122,100],[102,123,101],[103,124,102],[104,125,103],[105,126,104],[106,127,105],[107,128,106],[108,129,107],[109,130,108],[88,131,109],[141,139,135],[166,168,172],[133,154,132],[134,155,133],[135,156,134],[136,157,135],[137,158,136],[138,159,137],[139,160,138],[140,161,139],[141,162,140],[142,163,141],[143,164,142],[144,165,143],[145,166,144],[146,167,145],[147,168,146],[148,169,147],[149,170,148],[150,171,149],[151,172,150],[152,173,151],[153,174,152],[132,175,153],[21,0,10],[0,1,10],[1,2,3],[3,4,5],[5,6,7],[7,8,9],[9,10,3],[10,11,21],[3,10,1],[11,12,13],[13,14,15],[15,16,19],[16,17,19],[17,18,19],[19,20,21],[3,5,7],[7,9,3],[11,13,19],[13,15,19],[22,43,33],[43,42,33],[42,41,40],[40,39,38],[38,37,40],[37,36,40],[36,35,34],[34,33,40],[33,32,22],[40,33,42],[32,31,30],[30,29,28],[28,27,26],[26,25,28],[25,24,28],[24,23,22],[36,34,40],[32,30,24],[30,28,24],[22,23,1],[23,24,2],[24,25,3],[25,26,4],[26,27,5],[27,28,6],[28,29,7],[29,30,8],[30,31,9],[31,32,10],[32,33,11],[33,34,12],[34,35,13],[35,36,14],[36,37,15],[37,38,16],[38,39,17],[39,40,18],[40,41,19],[41,42,20],[42,43,21],[43,22,0],[65,44,54],[44,45,54],[45,46,47],[47,48,49],[49,50,47],[50,51,47],[51,52,53],[53,54,47],[54,55,65],[47,54,45],[55,56,57],[57,58,59],[59,60,61],[61,62,63],[63,64,65],[51,53,47],[55,57,63],[57,59,63],[59,61,63],[66,87,77],[87,86,77],[86,85,84],[84,83,80],[83,82,80],[82,81,80],[80,79,78],[78,77,84],[77,76,66],[84,77,86],[76,75,74],[74,73,72],[72,71,68],[71,70,68],[70,69,68],[68,67,66],[80,78,84],[76,74,68],[74,72,68],[66,67,45],[67,68,46],[68,69,47],[69,70,48],[70,71,49],[71,72,50],[72,73,51],[73,74,52],[74,75,53],[75,76,54],[76,77,55],[77,78,56],[78,79,57],[79,80,58],[80,81,59],[81,82,60],[82,83,61],[83,84,62],[84,85,63],[85,86,64],[86,87,65],[87,66,44],[89,88,98],[88,109,99],[109,108,107],[107,106,105],[105,104,107],[104,103,107],[103,102,101],[101,100,99],[99,98,88],[98,97,91],[97,96,95],[95,94,93],[93,92,91],[91,90,89],[109,107,99],[103,101,107],[101,99,107],[98,91,89],[97,95,91],[130,131,121],[131,110,120],[110,111,112],[112,113,116],[113,114,116],[114,115,116],[116,117,118],[118,119,120],[120,121,131],[121,122,128],[122,123,124],[124,125,128],[125,126,128],[126,127,128],[128,129,130],[110,112,120],[116,118,112],[118,120,112],[121,128,130],[89,111,110],[90,112,111],[91,113,112],[92,114,113],[93,115,114],[94,116,115],[95,117,116],[96,118,117],[97,119,118],[98,120,119],[99,121,120],[100,122,121],[101,123,122],[102,124,123],[103,125,124],[104,126,125],[105,127,126],[106,128,127],[107,129,128],[108,130,129],[109,131,130],[88,110,131],[133,132,142],[132,153,143],[153,152,151],[151,150,149],[149,148,147],[147,146,145],[145,144,143],[143,142,132],[142,141,135],[141,140,139],[139,138,135],[138,137,135],[137,136,135],[135,134,133],[153,151,143],[151,149,147],[147,145,151],[145,143,151],[142,135,133],[174,175,165],[175,154,164],[154,155,156],[156,157,158],[158,159,156],[159,160,156],[160,161,162],[162,163,164],[164,165,175],[165,166,172],[166,167,168],[168,169,170],[170,171,168],[171,172,168],[172,173,174],[154,156,164],[160,162,156],[162,164,156],[165,172,174],[133,155,154],[134,156,155],[135,157,156],[136,158,157],[137,159,158],[138,160,159],[139,161,160],[140,162,161],[141,163,162],[142,164,163],[143,165,164],[144,166,165],[145,167,166],[146,168,167],[147,169,168],[148,170,169],[149,171,170],[150,172,171],[151,173,172],[152,174,173],[153,175,174],[132,154,175]],"points":[[0.34569818,0.758339776,0.399797897],[0.34569818,0.765357508,0.412003349],[0.33924546,0.757903937,0.405161809],[0.34569818,0.768260135,0.425779979],[0.343547274,0.765775611,0.423499465],[0.33924546,0.760806564,0.418938439],[0.34569818,0.766763402,0.439779322],[0.343547274,0.764278879,0.437498808],[0.33924546,0.759309832,0.432937782],[0.34569818,0.761013938,0.452630947],[0.343547274,0.758529415,0.450350434],[0.33924546,0.753560368,0.445789407],[0.34569818,0.75157447,0.4630769],[0.343547274,0.749089947,0.460796386],[0.33924546,0.744120899,0.45623536],[0.347849087,0.741853572,0.472375145],[0.34569818,0.739369048,0.470094631],[0.343547274,0.736884525,0.467814118],[0.33924546,0.731915478,0.463253092],[0.347849087,0.728076971,0.475277742],[0.34569818,0.725592448,0.472997229],[0.343547274,0.723107924,0.470716715],[0.33924546,0.718138877,0.466155689],[0.347849087,0.714077628,0.473781039]],"inside":[[-0.374881795,0.506437858,0.465394675],[-0.366131796,0.753098523,0.427236497],[0.367678355,0.451073686,0.418925236],[0.367678355,0.479256774,0.475544262],[0.36188077,0.558458164,0.350741692],[0.35499999,0.520441353,0.474452346],[-0.365999994,0.497151121,0.512630403],[-0.376249991,0.504683891,0.465963334],[0.367499992,0.497122383,0.509885848],[0.357,0.405670216,0.383211315],[0.357,0.417670216,0.389211315],[0.357,0.426670216,0.392211315],[-0.378,0.405670216,0.386211315],[-0.378,0.420670216,0.371211315],[-0.378,0.429670216,0.380211315],[-0.357,0.279670216,0.335211315],[-0.357,0.294670216,0.356211315],[0.3675,0.276670216,0.329211315],[0.3675,0.276670216,0.335211315],[-0.3675,0.354670216,0.365211315],[-0.357,0.387670216,0.380211315],[0.378,0.351670216,0.359211315],[-0.3675,0.357670216,0.305211315],[-0.357,0.372670216,0.311211315],[0.378,0.351670216,0.299211315],[-0.3675,0.291670216,0.314211315],[0.357,0.303670216,0.317211315],[-0.3675,0.354670216,0.362211315],[-0.357,0.357670216,0.326211315]]} \ No newline at end of file +{"about":"The rocker's twin plates of the R-3 bell crank as Imagination's jointlib builds them: one mesh, triangulated, at rest, of four closed bars, a side's two overlapping about the pivot and sharing their faces' planes. `points`: 14 points 0.002 or more outside every bar and inside a bar's bounding box, each on the oracle's first ray 0.004 to 0.02 short of a vertex or an edge. One ray reads each inside; three read none inside. `inside`: 29 points 0.001 or more inside a bar, nine aimed along a ray of RAYS, x or y at a vertex or an edge, the rest from a grid where the bars overlap. Parity over the whole mesh reads the overlap outside (1,906 of 38,448 grid points inside the bars); read bar by bar, as ram.Signed reads a mesh, none of them and none of these reads outside.","verts":[[-0.349999994,0.740011215,0.389170021],[-0.349999994,0.752862871,0.394919485],[-0.349999994,0.763308823,0.404358923],[-0.349999994,0.770326555,0.416564375],[-0.349999994,0.773229182,0.430341005],[-0.349999994,0.77173245,0.444340348],[-0.349999994,0.765982985,0.457191974],[-0.349999994,0.756543517,0.467637926],[-0.349999994,0.744338095,0.474655658],[-0.349999994,0.730561495,0.477558255],[-0.349999994,0.716562152,0.476061553],[-0.349999994,0.305388123,0.365099549],[-0.349999994,0.292536497,0.359350085],[-0.349999994,0.282090545,0.349910617],[-0.349999994,0.275072783,0.337705195],[-0.349999994,0.272170216,0.323928565],[-0.349999994,0.273666918,0.309929222],[-0.349999994,0.279416382,0.297077596],[-0.349999994,0.288855821,0.286631644],[-0.349999994,0.301061243,0.279613912],[-0.349999994,0.314837903,0.276711315],[-0.349999994,0.328837216,0.278208017],[-0.38499999,0.740011215,0.389170021],[-0.38499999,0.752862871,0.394919485],[-0.38499999,0.763308823,0.404358923],[-0.38499999,0.770326555,0.416564375],[-0.38499999,0.773229182,0.430341005],[-0.38499999,0.77173245,0.444340348],[-0.38499999,0.765982985,0.457191974],[-0.38499999,0.756543517,0.467637926],[-0.38499999,0.744338095,0.474655658],[-0.38499999,0.730561495,0.477558255],[-0.38499999,0.716562152,0.476061553],[-0.38499999,0.305388123,0.365099549],[-0.38499999,0.292536497,0.359350085],[-0.38499999,0.282090545,0.349910617],[-0.38499999,0.275072783,0.337705195],[-0.38499999,0.272170216,0.323928565],[-0.38499999,0.273666918,0.309929222],[-0.38499999,0.279416382,0.297077596],[-0.38499999,0.288855821,0.286631644],[-0.38499999,0.301061243,0.279613912],[-0.38499999,0.314837903,0.276711315],[-0.38499999,0.328837216,0.278208017],[-0.349999994,0.514849424,0.463428885],[-0.349999994,0.522187293,0.473566681],[-0.349999994,0.526033282,0.485475808],[-0.349999994,0.526010931,0.497990549],[-0.349999994,0.522122383,0.509885848],[-0.349999994,0.514748275,0.519997358],[-0.349999994,0.504610479,0.527335227],[-0.349999994,0.492701381,0.531181216],[-0.349999994,0.480186641,0.531158805],[-0.349999994,0.468291312,0.527270257],[-0.349999994,0.458179832,0.519896209],[-0.349999994,0.288777888,0.349887431],[-0.349999994,0.28144002,0.339749664],[-0.349999994,0.27759403,0.327840507],[-0.349999994,0.277616382,0.315325767],[-0.349999994,0.281504929,0.303430468],[-0.349999994,0.288879007,0.293318987],[-0.349999994,0.299016804,0.285981119],[-0.349999994,0.310925931,0.282135129],[-0.349999994,0.323440671,0.282157511],[-0.349999994,0.335336,0.286046058],[-0.349999994,0.345447481,0.293420136],[-0.38499999,0.514849424,0.463428885],[-0.38499999,0.522187293,0.473566681],[-0.38499999,0.526033282,0.485475808],[-0.38499999,0.526010931,0.497990549],[-0.38499999,0.522122383,0.509885848],[-0.38499999,0.514748275,0.519997358],[-0.38499999,0.504610479,0.527335227],[-0.38499999,0.492701381,0.531181216],[-0.38499999,0.480186641,0.531158805],[-0.38499999,0.468291312,0.527270257],[-0.38499999,0.458179832,0.519896209],[-0.38499999,0.288777888,0.349887431],[-0.38499999,0.28144002,0.339749664],[-0.38499999,0.27759403,0.327840507],[-0.38499999,0.277616382,0.315325767],[-0.38499999,0.281504929,0.303430468],[-0.38499999,0.288879007,0.293318987],[-0.38499999,0.299016804,0.285981119],[-0.38499999,0.310925931,0.282135129],[-0.38499999,0.323440671,0.282157511],[-0.38499999,0.335336,0.286046058],[-0.38499999,0.345447481,0.293420136],[0.349999994,0.740011215,0.389170021],[0.349999994,0.752862871,0.394919485],[0.349999994,0.763308823,0.404358923],[0.349999994,0.770326555,0.416564375],[0.349999994,0.773229182,0.430341005],[0.349999994,0.77173245,0.444340348],[0.349999994,0.765982985,0.457191974],[0.349999994,0.756543517,0.467637926],[0.349999994,0.744338095,0.474655658],[0.349999994,0.730561495,0.477558255],[0.349999994,0.716562152,0.476061553],[0.349999994,0.305388123,0.365099549],[0.349999994,0.292536497,0.359350085],[0.349999994,0.282090545,0.349910617],[0.349999994,0.275072783,0.337705195],[0.349999994,0.272170216,0.323928565],[0.349999994,0.273666918,0.309929222],[0.349999994,0.279416382,0.297077596],[0.349999994,0.288855821,0.286631644],[0.349999994,0.301061243,0.279613912],[0.349999994,0.314837903,0.276711315],[0.349999994,0.328837216,0.278208017],[0.38499999,0.740011215,0.389170021],[0.38499999,0.752862871,0.394919485],[0.38499999,0.763308823,0.404358923],[0.38499999,0.770326555,0.416564375],[0.38499999,0.773229182,0.430341005],[0.38499999,0.77173245,0.444340348],[0.38499999,0.765982985,0.457191974],[0.38499999,0.756543517,0.467637926],[0.38499999,0.744338095,0.474655658],[0.38499999,0.730561495,0.477558255],[0.38499999,0.716562152,0.476061553],[0.38499999,0.305388123,0.365099549],[0.38499999,0.292536497,0.359350085],[0.38499999,0.282090545,0.349910617],[0.38499999,0.275072783,0.337705195],[0.38499999,0.272170216,0.323928565],[0.38499999,0.273666918,0.309929222],[0.38499999,0.279416382,0.297077596],[0.38499999,0.288855821,0.286631644],[0.38499999,0.301061243,0.279613912],[0.38499999,0.314837903,0.276711315],[0.38499999,0.328837216,0.278208017],[0.349999994,0.514849424,0.463428885],[0.349999994,0.522187293,0.473566681],[0.349999994,0.526033282,0.485475808],[0.349999994,0.526010931,0.497990549],[0.349999994,0.522122383,0.509885848],[0.349999994,0.514748275,0.519997358],[0.349999994,0.504610479,0.527335227],[0.349999994,0.492701381,0.531181216],[0.349999994,0.480186641,0.531158805],[0.349999994,0.468291312,0.527270257],[0.349999994,0.458179832,0.519896209],[0.349999994,0.288777888,0.349887431],[0.349999994,0.28144002,0.339749664],[0.349999994,0.27759403,0.327840507],[0.349999994,0.277616382,0.315325767],[0.349999994,0.281504929,0.303430468],[0.349999994,0.288879007,0.293318987],[0.349999994,0.299016804,0.285981119],[0.349999994,0.310925931,0.282135129],[0.349999994,0.323440671,0.282157511],[0.349999994,0.335336,0.286046058],[0.349999994,0.345447481,0.293420136],[0.38499999,0.514849424,0.463428885],[0.38499999,0.522187293,0.473566681],[0.38499999,0.526033282,0.485475808],[0.38499999,0.526010931,0.497990549],[0.38499999,0.522122383,0.509885848],[0.38499999,0.514748275,0.519997358],[0.38499999,0.504610479,0.527335227],[0.38499999,0.492701381,0.531181216],[0.38499999,0.480186641,0.531158805],[0.38499999,0.468291312,0.527270257],[0.38499999,0.458179832,0.519896209],[0.38499999,0.288777888,0.349887431],[0.38499999,0.28144002,0.339749664],[0.38499999,0.27759403,0.327840507],[0.38499999,0.277616382,0.315325767],[0.38499999,0.281504929,0.303430468],[0.38499999,0.288879007,0.293318987],[0.38499999,0.299016804,0.285981119],[0.38499999,0.310925931,0.282135129],[0.38499999,0.323440671,0.282157511],[0.38499999,0.335336,0.286046058],[0.38499999,0.345447481,0.293420136]],"faces":[[19,21,11],[24,22,32],[22,1,0],[23,2,1],[24,3,2],[25,4,3],[26,5,4],[27,6,5],[28,7,6],[29,8,7],[30,9,8],[31,10,9],[32,11,10],[33,12,11],[34,13,12],[35,14,13],[36,15,14],[37,16,15],[38,17,16],[39,18,17],[40,19,18],[41,20,19],[42,21,20],[43,0,21],[63,65,55],[68,66,76],[66,45,44],[67,46,45],[68,47,46],[69,48,47],[70,49,48],[71,50,49],[72,51,50],[73,52,51],[74,53,52],[75,54,53],[76,55,54],[77,56,55],[78,57,56],[79,58,57],[80,59,58],[81,60,59],[82,61,60],[83,62,61],[84,63,62],[85,64,63],[86,65,64],[87,44,65],[95,93,91],[122,124,128],[89,110,88],[90,111,89],[91,112,90],[92,113,91],[93,114,92],[94,115,93],[95,116,94],[96,117,95],[97,118,96],[98,119,97],[99,120,98],[100,121,99],[101,122,100],[102,123,101],[103,124,102],[104,125,103],[105,126,104],[106,127,105],[107,128,106],[108,129,107],[109,130,108],[88,131,109],[141,139,135],[166,168,172],[133,154,132],[134,155,133],[135,156,134],[136,157,135],[137,158,136],[138,159,137],[139,160,138],[140,161,139],[141,162,140],[142,163,141],[143,164,142],[144,165,143],[145,166,144],[146,167,145],[147,168,146],[148,169,147],[149,170,148],[150,171,149],[151,172,150],[152,173,151],[153,174,152],[132,175,153],[21,0,10],[0,1,10],[1,2,3],[3,4,5],[5,6,7],[7,8,9],[9,10,3],[10,11,21],[3,10,1],[11,12,13],[13,14,15],[15,16,19],[16,17,19],[17,18,19],[19,20,21],[3,5,7],[7,9,3],[11,13,19],[13,15,19],[22,43,33],[43,42,33],[42,41,40],[40,39,38],[38,37,40],[37,36,40],[36,35,34],[34,33,40],[33,32,22],[40,33,42],[32,31,30],[30,29,28],[28,27,26],[26,25,28],[25,24,28],[24,23,22],[36,34,40],[32,30,24],[30,28,24],[22,23,1],[23,24,2],[24,25,3],[25,26,4],[26,27,5],[27,28,6],[28,29,7],[29,30,8],[30,31,9],[31,32,10],[32,33,11],[33,34,12],[34,35,13],[35,36,14],[36,37,15],[37,38,16],[38,39,17],[39,40,18],[40,41,19],[41,42,20],[42,43,21],[43,22,0],[65,44,54],[44,45,54],[45,46,47],[47,48,49],[49,50,47],[50,51,47],[51,52,53],[53,54,47],[54,55,65],[47,54,45],[55,56,57],[57,58,59],[59,60,61],[61,62,63],[63,64,65],[51,53,47],[55,57,63],[57,59,63],[59,61,63],[66,87,77],[87,86,77],[86,85,84],[84,83,80],[83,82,80],[82,81,80],[80,79,78],[78,77,84],[77,76,66],[84,77,86],[76,75,74],[74,73,72],[72,71,68],[71,70,68],[70,69,68],[68,67,66],[80,78,84],[76,74,68],[74,72,68],[66,67,45],[67,68,46],[68,69,47],[69,70,48],[70,71,49],[71,72,50],[72,73,51],[73,74,52],[74,75,53],[75,76,54],[76,77,55],[77,78,56],[78,79,57],[79,80,58],[80,81,59],[81,82,60],[82,83,61],[83,84,62],[84,85,63],[85,86,64],[86,87,65],[87,66,44],[89,88,98],[88,109,99],[109,108,107],[107,106,105],[105,104,107],[104,103,107],[103,102,101],[101,100,99],[99,98,88],[98,97,91],[97,96,95],[95,94,93],[93,92,91],[91,90,89],[109,107,99],[103,101,107],[101,99,107],[98,91,89],[97,95,91],[130,131,121],[131,110,120],[110,111,112],[112,113,116],[113,114,116],[114,115,116],[116,117,118],[118,119,120],[120,121,131],[121,122,128],[122,123,124],[124,125,128],[125,126,128],[126,127,128],[128,129,130],[110,112,120],[116,118,112],[118,120,112],[121,128,130],[89,111,110],[90,112,111],[91,113,112],[92,114,113],[93,115,114],[94,116,115],[95,117,116],[96,118,117],[97,119,118],[98,120,119],[99,121,120],[100,122,121],[101,123,122],[102,124,123],[103,125,124],[104,126,125],[105,127,126],[106,128,127],[107,129,128],[108,130,129],[109,131,130],[88,110,131],[133,132,142],[132,153,143],[153,152,151],[151,150,149],[149,148,147],[147,146,145],[145,144,143],[143,142,132],[142,141,135],[141,140,139],[139,138,135],[138,137,135],[137,136,135],[135,134,133],[153,151,143],[151,149,147],[147,145,151],[145,143,151],[142,135,133],[174,175,165],[175,154,164],[154,155,156],[156,157,158],[158,159,156],[159,160,156],[160,161,162],[162,163,164],[164,165,175],[165,166,172],[166,167,168],[168,169,170],[170,171,168],[171,172,168],[172,173,174],[154,156,164],[160,162,156],[162,164,156],[165,172,174],[133,155,154],[134,156,155],[135,157,156],[136,158,157],[137,159,158],[138,160,159],[139,161,160],[140,162,161],[141,163,162],[142,164,163],[143,165,164],[144,166,165],[145,167,166],[146,168,167],[147,169,168],[148,170,169],[149,171,170],[150,172,171],[151,173,172],[152,174,173],[153,175,174],[132,154,175]],"points":[[-0.356452715,0.274636974,0.343069077],[0.378547269,0.274636974,0.343069077],[0.380698176,0.529455168,0.329127992],[0.378547269,0.526970645,0.326847479],[-0.373952713,0.274636974,0.343069077],[0.380698176,0.273612617,0.339246879],[-0.354301808,0.529455168,0.329127992],[-0.356452715,0.526970645,0.326847479],[0.374245455,0.745663229,0.388236637],[0.378547269,0.738983472,0.385203213],[0.361047271,0.274636974,0.343069077],[-0.354301808,0.273612617,0.339246879],[-0.360754529,0.745663229,0.388236637],[-0.356452715,0.738983472,0.385203213]],"inside":[[-0.374881795,0.506437858,0.465394675],[-0.366131796,0.753098523,0.427236497],[0.367678355,0.451073686,0.418925236],[0.367678355,0.479256774,0.475544262],[0.36188077,0.558458164,0.350741692],[0.35499999,0.520441353,0.474452346],[-0.365999994,0.497151121,0.512630403],[-0.376249991,0.504683891,0.465963334],[0.367499992,0.497122383,0.509885848],[0.357,0.405670216,0.383211315],[0.357,0.417670216,0.389211315],[0.357,0.426670216,0.392211315],[-0.378,0.405670216,0.386211315],[-0.378,0.420670216,0.371211315],[-0.378,0.429670216,0.380211315],[-0.357,0.279670216,0.335211315],[-0.357,0.294670216,0.356211315],[0.3675,0.276670216,0.329211315],[0.3675,0.276670216,0.335211315],[-0.3675,0.354670216,0.365211315],[-0.357,0.387670216,0.380211315],[0.378,0.351670216,0.359211315],[-0.3675,0.357670216,0.305211315],[-0.357,0.372670216,0.311211315],[0.378,0.351670216,0.299211315],[-0.3675,0.291670216,0.314211315],[0.357,0.303670216,0.317211315],[-0.3675,0.354670216,0.362211315],[-0.357,0.357670216,0.326211315]]} \ No newline at end of file diff --git a/surfaces/blender/tests/live/ram_knee.py b/surfaces/blender/tests/live/ram_knee.py index 28f182f..e32d3d1 100644 --- a/surfaces/blender/tests/live/ram_knee.py +++ b/surfaces/blender/tests/live/ram_knee.py @@ -10,10 +10,10 @@ without them). is an absolute path; writes .result.json and .r3_ -62.5 and -125) and exits 1 when a check failed. The oracle is ram.Signed, three rays by majority. Its ray count is held by tests/fixtures/ram_rays.json: the rocker -plates as Imagination's jointlib builds them and points between the plates that stand on the first ray short of an +plates as Imagination's jointlib builds them and points beside their bars that stand on the first ray short of an edge or a vertex. One ray reads them inside a plate they stand clear of; the oracle as it is made reads none inside. -Its rays are held by the fixture's points inside the plates, where the plates' two bars overlap: the oracle as it is -made reads each inside, and two rays, one, a repeated ray or rays along x and y read some outside. +The same mesh is four closed bars joined into one, a side's two overlapping: the oracle reads it bar by bar, and no +point of a grid inside the bars, nor of the fixture's 29 inside points, reads outside. A clearance verdict is a sign, the gate's own. FLAT follows lodur:ruling:deterministic-bound-margin. The checks run inside one try: an uncaught error is a failed check that names its section, and the result file is always written. @@ -323,32 +323,40 @@ try: exact = np.maximum.reduce([np.abs(cloud[:, 0]) - 0.13, np.abs(cloud[:, 1]) - 0.14, np.abs(cloud[:, 2] - 0.725) - 0.425]) check("three-rays: 4000 random points about a box are signed as the box signs them", ((core < 0) == (exact < 0)).all(), int(((core < 0) != (exact < 0)).sum())) - # the ray count: the jointlib rocker plates, and points between them aimed along the first ray at an edge or a vertex + # the ray count: the jointlib rocker plates, and points beside a bar, in its bounding box, aimed along the first ray at an edge or a vertex fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_rays.json").read_text(encoding="utf-8")) plates, aimed = {"plates": [(np.array(fixture["verts"]), fixture["faces"])]}, np.array(fixture["points"]) made, single = Signed(plates)("plates", aimed), Signed(plates, rays=1)("plates", aimed) RES["readings"]["jointlib plates: points one ray signs inside, of %d" % len(aimed)] = int((single < 0).sum()) RES["readings"]["jointlib plates: points the oracle signs inside"] = int((made < 0).sum()) - # one ray reads all 24 inside; the oracle as made reads none. The bound on one ray's count is the geometric mean of 1 and 24 - check("ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray", - (np.abs(aimed[:, 0]) < 0.349).all() and (made > 0).all() and (single < 0).sum() >= 5, [int((made < 0).sum()), int((single < 0).sum())]) + # one ray reads all 14 inside; the oracle as made reads none. The bound on one ray's count is the geometric mean of 1 and 14 + check("ray-count: beside the jointlib rocker plates' bars, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray", + (made > 0).all() and (single < 0).sum() >= 4, [int((made < 0).sum()), int((single < 0).sum())]) - # the other way, which the gate's proof between samples leans on: points inside the same plates. The oracle as it is - # made reads every one inside; each change of its rays reads some outside. Counts of points: shipped 0 (half a - # point, lodur:ruling:deterministic-bound-zero-reading), the least mutant 6 (the second and third rays along x - # and y), geometric mean 1.7: the check asks 2 - within = np.array(fixture["inside"]) - - def outside(count=None, rays=None): - oracle = Signed(plates) if count is None else Signed(plates, rays=count) # as made: the count is Signed's own - if rays is not None: - oracle.rays = [Vector(ray).normalized() for ray in rays] - return int((oracle("plates", within) >= 0).sum()) - read = {"as made": outside(), "two rays": outside(2), "one ray": outside(1), "the second ray the first": outside(rays=(R.RAYS[0], R.RAYS[0], R.RAYS[2])), - "the second and third along x and y": outside(rays=(R.RAYS[0], (1, 0, 0), (0, 1, 0)))} - RES["readings"]["jointlib plates: inside points read outside, of %d" % len(within)] = read - check("rays-inside: points inside the jointlib rocker plates all read inside by the oracle as it is made, and some read outside with two rays, with one, with the second ray the first, " - "and with the second and third along x and y", read["as made"] == 0 and min(count for name, count in read.items() if name != "as made") >= 2, read) + # the other way, which the gate's proof between samples leans on: no point inside the plates reads outside. The + # fixture's mesh is four closed bars, a side's two overlapping about the pivot; a point is truly inside where it is + # 0.001 or more inside one bar (each a convex prism: inside every face's plane). A grid 0.003 apart at three depths + # of each plate, and the fixture's 29 points. A count of points: shipped 0 (half a point, + # lodur:ruling:deterministic-bound-zero-reading), parity over the whole mesh (M-whole) 1,906; the check asks 0 + hulls = [] + for verts, faces in R._pieces(*plates["plates"][0]): + tri = np.array([[verts[i] for i in face[:3]] for face in faces]) + normal = np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]) + normal /= np.linalg.norm(normal, axis=1)[:, None] + level = (normal * tri[:, 0]).sum(axis=1) + out = (normal @ verts.mean(axis=0) - level) > 0 + normal[out], level[out] = -normal[out], -level[out] + hulls.append((normal, level)) + lo, hi = (np.array(fixture["verts"]).min(axis=0), np.array(fixture["verts"]).max(axis=0)) + cloud = np.array([(s * (SLAB_R[0] + 2 * HALF * f), y, z) for s in (-1.0, 1.0) for f in (0.2, 0.5, 0.8) + for y in np.arange(lo[1] + 0.0015, hi[1], 0.003) for z in np.arange(lo[2] + 0.0015, hi[2], 0.003)]) + deep = np.max([-(cloud @ normal.T - level).max(axis=1) for normal, level in hulls], axis=0) >= 0.001 + within = np.concatenate([cloud[deep], np.array(fixture["inside"])]) + missed = int((Signed(plates)("plates", within) >= 0).sum()) + RES["readings"]["jointlib plates: bars the mesh is read as"] = len(hulls) + RES["readings"]["jointlib plates: inside points read outside, of %d" % len(within)] = missed + check("inside-reads-inside: no point inside the jointlib rocker plates, where its bars overlap or not, reads outside by the oracle as it is made", + len(hulls) == 4 and int(deep.sum()) > 30000 and missed == 0, [len(hulls), int(deep.sum()), missed]) SECTION[0] = "seat" seat = np.concatenate([v for v, _ in shells["parent.seat"]]) diff --git a/surfaces/blender/tests/live/ram_knee.result.json b/surfaces/blender/tests/live/ram_knee.result.json index 8bd0d66..efb906b 100644 --- a/surfaces/blender/tests/live/ram_knee.result.json +++ b/surfaces/blender/tests/live/ram_knee.result.json @@ -17,7 +17,12 @@ "detail": null }, { - "name": "ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray", + "name": "ray-count: beside the jointlib rocker plates' bars, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray", + "ok": true, + "detail": null + }, + { + "name": "inside-reads-inside: no point inside the jointlib rocker plates, where its bars overlap or not, reads outside by the oracle as it is made", "ok": true, "detail": null }, @@ -108,10 +113,12 @@ "bell crank: least margin of a zoned pair, 251 steps uncapped": 0.000118, "bell crank: pairs": 60, "bell crank: pairs refused with nothing let": 19, - "bell crank: seconds, 49 steps capped": 2.12, + "bell crank: seconds, 49 steps capped": 0.946, "bell crank: zoned pairs": 20, "four bar: barrel inside the shin's clearance": -0.122, - "jointlib plates: points one ray signs inside, of 24": 24, + "jointlib plates: bars the mesh is read as": 4, + "jointlib plates: inside points read outside, of 38477": 0, + "jointlib plates: points one ray signs inside, of 14": 14, "jointlib plates: points the oracle signs inside": 0, "moved x: both": -0.0543, "moved x: the coupler at x 0.25, inside the horn's 0.23..0.31": -0.02, @@ -120,7 +127,7 @@ "search: candidates": 13824, "search: pass the gates before clearance": 78, "search: refused on their own parts": 21, - "search: seconds": 43.3, + "search: seconds": 32.7, "search: worlds built": 22, "the base clevis's foot inside the thigh": -0.01 }, @@ -496,9 +503,9 @@ } }, "renders": [ - "F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_0.png", - "F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_62p5.png", - "F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_125.png" + "F:/aeth-wt/fable-ramlows/scratch/out/live5.r3_0.png", + "F:/aeth-wt/fable-ramlows/scratch/out/live5.r3_62p5.png", + "F:/aeth-wt/fable-ramlows/scratch/out/live5.r3_125.png" ], "ok": true } \ No newline at end of file From 404849a30ee5bc573edb129c2b2f00a95eac61fb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 00:12:42 +0100 Subject: [PATCH 163/223] brokkr_kitbash.ram: Signed signs by the generalized winding number; the piece split and the rays are cut Inside is where the winding number of the part's triangles about the point is 0.5 or more (Jacobson, Kavan and Sorkine-Hornung 2013), the plain sum in numpy. Overlapping solids, welded or not, wind by their count; a nonconvex prism winds whole; an open cube reads inside up to its hole's plane. _pieces, RAYS, the rays parameter and the ray fixture's points are gone; ram_rays.json is ram_plates.json and keeps the overlapping bars. Live ram_knee: 20 checks, search 34.5 s (the parity oracle beside it 34.5 s). Closes cut-kit-ram-lows.s1 signed-trusts-closed-and-unwelded and rays-three-pinned-by-no-check. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/ram.py | 112 ++++++++---------- surfaces/blender/docs/kitbash.md | 31 +++-- .../blender/tests/fixtures/ram_plates.json | 1 + surfaces/blender/tests/fixtures/ram_rays.json | 1 - surfaces/blender/tests/live/ram_knee.py | 79 ++++++------ .../blender/tests/live/ram_knee.result.json | 31 ++--- surfaces/blender/tests/test_ram.py | 94 +++++++++++++-- 7 files changed, 198 insertions(+), 151 deletions(-) create mode 100644 surfaces/blender/tests/fixtures/ram_plates.json delete mode 100644 surfaces/blender/tests/fixtures/ram_rays.json diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py index 7799526..f27ac23 100644 --- a/surfaces/blender/brokkr_kitbash/ram.py +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -24,7 +24,8 @@ the coupler bar at c's, the ram at a's plus each of `offsets`. search(kind, hinge, ram, seats, ...) the best of a seat grid, or the tally and the nearest miss record(m, ram), from_record the JSON record a rig or runtime drives from swept(fit, body, ...) points of the swept ram's surface in a body's rest frame - Signed(shells, cap) the distance oracle over closed meshes, piece by piece, signed by three rays + winding(vertices, triangles, points) the generalized winding number of a triangle soup about points + Signed(shells, cap) the distance oracle over meshes, signed by the winding number Clearance. The record names the mechanism's `parts`, each a piece of one body (part -> the body whose rest frame it turns with: a thigh's core, the bracket that carries the rocker's pivot, a link's plates, a pin), and `touch`: @@ -79,7 +80,6 @@ SCHEMA, VERSION = "brokkr.ram", 2 ZONE = ("part", "pin", "radius", "depth") # a zone of `touch`, as the record writes it BAND = 1e-9 # the loop is refused within this of a dead centre of the rocker and coupler FINE = 64 # in a zone a segment between samples is halved down to spacing / FINE -RAYS = ((0.5377, 0.6211, 0.5701), (-0.7071, 0.2903, 0.6447), (0.1873, -0.8011, -0.5684)) # Signed's, in order class RamError(ValueError): @@ -749,72 +749,64 @@ def swept(f, body, margin=0.0, steps=13, around=8): return _into(m, p, body, np.concatenate(pts, axis=1)).reshape(-1, 3) -def _pieces(vertices, faces): - """A mesh's pieces, [(vertices, faces)]: each the faces joined to one another through shared vertices.""" - vertices, root = np.asarray(vertices, dtype=float), list(range(len(vertices))) - - def find(i): - while root[i] != i: - root[i] = root[root[i]] - i = root[i] - return i - for face in faces: - for i in face[1:]: - root[find(i)] = find(face[0]) - groups = {} - for face in faces: - groups.setdefault(find(face[0]), []).append(face) - out = [] - for group in groups.values(): - used = sorted({i for face in group for i in face}) - at = {i: k for k, i in enumerate(used)} - out.append((vertices[used], [tuple(at[i] for i in face) for face in group])) - return out +def winding(vertices, triangles, points): + """The generalized winding number of a triangle soup about each of `points` (Jacobson, Kavan and Sorkine-Hornung + 2013): the triangles' signed solid angles, summed, over 4 pi. A triangle counts positive from the side its normal + points away from (counterclockwise seen from outside). About a closed mesh it is the whole number of times the + surface wraps the point: 0 outside, 1 inside, 2 where two solids of one mesh overlap, whether they share vertices + or cut through one another. About an open mesh it is a fraction that falls off toward the hole: the closed + mesh's number less the missing faces' share of the sphere about the point, so across a flat hole it passes + through 0.5 on the hole's own plane. The plain sum: a point costs every triangle. The corners' offsets from the + point are taken in double precision and the angles in single (2.4 times the pace): the number is good to 1e-5 a + millimetre off a face and to 1e-2 at 1e-7 off it, and nearer than that its side of the face is not held.""" + v, t, pts = np.asarray(vertices, dtype=float).reshape(-1, 3), np.asarray(triangles, dtype=int).reshape(-1, 3), np.asarray(points, dtype=float).reshape(-1, 3) + A, B, C = (np.ascontiguousarray(v[t[:, k]].T) for k in range(3)) # each (3, F): a corner of every triangle + out, step = np.zeros(len(pts)), max(1, 32768 // max(len(t), 1)) # a block of pairs that stays in cache: 3.1 times the pace of 400,000 + for k in range(0, len(pts), step): + p = pts[k:k + step].T[:, :, None] + (ax, ay, az), (bx, by, bz), (cx, cy, cz) = ((corner[:, None, :] - p).astype(np.float32) for corner in (A, B, C)) + la, lb, lc = np.sqrt(ax * ax + ay * ay + az * az), np.sqrt(bx * bx + by * by + bz * bz), np.sqrt(cx * cx + cy * cy + cz * cz) + volume = ax * (by * cz - bz * cy) + ay * (bz * cx - bx * cz) + az * (bx * cy - by * cx) + out[k:k + step] = np.arctan2(volume, la * lb * lc + (ax * bx + ay * by + az * bz) * lc + (bx * cx + by * cy + bz * cz) * la + (cx * ax + cy * ay + cz * az) * lb).sum(axis=1, dtype=float) + return out / (2.0 * math.pi) class Signed: - """The distance oracle over closed meshes: distance(part, points) is the nearest face's distance, negative - where the point is inside one of the part's shells (its depth below the nearest face), capped at `cap` outside - only. shells: part -> [(vertices (N, 3), faces)], in the rest frame of the part's body. A mesh is read piece by - piece (_pieces), each piece closed: a point is inside the part where it is inside any piece, so pieces joined - into one mesh may overlap (parity over the whole mesh would read where two overlap as outside). Inside a - piece is the crossing parity of `rays` of RAYS, by majority: one ray that runs through an edge or a vertex - miscounts, and a sample then reads inside a plate it stands clear of. An unknown part raises. Needs Blender's - mathutils (BVHTree).""" + """The distance oracle over meshes: distance(part, points) is the nearest face's distance, negative where the + point is inside the part (its depth below the nearest face), capped at `cap` outside only. shells: part -> + [(vertices (N, 3), faces)], in the rest frame of the part's body, faces wound counterclockwise seen from + outside. Inside is where the winding number of all the part's faces (winding; a face of more than three corners + as a fan) is 0.5 or more: solids that overlap, in one mesh or several, welded or not, read inside wherever any + is. A mesh wound inside out reads outside everywhere. An open mesh is read as its faces wind: no point is + refused, and a point inside by a flat hole reads inside up to the hole's plane, where the sign turns with no + face there, so the reading steps by twice the distance to the hole's rim. The depth is to the nearest face of + any of the part's meshes, one buried in another included. An unknown part raises. Needs Blender's mathutils + (BVHTree) for the nearest face.""" - def __init__(self, shells, cap=None, rays=3): + def __init__(self, shells, cap=None): from mathutils import Vector from mathutils.bvhtree import BVHTree - self.cap, self.asked, self.vector = cap, 0, Vector - self.rays = [Vector(ray).normalized() for ray in RAYS[:rays]] - self.trees = {part: [(BVHTree.FromPolygons(v.tolist(), [tuple(face) for face in f], epsilon=0.0), np.min(v, axis=0), np.max(v, axis=0)) - for mesh in made for v, f in _pieces(*mesh)] for part, made in shells.items()} - - @staticmethod - def crossings(tree, v, ray): - count, o = 0, v - for _ in range(64): - loc = tree.ray_cast(o, ray)[0] - if loc is None: - break - count, o = count + 1, loc + ray * 1e-6 - return count - - def inside(self, tree, v): - return 2 * sum(self.crossings(tree, v, ray) % 2 for ray in self.rays) > len(self.rays) + self.cap, self.asked, self.vector, self.parts = cap, 0, Vector, {} + for part, made in shells.items(): + verts, faces, at = [], [], 0 + for v, f in made: + v = np.asarray(v, dtype=float).reshape(-1, 3) + verts.append(v) + faces += [tuple(at + int(i) for i in face) for face in f] + at += len(v) + verts = np.concatenate(verts) + fan = np.array([(face[0], face[k], face[k + 1]) for face in faces for k in range(1, len(face) - 1)], dtype=int) + self.parts[part] = (BVHTree.FromPolygons(verts.tolist(), faces, epsilon=0.0), verts, fan) def __call__(self, part, pts): - pts = np.asarray(pts, dtype=float) + pts = np.asarray(pts, dtype=float).reshape(-1, 3) self.asked += len(pts) + tree, verts, fan = self.parts[part] out = np.full(len(pts), math.inf if self.cap is None else self.cap) - for tree, lo, hi in self.trees[part]: - boxed = ((pts >= lo) & (pts <= hi)).all(axis=1) - for i, p in enumerate(pts): - v = self.vector(p) - if boxed[i] and self.inside(tree, v): - out[i] = min(out[i], -tree.find_nearest(v)[3]) - continue - hit = tree.find_nearest(v, self.cap) if self.cap else tree.find_nearest(v) - if hit[0] is not None and hit[3] < out[i]: - out[i] = hit[3] + for i in np.flatnonzero(winding(verts, fan, pts) >= 0.5): + out[i] = -tree.find_nearest(self.vector(pts[i]))[3] + for i in np.flatnonzero(out >= 0): + hit = tree.find_nearest(self.vector(pts[i]), self.cap) if self.cap else tree.find_nearest(self.vector(pts[i])) + if hit[0] is not None: + out[i] = hit[3] return out diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 5bb0ad6..8eb7ab9 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1030,17 +1030,20 @@ Bore 0.042, range 0..-125. The kinematic rows are tests/test_ram.py's. The clear test generates (thigh with its front plate, shin with caps and armour, the bracket that carries R, the horn that carries `c`, twin link plates stacked 5 mm apart at x 0.31..0.345 and 0.35..0.385, pins through the knee's width, collars at the eye and a base clevis whose foot runs 0.01 into the thigh; 12 parts) and the package's signed BVH -oracle, `ram.Signed(shells, cap)`: the nearest face for the depth, the crossing parity of three rays, by majority, -for the side. One ray that runs through an edge or a vertex miscounts and signs a sample inside a plate it stands -clear of. `tests/fixtures/ram_rays.json` holds the ray count: the rocker plates as the joint library builds them -and 14 points beside their bars, each on the first ray short of an edge or a vertex. One ray signs all 14 -inside; three sign none. Three rays are not a proof: of 146 such points one ray missigned, two rays missigned 16. -Two rays, or a second and third along x and y, read those 14 as three do: the fixture holds the count above one. -A mesh is read piece by piece: `Signed` splits it into the pieces its faces join, each closed, and a point is -inside the part where it is inside any piece. The joint library's plates are one mesh of four bars, a side's two -overlapping about the pivot; parity over the whole mesh reads the overlap as outside (1,906 of 38,448 grid -points inside the bars, the direction the proof between samples cannot bear), and piece by piece none of them -reads outside, which the live check holds. +oracle, `ram.Signed(shells, cap)`: the nearest face for the depth, the generalized winding number for the side +(Jacobson, Kavan and Sorkine-Hornung 2013). `ram.winding` sums the signed solid angle of every triangle of the part +about the point, over 4 pi: about a closed mesh the whole number of times the surface wraps the point, 0 outside, 1 +inside, 2 where two solids overlap. A point is inside the part at 0.5 or more. The joint library's plates are one +mesh of four bars, a side's two overlapping about the pivot (`tests/fixtures/ram_plates.json`, with 29 points +inside them, 13 inside two bars): each reads inside, as does the overlap of two boxes welded at a corner and a +staircase prism a line crosses six times. Faces are wound counterclockwise seen from outside; a mesh wound inside +out reads outside everywhere. An open mesh is answered, not refused: the number is the closed mesh's less the +missing faces' share of the sphere about the point, so a cube with a face open reads inside up to the hole's plane +(0.5009 at 0.001 under the centre of a unit face) and the sign turns on that plane with no face there. The gate's +proof between samples assumes a distance changes by no more than the way between two points, which holds across a +face and not across a hole: a part with a hole the axis may reach is closed before it is given. The depth is to the +nearest face of any of the part's meshes, one buried inside another included, so inside two overlapping solids a +point may read shallower than its depth below their union. | drive | reading | | --- | --- | @@ -1055,8 +1058,10 @@ Cost on Starfire, Python 3.13, 100 repetitions paired and interleaved: one candi 49 steps took 0.79 ms median on the bell crank; its clearance against the analytic parts (50 pairs) took 42 ms (5th to 95th percentile 38 to 57) over 97,875 points, of which 23,520 are the samples and the rest the halving in zones (the own plates, stated with no slack, to the floor); the samples alone took 11 ms. A search without a world ran 1.6 to 1.8 ms a candidate over 3,456, so `limit` -(20,000) is 30 to 40 s. On the meshes the bell crank's 60 pairs at 49 steps took 1.95 to 2.12 s capped (two runs), in a -Python loop of BVH queries with three rays a sample, and the 13,824-candidate search with its 22 worlds 43 s (one run). +(20,000) is 30 to 40 s. On the meshes the bell crank's 60 pairs at 49 steps took 0.80 to 1.00 s capped (two runs), the +winding number as the plain sum over a part's 124 to 408 triangles in numpy (single precision over double offsets, +blocks of 32,768 pairs) and the depth a Python loop of BVH queries, and the 13,824-candidate search with its 22 +worlds 34.5 and 38.5 s (two runs). With the angles in double precision the search took 47.7 to 47.9 s (three runs). ## The actions diff --git a/surfaces/blender/tests/fixtures/ram_plates.json b/surfaces/blender/tests/fixtures/ram_plates.json new file mode 100644 index 0000000..be72f30 --- /dev/null +++ b/surfaces/blender/tests/fixtures/ram_plates.json @@ -0,0 +1 @@ +{"about":"The rocker's twin plates of the R-3 bell crank as Imagination's jointlib builds them: one mesh, triangulated, at rest, of four closed bars, a side's two overlapping about the pivot and sharing their faces' planes. `inside`: 29 points 0.001 or more inside a bar, 13 of them where two bars overlap. The winding number about each is the count of bars it is inside, 1 or 2: ram.Signed reads every one inside. Crossing parity reads the 13 outside.","verts":[[-0.349999994,0.740011215,0.389170021],[-0.349999994,0.752862871,0.394919485],[-0.349999994,0.763308823,0.404358923],[-0.349999994,0.770326555,0.416564375],[-0.349999994,0.773229182,0.430341005],[-0.349999994,0.77173245,0.444340348],[-0.349999994,0.765982985,0.457191974],[-0.349999994,0.756543517,0.467637926],[-0.349999994,0.744338095,0.474655658],[-0.349999994,0.730561495,0.477558255],[-0.349999994,0.716562152,0.476061553],[-0.349999994,0.305388123,0.365099549],[-0.349999994,0.292536497,0.359350085],[-0.349999994,0.282090545,0.349910617],[-0.349999994,0.275072783,0.337705195],[-0.349999994,0.272170216,0.323928565],[-0.349999994,0.273666918,0.309929222],[-0.349999994,0.279416382,0.297077596],[-0.349999994,0.288855821,0.286631644],[-0.349999994,0.301061243,0.279613912],[-0.349999994,0.314837903,0.276711315],[-0.349999994,0.328837216,0.278208017],[-0.38499999,0.740011215,0.389170021],[-0.38499999,0.752862871,0.394919485],[-0.38499999,0.763308823,0.404358923],[-0.38499999,0.770326555,0.416564375],[-0.38499999,0.773229182,0.430341005],[-0.38499999,0.77173245,0.444340348],[-0.38499999,0.765982985,0.457191974],[-0.38499999,0.756543517,0.467637926],[-0.38499999,0.744338095,0.474655658],[-0.38499999,0.730561495,0.477558255],[-0.38499999,0.716562152,0.476061553],[-0.38499999,0.305388123,0.365099549],[-0.38499999,0.292536497,0.359350085],[-0.38499999,0.282090545,0.349910617],[-0.38499999,0.275072783,0.337705195],[-0.38499999,0.272170216,0.323928565],[-0.38499999,0.273666918,0.309929222],[-0.38499999,0.279416382,0.297077596],[-0.38499999,0.288855821,0.286631644],[-0.38499999,0.301061243,0.279613912],[-0.38499999,0.314837903,0.276711315],[-0.38499999,0.328837216,0.278208017],[-0.349999994,0.514849424,0.463428885],[-0.349999994,0.522187293,0.473566681],[-0.349999994,0.526033282,0.485475808],[-0.349999994,0.526010931,0.497990549],[-0.349999994,0.522122383,0.509885848],[-0.349999994,0.514748275,0.519997358],[-0.349999994,0.504610479,0.527335227],[-0.349999994,0.492701381,0.531181216],[-0.349999994,0.480186641,0.531158805],[-0.349999994,0.468291312,0.527270257],[-0.349999994,0.458179832,0.519896209],[-0.349999994,0.288777888,0.349887431],[-0.349999994,0.28144002,0.339749664],[-0.349999994,0.27759403,0.327840507],[-0.349999994,0.277616382,0.315325767],[-0.349999994,0.281504929,0.303430468],[-0.349999994,0.288879007,0.293318987],[-0.349999994,0.299016804,0.285981119],[-0.349999994,0.310925931,0.282135129],[-0.349999994,0.323440671,0.282157511],[-0.349999994,0.335336,0.286046058],[-0.349999994,0.345447481,0.293420136],[-0.38499999,0.514849424,0.463428885],[-0.38499999,0.522187293,0.473566681],[-0.38499999,0.526033282,0.485475808],[-0.38499999,0.526010931,0.497990549],[-0.38499999,0.522122383,0.509885848],[-0.38499999,0.514748275,0.519997358],[-0.38499999,0.504610479,0.527335227],[-0.38499999,0.492701381,0.531181216],[-0.38499999,0.480186641,0.531158805],[-0.38499999,0.468291312,0.527270257],[-0.38499999,0.458179832,0.519896209],[-0.38499999,0.288777888,0.349887431],[-0.38499999,0.28144002,0.339749664],[-0.38499999,0.27759403,0.327840507],[-0.38499999,0.277616382,0.315325767],[-0.38499999,0.281504929,0.303430468],[-0.38499999,0.288879007,0.293318987],[-0.38499999,0.299016804,0.285981119],[-0.38499999,0.310925931,0.282135129],[-0.38499999,0.323440671,0.282157511],[-0.38499999,0.335336,0.286046058],[-0.38499999,0.345447481,0.293420136],[0.349999994,0.740011215,0.389170021],[0.349999994,0.752862871,0.394919485],[0.349999994,0.763308823,0.404358923],[0.349999994,0.770326555,0.416564375],[0.349999994,0.773229182,0.430341005],[0.349999994,0.77173245,0.444340348],[0.349999994,0.765982985,0.457191974],[0.349999994,0.756543517,0.467637926],[0.349999994,0.744338095,0.474655658],[0.349999994,0.730561495,0.477558255],[0.349999994,0.716562152,0.476061553],[0.349999994,0.305388123,0.365099549],[0.349999994,0.292536497,0.359350085],[0.349999994,0.282090545,0.349910617],[0.349999994,0.275072783,0.337705195],[0.349999994,0.272170216,0.323928565],[0.349999994,0.273666918,0.309929222],[0.349999994,0.279416382,0.297077596],[0.349999994,0.288855821,0.286631644],[0.349999994,0.301061243,0.279613912],[0.349999994,0.314837903,0.276711315],[0.349999994,0.328837216,0.278208017],[0.38499999,0.740011215,0.389170021],[0.38499999,0.752862871,0.394919485],[0.38499999,0.763308823,0.404358923],[0.38499999,0.770326555,0.416564375],[0.38499999,0.773229182,0.430341005],[0.38499999,0.77173245,0.444340348],[0.38499999,0.765982985,0.457191974],[0.38499999,0.756543517,0.467637926],[0.38499999,0.744338095,0.474655658],[0.38499999,0.730561495,0.477558255],[0.38499999,0.716562152,0.476061553],[0.38499999,0.305388123,0.365099549],[0.38499999,0.292536497,0.359350085],[0.38499999,0.282090545,0.349910617],[0.38499999,0.275072783,0.337705195],[0.38499999,0.272170216,0.323928565],[0.38499999,0.273666918,0.309929222],[0.38499999,0.279416382,0.297077596],[0.38499999,0.288855821,0.286631644],[0.38499999,0.301061243,0.279613912],[0.38499999,0.314837903,0.276711315],[0.38499999,0.328837216,0.278208017],[0.349999994,0.514849424,0.463428885],[0.349999994,0.522187293,0.473566681],[0.349999994,0.526033282,0.485475808],[0.349999994,0.526010931,0.497990549],[0.349999994,0.522122383,0.509885848],[0.349999994,0.514748275,0.519997358],[0.349999994,0.504610479,0.527335227],[0.349999994,0.492701381,0.531181216],[0.349999994,0.480186641,0.531158805],[0.349999994,0.468291312,0.527270257],[0.349999994,0.458179832,0.519896209],[0.349999994,0.288777888,0.349887431],[0.349999994,0.28144002,0.339749664],[0.349999994,0.27759403,0.327840507],[0.349999994,0.277616382,0.315325767],[0.349999994,0.281504929,0.303430468],[0.349999994,0.288879007,0.293318987],[0.349999994,0.299016804,0.285981119],[0.349999994,0.310925931,0.282135129],[0.349999994,0.323440671,0.282157511],[0.349999994,0.335336,0.286046058],[0.349999994,0.345447481,0.293420136],[0.38499999,0.514849424,0.463428885],[0.38499999,0.522187293,0.473566681],[0.38499999,0.526033282,0.485475808],[0.38499999,0.526010931,0.497990549],[0.38499999,0.522122383,0.509885848],[0.38499999,0.514748275,0.519997358],[0.38499999,0.504610479,0.527335227],[0.38499999,0.492701381,0.531181216],[0.38499999,0.480186641,0.531158805],[0.38499999,0.468291312,0.527270257],[0.38499999,0.458179832,0.519896209],[0.38499999,0.288777888,0.349887431],[0.38499999,0.28144002,0.339749664],[0.38499999,0.27759403,0.327840507],[0.38499999,0.277616382,0.315325767],[0.38499999,0.281504929,0.303430468],[0.38499999,0.288879007,0.293318987],[0.38499999,0.299016804,0.285981119],[0.38499999,0.310925931,0.282135129],[0.38499999,0.323440671,0.282157511],[0.38499999,0.335336,0.286046058],[0.38499999,0.345447481,0.293420136]],"faces":[[19,21,11],[24,22,32],[22,1,0],[23,2,1],[24,3,2],[25,4,3],[26,5,4],[27,6,5],[28,7,6],[29,8,7],[30,9,8],[31,10,9],[32,11,10],[33,12,11],[34,13,12],[35,14,13],[36,15,14],[37,16,15],[38,17,16],[39,18,17],[40,19,18],[41,20,19],[42,21,20],[43,0,21],[63,65,55],[68,66,76],[66,45,44],[67,46,45],[68,47,46],[69,48,47],[70,49,48],[71,50,49],[72,51,50],[73,52,51],[74,53,52],[75,54,53],[76,55,54],[77,56,55],[78,57,56],[79,58,57],[80,59,58],[81,60,59],[82,61,60],[83,62,61],[84,63,62],[85,64,63],[86,65,64],[87,44,65],[95,93,91],[122,124,128],[89,110,88],[90,111,89],[91,112,90],[92,113,91],[93,114,92],[94,115,93],[95,116,94],[96,117,95],[97,118,96],[98,119,97],[99,120,98],[100,121,99],[101,122,100],[102,123,101],[103,124,102],[104,125,103],[105,126,104],[106,127,105],[107,128,106],[108,129,107],[109,130,108],[88,131,109],[141,139,135],[166,168,172],[133,154,132],[134,155,133],[135,156,134],[136,157,135],[137,158,136],[138,159,137],[139,160,138],[140,161,139],[141,162,140],[142,163,141],[143,164,142],[144,165,143],[145,166,144],[146,167,145],[147,168,146],[148,169,147],[149,170,148],[150,171,149],[151,172,150],[152,173,151],[153,174,152],[132,175,153],[21,0,10],[0,1,10],[1,2,3],[3,4,5],[5,6,7],[7,8,9],[9,10,3],[10,11,21],[3,10,1],[11,12,13],[13,14,15],[15,16,19],[16,17,19],[17,18,19],[19,20,21],[3,5,7],[7,9,3],[11,13,19],[13,15,19],[22,43,33],[43,42,33],[42,41,40],[40,39,38],[38,37,40],[37,36,40],[36,35,34],[34,33,40],[33,32,22],[40,33,42],[32,31,30],[30,29,28],[28,27,26],[26,25,28],[25,24,28],[24,23,22],[36,34,40],[32,30,24],[30,28,24],[22,23,1],[23,24,2],[24,25,3],[25,26,4],[26,27,5],[27,28,6],[28,29,7],[29,30,8],[30,31,9],[31,32,10],[32,33,11],[33,34,12],[34,35,13],[35,36,14],[36,37,15],[37,38,16],[38,39,17],[39,40,18],[40,41,19],[41,42,20],[42,43,21],[43,22,0],[65,44,54],[44,45,54],[45,46,47],[47,48,49],[49,50,47],[50,51,47],[51,52,53],[53,54,47],[54,55,65],[47,54,45],[55,56,57],[57,58,59],[59,60,61],[61,62,63],[63,64,65],[51,53,47],[55,57,63],[57,59,63],[59,61,63],[66,87,77],[87,86,77],[86,85,84],[84,83,80],[83,82,80],[82,81,80],[80,79,78],[78,77,84],[77,76,66],[84,77,86],[76,75,74],[74,73,72],[72,71,68],[71,70,68],[70,69,68],[68,67,66],[80,78,84],[76,74,68],[74,72,68],[66,67,45],[67,68,46],[68,69,47],[69,70,48],[70,71,49],[71,72,50],[72,73,51],[73,74,52],[74,75,53],[75,76,54],[76,77,55],[77,78,56],[78,79,57],[79,80,58],[80,81,59],[81,82,60],[82,83,61],[83,84,62],[84,85,63],[85,86,64],[86,87,65],[87,66,44],[89,88,98],[88,109,99],[109,108,107],[107,106,105],[105,104,107],[104,103,107],[103,102,101],[101,100,99],[99,98,88],[98,97,91],[97,96,95],[95,94,93],[93,92,91],[91,90,89],[109,107,99],[103,101,107],[101,99,107],[98,91,89],[97,95,91],[130,131,121],[131,110,120],[110,111,112],[112,113,116],[113,114,116],[114,115,116],[116,117,118],[118,119,120],[120,121,131],[121,122,128],[122,123,124],[124,125,128],[125,126,128],[126,127,128],[128,129,130],[110,112,120],[116,118,112],[118,120,112],[121,128,130],[89,111,110],[90,112,111],[91,113,112],[92,114,113],[93,115,114],[94,116,115],[95,117,116],[96,118,117],[97,119,118],[98,120,119],[99,121,120],[100,122,121],[101,123,122],[102,124,123],[103,125,124],[104,126,125],[105,127,126],[106,128,127],[107,129,128],[108,130,129],[109,131,130],[88,110,131],[133,132,142],[132,153,143],[153,152,151],[151,150,149],[149,148,147],[147,146,145],[145,144,143],[143,142,132],[142,141,135],[141,140,139],[139,138,135],[138,137,135],[137,136,135],[135,134,133],[153,151,143],[151,149,147],[147,145,151],[145,143,151],[142,135,133],[174,175,165],[175,154,164],[154,155,156],[156,157,158],[158,159,156],[159,160,156],[160,161,162],[162,163,164],[164,165,175],[165,166,172],[166,167,168],[168,169,170],[170,171,168],[171,172,168],[172,173,174],[154,156,164],[160,162,156],[162,164,156],[165,172,174],[133,155,154],[134,156,155],[135,157,156],[136,158,157],[137,159,158],[138,160,159],[139,161,160],[140,162,161],[141,163,162],[142,164,163],[143,165,164],[144,166,165],[145,167,166],[146,168,167],[147,169,168],[148,170,169],[149,171,170],[150,172,171],[151,173,172],[152,174,173],[153,175,174],[132,154,175]],"inside":[[-0.374881795,0.506437858,0.465394675],[-0.366131796,0.753098523,0.427236497],[0.367678355,0.451073686,0.418925236],[0.367678355,0.479256774,0.475544262],[0.36188077,0.558458164,0.350741692],[0.35499999,0.520441353,0.474452346],[-0.365999994,0.497151121,0.512630403],[-0.376249991,0.504683891,0.465963334],[0.367499992,0.497122383,0.509885848],[0.357,0.405670216,0.383211315],[0.357,0.417670216,0.389211315],[0.357,0.426670216,0.392211315],[-0.378,0.405670216,0.386211315],[-0.378,0.420670216,0.371211315],[-0.378,0.429670216,0.380211315],[-0.357,0.279670216,0.335211315],[-0.357,0.294670216,0.356211315],[0.3675,0.276670216,0.329211315],[0.3675,0.276670216,0.335211315],[-0.3675,0.354670216,0.365211315],[-0.357,0.387670216,0.380211315],[0.378,0.351670216,0.359211315],[-0.3675,0.357670216,0.305211315],[-0.357,0.372670216,0.311211315],[0.378,0.351670216,0.299211315],[-0.3675,0.291670216,0.314211315],[0.357,0.303670216,0.317211315],[-0.3675,0.354670216,0.362211315],[-0.357,0.357670216,0.326211315]]} \ No newline at end of file diff --git a/surfaces/blender/tests/fixtures/ram_rays.json b/surfaces/blender/tests/fixtures/ram_rays.json deleted file mode 100644 index ab8fd15..0000000 --- a/surfaces/blender/tests/fixtures/ram_rays.json +++ /dev/null @@ -1 +0,0 @@ -{"about":"The rocker's twin plates of the R-3 bell crank as Imagination's jointlib builds them: one mesh, triangulated, at rest, of four closed bars, a side's two overlapping about the pivot and sharing their faces' planes. `points`: 14 points 0.002 or more outside every bar and inside a bar's bounding box, each on the oracle's first ray 0.004 to 0.02 short of a vertex or an edge. One ray reads each inside; three read none inside. `inside`: 29 points 0.001 or more inside a bar, nine aimed along a ray of RAYS, x or y at a vertex or an edge, the rest from a grid where the bars overlap. Parity over the whole mesh reads the overlap outside (1,906 of 38,448 grid points inside the bars); read bar by bar, as ram.Signed reads a mesh, none of them and none of these reads outside.","verts":[[-0.349999994,0.740011215,0.389170021],[-0.349999994,0.752862871,0.394919485],[-0.349999994,0.763308823,0.404358923],[-0.349999994,0.770326555,0.416564375],[-0.349999994,0.773229182,0.430341005],[-0.349999994,0.77173245,0.444340348],[-0.349999994,0.765982985,0.457191974],[-0.349999994,0.756543517,0.467637926],[-0.349999994,0.744338095,0.474655658],[-0.349999994,0.730561495,0.477558255],[-0.349999994,0.716562152,0.476061553],[-0.349999994,0.305388123,0.365099549],[-0.349999994,0.292536497,0.359350085],[-0.349999994,0.282090545,0.349910617],[-0.349999994,0.275072783,0.337705195],[-0.349999994,0.272170216,0.323928565],[-0.349999994,0.273666918,0.309929222],[-0.349999994,0.279416382,0.297077596],[-0.349999994,0.288855821,0.286631644],[-0.349999994,0.301061243,0.279613912],[-0.349999994,0.314837903,0.276711315],[-0.349999994,0.328837216,0.278208017],[-0.38499999,0.740011215,0.389170021],[-0.38499999,0.752862871,0.394919485],[-0.38499999,0.763308823,0.404358923],[-0.38499999,0.770326555,0.416564375],[-0.38499999,0.773229182,0.430341005],[-0.38499999,0.77173245,0.444340348],[-0.38499999,0.765982985,0.457191974],[-0.38499999,0.756543517,0.467637926],[-0.38499999,0.744338095,0.474655658],[-0.38499999,0.730561495,0.477558255],[-0.38499999,0.716562152,0.476061553],[-0.38499999,0.305388123,0.365099549],[-0.38499999,0.292536497,0.359350085],[-0.38499999,0.282090545,0.349910617],[-0.38499999,0.275072783,0.337705195],[-0.38499999,0.272170216,0.323928565],[-0.38499999,0.273666918,0.309929222],[-0.38499999,0.279416382,0.297077596],[-0.38499999,0.288855821,0.286631644],[-0.38499999,0.301061243,0.279613912],[-0.38499999,0.314837903,0.276711315],[-0.38499999,0.328837216,0.278208017],[-0.349999994,0.514849424,0.463428885],[-0.349999994,0.522187293,0.473566681],[-0.349999994,0.526033282,0.485475808],[-0.349999994,0.526010931,0.497990549],[-0.349999994,0.522122383,0.509885848],[-0.349999994,0.514748275,0.519997358],[-0.349999994,0.504610479,0.527335227],[-0.349999994,0.492701381,0.531181216],[-0.349999994,0.480186641,0.531158805],[-0.349999994,0.468291312,0.527270257],[-0.349999994,0.458179832,0.519896209],[-0.349999994,0.288777888,0.349887431],[-0.349999994,0.28144002,0.339749664],[-0.349999994,0.27759403,0.327840507],[-0.349999994,0.277616382,0.315325767],[-0.349999994,0.281504929,0.303430468],[-0.349999994,0.288879007,0.293318987],[-0.349999994,0.299016804,0.285981119],[-0.349999994,0.310925931,0.282135129],[-0.349999994,0.323440671,0.282157511],[-0.349999994,0.335336,0.286046058],[-0.349999994,0.345447481,0.293420136],[-0.38499999,0.514849424,0.463428885],[-0.38499999,0.522187293,0.473566681],[-0.38499999,0.526033282,0.485475808],[-0.38499999,0.526010931,0.497990549],[-0.38499999,0.522122383,0.509885848],[-0.38499999,0.514748275,0.519997358],[-0.38499999,0.504610479,0.527335227],[-0.38499999,0.492701381,0.531181216],[-0.38499999,0.480186641,0.531158805],[-0.38499999,0.468291312,0.527270257],[-0.38499999,0.458179832,0.519896209],[-0.38499999,0.288777888,0.349887431],[-0.38499999,0.28144002,0.339749664],[-0.38499999,0.27759403,0.327840507],[-0.38499999,0.277616382,0.315325767],[-0.38499999,0.281504929,0.303430468],[-0.38499999,0.288879007,0.293318987],[-0.38499999,0.299016804,0.285981119],[-0.38499999,0.310925931,0.282135129],[-0.38499999,0.323440671,0.282157511],[-0.38499999,0.335336,0.286046058],[-0.38499999,0.345447481,0.293420136],[0.349999994,0.740011215,0.389170021],[0.349999994,0.752862871,0.394919485],[0.349999994,0.763308823,0.404358923],[0.349999994,0.770326555,0.416564375],[0.349999994,0.773229182,0.430341005],[0.349999994,0.77173245,0.444340348],[0.349999994,0.765982985,0.457191974],[0.349999994,0.756543517,0.467637926],[0.349999994,0.744338095,0.474655658],[0.349999994,0.730561495,0.477558255],[0.349999994,0.716562152,0.476061553],[0.349999994,0.305388123,0.365099549],[0.349999994,0.292536497,0.359350085],[0.349999994,0.282090545,0.349910617],[0.349999994,0.275072783,0.337705195],[0.349999994,0.272170216,0.323928565],[0.349999994,0.273666918,0.309929222],[0.349999994,0.279416382,0.297077596],[0.349999994,0.288855821,0.286631644],[0.349999994,0.301061243,0.279613912],[0.349999994,0.314837903,0.276711315],[0.349999994,0.328837216,0.278208017],[0.38499999,0.740011215,0.389170021],[0.38499999,0.752862871,0.394919485],[0.38499999,0.763308823,0.404358923],[0.38499999,0.770326555,0.416564375],[0.38499999,0.773229182,0.430341005],[0.38499999,0.77173245,0.444340348],[0.38499999,0.765982985,0.457191974],[0.38499999,0.756543517,0.467637926],[0.38499999,0.744338095,0.474655658],[0.38499999,0.730561495,0.477558255],[0.38499999,0.716562152,0.476061553],[0.38499999,0.305388123,0.365099549],[0.38499999,0.292536497,0.359350085],[0.38499999,0.282090545,0.349910617],[0.38499999,0.275072783,0.337705195],[0.38499999,0.272170216,0.323928565],[0.38499999,0.273666918,0.309929222],[0.38499999,0.279416382,0.297077596],[0.38499999,0.288855821,0.286631644],[0.38499999,0.301061243,0.279613912],[0.38499999,0.314837903,0.276711315],[0.38499999,0.328837216,0.278208017],[0.349999994,0.514849424,0.463428885],[0.349999994,0.522187293,0.473566681],[0.349999994,0.526033282,0.485475808],[0.349999994,0.526010931,0.497990549],[0.349999994,0.522122383,0.509885848],[0.349999994,0.514748275,0.519997358],[0.349999994,0.504610479,0.527335227],[0.349999994,0.492701381,0.531181216],[0.349999994,0.480186641,0.531158805],[0.349999994,0.468291312,0.527270257],[0.349999994,0.458179832,0.519896209],[0.349999994,0.288777888,0.349887431],[0.349999994,0.28144002,0.339749664],[0.349999994,0.27759403,0.327840507],[0.349999994,0.277616382,0.315325767],[0.349999994,0.281504929,0.303430468],[0.349999994,0.288879007,0.293318987],[0.349999994,0.299016804,0.285981119],[0.349999994,0.310925931,0.282135129],[0.349999994,0.323440671,0.282157511],[0.349999994,0.335336,0.286046058],[0.349999994,0.345447481,0.293420136],[0.38499999,0.514849424,0.463428885],[0.38499999,0.522187293,0.473566681],[0.38499999,0.526033282,0.485475808],[0.38499999,0.526010931,0.497990549],[0.38499999,0.522122383,0.509885848],[0.38499999,0.514748275,0.519997358],[0.38499999,0.504610479,0.527335227],[0.38499999,0.492701381,0.531181216],[0.38499999,0.480186641,0.531158805],[0.38499999,0.468291312,0.527270257],[0.38499999,0.458179832,0.519896209],[0.38499999,0.288777888,0.349887431],[0.38499999,0.28144002,0.339749664],[0.38499999,0.27759403,0.327840507],[0.38499999,0.277616382,0.315325767],[0.38499999,0.281504929,0.303430468],[0.38499999,0.288879007,0.293318987],[0.38499999,0.299016804,0.285981119],[0.38499999,0.310925931,0.282135129],[0.38499999,0.323440671,0.282157511],[0.38499999,0.335336,0.286046058],[0.38499999,0.345447481,0.293420136]],"faces":[[19,21,11],[24,22,32],[22,1,0],[23,2,1],[24,3,2],[25,4,3],[26,5,4],[27,6,5],[28,7,6],[29,8,7],[30,9,8],[31,10,9],[32,11,10],[33,12,11],[34,13,12],[35,14,13],[36,15,14],[37,16,15],[38,17,16],[39,18,17],[40,19,18],[41,20,19],[42,21,20],[43,0,21],[63,65,55],[68,66,76],[66,45,44],[67,46,45],[68,47,46],[69,48,47],[70,49,48],[71,50,49],[72,51,50],[73,52,51],[74,53,52],[75,54,53],[76,55,54],[77,56,55],[78,57,56],[79,58,57],[80,59,58],[81,60,59],[82,61,60],[83,62,61],[84,63,62],[85,64,63],[86,65,64],[87,44,65],[95,93,91],[122,124,128],[89,110,88],[90,111,89],[91,112,90],[92,113,91],[93,114,92],[94,115,93],[95,116,94],[96,117,95],[97,118,96],[98,119,97],[99,120,98],[100,121,99],[101,122,100],[102,123,101],[103,124,102],[104,125,103],[105,126,104],[106,127,105],[107,128,106],[108,129,107],[109,130,108],[88,131,109],[141,139,135],[166,168,172],[133,154,132],[134,155,133],[135,156,134],[136,157,135],[137,158,136],[138,159,137],[139,160,138],[140,161,139],[141,162,140],[142,163,141],[143,164,142],[144,165,143],[145,166,144],[146,167,145],[147,168,146],[148,169,147],[149,170,148],[150,171,149],[151,172,150],[152,173,151],[153,174,152],[132,175,153],[21,0,10],[0,1,10],[1,2,3],[3,4,5],[5,6,7],[7,8,9],[9,10,3],[10,11,21],[3,10,1],[11,12,13],[13,14,15],[15,16,19],[16,17,19],[17,18,19],[19,20,21],[3,5,7],[7,9,3],[11,13,19],[13,15,19],[22,43,33],[43,42,33],[42,41,40],[40,39,38],[38,37,40],[37,36,40],[36,35,34],[34,33,40],[33,32,22],[40,33,42],[32,31,30],[30,29,28],[28,27,26],[26,25,28],[25,24,28],[24,23,22],[36,34,40],[32,30,24],[30,28,24],[22,23,1],[23,24,2],[24,25,3],[25,26,4],[26,27,5],[27,28,6],[28,29,7],[29,30,8],[30,31,9],[31,32,10],[32,33,11],[33,34,12],[34,35,13],[35,36,14],[36,37,15],[37,38,16],[38,39,17],[39,40,18],[40,41,19],[41,42,20],[42,43,21],[43,22,0],[65,44,54],[44,45,54],[45,46,47],[47,48,49],[49,50,47],[50,51,47],[51,52,53],[53,54,47],[54,55,65],[47,54,45],[55,56,57],[57,58,59],[59,60,61],[61,62,63],[63,64,65],[51,53,47],[55,57,63],[57,59,63],[59,61,63],[66,87,77],[87,86,77],[86,85,84],[84,83,80],[83,82,80],[82,81,80],[80,79,78],[78,77,84],[77,76,66],[84,77,86],[76,75,74],[74,73,72],[72,71,68],[71,70,68],[70,69,68],[68,67,66],[80,78,84],[76,74,68],[74,72,68],[66,67,45],[67,68,46],[68,69,47],[69,70,48],[70,71,49],[71,72,50],[72,73,51],[73,74,52],[74,75,53],[75,76,54],[76,77,55],[77,78,56],[78,79,57],[79,80,58],[80,81,59],[81,82,60],[82,83,61],[83,84,62],[84,85,63],[85,86,64],[86,87,65],[87,66,44],[89,88,98],[88,109,99],[109,108,107],[107,106,105],[105,104,107],[104,103,107],[103,102,101],[101,100,99],[99,98,88],[98,97,91],[97,96,95],[95,94,93],[93,92,91],[91,90,89],[109,107,99],[103,101,107],[101,99,107],[98,91,89],[97,95,91],[130,131,121],[131,110,120],[110,111,112],[112,113,116],[113,114,116],[114,115,116],[116,117,118],[118,119,120],[120,121,131],[121,122,128],[122,123,124],[124,125,128],[125,126,128],[126,127,128],[128,129,130],[110,112,120],[116,118,112],[118,120,112],[121,128,130],[89,111,110],[90,112,111],[91,113,112],[92,114,113],[93,115,114],[94,116,115],[95,117,116],[96,118,117],[97,119,118],[98,120,119],[99,121,120],[100,122,121],[101,123,122],[102,124,123],[103,125,124],[104,126,125],[105,127,126],[106,128,127],[107,129,128],[108,130,129],[109,131,130],[88,110,131],[133,132,142],[132,153,143],[153,152,151],[151,150,149],[149,148,147],[147,146,145],[145,144,143],[143,142,132],[142,141,135],[141,140,139],[139,138,135],[138,137,135],[137,136,135],[135,134,133],[153,151,143],[151,149,147],[147,145,151],[145,143,151],[142,135,133],[174,175,165],[175,154,164],[154,155,156],[156,157,158],[158,159,156],[159,160,156],[160,161,162],[162,163,164],[164,165,175],[165,166,172],[166,167,168],[168,169,170],[170,171,168],[171,172,168],[172,173,174],[154,156,164],[160,162,156],[162,164,156],[165,172,174],[133,155,154],[134,156,155],[135,157,156],[136,158,157],[137,159,158],[138,160,159],[139,161,160],[140,162,161],[141,163,162],[142,164,163],[143,165,164],[144,166,165],[145,167,166],[146,168,167],[147,169,168],[148,170,169],[149,171,170],[150,172,171],[151,173,172],[152,174,173],[153,175,174],[132,154,175]],"points":[[-0.356452715,0.274636974,0.343069077],[0.378547269,0.274636974,0.343069077],[0.380698176,0.529455168,0.329127992],[0.378547269,0.526970645,0.326847479],[-0.373952713,0.274636974,0.343069077],[0.380698176,0.273612617,0.339246879],[-0.354301808,0.529455168,0.329127992],[-0.356452715,0.526970645,0.326847479],[0.374245455,0.745663229,0.388236637],[0.378547269,0.738983472,0.385203213],[0.361047271,0.274636974,0.343069077],[-0.354301808,0.273612617,0.339246879],[-0.360754529,0.745663229,0.388236637],[-0.356452715,0.738983472,0.385203213]],"inside":[[-0.374881795,0.506437858,0.465394675],[-0.366131796,0.753098523,0.427236497],[0.367678355,0.451073686,0.418925236],[0.367678355,0.479256774,0.475544262],[0.36188077,0.558458164,0.350741692],[0.35499999,0.520441353,0.474452346],[-0.365999994,0.497151121,0.512630403],[-0.376249991,0.504683891,0.465963334],[0.367499992,0.497122383,0.509885848],[0.357,0.405670216,0.383211315],[0.357,0.417670216,0.389211315],[0.357,0.426670216,0.392211315],[-0.378,0.405670216,0.386211315],[-0.378,0.420670216,0.371211315],[-0.378,0.429670216,0.380211315],[-0.357,0.279670216,0.335211315],[-0.357,0.294670216,0.356211315],[0.3675,0.276670216,0.329211315],[0.3675,0.276670216,0.335211315],[-0.3675,0.354670216,0.365211315],[-0.357,0.387670216,0.380211315],[0.378,0.351670216,0.359211315],[-0.3675,0.357670216,0.305211315],[-0.357,0.372670216,0.311211315],[0.378,0.351670216,0.299211315],[-0.3675,0.291670216,0.314211315],[0.357,0.303670216,0.317211315],[-0.3675,0.354670216,0.362211315],[-0.357,0.357670216,0.326211315]]} \ No newline at end of file diff --git a/surfaces/blender/tests/live/ram_knee.py b/surfaces/blender/tests/live/ram_knee.py index e32d3d1..272fe15 100644 --- a/surfaces/blender/tests/live/ram_knee.py +++ b/surfaces/blender/tests/live/ram_knee.py @@ -9,11 +9,10 @@ Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USE without them). is an absolute path; writes .result.json and .r3_.png (the bell crank at 0, -62.5 and -125) and exits 1 when a check failed. -The oracle is ram.Signed, three rays by majority. Its ray count is held by tests/fixtures/ram_rays.json: the rocker -plates as Imagination's jointlib builds them and points beside their bars that stand on the first ray short of an -edge or a vertex. One ray reads them inside a plate they stand clear of; the oracle as it is made reads none inside. -The same mesh is four closed bars joined into one, a side's two overlapping: the oracle reads it bar by bar, and no -point of a grid inside the bars, nor of the fixture's 29 inside points, reads outside. +The oracle is ram.Signed: a point is inside a part where the winding number of the part's faces about it is 0.5 or +more. tests/fixtures/ram_plates.json holds the rocker plates as Imagination's jointlib builds them, four closed bars +joined into one mesh, a side's two overlapping, and 29 points inside them: none reads outside. Nor does a point where +two welded boxes overlap, or inside a cube with a face left open. A clearance verdict is a sign, the gate's own. FLAT follows lodur:ruling:deterministic-bound-margin. The checks run inside one try: an uncaught error is a failed check that names its section, and the result file is always written. @@ -306,57 +305,45 @@ try: # plates and none is inside; where the plate is under the point the reading is the 0.0225 ys, zs = np.meshgrid(np.linspace(0.1, 0.9, 96), np.linspace(0.1, 0.7, 72)) plane = np.stack([np.full(ys.size, X_C), ys.ravel(), zs.ravel()], axis=1) - three, one = Signed(shells)("rocker.plate", plane), Signed(shells, rays=1)("rocker.plate", plane) + off_plates = Signed(shells)("rocker.plate", plane) def off(a, b): # each grid point's distance from the segment a -> b, across the axis a, b = np.array(a), np.array(b) t = np.clip(((plane[:, 1:] - a) @ (b - a)) / ((b - a) @ (b - a)), 0.0, 1.0) return np.linalg.norm(plane[:, 1:] - a - t[:, None] * (b - a), axis=1) under = (off(CRANK["rocker"], CRANK["p"]) < W_ROCKER - 0.005) | (off(CRANK["rocker"], CRANK["d"]) < W_ARM - 0.005) - RES["readings"]["FLAT"] = float(np.abs(three[under] - (SLAB_R[0] - X_C)).max()) - RES["readings"]["one ray: samples signed inside, of %d" % len(plane)] = int((one < 0).sum()) - check("three-rays: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225", - (three >= SLAB_R[0] - X_C - FLAT).all() and under.sum() > 500 and RES["readings"]["FLAT"] < FLAT, [float(three.min()), int(under.sum()), RES["readings"]["FLAT"]]) - # against shells whose inside is known in closed form: a box and a disc, random points, each ray's edges and vertices among them + RES["readings"]["FLAT"] = float(np.abs(off_plates[under] - (SLAB_R[0] - X_C)).max()) + check("off-the-plates: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225", + (off_plates >= SLAB_R[0] - X_C - FLAT).all() and under.sum() > 500 and RES["readings"]["FLAT"] < FLAT, [float(off_plates.min()), int(under.sum()), RES["readings"]["FLAT"]]) + # against a shell whose inside is known in closed form: a box, random points rng = np.random.default_rng(7) cloud = rng.uniform((-0.2, -0.2, 0.2), (0.2, 0.2, 1.25), (4000, 3)) core = Signed({"core": [box((0, 0, 0.725), (0.26, 0.28, 0.85))]})("core", cloud) exact = np.maximum.reduce([np.abs(cloud[:, 0]) - 0.13, np.abs(cloud[:, 1]) - 0.14, np.abs(cloud[:, 2] - 0.725) - 0.425]) - check("three-rays: 4000 random points about a box are signed as the box signs them", ((core < 0) == (exact < 0)).all(), int(((core < 0) != (exact < 0)).sum())) + check("box: 4000 random points about a box are signed as the box signs them", ((core < 0) == (exact < 0)).all(), int(((core < 0) != (exact < 0)).sum())) - # the ray count: the jointlib rocker plates, and points beside a bar, in its bounding box, aimed along the first ray at an edge or a vertex - fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_rays.json").read_text(encoding="utf-8")) - plates, aimed = {"plates": [(np.array(fixture["verts"]), fixture["faces"])]}, np.array(fixture["points"]) - made, single = Signed(plates)("plates", aimed), Signed(plates, rays=1)("plates", aimed) - RES["readings"]["jointlib plates: points one ray signs inside, of %d" % len(aimed)] = int((single < 0).sum()) - RES["readings"]["jointlib plates: points the oracle signs inside"] = int((made < 0).sum()) - # one ray reads all 14 inside; the oracle as made reads none. The bound on one ray's count is the geometric mean of 1 and 14 - check("ray-count: beside the jointlib rocker plates' bars, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray", - (made > 0).all() and (single < 0).sum() >= 4, [int((made < 0).sum()), int((single < 0).sum())]) - - # the other way, which the gate's proof between samples leans on: no point inside the plates reads outside. The - # fixture's mesh is four closed bars, a side's two overlapping about the pivot; a point is truly inside where it is - # 0.001 or more inside one bar (each a convex prism: inside every face's plane). A grid 0.003 apart at three depths - # of each plate, and the fixture's 29 points. A count of points: shipped 0 (half a point, - # lodur:ruling:deterministic-bound-zero-reading), parity over the whole mesh (M-whole) 1,906; the check asks 0 - hulls = [] - for verts, faces in R._pieces(*plates["plates"][0]): - tri = np.array([[verts[i] for i in face[:3]] for face in faces]) - normal = np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]) - normal /= np.linalg.norm(normal, axis=1)[:, None] - level = (normal * tri[:, 0]).sum(axis=1) - out = (normal @ verts.mean(axis=0) - level) > 0 - normal[out], level[out] = -normal[out], -level[out] - hulls.append((normal, level)) - lo, hi = (np.array(fixture["verts"]).min(axis=0), np.array(fixture["verts"]).max(axis=0)) - cloud = np.array([(s * (SLAB_R[0] + 2 * HALF * f), y, z) for s in (-1.0, 1.0) for f in (0.2, 0.5, 0.8) - for y in np.arange(lo[1] + 0.0015, hi[1], 0.003) for z in np.arange(lo[2] + 0.0015, hi[2], 0.003)]) - deep = np.max([-(cloud @ normal.T - level).max(axis=1) for normal, level in hulls], axis=0) >= 0.001 - within = np.concatenate([cloud[deep], np.array(fixture["inside"])]) - missed = int((Signed(plates)("plates", within) >= 0).sum()) - RES["readings"]["jointlib plates: bars the mesh is read as"] = len(hulls) - RES["readings"]["jointlib plates: inside points read outside, of %d" % len(within)] = missed - check("inside-reads-inside: no point inside the jointlib rocker plates, where its bars overlap or not, reads outside by the oracle as it is made", - len(hulls) == 4 and int(deep.sum()) > 30000 and missed == 0, [len(hulls), int(deep.sum()), missed]) + # what the gate's proof between samples leans on: no point inside a part reads outside. The jointlib rocker plates + # are four closed bars in one mesh, a side's two overlapping about the pivot (crossing parity read the overlap + # outside); the fixture's 29 points are 0.001 or more inside a bar, 13 of them inside two. A count of points + fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_plates.json").read_text(encoding="utf-8")) + plates = Signed({"plates": [(np.array(fixture["verts"]), fixture["faces"])]})("plates", np.array(fixture["inside"])) + # two boxes cut through one another and welded at the corner they share; and a cube with its top left open + def wound(lo, hi): + verts = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])], float) + return verts, [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)] + (v1, f1), (v2, f2) = wound((0, 0, 0), (1, 1, 1)), wound((0, 0, 0), (2, 0.5, 0.5)) + welded = (np.concatenate([v1, v2[1:]]), f1 + [tuple(i + 7 if i else 0 for i in face) for face in f2]) + cloud = rng.uniform(-0.2, 2.2, (6000, 3)) + truth = ((cloud >= 0) & (cloud <= 1)).all(axis=1) | ((cloud >= 0) & (cloud <= (2, 0.5, 0.5))).all(axis=1) + both = ((cloud >= 0) & (cloud <= (1, 0.5, 0.5))).all(axis=1) + got = Signed({"welded": [welded]})("welded", cloud) < 0 + inner = rng.uniform(0.001, 0.999, (4000, 3)) + opened = Signed({"open": [(v1, [face for face in f1 if face != (1, 5, 7, 3)])]})("open", inner) + RES["readings"]["jointlib plates: inside points read outside, of %d" % len(plates)] = int((plates >= 0).sum()) + RES["readings"]["welded boxes: points missigned, of %d (%d in the overlap)" % (len(cloud), int(both.sum()))] = int((got != truth).sum()) + RES["readings"]["open cube: inside points read outside, of %d" % len(inner)] = int((opened >= 0).sum()) + check("inside-reads-inside: no point inside the jointlib rocker plates' bars, in two welded boxes' overlap or in a cube with a face open reads outside, and none outside the boxes reads inside", + len(plates) == 29 and int((plates >= 0).sum()) == 0 and int(both.sum()) > 50 and int((got != truth).sum()) == 0 and int((opened >= 0).sum()) == 0, + [int((plates >= 0).sum()), int(both.sum()), int((got != truth).sum()), int((opened >= 0).sum())]) SECTION[0] = "seat" seat = np.concatenate([v for v, _ in shells["parent.seat"]]) diff --git a/surfaces/blender/tests/live/ram_knee.result.json b/surfaces/blender/tests/live/ram_knee.result.json index efb906b..34bb0b1 100644 --- a/surfaces/blender/tests/live/ram_knee.result.json +++ b/surfaces/blender/tests/live/ram_knee.result.json @@ -7,22 +7,17 @@ "detail": null }, { - "name": "three-rays: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225", + "name": "off-the-plates: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225", "ok": true, "detail": null }, { - "name": "three-rays: 4000 random points about a box are signed as the box signs them", + "name": "box: 4000 random points about a box are signed as the box signs them", "ok": true, "detail": null }, { - "name": "ray-count: beside the jointlib rocker plates' bars, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray", - "ok": true, - "detail": null - }, - { - "name": "inside-reads-inside: no point inside the jointlib rocker plates, where its bars overlap or not, reads outside by the oracle as it is made", + "name": "inside-reads-inside: no point inside the jointlib rocker plates' bars, in two welded boxes' overlap or in a cube with a face open reads outside, and none outside the boxes reads inside", "ok": true, "detail": null }, @@ -113,23 +108,21 @@ "bell crank: least margin of a zoned pair, 251 steps uncapped": 0.000118, "bell crank: pairs": 60, "bell crank: pairs refused with nothing let": 19, - "bell crank: seconds, 49 steps capped": 0.946, + "bell crank: seconds, 49 steps capped": 0.8, "bell crank: zoned pairs": 20, "four bar: barrel inside the shin's clearance": -0.122, - "jointlib plates: bars the mesh is read as": 4, - "jointlib plates: inside points read outside, of 38477": 0, - "jointlib plates: points one ray signs inside, of 14": 14, - "jointlib plates: points the oracle signs inside": 0, + "jointlib plates: inside points read outside, of 29": 0, "moved x: both": -0.0543, "moved x: the coupler at x 0.25, inside the horn's 0.23..0.31": -0.02, "moved x: the rocker at x 0.25, inside the bracket's 0.13..0.35": -0.0543, - "one ray: samples signed inside, of 6912": 0, + "open cube: inside points read outside, of 4000": 0, "search: candidates": 13824, "search: pass the gates before clearance": 78, "search: refused on their own parts": 21, - "search: seconds": 32.7, + "search: seconds": 34.5, "search: worlds built": 22, - "the base clevis's foot inside the thigh": -0.01 + "the base clevis's foot inside the thigh": -0.01, + "welded boxes: points missigned, of 6000 (91 in the overlap)": 0 }, "zones": { "barrel[0] | parent.seat": { @@ -503,9 +496,9 @@ } }, "renders": [ - "F:/aeth-wt/fable-ramlows/scratch/out/live5.r3_0.png", - "F:/aeth-wt/fable-ramlows/scratch/out/live5.r3_62p5.png", - "F:/aeth-wt/fable-ramlows/scratch/out/live5.r3_125.png" + "F:/aeth-wt/fable-ramlows/scratch/out/h3f.r3_0.png", + "F:/aeth-wt/fable-ramlows/scratch/out/h3f.r3_62p5.png", + "F:/aeth-wt/fable-ramlows/scratch/out/h3f.r3_125.png" ], "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py index 2a94872..2074ff8 100644 --- a/surfaces/blender/tests/test_ram.py +++ b/surfaces/blender/tests/test_ram.py @@ -83,6 +83,40 @@ def yz(p, x=0.0): return (x, float(p[0]), float(p[1])) +def block(lo, hi): + """A box as a mesh: 8 vertices and 12 triangles wound counterclockwise seen from outside.""" + lo, hi = np.asarray(lo, float), np.asarray(hi, float) + verts = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]) + quads = ((0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)) + return verts, np.array([t for a, b, c, d in quads for t in ((a, b, c), (a, c, d))]) + + +def joined(first, second, weld): + """Two meshes as one; with `weld`, vertices of the second that stand on one of the first take its index.""" + (v1, t1), (v2, t2) = first, second + verts, index = [tuple(p) for p in v1], [] + for p in map(tuple, v2): + if weld and p in verts: + index.append(verts.index(p)) + else: + index.append(len(verts)) + verts.append(p) + return np.array(verts), np.concatenate([t1, np.array(index)[t2]]) + + +def staircase(): + """A prism of three steps along y from 0 to 1: under z = 1 for x in 0..1, z = 2 for 1..2, z = 3 for 2..3.""" + profile = ((0, 0), (3, 0), (3, 3), (2, 3), (2, 2), (1, 2), (1, 1), (0, 1)) # (x, z) + verts = np.array([(x, y, z) for y in (0.0, 1.0) for x, z in profile], float) + tris = [] + for k in range(8): + n = (k + 1) % 8 + tris += [(k, n + 8, n), (k, k + 8, n + 8)] + for a, b, c in ((0, 1, 6), (0, 6, 7), (1, 4, 5), (1, 5, 6), (1, 2, 3), (1, 3, 4)): # the cap at y = 0, and at y = 1 turned over + tris += [(a, b, c), (a + 8, c + 8, b + 8)] + return verts, np.array(tris) + + def grid(lo, hi, counts): lo, hi = np.asarray(lo, float), np.asarray(hi, float) axes = [np.linspace(lo[k], hi[k], n) if n > 1 else np.array([(lo[k] + hi[k]) / 2]) for k, n in enumerate(counts)] @@ -505,6 +539,7 @@ ZONED = 2.2e-10 # a rocker sample against its own plates: shipped 0 (hal BESIDE = 1.2e-10 # a wall 0.02 beside the coupler, read at the nearest sample: shipped 0 (half an ulp of 0.0242, 1.7e-18), B1 (the proof by the nearer end's reading less the span, which halves and reads beside the wall) 0.00423 off, separation 4.9e7 each side FLOOR_UNDER = 0.319 # how near the axis a wall held outside reads as touched, in spacing / 64: shipped under 0.451, FINE 128 under 0.2255, separation 1.41 each side FLOOR_OVER = 0.638 # shipped under 0.451, FINE 32 under 0.902, separation 1.41 each side +WHOLE = 3.8e-4 # a winding number against the count or share a hand value states: shipped 6.3e-6 at most (the plates; the angles are single precision), W1 (the denominator's a.b term without the third length) 0.0224 off on the open cube's axis, separation 60 each side SPAN_RAM = 0.848 # the ram's span with its base 0.1 from the rocker's pivot: shipped 0.5390 (about that pivot), the span about the knee's pivot 1.3347, separation 1.57 each side @@ -1268,18 +1303,53 @@ class Refusals(unittest.TestCase): self.assertEqual((caught.exception.gate, caught.exception.pin), ("arm", "b")) self.assertIn(f"arm at {caught.exception.angle:g} deg (pin b)", str(caught.exception)) - def test_a_mesh_is_read_piece_by_piece(self): - # Signed's split: two tetrahedra in one mesh, the second's vertices listed first and its faces interleaved, - # come back as two closed pieces with their own vertices; a mesh of one piece comes back whole - tet = [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)] - a, b = np.array([(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)], float), np.array([(0.2, 0.2, 0.2), (5, 0, 0), (0, 5, 0), (0, 0, 5)], float) - faces = [face for pair in zip([tuple(i + 4 for i in f) for f in tet], tet) for face in pair] - pieces = R._pieces(np.concatenate([b, a]), faces) - self.assertEqual(len(pieces), 2) - for (verts, got), want in zip(pieces, (a, b)): - self.assertEqual((verts.tolist(), sorted(got)), (want.tolist(), tet)) - whole = R._pieces(a, tet) - self.assertEqual((len(whole), whole[0][0].tolist(), whole[0][1]), (1, a.tolist(), tet)) + def test_overlapping_solids_wind_by_their_count(self): + # two boxes that cut through one another in one mesh, each with its own vertices, then sharing the one index + # at the corner they have in common (all a merge by distance welds): the winding number is the count of + # boxes about the point, 2 in the overlap, where crossing parity read outside + big, small = block((0, 0, 0), (1, 1, 1)), block((0, 0, 0), (2, 0.5, 0.5)) + pts = np.random.default_rng(1).uniform(-0.2, 2.2, (6000, 3)) + count = sum(((pts >= lo) & (pts <= hi)).all(axis=1).astype(int) for lo, hi in (((0, 0, 0), (1, 1, 1)), ((0, 0, 0), (2, 0.5, 0.5)))) + self.assertGreater(int((count == 2).sum()), 50) + for weld in (False, True): + verts, tris = joined(big, small, weld) + self.assertEqual(len(verts), 15 if weld else 16) + self.assertLess(float(np.abs(R.winding(verts, tris, pts) - count).max()), WHOLE, weld) + + def test_the_plates_overlapping_bars_wind_by_their_count(self): + # the jointlib rocker plates: four closed bars in one mesh, a side's two overlapping. Every inside point of + # the fixture winds 1, or 2 where two bars overlap + fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_plates.json").read_text(encoding="utf-8")) + w = R.winding(fixture["verts"], fixture["faces"], fixture["inside"]) + self.assertLess(float(np.abs(w - np.round(w)).max()), WHOLE) + self.assertEqual((int((np.round(w) == 1).sum()), int((np.round(w) == 2).sum())), (16, 13)) + + def test_a_staircase_winds_whole(self): + # a nonconvex prism of three steps, which a line crosses up to six times: 1 inside, 0 outside + verts, tris = staircase() + g = np.arange(-0.375, 3.5, 0.25) + pts = np.array([(x, y, z) for x in g for y in (-0.25, 0.125, 0.5, 0.875, 1.25) for z in g]) + truth = (pts[:, 1] > 0) & (pts[:, 1] < 1) & (pts[:, 0] > 0) & (pts[:, 0] < 3) & (pts[:, 2] > 0) & (pts[:, 2] < np.ceil(pts[:, 0])) + self.assertGreater(min(int(truth.sum()), int((~truth).sum())), 200) + self.assertLess(float(np.abs(R.winding(verts, tris, pts) - truth).max()), WHOLE) + + def test_an_open_cube_winds_by_what_its_hole_takes(self): + # a unit cube less its top face: about a point on the hole's axis the winding number is 1 less the hole's + # share of the sphere inside, and that share outside, 4 asin(a^2 / (a^2 + h^2)) of 4 pi for a square of half + # side a seen from h off its centre. So it is over 0.5 everywhere inside and under 0.5 over the hole, and + # passes through 0.5 on the hole's plane, where no face is. Less one triangle of the top it is the same + verts, tris = block((0, 0, 0), (1, 1, 1)) + top = [k for k, t in enumerate(tris) if (verts[t][:, 2] == 1.0).all()] + self.assertEqual(len(top), 2) + z = np.array((0.5, 0.9, 0.999, 1.001, 1.1, 1.5)) + share = np.arcsin(0.25 / (0.25 + (1.0 - z) ** 2)) / math.pi + w = R.winding(verts, np.delete(tris, top, axis=0), np.stack([np.full(6, 0.5), np.full(6, 0.5), z], axis=1)) + self.assertLess(float(np.abs(w - np.where(z < 1, 1.0 - share, share)).max()), WHOLE) + self.assertTrue((w[:3] > 0.5).all() and (w[3:] < 0.5).all(), w.tolist()) # 0.001 under the plane 0.5009, 0.001 over it 0.4991 + # no point inside either open cube, down to 0.001 from its faces and its hole, winds under 0.5: a count + inner = np.random.default_rng(3).uniform(0.001, 0.999, (4000, 3)) + for gone in (top, top[:1]): + self.assertEqual(int((R.winding(verts, np.delete(tris, gone, axis=0), inner) < 0.5).sum()), 0) def test_no_blender(self): source = (SURFACE / "brokkr_kitbash" / "ram.py").read_text(encoding="utf-8") From 3b56cdec6e4eff8bdbe996659729e8ecb53c64a3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 01:35:12 +0100 Subject: [PATCH 164/223] brokkr_kitbash.ram: Signed refuses a part that is open or wound inside out, by its solid; the depth is to exposed faces solids() splits a part into edge-connected solids and refuses one with an edge no face runs the other way (the count) or of negative volume (the solid, its first face, the volume). Nothing is repaired. inside() holds the 0.5 bound, pinned in the unit suite on a test-only open cube (0.527 and 0.473 about the hole). Inside, the depth is read from a tree of the faces whose centroid, set off along the normal, is not inside the part; outside, from all faces as before. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/ram.py | 94 ++++++++++++++++++++------ surfaces/blender/tests/test_ram.py | 57 ++++++++++++++++ 2 files changed, 132 insertions(+), 19 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py index f27ac23..d5fa6f5 100644 --- a/surfaces/blender/brokkr_kitbash/ram.py +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -25,6 +25,8 @@ the coupler bar at c's, the ram at a's plus each of `offsets`. record(m, ram), from_record the JSON record a rig or runtime drives from swept(fit, body, ...) points of the swept ram's surface in a body's rest frame winding(vertices, triangles, points) the generalized winding number of a triangle soup about points + inside(vertices, triangles, points) whether points are inside it: the number is 0.5 or more + solids(part, vertices, faces) the closed, outward wound solids of a part, or the refusal Signed(shells, cap) the distance oracle over meshes, signed by the winding number Clearance. The record names the mechanism's `parts`, each a piece of one body (part -> the body whose rest frame @@ -754,11 +756,12 @@ def winding(vertices, triangles, points): 2013): the triangles' signed solid angles, summed, over 4 pi. A triangle counts positive from the side its normal points away from (counterclockwise seen from outside). About a closed mesh it is the whole number of times the surface wraps the point: 0 outside, 1 inside, 2 where two solids of one mesh overlap, whether they share vertices - or cut through one another. About an open mesh it is a fraction that falls off toward the hole: the closed - mesh's number less the missing faces' share of the sphere about the point, so across a flat hole it passes - through 0.5 on the hole's own plane. The plain sum: a point costs every triangle. The corners' offsets from the - point are taken in double precision and the angles in single (2.4 times the pace): the number is good to 1e-5 a - millimetre off a face and to 1e-2 at 1e-7 off it, and nearer than that its side of the face is not held.""" + or cut through one another. About an open mesh it is a fraction that falls off toward the hole (the closed + mesh's number less the missing faces' share of the sphere about the point), and about a mesh wound inside out + it is the negative: neither has an inside to read, and Signed refuses both. The plain sum: a point costs every + triangle. The corners' offsets from the point are taken in double precision and the angles in single (2.4 times + the pace): the number is good to 1e-5 a millimetre off a face and to 1e-2 at 1e-7 off it, and nearer than that + its side of the face is not held.""" v, t, pts = np.asarray(vertices, dtype=float).reshape(-1, 3), np.asarray(triangles, dtype=int).reshape(-1, 3), np.asarray(points, dtype=float).reshape(-1, 3) A, B, C = (np.ascontiguousarray(v[t[:, k]].T) for k in range(3)) # each (3, F): a corner of every triangle out, step = np.zeros(len(pts)), max(1, 32768 // max(len(t), 1)) # a block of pairs that stays in cache: 3.1 times the pace of 400,000 @@ -771,17 +774,61 @@ def winding(vertices, triangles, points): return out / (2.0 * math.pi) +def inside(vertices, triangles, points): + """Whether each of `points` is inside the triangle soup: its winding number is 0.5 or more. About the closed, + outward wound solids `solids` passes the number is whole and any bound over 0 and up to 1 reads the same; 0.5 + is the bound because it is the middle, the farthest from both whole numbers the single-precision sum rounds + about.""" + return winding(vertices, triangles, points) >= 0.5 + + +def solids(part, vertices, faces): + """The solid each face of a part belongs to (faces joined across an edge are one solid), or a RamError where + the part has no inside to sign: a solid with an edge no face runs the other way (a boundary edge, or two faces + wound against each other across it) is open, and a closed solid of negative volume is wound inside out. + Nothing is repaired. A cavity cut as its own inward shell is such a solid and is refused with the rest.""" + v = np.asarray(vertices, dtype=float).reshape(-1, 3) + owner, edges = list(range(len(faces))), {} + + def root(k): + while owner[k] != k: + owner[k] = k = owner[owner[k]] + return k + + for k, face in enumerate(faces): + for i, j in zip(face, tuple(face[1:]) + tuple(face[:1])): + there = edges.setdefault((min(i, j), max(i, j)), [k, 0]) + there[1] += 1 if i < j else -1 + owner[root(k)] = root(there[0]) + of = np.array([root(k) for k in range(len(faces))], dtype=int) + names = {r: n for n, r in enumerate(dict.fromkeys(of.tolist()))} # solids numbered in the order of their first faces + unmatched = {} + for first, balance in edges.values(): + if balance: + unmatched[names[of[first]]] = unmatched.get(names[of[first]], 0) + 1 + for n, count in sorted(unmatched.items()): + raise RamError("mesh", "signed", f"part {part!r} is open: solid {n} of {len(names)} has {count} edge{'s' if count > 1 else ''} no face runs the other way") + of = np.array([names[r] for r in of.tolist()], dtype=int) + fan = np.array([(k, face[0], face[n], face[n + 1]) for k, face in enumerate(faces) for n in range(1, len(face) - 1)], dtype=int).reshape(-1, 4) + volume = np.bincount(of[fan[:, 0]], (v[fan[:, 1]] * np.cross(v[fan[:, 2]], v[fan[:, 3]])).sum(axis=1) / 6.0, len(names)) + for n in np.flatnonzero(volume < 0.0): + raise RamError("mesh", "signed", f"part {part!r} is wound inside out: solid {n} of {len(names)} ({int((of == n).sum())} faces from face {int(np.flatnonzero(of == n)[0])}) has volume {volume[n]:.3g}") + return of + + class Signed: - """The distance oracle over meshes: distance(part, points) is the nearest face's distance, negative where the - point is inside the part (its depth below the nearest face), capped at `cap` outside only. shells: part -> - [(vertices (N, 3), faces)], in the rest frame of the part's body, faces wound counterclockwise seen from - outside. Inside is where the winding number of all the part's faces (winding; a face of more than three corners - as a fan) is 0.5 or more: solids that overlap, in one mesh or several, welded or not, read inside wherever any - is. A mesh wound inside out reads outside everywhere. An open mesh is read as its faces wind: no point is - refused, and a point inside by a flat hole reads inside up to the hole's plane, where the sign turns with no - face there, so the reading steps by twice the distance to the hole's rim. The depth is to the nearest face of - any of the part's meshes, one buried in another included. An unknown part raises. Needs Blender's mathutils - (BVHTree) for the nearest face.""" + """The distance oracle over meshes: distance(part, points) is the distance to the part's surface, negative + where the point is inside the part (its depth), capped at `cap` outside only. shells: part -> [(vertices + (N, 3), faces)], in the rest frame of the part's body. Every solid of a part (`solids`) is closed and wound + counterclockwise seen from outside: a part with an open or an inside-out solid is refused when the oracle is + made, by a RamError that names the part, the solid and the edge count or the volume. Inside is where `inside` + says, by the winding number of all the part's faces (a face of more than three corners as a fan): solids that + overlap, in one mesh or several, welded or not, read inside wherever any is. The depth is to the nearest + exposed face: one whose centroid, set 1e-6 of the part's extent off the face along its normal, is not inside + the part. A face buried in another solid is not the part's surface and is left out. A face that crosses + another solid is taken whole by where its centroid is: left out, the depth by it reads greater than it is; + kept, a point by its buried stretch reads shallower than the part's surface is. Outside, the distance is to + the nearest face of all. An unknown part raises. Needs Blender's mathutils (BVHTree) for the nearest face.""" def __init__(self, shells, cap=None): from mathutils import Vector @@ -795,16 +842,25 @@ class Signed: faces += [tuple(at + int(i) for i in face) for face in f] at += len(v) verts = np.concatenate(verts) + solids(part, verts, faces) fan = np.array([(face[0], face[k], face[k + 1]) for face in faces for k in range(1, len(face) - 1)], dtype=int) - self.parts[part] = (BVHTree.FromPolygons(verts.tolist(), faces, epsilon=0.0), verts, fan) + normal = np.zeros((len(faces), 3)) + np.add.at(normal, np.repeat(np.arange(len(faces)), [len(face) - 2 for face in faces]), np.cross(verts[fan[:, 1]] - verts[fan[:, 0]], verts[fan[:, 2]] - verts[fan[:, 0]])) + size = np.linalg.norm(normal, axis=1) + flat = np.flatnonzero(size > 0.0) # a face of no area has no side to be exposed on + off = np.array([verts[list(faces[k])].mean(axis=0) for k in flat]) + 1e-6 * np.linalg.norm(np.ptp(verts, axis=0)) * normal[flat] / size[flat, None] + exposed = [faces[k] for k in flat[~inside(verts, fan, off)]] + if not exposed: + raise RamError("mesh", "signed", f"part {part!r} has no exposed face") + self.parts[part] = (BVHTree.FromPolygons(verts.tolist(), faces, epsilon=0.0), BVHTree.FromPolygons(verts.tolist(), exposed, epsilon=0.0), verts, fan) def __call__(self, part, pts): pts = np.asarray(pts, dtype=float).reshape(-1, 3) self.asked += len(pts) - tree, verts, fan = self.parts[part] + tree, surface, verts, fan = self.parts[part] out = np.full(len(pts), math.inf if self.cap is None else self.cap) - for i in np.flatnonzero(winding(verts, fan, pts) >= 0.5): - out[i] = -tree.find_nearest(self.vector(pts[i]))[3] + for i in np.flatnonzero(inside(verts, fan, pts)): + out[i] = -surface.find_nearest(self.vector(pts[i]))[3] for i in np.flatnonzero(out >= 0): hit = tree.find_nearest(self.vector(pts[i]), self.cap) if self.cap else tree.find_nearest(self.vector(pts[i])) if hit[0] is not None: diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py index 2074ff8..3cb02f5 100644 --- a/surfaces/blender/tests/test_ram.py +++ b/surfaces/blender/tests/test_ram.py @@ -1351,6 +1351,63 @@ class Refusals(unittest.TestCase): for gone in (top, top[:1]): self.assertEqual(int((R.winding(verts, np.delete(tris, gone, axis=0), inner) < 0.5).sum()), 0) + def test_inside_is_half_a_winding_or_more(self): + # the bound, on a mesh only a test may read: a unit cube less its top winds 0.527 on the hole's axis 0.03 + # under the hole's plane and 0.473 as far over it (1 less, and plainly, asin(0.25 / 0.2509) / pi). A bound + # of 0.45 reads the point over the hole inside and one of 0.55 the point under it outside: 0.473 and 0.527 + # stand at the geometric means of 0.5 and those two, 1.06 from each, all the room there is between them + verts, tris = block((0, 0, 0), (1, 1, 1)) + opened = np.delete(tris, [k for k, t in enumerate(tris) if (verts[t][:, 2] == 1.0).all()], axis=0) + pts = np.array([(0.5, 0.5, 0.97), (0.5, 0.5, 1.03)]) + w = R.winding(verts, opened, pts) + self.assertLess(float(np.abs(w - (0.5270, 0.4730)).max()), 1e-4) + self.assertEqual(R.inside(verts, opened, pts).tolist(), [True, False]) + # about closed solids the number is whole, so there the bound reads as any over 0 and up to 1 would + cloud = np.random.default_rng(5).uniform(-0.2, 1.2, (500, 3)) + self.assertEqual(R.inside(verts, tris, cloud).tolist(), ((cloud > 0) & (cloud < 1)).all(axis=1).tolist()) + + def test_solids_are_the_closed_pieces_of_a_part(self): + # the jointlib rocker plates are four closed bars, each wound outward: none is refused. Two boxes that cut + # through one another are two solids, sharing a corner's index or not + fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_plates.json").read_text(encoding="utf-8")) + self.assertEqual(np.bincount(R.solids("plates", fixture["verts"], fixture["faces"])).tolist(), [84, 84, 84, 84]) + for weld in (False, True): + verts, tris = joined(block((0, 0, 0), (1, 1, 1)), block((0, 0, 0), (2, 0.5, 0.5)), weld) + self.assertEqual(R.solids("boxes", verts, tris).tolist(), [0] * 12 + [1] * 12) + self.assertEqual(R.solids("stairs", *staircase()).tolist(), [0] * 28) + + def test_an_open_part_is_refused_by_its_edge_count(self): + # a cube less a triangle has 3 edges no face runs back along, less its top 4, less two adjacent faces 6 + # (the edge between them is gone with both); one triangle turned over leaves its 3 edges run twice one way + verts, tris = block((0, 0, 0), (1, 1, 1)) + top = [k for k, t in enumerate(tris) if (verts[t][:, 2] == 1.0).all()] + side = [k for k, t in enumerate(tris) if (verts[t][:, 1] == 1.0).all()] + turned_over = tris.copy() + turned_over[0] = tris[0][::-1] + less = lambda gone: (verts, np.delete(tris, gone, axis=0)) + for name, mesh, count, solid in (("a triangle off", less(top[:1]), 3, "solid 0 of 1"), ("the top off", less(top), 4, "solid 0 of 1"), ("two faces off", less(top + side), 6, "solid 0 of 1"), + ("a triangle turned over", (verts, turned_over), 3, "solid 0 of 1"), ("the second of two open", joined(block((2, 0, 0), (3, 1, 1)), less(top), False), 4, "solid 1 of 2")): + with self.assertRaises(R.RamError, msg=name) as caught: + R.solids("cube", *mesh) + self.assertEqual(caught.exception.gate, "signed", name) + self.assertIn(f"part 'cube' is open: {solid} has {count} edges no face runs the other way", str(caught.exception), name) + + def test_an_inside_out_solid_is_refused_by_name(self): + # a cube with every face turned over, or mirrored with its winding kept, has volume -1. A cube with a bar + # of half its volume turned over beside it has a positive volume in all: the bar is refused as its solid + verts, tris = block((0, 0, 0), (1, 1, 1)) + for name, v, t in (("turned over", verts, tris[:, ::-1]), ("mirrored", verts * (-1, 1, 1), tris)): + with self.assertRaises(R.RamError, msg=name) as caught: + R.solids("cube", v, t) + self.assertIn("part 'cube' is wound inside out: solid 0 of 1 (12 faces from face 0) has volume -1", str(caught.exception), name) + bar_v, bar_t = block((2, 0, 0), (3, 1, 0.5)) + mixed = joined((verts, tris), (bar_v, bar_t[:, ::-1]), False) + self.assertAlmostEqual(sum(float(mixed[0][a] @ np.cross(mixed[0][b], mixed[0][c])) / 6.0 for a, b, c in mixed[1]), 0.5, places=12) + with self.assertRaises(R.RamError) as caught: + R.solids("pair", *mixed) + self.assertIn("part 'pair' is wound inside out: solid 1 of 2 (12 faces from face 12) has volume -0.5", str(caught.exception)) + self.assertEqual(R.solids("pair", *joined((bar_v, bar_t), (verts, tris), False)).tolist(), [0] * 12 + [1] * 12) + def test_no_blender(self): source = (SURFACE / "brokkr_kitbash" / "ram.py").read_text(encoding="utf-8") for word in ("bpy", "np.gradient"): From 18adf73a27836ad4e4c6cfd2f5903659bebaa2f8 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 01:35:12 +0100 Subject: [PATCH 165/223] live ram_knee: open and inside-out parts are refused by reason; a buried box does not hide the cube's depth; docs The open cube's reading is cut for five refusals. The search's seconds are a reading, stated in docs/kitbash.md as a quiet-machine figure beside the loaded ones. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 36 +++++++++++---- surfaces/blender/tests/live/ram_knee.py | 46 +++++++++++++++---- .../blender/tests/live/ram_knee.result.json | 43 ++++++++++++++--- 3 files changed, 101 insertions(+), 24 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 8eb7ab9..1f974ed 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1036,14 +1036,28 @@ about the point, over 4 pi: about a closed mesh the whole number of times the su inside, 2 where two solids overlap. A point is inside the part at 0.5 or more. The joint library's plates are one mesh of four bars, a side's two overlapping about the pivot (`tests/fixtures/ram_plates.json`, with 29 points inside them, 13 inside two bars): each reads inside, as does the overlap of two boxes welded at a corner and a -staircase prism a line crosses six times. Faces are wound counterclockwise seen from outside; a mesh wound inside -out reads outside everywhere. An open mesh is answered, not refused: the number is the closed mesh's less the -missing faces' share of the sphere about the point, so a cube with a face open reads inside up to the hole's plane -(0.5009 at 0.001 under the centre of a unit face) and the sign turns on that plane with no face there. The gate's -proof between samples assumes a distance changes by no more than the way between two points, which holds across a -face and not across a hole: a part with a hole the axis may reach is closed before it is given. The depth is to the -nearest face of any of the part's meshes, one buried inside another included, so inside two overlapping solids a -point may read shallower than its depth below their union. +staircase prism a line crosses six times. + +`Signed` checks what the winding number needs before it answers, and refuses a part by its reason when the oracle is +made (`ram.solids`, a `RamError` at gate `signed`). A part's faces fall into solids, the faces joined across an +edge. Every solid is closed: each edge one face runs is run the other way by another, and a solid with an edge +that is not (a boundary edge, or two faces wound against each other) is refused with the count of such edges. Every +solid is wound counterclockwise seen from outside: one of negative volume is refused with its number, its first +face and its volume, a turned-over bar beside a whole cube included, whose volume in all is positive. Nothing is +repaired or guessed. The shipped plates are four closed solids of 84 faces each, and the 12 parts of both R-3 knees +pass. What it gives up: a part exported open is capped before it is given, a part mirrored by a negative scale has +its faces turned back, and a cavity cut as its own inward shell is refused with the inside-out solids. + +With every solid closed the number is whole, so `ram.inside` reads the same at any bound over 0 and up to 1; 0.5 is +pinned in the unit suite on a test-only open cube, where the number is 0.527 under the hole and 0.473 over it. + +Outside, the distance is to the nearest face of all. Inside, the depth is to the nearest exposed face: one whose +centroid, set 1e-6 of the part's extent off the face along its normal, is not inside the part. A face buried in +another of the part's solids is left out, so a pin sunk 0.056 into a slab with a thin sheet buried along it reads +0.056 and is refused by a zone of depth 0.01. A face that crosses another solid is kept or left whole by where its +centroid is, not split: left out, the depth by it reads greater than it is, which the gate takes as a refusal; +kept, a point by its buried stretch reads shallower than the union's surface is (a boss through a wall: 0.500 for +0.502 and 0.539 for 0.583 in the live readings). | drive | reading | | --- | --- | @@ -1061,7 +1075,11 @@ zones (the own plates, stated with no slack, to the floor); the samples alone to (20,000) is 30 to 40 s. On the meshes the bell crank's 60 pairs at 49 steps took 0.80 to 1.00 s capped (two runs), the winding number as the plain sum over a part's 124 to 408 triangles in numpy (single precision over double offsets, blocks of 32,768 pairs) and the depth a Python loop of BVH queries, and the 13,824-candidate search with its 22 -worlds 34.5 and 38.5 s (two runs). With the angles in double precision the search took 47.7 to 47.9 s (three runs). +worlds 34.5 and 38.5 s (two runs) on a quiet machine. With the angles in double precision the search took 47.7 to +47.9 s (three runs). The live result reports the search's seconds as a reading and no check holds it: beside other +agents' Blenders at full load the same search took 61 to 94 s. With the refusals and +the exposed faces found as each of its 22 worlds is made it took 66.8 s, run after 59.3 s for the oracle before +them under that load (one pair); finding the solids of a 336-face part takes 1.6 ms. ## The actions diff --git a/surfaces/blender/tests/live/ram_knee.py b/surfaces/blender/tests/live/ram_knee.py index 272fe15..d503e2c 100644 --- a/surfaces/blender/tests/live/ram_knee.py +++ b/surfaces/blender/tests/live/ram_knee.py @@ -12,7 +12,8 @@ without them). is an absolute path; writes .result.json and .r3_ The oracle is ram.Signed: a point is inside a part where the winding number of the part's faces about it is 0.5 or more. tests/fixtures/ram_plates.json holds the rocker plates as Imagination's jointlib builds them, four closed bars joined into one mesh, a side's two overlapping, and 29 points inside them: none reads outside. Nor does a point where -two welded boxes overlap, or inside a cube with a face left open. +two welded boxes overlap. A part that is open or wound inside out is refused when the oracle is made, and the depth +is to the part's surface: a face buried in another of the part's solids is not read. A clearance verdict is a sign, the gate's own. FLAT follows lodur:ruling:deterministic-bound-margin. The checks run inside one try: an uncaught error is a failed check that names its section, and the result file is always written. @@ -326,7 +327,7 @@ try: # outside); the fixture's 29 points are 0.001 or more inside a bar, 13 of them inside two. A count of points fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_plates.json").read_text(encoding="utf-8")) plates = Signed({"plates": [(np.array(fixture["verts"]), fixture["faces"])]})("plates", np.array(fixture["inside"])) - # two boxes cut through one another and welded at the corner they share; and a cube with its top left open + # two boxes cut through one another and welded at the corner they share def wound(lo, hi): verts = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])], float) return verts, [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)] @@ -336,14 +337,43 @@ try: truth = ((cloud >= 0) & (cloud <= 1)).all(axis=1) | ((cloud >= 0) & (cloud <= (2, 0.5, 0.5))).all(axis=1) both = ((cloud >= 0) & (cloud <= (1, 0.5, 0.5))).all(axis=1) got = Signed({"welded": [welded]})("welded", cloud) < 0 - inner = rng.uniform(0.001, 0.999, (4000, 3)) - opened = Signed({"open": [(v1, [face for face in f1 if face != (1, 5, 7, 3)])]})("open", inner) RES["readings"]["jointlib plates: inside points read outside, of %d" % len(plates)] = int((plates >= 0).sum()) RES["readings"]["welded boxes: points missigned, of %d (%d in the overlap)" % (len(cloud), int(both.sum()))] = int((got != truth).sum()) - RES["readings"]["open cube: inside points read outside, of %d" % len(inner)] = int((opened >= 0).sum()) - check("inside-reads-inside: no point inside the jointlib rocker plates' bars, in two welded boxes' overlap or in a cube with a face open reads outside, and none outside the boxes reads inside", - len(plates) == 29 and int((plates >= 0).sum()) == 0 and int(both.sum()) > 50 and int((got != truth).sum()) == 0 and int((opened >= 0).sum()) == 0, - [int((plates >= 0).sum()), int(both.sum()), int((got != truth).sum()), int((opened >= 0).sum())]) + check("inside-reads-inside: no point inside the jointlib rocker plates' bars or in two welded boxes' overlap reads outside, and none outside the boxes reads inside", + len(plates) == 29 and int((plates >= 0).sum()) == 0 and int(both.sum()) > 50 and int((got != truth).sum()) == 0, + [int((plates >= 0).sum()), int(both.sum()), int((got != truth).sum())]) + + # a part with no inside to sign is refused when the oracle is made, by its reason: a cube with its top off, or + # two adjacent faces off, is open; a cube turned over, mirrored, or a turned-over bar beside a whole cube (a + # positive volume in all) is wound inside out. Every part of both knees made here passed the same two checks + turned = [face[::-1] for face in f1] + said = {} + for name, made in (("top off", [(v1, [face for face in f1 if face != (1, 5, 7, 3)])]), ("two faces off", [(v1, [face for face in f1 if face not in ((1, 5, 7, 3), (2, 3, 7, 6))])]), + ("turned over", [(v1, turned)]), ("mirrored", [(v1 * (-1, 1, 1), f1)]), ("a turned-over bar beside a cube", [(v1, f1), (v2 + (0, 2, 0), [face[::-1] for face in f2])])): + try: + Signed({"cube": made}) + said[name] = None + except R.RamError as error: + said[name] = str(error) + RES["refusals"] = said + want = {"top off": "is open: solid 0 of 1 has 4 edges", "two faces off": "is open: solid 0 of 1 has 6 edges", "turned over": "is wound inside out: solid 0 of 1 (6 faces from face 0) has volume -1", + "mirrored": "is wound inside out: solid 0 of 1 (6 faces from face 0) has volume -1", "a turned-over bar beside a cube": "is wound inside out: solid 1 of 2 (6 faces from face 6) has volume -0.5"} + check("no-inside-is-refused: an open part is refused by its solid and edge count, an inside-out one by its solid and volume, a turned-over bar beside a whole cube included", + all(said[name] is not None and "part 'cube' " + text in said[name] for name, text in want.items()), said) + + # the depth is to the part's surface, not to a face buried in another of its solids: a cube of half side 1 with a + # box of side 0.2 buried about (0.5, 0.5, 0.5) reads its own depth by the box and at its centre (the nearest face + # of all is the buried box's: 0.05 and 0.693). A boss through a wall is read, not checked: its side faces cross the + # wall and are kept whole by their centroids, so in the wall by the boss the depth reads to their buried stretch + cube, small = wound((-1, -1, -1), (1, 1, 1)), wound((0.4, 0.4, 0.4), (0.6, 0.6, 0.6)) + boss = wound((0.9, -0.5, -0.5), (1.5, 0.5, 0.5)) + at = np.array([(0.5, 0.5, 0.55), (0.0, 0.0, 0.0), (0.5, 0.5, 0.95), (0.5, 0.5, 0.5), (1.2, 0.0, 0.0)]) + alone, buried, bossed = Signed({"p": [cube]})("p", at), Signed({"p": [cube, small]})("p", at), Signed({"p": [cube, boss]})("p", np.array([(0.95, 0.0, 0.0), (0.7, 0.0, 0.0), (1.2, 0.0, 0.0), (1.6, 0.0, 0.0)])) + RES["readings"]["buried box: depth by it, at the cube's centre, under the cube's face, at the box's centre; outside"] = buried.tolist() + RES["readings"]["boss through a wall (faces that cross a solid are kept or left whole): in both (the surface is 0.502 off), in the wall (0.583), in the boss (0.2), off it (0.1)"] = bossed.tolist() + check("depth-is-to-the-surface: a face buried in another solid of the part is not read: by a buried box the cube reads as the cube alone", + float(np.abs(buried - (-0.45, -1.0, -0.05, -0.5, 0.2)).max()) < FLAT and float(np.abs(buried - alone).max()) < FLAT, + [buried.tolist(), alone.tolist()]) SECTION[0] = "seat" seat = np.concatenate([v for v, _ in shells["parent.seat"]]) diff --git a/surfaces/blender/tests/live/ram_knee.result.json b/surfaces/blender/tests/live/ram_knee.result.json index 34bb0b1..6935ca7 100644 --- a/surfaces/blender/tests/live/ram_knee.result.json +++ b/surfaces/blender/tests/live/ram_knee.result.json @@ -17,7 +17,17 @@ "detail": null }, { - "name": "inside-reads-inside: no point inside the jointlib rocker plates' bars, in two welded boxes' overlap or in a cube with a face open reads outside, and none outside the boxes reads inside", + "name": "inside-reads-inside: no point inside the jointlib rocker plates' bars or in two welded boxes' overlap reads outside, and none outside the boxes reads inside", + "ok": true, + "detail": null + }, + { + "name": "no-inside-is-refused: an open part is refused by its solid and edge count, an inside-out one by its solid and volume, a turned-over bar beside a whole cube included", + "ok": true, + "detail": null + }, + { + "name": "depth-is-to-the-surface: a face buried in another solid of the part is not read: by a buried box the cube reads as the cube alone", "ok": true, "detail": null }, @@ -108,22 +118,41 @@ "bell crank: least margin of a zoned pair, 251 steps uncapped": 0.000118, "bell crank: pairs": 60, "bell crank: pairs refused with nothing let": 19, - "bell crank: seconds, 49 steps capped": 0.8, + "bell crank: seconds, 49 steps capped": 1.34, "bell crank: zoned pairs": 20, + "boss through a wall (faces that cross a solid are kept or left whole): in both (the surface is 0.502 off), in the wall (0.583), in the boss (0.2), off it (0.1)": [ + -0.5, + -0.5385164618492126, + -0.2999999523162842, + 0.10000002384185791 + ], + "buried box: depth by it, at the cube's centre, under the cube's face, at the box's centre; outside": [ + -0.44999998807907104, + -1.0, + -0.050000011920928955, + -0.5, + 0.20000004768371582 + ], "four bar: barrel inside the shin's clearance": -0.122, "jointlib plates: inside points read outside, of 29": 0, "moved x: both": -0.0543, "moved x: the coupler at x 0.25, inside the horn's 0.23..0.31": -0.02, "moved x: the rocker at x 0.25, inside the bracket's 0.13..0.35": -0.0543, - "open cube: inside points read outside, of 4000": 0, "search: candidates": 13824, "search: pass the gates before clearance": 78, "search: refused on their own parts": 21, - "search: seconds": 34.5, + "search: seconds": 66.8, "search: worlds built": 22, "the base clevis's foot inside the thigh": -0.01, "welded boxes: points missigned, of 6000 (91 in the overlap)": 0 }, + "refusals": { + "top off": "mesh ram: signed: part 'cube' is open: solid 0 of 1 has 4 edges no face runs the other way", + "two faces off": "mesh ram: signed: part 'cube' is open: solid 0 of 1 has 6 edges no face runs the other way", + "turned over": "mesh ram: signed: part 'cube' is wound inside out: solid 0 of 1 (6 faces from face 0) has volume -1", + "mirrored": "mesh ram: signed: part 'cube' is wound inside out: solid 0 of 1 (6 faces from face 0) has volume -1", + "a turned-over bar beside a cube": "mesh ram: signed: part 'cube' is wound inside out: solid 1 of 2 (6 faces from face 6) has volume -0.5" + }, "zones": { "barrel[0] | parent.seat": { "stated": [ @@ -496,9 +525,9 @@ } }, "renders": [ - "F:/aeth-wt/fable-ramlows/scratch/out/h3f.r3_0.png", - "F:/aeth-wt/fable-ramlows/scratch/out/h3f.r3_62p5.png", - "F:/aeth-wt/fable-ramlows/scratch/out/h3f.r3_125.png" + "F:/aeth-wt/fable-ramlows/scratch/out/live_h4b.r3_0.png", + "F:/aeth-wt/fable-ramlows/scratch/out/live_h4b.r3_62p5.png", + "F:/aeth-wt/fable-ramlows/scratch/out/live_h4b.r3_125.png" ], "ok": true } \ No newline at end of file From d80b16402621e95dafe4be7181556284fe9d2795 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 02:38:12 +0100 Subject: [PATCH 166/223] brokkr_kitbash.shell: the sheet takes a free cage (verts, faces of 3 or 4 sides, creases, corners, declared poles, mirror seam) beside the loft; core.sheet compiles both to one Sheet; report gains cageVerts, triangles, poles, closed Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 30 +-- .../brokkr_kitbash/brokkr_actions.json | 6 +- surfaces/blender/brokkr_kitbash/core.py | 206 +++++++++++++++++- surfaces/blender/tests/test_kitbash.py | 124 ++++++++++- 4 files changed, 340 insertions(+), 26 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 45e6807..ac8e9cf 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -44,7 +44,7 @@ a cutter. The ribs object is a bake of the cage at that call, and kit_ribs on it nothing reads it to decide geometry, and ribs is its one writer. The one Manifold Boolean in the package is the hole cut inside ribs, on webs it built as closed shells that do not cross; a target's live Booleans stay Exact. -shell makes the cage that cut and ribs work on: a loft of rings with crease runs (core.sheet) under a Kit Subsurf +shell makes the cage that cut and ribs work on: a loft of rings or a free cage, with creases (core.sheet), under a Kit Subsurf and a Kit Solidify. kit_shell on the object is the request, and it owns the cage mesh as kit_params owns a part's: shell is the one writer of the mesh, its crease attributes and those two modifiers, and calling it again on the object rewrites the mesh in place, leaving the object, its cutters, ribs, Booleans and material slots. shell @@ -106,7 +106,7 @@ RIBS_LIMIT = 64 # planes in one ribs LONGERONS_LIMIT = 16 # longerons in one ribs SHELL = "kit_shell" # on a shell: the request its cage is derived from, as JSON; its presence admits a rebuild, and nothing reads it to decide geometry SUBSURF, SOLIDIFY = "Kit Subsurf", "Kit Solidify" # a shell's own modifiers, in that order, before any of its Booleans and the Kit Bevel -SHELL_FACES_LIMIT = 262144 # faces of a shell's subdivided surface: cage quads times 4 to the levels +SHELL_FACES_LIMIT = 262144 # faces of a shell's subdivided surface: core.subdivided_faces HOSE = "kit_hose" # on a hose: the request it was routed from, as JSON; its presence admits a rebuild, and another hose reads its two ends to know that it crosses the same pin HOSE_CLAMPS = 8 # clamps in one hose: each is one more leg to search HOSE_VOXELS = 2 ** 19 # voxels of one leg's search box: 1.8 s of capped nearest-face queries at 3.4 us each @@ -1585,13 +1585,13 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): class BROKKR_KITBASH_OT_shell(PolishOperator): - """Make a faceted, hollow armor shell from a loft of rings: a quad cage with crease runs and a creased rim, under - a Subdivision and a Solidify; on an object that is already a shell, rebuild its cage in place under its cutters, + """Make a faceted, hollow armor shell from a cage, a loft of rings or a free cage of vertices and faces of 3 or 4 + sides, with creases and a creased rim, under a Subdivision and a Solidify; on an object that is already a shell, rebuild its cage in place under its cutters, ribs and Booleans""" bl_idname = "brokkr_kitbash.shell" bl_label = "Make A Shell" object_name: bpy.props.StringProperty(name="Object", description="The shell's name: a new object, or a shell to rebuild") - sheet: bpy.props.StringProperty(name="Sheet", description="A JSON object {rings, closed, mirror, creases, rim, flip}: rings of [x, y, z] points in the shell's own frame") + sheet: bpy.props.StringProperty(name="Sheet", description="A JSON object, a loft {rings, closed, mirror, creases, rim, flip} or a free cage {verts, faces, creases, corners, poles, mirror, rim, flip}, in the shell's own frame") thickness: bpy.props.FloatProperty(name="Thickness", default=0.05, min=0.0009, max=1.0, description="The wall's thickness") offset: bpy.props.FloatProperty(name="Offset", default=-1.0, min=-1.0, max=1.0, description="-1: the wall grows inward from the designed surface; 1: outward") levels: bpy.props.IntProperty(name="Levels", default=3, min=1, max=4, description="Subdivision levels") @@ -1622,9 +1622,9 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): except ValueError as error: raise Refused(f"sheet is not JSON ({error}); nothing changed.") from None built = core.sheet(document) - cage_faces = len(built.counts) - if cage_faces * 4 ** self.levels > SHELL_FACES_LIMIT: - raise Refused(f"sheet: {cage_faces} cage quads at {self.levels} levels subdivide to {cage_faces * 4 ** self.levels} faces, over {SHELL_FACES_LIMIT}. " + subdivided = core.subdivided_faces(built, self.levels) + if subdivided > SHELL_FACES_LIMIT: + raise Refused(f"sheet: {len(built.counts)} cage faces at {self.levels} levels subdivide to {subdivided} faces, over {SHELL_FACES_LIMIT}. " "Use fewer levels or a sparser sheet; nothing changed.") rebuilt = obj is not None if rebuilt: @@ -1653,12 +1653,14 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): wall.thickness, wall.offset, wall.use_even_offset, wall.use_rim = self.thickness, self.offset, True, True sync_bevel(obj, self.bevel) obj[SHELL] = json.dumps({"sheet": document, "thickness": self.thickness, "offset": self.offset, "levels": self.levels, "bevel": self.bevel}) - corners = built.V[built.faces.reshape(-1, 4)] - facing = np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]).sum(axis=0) # twice the quads' vector areas, summed - cancels = np.linalg.norm(facing) <= 1e-9 * np.linalg.norm(np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]), axis=1).sum() - return {"object": obj.name, "rebuilt": rebuilt, "rings": built.rings, "points": built.points, "cageFaces": cage_faces, "creases": len(built.creases), - "folded": self.folded_faces(context, obj, cage_faces * 4 ** self.levels) if self.count_folds else None, - "corners": len(built.corners), "subdividedFaces": cage_faces * 4 ** self.levels, + starts = np.cumsum(built.counts) - built.counts + first, second, third, last = (built.V[built.faces[starts + k]] for k in (0, 1, 2, built.counts - 1)) + areas = np.where((built.counts == 3)[:, None], np.cross(second - first, third - first), np.cross(third - first, last - second)) # twice each face's vector area + facing = areas.sum(axis=0) + cancels = np.linalg.norm(facing) <= 1e-9 * np.linalg.norm(areas, axis=1).sum() + return {"object": obj.name, "rebuilt": rebuilt, "rings": built.rings, "points": built.points, **core.cage_report(built), + "folded": self.folded_faces(context, obj, subdivided) if self.count_folds else None, + "subdividedFaces": subdivided, "facing": None if cancels else [round(float(v), 6) for v in facing / np.linalg.norm(facing)], "thickness": round(self.thickness, 6), "offset": round(self.offset, 6), "levels": self.levels, "children": sorted(child.name for child in obj.children)} diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index e0d6282..3114140 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -804,7 +804,7 @@ }, { "name": "brokkr_kitbash.shell", - "doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. A thickness the cage cannot hold is not refused: the wall folds over itself beside a tight crease or rim corner, and a cut there is unsound. count_folds evaluates the wall alone (Kit Subsurf and Kit Solidify, no Boolean; 4 ms on a plate of 1600 subdivided faces) and counts the folded inner faces; nothing else in the report reads an evaluated mesh, and no figure of the cage bounds the fold. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings, points, cageFaces, creases, folded (null unless count_folds: then the number of the wall's inner faces that fold over, counted on the evaluated wall; 0 is a wall with no folded face, which an Exact Boolean can still fail on just short of a fold: read nonManifoldEdges after cutting), corners, subdividedFaces, facing, thickness, offset, levels and children.", + "doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object in one of two forms, a loft of rings or a free cage; exactly one of rings and verts. The loft: {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The free cage, for a form a few vertices and creases hold: {\"verts\": 4 to 256 [x, y, z]; \"faces\": each 3 or 4 vertex indices, counter-clockwise seen from outside; \"creases\": [[a, b, w]], an edge by its two vertices, weight 0 to 1; \"corners\": [[vertex, w]]; \"poles\": the vertex indices of irregular valence (not 4 off the boundary, not 2 or 3 on it); \"mirror\": every vertex is authored on one side of x = 0, one within 0.005 m of it is on the seam (snapped to x = 0 and shared), the others are reflected with their faces, creases, corners and poles (false); \"rim\" and \"flip\" as on the loft}. The pole gate: poles must equal the poles the faces make, or the sheet is refused naming each undeclared pole and each declared vertex that is none, with its valence. A free cage is also refused for a vertex in no face, a repeated index, a duplicate or collapsed face, an edge in three faces, two faces wound against each other, a crease on no edge, and a face or shared edge lying on the mirror plane. A triangle subdivides to three quads. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. A thickness the cage cannot hold is not refused: the wall folds over itself beside a tight crease or rim corner, and a cut there is unsound. count_folds evaluates the wall alone (Kit Subsurf and Kit Solidify, no Boolean; 4 ms on a plate of 1600 subdivided faces) and counts the folded inner faces; nothing else in the report reads an evaluated mesh, and no figure of the cage bounds the fold. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings and points (null on a free cage), cageVerts, cageFaces, triangles, creases, poles ({valence: how many vertices}, on the cage as built), closed (no boundary edge), folded (null unless count_folds: then the number of the wall's inner faces that fold over, counted on the evaluated wall; 0 is a wall with no folded face, which an Exact Boolean can still fail on just short of a fold: read nonManifoldEdges after cutting), corners, subdividedFaces, facing, thickness, offset, levels and children.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -823,7 +823,7 @@ "required": true, "minLength": 2, "maxLength": 32000, - "doc": "the shell description, a JSON object: rings, closed, mirror, creases, rim, flip" + "doc": "the shell description, a JSON object: a loft (rings, closed, mirror, creases, rim, flip) or a free cage (verts, faces, creases, corners, poles, mirror, rim, flip)" }, { "name": "thickness", @@ -847,7 +847,7 @@ "minimum": 1, "maximum": 4, "default": 3, - "doc": "subdivision levels; cage quads times 4 to the levels may not pass 262144" + "doc": "subdivision levels; the subdivided faces (a quad 4 to the levels, a triangle three quarters of that) may not pass 262144" }, { "name": "bevel", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 345a6ee..78ec6b6 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1024,19 +1024,24 @@ def spans(flags, lengths, closed: bool, bridge: float, clearance: float) -> list return kept -# --- shells: a loft of rings and its creases ------------------------------------------------------------------- +# --- shells: a cage (a loft of rings, or free) and its creases -------------------------------------------------- SHEET_LIMIT = 64 # rings in a sheet, and authored points in a ring SHEET_AREA = 1e-8 # square metres: a cage quad under this is a collapsed corner MIRROR_EPS = 1e-6 # metres a mirrored ring's point 0 may stand off x = 0, and any of its points behind it +SEAM_EPS = 5e-3 # metres from x = 0 within which a mirrored free cage's vertex is on the seam: snapped to 0 and shared +CAGE_VERTS = 256 # authored vertices in a free cage SHEET_KEYS = ("closed", "mirror", "creases", "rim", "flip") +CAGE_KEYS = ("creases", "corners", "poles", "mirror", "rim", "flip") class Sheet(NamedTuple): - """A shell's cage, in the shell's frame, metres: the five fields a mesh is written from (every face a quad, + """A shell's cage, in the shell's frame, metres: the five fields a mesh is written from (faces of 3 or 4 sides, shaded smooth, no sharp edge) and what a subdivision surface creases. creases is an (E, 2) array of vertex index - pairs with weights (E,) in (0, 1]; corners (K,) are vertex indices with corner_weights (K,) in (0, 1]. Vertex - i * points + j is ring i's point j, of rings rings of points points (2C - 1 when mirrored).""" + pairs with weights (E,) in (0, 1]; corners (K,) are vertex indices with corner_weights (K,) in (0, 1]. On a loft + vertex i * points + j is ring i's point j, of rings rings of points points (2C - 1 when mirrored); on a free + cage rings and points are None, the authored vertices keep their indices and a mirror's reflections follow them. + poles (P,) are the cage's vertices of irregular valence, as built; triangles is how many faces have 3 sides.""" V: np.ndarray faces: np.ndarray counts: np.ndarray @@ -1046,8 +1051,10 @@ class Sheet(NamedTuple): weights: np.ndarray corners: np.ndarray corner_weights: np.ndarray - rings: int - points: int + rings: int | None + points: int | None + poles: np.ndarray + triangles: int def _index(value: Any, where: str, least: int, most: int) -> int: @@ -1063,7 +1070,8 @@ def _weight(value: Any, where: str) -> float: def sheet(document: Any) -> Sheet: - """The cage of a shell description {rings, closed, mirror, creases, rim, flip}. + """The cage of a shell description, in one of two forms: a loft {rings, closed, mirror, creases, rim, flip}, or + a free cage {verts, faces, creases, corners, poles, mirror, rim, flip} (see _cage). Exactly one of rings, verts. rings: 2 to 64 rings of 2 to 64 [x, y, z] points, equal counts. Quad (i, j) is P[i][j], P[i][j+1], P[i+1][j+1], P[i+1][j], so its normal (P[i][j+1] - P[i][j]) x (P[i+1][j] - P[i][j]) faces out: seen from outside, a ring's @@ -1075,6 +1083,11 @@ def sheet(document: Any) -> Sheet: may be the count: the edge back to point 0); {column, from, to, weight} a column's edges from ring `from` to ring `to`; {point: [ring, point], weight} one vertex. rim is the weight of every boundary edge no run names. An edge has one weight: two runs that give it different ones are refused.""" + if isinstance(document, dict) and ("rings" in document) == ("verts" in document): + raise KitError("sheet states both rings and verts: a sheet is a loft of rings or a free cage of verts and faces, one of them" if "rings" in document else + "sheet lacks 'rings' and 'verts': a sheet is a loft of rings or a free cage of verts and faces") + if isinstance(document, dict) and "verts" in document: + return _cage(document) _keys(document, "sheet", ("rings",), SHEET_KEYS) flags = {} for key in ("closed", "mirror", "flip"): @@ -1178,7 +1191,184 @@ def sheet(document: Any) -> Sheet: pinned = sorted((key, weight) for key, (weight, _) in verts.items() if weight > 0) return Sheet(V=V.copy(), faces=quads.ravel().astype(np.int32), counts=np.full(len(quads), 4, dtype=np.int32), smooth=np.ones(len(quads), dtype=bool), sharp=NO_SHARP, creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64), - corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N) + corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N, + poles=np.zeros(0, dtype=np.int64), triangles=0) + + +def _cage_facts(vertices: int, faces, counts): + """What a cage's connectivity says: (edges, boundary, valences, poles). edges maps each (low, high) vertex pair + to how many faces use it; boundary lists the pairs one face uses; valences (vertices,) counts each vertex's + edges; poles are the vertices of irregular valence, ascending: not 4 off the boundary, not 2 or 3 on it.""" + edges: dict[tuple[int, int], int] = {} + at = 0 + for count in counts: + face = [int(v) for v in faces[at:at + count]] + at += count + for a, b in zip(face, face[1:] + face[:1]): + key = (min(a, b), max(a, b)) + edges[key] = edges.get(key, 0) + 1 + boundary = sorted(key for key, used in edges.items() if used == 1) + valences = np.zeros(vertices, dtype=np.int64) + for a, b in edges: + valences[a] += 1 + valences[b] += 1 + rim = np.zeros(vertices, dtype=bool) + rim[[v for key in boundary for v in key]] = True + poles = np.flatnonzero(np.where(rim, (valences != 2) & (valences != 3), valences != 4)) + return edges, boundary, valences, poles + + +def cage_report(built: Sheet) -> dict: + """A cage's counts for a report, either form: cageVerts, cageFaces, triangles, creases, corners, poles (valence + -> how many vertices, the irregular ones only) and closed (no boundary edge).""" + _, boundary, valences, poles = _cage_facts(len(built.V), built.faces, built.counts) + tally: dict[str, int] = {} + for valence in sorted(int(valences[v]) for v in poles): + tally[str(valence)] = tally.get(str(valence), 0) + 1 + return {"cageVerts": len(built.V), "cageFaces": len(built.counts), "triangles": built.triangles, "creases": len(built.creases), + "corners": len(built.corners), "poles": tally, "closed": not boundary} + + +def subdivided_faces(built: Sheet, levels: int) -> int: + """Faces of the cage after `levels` Catmull-Clark levels (1 or more): a quad gives 4^levels, a triangle three + quads at the first level and so 3 * 4^(levels - 1).""" + return (len(built.counts) - built.triangles) * 4 ** levels + built.triangles * 3 * 4 ** (levels - 1) + + +def _cage(document: Any) -> Sheet: + """The cage of a free description {verts, faces, creases, corners, poles, mirror, rim, flip}. + + verts: 4 to 256 [x, y, z]. faces: 3 or 4 vertex indices each, wound so the normal (counter-clockwise seen from + outside) faces out; flip reverses every face. creases: [a, b, weight], an edge by its two vertices; corners: + [vertex, weight]. rim is the weight of every boundary edge no crease names. mirror: every vertex is authored on + one side of x = 0; one within SEAM_EPS of it is on the seam, snapped to x = 0 and shared; the others are + reflected (vertex len(verts) + k is the k-th of them), each face gets a reversed twin, and creases, corners and + poles land on both halves. poles: the vertices of irregular valence on the cage as built (not 4 off the + boundary, not 2 or 3 on it), by authored index. The list is a gate, not a setting: it must equal what the + faces make, so a pole is never an accident.""" + _keys(document, "sheet", ("verts", "faces"), CAGE_KEYS) + flags = {} + for key in ("mirror", "flip"): + flags[key] = document.get(key, False) + if not isinstance(flags[key], bool): + raise KitError(f"sheet.{key} must be true or false, not {flags[key]!r}") + mirror, flip = flags["mirror"], flags["flip"] + rim = _weight(document.get("rim", 1.0), "sheet.rim") + verts, faces = document["verts"], document["faces"] + if not isinstance(verts, list) or not 4 <= len(verts) <= CAGE_VERTS: + raise KitError(f"sheet.verts must be 4 to {CAGE_VERTS} vertices, not {len(verts) if isinstance(verts, list) else verts!r}") + for i, point in enumerate(verts): + if not isinstance(point, list) or len(point) != 3 or not all(finite(v) for v in point): + raise KitError(f"sheet.verts[{i}] must be three finite numbers [x, y, z]") + A = len(verts) + if not isinstance(faces, list) or not faces: + raise KitError("sheet.faces must be an array of faces, each 3 or 4 vertex indices") + for f, face in enumerate(faces): + if not isinstance(face, list) or len(face) not in (3, 4): + raise KitError(f"sheet.faces[{f}] must be 3 or 4 vertex indices, not {len(face) if isinstance(face, list) else face!r}: a cage's faces are triangles and quads") + for k, v in enumerate(face): + _index(v, f"sheet.faces[{f}][{k}]", 0, A - 1) + if len(set(face)) != len(face): + raise KitError(f"sheet.faces[{f}] names vertex {next(v for v in face if face.count(v) > 1)} twice") + used = {v for face in faces for v in face} + if len(used) != A: + raise KitError(f"sheet.verts[{min(set(range(A)) - used)}] is in no face: every vertex of a cage is used") + V = np.array(verts, dtype=np.float64) + seam = np.zeros(A, dtype=bool) + if mirror: + if (V[:, 0] < -MIRROR_EPS).any() and (V[:, 0] > MIRROR_EPS).any(): + side = 1.0 if (V[:, 0] > MIRROR_EPS).sum() >= (V[:, 0] < -MIRROR_EPS).sum() else -1.0 + worst = int((V[:, 0] * side).argmin()) + raise KitError(f"sheet.verts[{worst}] has x = {V[worst, 0]:.6g}: a mirrored cage is authored on one side of x = 0, and the others stand on the {'+' if side > 0 else '-'}x side") + seam = np.abs(V[:, 0]) <= SEAM_EPS + V[seam, 0] = 0.0 + seen, directed = {}, {} + for f, face in enumerate(faces): + key = tuple(sorted(face)) + if key in seen: + raise KitError(f"sheet.faces[{f}] has the vertices of sheet.faces[{seen[key]}]: a duplicate face") + seen[key] = f + if mirror and all(seam[v] for v in face): + raise KitError(f"sheet.faces[{f}] lies on the mirror plane (every vertex within {SEAM_EPS:g} m of x = 0): its reflection is itself") + corners = V[face] + area = 0.5 * np.linalg.norm(np.cross(corners[1] - corners[0], corners[-1] - corners[0])) + if len(face) == 4: + area += 0.5 * np.linalg.norm(np.cross(corners[3] - corners[2], corners[1] - corners[2])) + if area < SHEET_AREA: + raise KitError(f"sheet.faces[{f}] has area {area:.3g} m2, under {SHEET_AREA:g}: a collapsed face. Move its vertices apart") + for a, b in zip(face, face[1:] + face[:1]): + directed.setdefault((a, b), []).append(f) + for (a, b), users in sorted(directed.items()): + both = users + directed.get((b, a), []) + if len(both) > 2 and a < b or len(users) > 2: + raise KitError(f"sheet.faces: the edge between vertices {min(a, b)} and {max(a, b)} is in {len(both)} faces ({', '.join(str(f) for f in sorted(both))}): a cage's edge is in at most two") + if len(users) == 2: + raise KitError(f"sheet.faces[{users[1]}] crosses the edge between vertices {a} and {b} the same way as sheet.faces[{users[0]}]: the two are wound against each other. Reverse one") + if mirror and seam[a] and seam[b] and len(both) == 2: + raise KitError(f"sheet.faces[{both[0]}] and sheet.faces[{both[1]}] share the edge between vertices {min(a, b)} and {max(a, b)}, which lies on the mirror plane: " + "with their reflections that edge is in four faces (a fin on the plane)") + twin = np.arange(A) + if mirror: + twin[~seam] = A + np.arange(int((~seam).sum())) + V = np.concatenate([V, V[~seam] * (-1.0, 1.0, 1.0)]) + built = [list(face) for face in faces] + [[int(twin[v]) for v in reversed(face)] for face in faces] + else: + built = [list(face) for face in faces] + if flip: + built = [face[::-1] for face in built] + counts = np.array([len(face) for face in built], dtype=np.int32) + flat = np.array([v for face in built for v in face], dtype=np.int32) + cage_edges, boundary, valences, poles = _cage_facts(len(V), flat, counts) + + declared = document.get("poles", []) + if not isinstance(declared, list): + raise KitError("sheet.poles must be an array of vertex indices") + for k, v in enumerate(declared): + _index(v, f"sheet.poles[{k}]", 0, A - 1) + if v in declared[:k]: + raise KitError(f"sheet.poles[{k}] names vertex {v} twice") + computed = [int(v) for v in poles if v < A] + where = lambda v: f"vertex {v} (valence {int(valences[v])}{', on the boundary' if any(v in key for key in boundary) else ''})" # noqa: E731 + undeclared, regular = [v for v in computed if v not in declared], [v for v in declared if v not in computed] + if undeclared: + raise KitError(f"sheet.poles lacks {', '.join(where(v) for v in undeclared)}: a pole is declared or the faces are changed. " + "A vertex is a pole when its valence is not 4 off the boundary, or not 2 or 3 on it") + if regular: + raise KitError(f"sheet.poles[{declared.index(regular[0])}] names {where(regular[0])}, which is no pole; the regular ones named: {', '.join(str(v) for v in regular)}") + + def state(table, key, weight, where, what): + if key in table and table[key][0] != weight: + raise KitError(f"{where} gives {what} weight {weight:g} that {table[key][1]} gives {table[key][0]:g}: {what} has one weight") + table.setdefault(key, (weight, where)) + + edges, pinned = {}, {} + for name, table, size in (("creases", edges, 3), ("corners", pinned, 2)): + runs = document.get(name, []) + if not isinstance(runs, list): + raise KitError(f"sheet.{name} must be an array") + for k, run in enumerate(runs): + where_run = f"sheet.{name}[{k}]" + if not isinstance(run, list) or len(run) != size: + raise KitError(f"{where_run} must be {'[a, b, weight]: an edge by its two vertices' if size == 3 else '[vertex, weight]'}") + ends = [_index(v, f"{where_run}[{i}]", 0, A - 1) for i, v in enumerate(run[:-1])] + weight = _weight(run[-1], f"{where_run}[{size - 1}]") + if size == 2: + for v in {ends[0], int(twin[ends[0]])}: + state(pinned, v, weight, where_run, "a point") + continue + key = (min(ends), max(ends)) + if key not in cage_edges: + raise KitError(f"{where_run}: vertices {ends[0]} and {ends[1]} share no face's edge: a crease lies on an edge of the cage") + for a, b in {key, tuple(sorted((int(twin[ends[0]]), int(twin[ends[1]]))))}: + state(edges, (a, b), weight, where_run, "an edge") + for key in boundary: + edges.setdefault(key, (rim, "sheet.rim")) + kept = sorted((key, weight) for key, (weight, _) in edges.items() if weight > 0) + held = sorted((key, weight) for key, (weight, _) in pinned.items() if weight > 0) + return Sheet(V=V, faces=flat, counts=counts, smooth=np.ones(len(counts), dtype=bool), sharp=NO_SHARP, + creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64), + corners=np.array([key for key, _ in held], dtype=np.int64), corner_weights=np.array([w for _, w in held], dtype=np.float64), + rings=None, points=None, poles=poles, triangles=int((counts == 3).sum())) # --- reports ------------------------------------------------------------------------------------------------- diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 82e4d10..caa2e05 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -2003,6 +2003,128 @@ ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbas "brokkr_kitbash.shell", "brokkr_kitbash.hose"] +class CageTests(unittest.TestCase): + """core.sheet's free form: a cage of vertices and faces of 3 or 4 sides. Exact arithmetic: each assertion is + the built value and names the mutant it kills.""" + + @staticmethod + def fan(quads: int, lift=0.2): + """`quads` quads round vertex 0, counter-clockwise seen from +z (their outside): 0 has valence `quads`.""" + ring = [[math.cos(k * math.pi / quads), math.sin(k * math.pi / quads), 0.0] for k in range(2 * quads)] + return [[0.0, 0.0, lift]] + ring, [[0, 2 * k + 1, 2 * k + 2, (2 * k + 2) % (2 * quads) + 1] for k in range(quads)] + + PYRAMID = ([[0.0, 0.0, 0.5], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [1.0, 0.0, -1.0], [0.0, 1.0, -1.0]], + [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [2, 1, 5, 6]]) # four triangles round an apex of valence 4, a quad hung under one edge + + def refused(self, pattern, **sheet): + with self.assertRaisesRegex(core.KitError, pattern): + core.sheet(sheet) + + def test_a_free_cage_stating_a_loft_is_the_loft(self): + """free-cage-grid-equals-loft. C1 (a second path that orders, winds or creases differently): the same Sheet, + array for array, open and closed.""" + for extra in ({"creases": [{"ring": 1, "from": 0, "to": 3, "weight": 0.5}, {"column": 2, "from": 0, "to": 2, "weight": 0.25}], "rim": 0.75}, + {"closed": True, "creases": [{"ring": 1, "from": 0, "to": 4, "weight": 1.0}]}, {"flip": True, "rim": 0.0}): + loft = core.sheet({"rings": SheetTests.rings(3, 4), **extra}) + runs = [[int(a), int(b), w] for (a, b), w in zip(loft.creases.tolist(), loft.weights.tolist())] + free = core.sheet({"verts": loft.V.tolist(), "faces": loft.faces.reshape(-1, 4).tolist(), "creases": runs, "rim": 0.0}) + for field in ("V", "faces", "counts", "smooth", "creases", "weights", "corners", "corner_weights", "poles"): + self.assertEqual(getattr(free, field).tolist(), getattr(loft, field).tolist(), (field, extra)) + self.assertEqual((free.rings, free.points, free.triangles, loft.triangles, len(loft.poles)), (None, None, 0, 0, 0)) + self.assertEqual(core.cage_report(free), core.cage_report(loft)) + plain = core.sheet({"rings": SheetTests.rings(3, 4)}) # rim defaults to 1 on the boundary edges of either form + free = core.sheet({"verts": plain.V.tolist(), "faces": plain.faces.reshape(-1, 4).tolist()}) + self.assertEqual((free.creases.tolist(), free.weights.tolist()), (plain.creases.tolist(), plain.weights.tolist())) + self.assertEqual(core.cage_report(free), {"cageVerts": 12, "cageFaces": 6, "triangles": 0, "creases": 10, "corners": 0, "poles": {}, "closed": False}) + + def test_a_mirrored_cage_shares_its_seam(self): + """free-cage-mirror. C2 (the seam duplicated: an open cage; the reflected faces not reversed): seam vertices + within SEAM_EPS are snapped and shared, the rest reflected, and creases, corners and poles land on both halves.""" + verts = [[0.0, 0.0, 0.0], [0.004, 0.0, 1.0], [0.5, 0.0, 0.0], [0.5, 0.0, 1.0], [1.0, 0.2, 0.0], [1.0, 0.2, 1.0]] + faces = [[0, 1, 3, 2], [2, 3, 5, 4]] # outside is +y + built = core.sheet({"verts": verts, "faces": faces, "mirror": True, "creases": [[2, 3, 0.75]], "corners": [[4, 0.5], [0, 1.0]], "rim": 0.0}) + self.assertEqual((len(built.V), built.counts.tolist()), (10, [4, 4, 4, 4])) + self.assertEqual(built.V[:2, 0].tolist(), [0.0, 0.0]) # 0.004 is inside SEAM_EPS: snapped + self.assertEqual(built.V[6:].tolist(), [[-0.5, 0.0, 0.0], [-0.5, 0.0, 1.0], [-1.0, 0.2, 0.0], [-1.0, 0.2, 1.0]]) + self.assertEqual(built.faces.reshape(-1, 4).tolist(), [[0, 1, 3, 2], [2, 3, 5, 4], [6, 7, 1, 0], [8, 9, 7, 6]]) + V = built.V[built.faces.reshape(-1, 4)] + self.assertTrue((np.cross(V[:, 1] - V[:, 0], V[:, 3] - V[:, 0])[:, 1] > 0).all()) # both halves face +y + self.assertEqual(SheetTests.weights(built), {(2, 3): 0.75, (6, 7): 0.75}) + self.assertEqual((built.corners.tolist(), built.corner_weights.tolist()), ([0, 4, 8], [1.0, 0.5, 0.5])) + edges, boundary, _, _ = core._cage_facts(len(built.V), built.faces, built.counts) + self.assertEqual((edges[(0, 1)], (0, 1) in boundary, len(boundary)), (2, False, 10)) # the seam edge is interior + verts[1][0] = 0.006 # outside SEAM_EPS: reflected, not shared, and vertex 0 now joins four boundary edges + self.refused(r"sheet\.poles lacks vertex 0 \(valence 4, on the boundary\)", verts=verts, faces=faces, mirror=True) + apart = core.sheet({"verts": verts, "faces": faces, "mirror": True, "poles": [0]}) + self.assertEqual((len(apart.V), apart.V[6].tolist(), apart.poles.tolist()), (11, [-0.006, 0.0, 1.0], [0])) + fan_verts, fan_faces = self.fan(3) + aside = core.sheet({"verts": [[x + 2.0, y, z] for x, y, z in fan_verts], "faces": fan_faces, "mirror": True, "poles": [0]}) + self.assertEqual((aside.poles.tolist(), core.cage_report(aside)["poles"]), ([0, 7], {"3": 2})) # a pole off the seam stands on both halves + left = core.sheet({"verts": [[-x, y, z] for x, y, z in verts[:1] + [[0.0, 0.0, 1.0]] + verts[2:]], "faces": [face[::-1] for face in faces], "mirror": True}) + self.assertEqual(left.V[6:, 0].tolist(), [0.5, 0.5, 1.0, 1.0]) # authored on -x, reflected to +x + verts[5][0] = -1.0 + self.refused(r"sheet\.verts\[5\] has x = -1: a mirrored cage is authored on one side", verts=verts, faces=faces, mirror=True) + + def test_triangles_are_counted_as_three_quads(self): + """free-cage-triangle-counts. C3 (every face counted as a quad): q quads and t triangles subdivide to + q * 4^L + t * 3 * 4^(L-1) faces.""" + verts, faces = self.PYRAMID + built = core.sheet({"verts": verts, "faces": faces, "poles": [1, 2]}) + self.assertEqual((built.counts.tolist(), built.triangles, len(built.faces)), ([3, 3, 3, 3, 4], 4, 16)) + self.assertEqual([core.subdivided_faces(built, levels) for levels in (1, 2, 3)], [4 * 3 + 4, 4 * 12 + 16, 4 * 48 + 64]) + self.assertEqual(core.cage_report(built), {"cageVerts": 7, "cageFaces": 5, "triangles": 4, "creases": 6, "corners": 0, "poles": {"4": 2}, "closed": False}) + loft = core.sheet({"rings": SheetTests.rings(3, 4)}) + self.assertEqual([core.subdivided_faces(loft, levels) for levels in (1, 3)], [24, 384]) + + def test_poles_are_declared_or_refused(self): + """free-cage-pole-gate. C4 (a gate that compares counts, or skips the check): the declared set must be the + computed set, vertex for vertex.""" + for quads in (3, 5): + verts, faces = self.fan(quads) + self.refused(rf"sheet\.poles lacks vertex 0 \(valence {quads}\)", verts=verts, faces=faces) + self.refused(rf"sheet\.poles lacks vertex 0 \(valence {quads}\)", verts=verts, faces=faces, poles=[1]) # one named, one computed: the count agrees, the set does not + built = core.sheet({"verts": verts, "faces": faces, "poles": [0]}) + self.assertEqual((built.poles.tolist(), core.cage_report(built)["poles"]), ([0], {str(quads): 1})) + verts, faces = self.fan(4) # valence 4 at the centre; the rim has valence 2 and 3: no pole anywhere + self.assertEqual(core.sheet({"verts": verts, "faces": faces}).poles.tolist(), []) + self.refused(r"sheet\.poles\[0\] names vertex 0 \(valence 4\), which is no pole", verts=verts, faces=faces, poles=[0]) + self.refused(r"sheet\.poles\[0\] names vertex 2 \(valence 2, on the boundary\), which is no pole", verts=verts, faces=faces, poles=[2]) + self.refused(r"sheet\.poles\[1\] names vertex 0 twice", verts=self.fan(3)[0], faces=self.fan(3)[1], poles=[0, 0]) + verts, faces = self.PYRAMID + self.refused(r"sheet\.poles lacks vertex 1 \(valence 4, on the boundary\), vertex 2 \(valence 4, on the boundary\)", verts=verts, faces=faces) + + def test_a_bad_cage_is_refused_by_field_and_index(self): + """free-cage-refusals. C5 (a check dropped): each fault is refused, naming where.""" + verts, faces = self.fan(4) + ok = {"verts": verts, "faces": faces} + self.refused(r"sheet\.verts\[9\] is in no face", **{**ok, "verts": verts + [[5.0, 5.0, 5.0]]}) + self.refused(r"sheet\.faces\[1\] must be 3 or 4 vertex indices, not 2", **{**ok, "faces": [faces[0], [0, 3]] + faces[1:]}) + self.refused(r"sheet\.faces\[0\] must be 3 or 4 vertex indices, not 5", **{**ok, "faces": [[0, 1, 2, 3, 4]] + faces[1:]}) + self.refused(r"sheet\.faces\[2\] names vertex 5 twice", **{**ok, "faces": faces[:2] + [[0, 5, 5, 7]] + faces[3:]}) + self.refused(r"sheet\.faces\[3\]\[2\] must be a whole number from 0 to 8, not 9", **{**ok, "faces": faces[:3] + [[0, 7, 9, 1]]}) + self.refused(r"sheet\.faces\[4\] has the vertices of sheet\.faces\[0\]: a duplicate face", **{**ok, "faces": faces + [[3, 2, 1, 0]]}) + wing = [[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [-1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0]] + self.refused(r"the edge between vertices 0 and 1 is in 3 faces \(0, 1, 2\)", verts=wing, faces=[[0, 1, 2, 3], [1, 0, 4, 5], [0, 1, 7, 6]]) + self.refused(r"sheet\.faces\[1\] crosses the edge between vertices 0 and 1 the same way as sheet\.faces\[0\]", verts=wing[:6], faces=[[0, 1, 2, 3], [0, 1, 5, 4]]) + self.refused(r"sheet\.faces\[0\] and sheet\.faces\[1\] share the edge between vertices 0 and 1, which lies on the mirror plane", + verts=wing[:4] + [[1.0, 1.0, 0.0], [1.0, 1.0, 1.0]], faces=[[0, 1, 2, 3], [1, 0, 4, 5]], mirror=True) + self.refused(r"sheet\.faces\[0\] lies on the mirror plane", verts=[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0]], faces=[[0, 1, 2], [0, 3, 1]], mirror=True) + self.refused(r"sheet\.faces\[1\] has area 0 m2, under 1e-08: a collapsed face", + verts=[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0]], faces=[[0, 1, 2], [1, 3, 4]]) + self.refused(r"sheet states both rings and verts", rings=SheetTests.rings(), **ok) + self.refused(r"sheet lacks 'rings' and 'verts'", creases=[]) + self.refused(r"sheet\.verts must be 4 to 256 vertices, not 257", verts=[[0.0, 0.0, float(k)] for k in range(257)], faces=faces) + self.refused(r"sheet\.verts must be 4 to 256 vertices, not 3", verts=verts[:3], faces=[[0, 1, 2]]) + self.refused(r"sheet\.verts\[2\] must be three finite numbers", **{**ok, "verts": verts[:2] + [[0.0, float("nan"), 0.0]] + verts[3:]}) + self.refused(r"sheet has no key 'closed'", closed=True, **ok) + self.refused(r"sheet\.creases\[0\]: vertices 1 and 5 share no face's edge", creases=[[1, 5, 1.0]], **ok) + self.refused(r"sheet\.creases\[1\] gives an edge weight 0\.5 that sheet\.creases\[0\] gives 1", creases=[[0, 1, 1.0], [1, 0, 0.5]], **ok) + self.refused(r"sheet\.creases\[0\]\[2\] must be a number from 0 to 1, not 2", creases=[[0, 1, 2]], **ok) + self.refused(r"sheet\.corners\[0\] must be \[vertex, weight\]", corners=[[0]], **ok) + self.refused(r"sheet\.creases\[0\] must be \{ring, from, to, weight\}", rings=SheetTests.rings(), creases=[[0, 1, 1.0]]) # the loft keeps its own crease form + self.refused(r"sheet has no key 'poles'", rings=SheetTests.rings(), poles=[]) + + class HostFileTests(unittest.TestCase): def setUp(self): self.document = json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8")) @@ -2195,7 +2317,7 @@ class OwnershipTests(unittest.TestCase): self.assertEqual((shell.count("evaluable("), shell.count("folded_faces("), shell.count("self.count_folds")), (1, 1, 2)) self.assertLess(shell.index("if self.count_folds:"), shell.index("with self.wall_alone(obj):")) self.assertLess(shell.index("with self.wall_alone(obj):"), shell.index("evaluable(")) - self.assertIn("self.folded_faces(context, obj, cage_faces * 4 ** self.levels) if self.count_folds else None", shell) + self.assertIn("self.folded_faces(context, obj, subdivided) if self.count_folds else None", shell) self.assertLess(count.index("wall_alone(shell):"), count.index("evaluable(")) self.assertEqual((count.count("evaluable("), count.count("to_mesh("), source.count("folded_faces("), source.count("wall_alone(")), (1, 1, 2, 3)) self.assertLess(alone.index("finally:"), alone.index("modifier.show_viewport = True")) From 739cdb1e6b3710005f93bd5c4e4e740326ceea4c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 02:46:57 +0100 Subject: [PATCH 167/223] tools/cage_export.py and cage_score.py: a mesh read as a free cage, and two cages scored through shell (counts, limit distance, silhouette IoU, crease chamfer); core.poles; live proof kitbash_cage with its bounds by the margin rule Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 2 +- surfaces/blender/brokkr_kitbash/core.py | 10 +- surfaces/blender/tests/live/kitbash_cage.py | 263 ++++++++++++++++++ .../tests/live/kitbash_cage.result.json | 120 ++++++++ .../blender/tests/live/kitbash_faceted.py | 3 +- surfaces/blender/tools/cage_export.py | 84 ++++++ surfaces/blender/tools/cage_score.py | 186 +++++++++++++ 7 files changed, 664 insertions(+), 4 deletions(-) create mode 100644 surfaces/blender/tests/live/kitbash_cage.py create mode 100644 surfaces/blender/tests/live/kitbash_cage.result.json create mode 100644 surfaces/blender/tools/cage_export.py create mode 100644 surfaces/blender/tools/cage_score.py diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index ac8e9cf..b7c3119 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1624,7 +1624,7 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): built = core.sheet(document) subdivided = core.subdivided_faces(built, self.levels) if subdivided > SHELL_FACES_LIMIT: - raise Refused(f"sheet: {len(built.counts)} cage faces at {self.levels} levels subdivide to {subdivided} faces, over {SHELL_FACES_LIMIT}. " + raise Refused(f"sheet: {len(built.counts)} cage {'faces' if built.triangles else 'quads'} at {self.levels} levels subdivide to {subdivided} faces, over {SHELL_FACES_LIMIT}. " "Use fewer levels or a sparser sheet; nothing changed.") rebuilt = obj is not None if rebuilt: diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 78ec6b6..cd0db1c 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1235,7 +1235,13 @@ def subdivided_faces(built: Sheet, levels: int) -> int: return (len(built.counts) - built.triangles) * 4 ** levels + built.triangles * 3 * 4 ** (levels - 1) -def _cage(document: Any) -> Sheet: +def poles(document: Any) -> list[int]: + """The poles a free cage's faces make, by authored index, ascending: what its sheet.poles must state. For a + reader of a cage someone else modelled (tools/cage_export.py); every other refusal of the free form stands.""" + return [int(v) for v in _cage(document, gate=False).poles if v < len(document["verts"])] + + +def _cage(document: Any, gate: bool = True) -> Sheet: """The cage of a free description {verts, faces, creases, corners, poles, mirror, rim, flip}. verts: 4 to 256 [x, y, z]. faces: 3 or 4 vertex indices each, wound so the normal (counter-clockwise seen from @@ -1320,7 +1326,7 @@ def _cage(document: Any) -> Sheet: flat = np.array([v for face in built for v in face], dtype=np.int32) cage_edges, boundary, valences, poles = _cage_facts(len(V), flat, counts) - declared = document.get("poles", []) + declared = document.get("poles", []) if gate else [int(v) for v in poles if v < A] if not isinstance(declared, list): raise KitError("sheet.poles must be an array of vertex indices") for k, v in enumerate(declared): diff --git a/surfaces/blender/tests/live/kitbash_cage.py b/surfaces/blender/tests/live/kitbash_cage.py new file mode 100644 index 0000000..b10fe49 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_cage.py @@ -0,0 +1,263 @@ +"""Live proof, in a background Blender, of brokkr_kitbash.shell's free cage through run_intent: a cage of triangles +and quads with declared poles becomes a shell whose subdivided face count is the reported one at each level, takes a +wall, counts folds and is cut; a mirrored cage closes over its seam; a loft shell is rebuilt in place as a free cage +under its cutters; the pole gate refuses without writing; and tools/cage_export.py and tools/cage_score.py read a +cage back and score it. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_cage.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 reading and +the least claimed mutant's, both written beside it; the result file carries the readings. The checks run inside +one try: an uncaught error is a failed check that names its section, and the result file is always written. +""" +import importlib.util +import json +import math +import os +import sys +import tempfile +import traceback +import types +from pathlib import Path + +import bmesh +import bpy +import numpy as np + +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 +import cage_export # noqa: E402 +import cage_score # noqa: E402 + +core = cage_export.load_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-cage-")) +target.configure_action_dirs("", str(WORK)) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}} +COUNT, SECTION = [0], ["setup"] +# Degrees: the largest dihedral angle across an edge of the tent's subdivided surface off its boundary; it is on the +# creased ridge. Shipped 71; least claimed mutant 16 (K1, the free form's creases not written to crease_edge: the +# ridge subdivides smooth), read here by clearing the attribute; the geometric mean, separation 2.1 each side. +CRISP = 34.0 +# Per cent of the reference's extent: cage_score's median surface distance between the tent and the tent with its apex +# moved 5% of the extent. Shipped (a cage against itself) 0, read as 5e-6 (1e-7 m, what a float32 mesh is good to, of +# a 2 m extent); least claimed mutant 0.68 (the moved apex); the geometric mean, separation 370 each side. The moved +# apex's silhouette reads IoU 0.95 along y, under 1: checked as a strict inequality, not bounded. +SAME = 1.8e-3 + +# A tent: four triangles round an apex of valence 4 with two ridges creased, and a quad hung under one edge: 7 +# vertices, vertices 1 and 2 boundary poles of valence 4. +TENT = {"verts": [[0.0, 0.0, 0.5], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [1.0, 0.0, -1.0], [0.0, 1.0, -1.0]], + "faces": [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [2, 1, 5, 6]], "creases": [[0, 1, 1.0], [0, 3, 1.0]], "poles": [1, 2], "rim": 0.0} +# Half a lozenge hull, mirrored: seam vertices 0 to 3 (one 4 mm off the plane), a nose and tail triangle each side. +HULL = {"verts": [[0.0, -1.0, 0.0], [0.004, 0.0, 0.3], [0.0, 1.0, 0.0], [0.0, 0.0, -0.3], [0.6, 0.0, 0.0]], + "faces": [[0, 4, 1], [1, 4, 2], [2, 4, 3], [3, 4, 0]], "creases": [[0, 4, 1.0], [4, 2, 1.0]], "mirror": True} +LOFT = {"rings": [[[0.3 * j - 0.45, 0.02 * j * j, 0.3 * i] for j in range(4)] for i in range(3)], "flip": True} +CUTS = [{"name": "TentLine", "part": "slab", "params": "gap=0.02; length=0.4; depth=0.03", "origin": [0.3, -0.35, 3.0], "direction": [0, 0, -1]}] + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else json.loads(json.dumps(detail, default=str))}) + + +def section(name): + SECTION[0] = name + + +def send(action, **fields): + COUNT[0] += 1 + receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "nibu/hands", "action": action, **fields}) + result = None + if receipt.get("hostResult"): + try: + result = json.loads(receipt["hostResult"]) + except ValueError: + result = None + print("SEND", action, receipt["status"], str(receipt["message"])[:300], flush=True) + return receipt, result + + +def evaluated(obj, only=None): + """An object as Blender evaluates it, as a bmesh; with `only`, with just the modifiers of those names shown.""" + hidden = [m for m in obj.modifiers if only is not None and m.name not in only and m.show_viewport] + for m in hidden: + m.show_viewport = False + try: + bpy.context.view_layer.update() + owner = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()) + bm = bmesh.new() + bm.from_mesh(owner.to_mesh()) + owner.to_mesh_clear() + finally: + for m in hidden: + m.show_viewport = True + bpy.context.view_layer.update() + bm.normal_update() + return bm + + +def sharpest(obj): + bm = evaluated(obj, only=("Kit Subsurf",)) + worst = max(math.degrees(e.link_faces[0].normal.angle(e.link_faces[1].normal, 0.0)) for e in bm.edges if len(e.link_faces) == 2) + bm.free() + return worst + + +def state(): + return {o.name: (sorted(k for k in o.keys() if k.startswith("kit_")), len(o.data.vertices) if o.type == "MESH" else None, [m.name for m in o.modifiers]) for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes) + + +try: + # --- live-free-cage-shell: counts at each level ---------------------------------------------------------------- + section("free-cage-triangle-counts") + for levels in (1, 2, 3): + receipt, report = send("brokkr_kitbash.shell", object_name="Tent", sheet=json.dumps(TENT), thickness=0.04, levels=levels, count_folds=True) + tent = bpy.data.objects.get("Tent") + expected = 1 * 4 ** levels + 4 * 3 * 4 ** (levels - 1) + bm = evaluated(tent, only=("Kit Subsurf",)) + faces, sides = len(bm.faces), {len(f.verts) for f in bm.faces} + bm.free() + wall = evaluated(tent, only=("Kit Subsurf", "Kit Solidify")) + closed, walled = all(e.is_manifold for e in wall.edges), len(wall.faces) + wall.free() + check(f"a cage of 4 triangles and a quad at {levels} levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads", + receipt["status"] == "accepted" and report["subdividedFaces"] == expected == faces and sides == {4}, [receipt["message"], expected, faces, sides]) + check(f"at {levels} levels the wall is closed, twice the surface and a rim, and count_folds counts none folded", + closed and walled > 2 * expected and report["folded"] == 0, [closed, walled, report and report["folded"]]) + built = core.sheet(TENT) + check("the report carries the cage's facts: 7 vertices, 5 faces of which 4 triangles, 2 creases, two poles of valence 4, open; rings and points null", + report and {k: report[k] for k in ("rings", "points", "cageVerts", "cageFaces", "triangles", "creases", "corners", "poles", "closed")} + == {"rings": None, "points": None, "cageVerts": 7, "cageFaces": 5, "triangles": 4, "creases": 2, "corners": 0, "poles": {"4": 2}, "closed": False}, report) + check("the cage mesh is core.sheet's, face for face, and kit_shell is the request", + [tuple(p.vertices) for p in tent.data.polygons] == [tuple(f) for f in TENT["faces"]] and np.abs(np.array([v.co[:] for v in tent.data.vertices]) - built.V).max() < 1e-6 + and json.loads(tent["kit_shell"])["sheet"] == TENT, tent["kit_shell"]) + + # --- the creases reach the surface ----------------------------------------------------------------------------------- + section("free-cage-crisp") + crisp = sharpest(tent) + attribute = tent.data.attributes["crease_edge"] + kept = [d.value for d in attribute.data] + attribute.data.foreach_set("value", [0.0] * len(kept)) # K1: what the surface is when the creases are not written + tent.data.update() + soft = sharpest(tent) + attribute.data.foreach_set("value", kept) + tent.data.update() + R["readings"].update({"crispDegrees": crisp, "crispDegreesK1": soft}) + check(f"the creased ridge stays an edge under subdivision: over {CRISP} degrees, and under it with crease_edge cleared", crisp > CRISP * 1.2 and soft < CRISP / 1.2, [crisp, soft]) + + # --- cut ------------------------------------------------------------------------------------------------------------- + section("live-free-cage-shell") + receipt, cut = send("brokkr_kitbash.cut_many", object_name="Tent", cuts=json.dumps(CUTS)) + plate = evaluated(tent) + uncut = 2 * (4 ** 3 + 12 * 4 ** 2) + check("cut_many cuts a free-cage shell: the Boolean stands after the wall, the plate has more faces than the wall and no non-manifold edge", + receipt["status"] == "accepted" and [m.name for m in tent.modifiers] == ["Kit Subsurf", "Kit Solidify", "Kit Difference"] and len(plate.faces) > uncut + 20 + and sum(1 for e in plate.edges if not e.is_manifold) == 0, [receipt["message"], len(plate.faces), sum(1 for e in plate.edges if not e.is_manifold)]) + plate.free() + + # --- mirror ---------------------------------------------------------------------------------------------------------- + section("free-cage-mirror") + receipt, report = send("brokkr_kitbash.shell", object_name="Hull", sheet=json.dumps(HULL), thickness=0.01) + hull = bpy.data.objects.get("Hull") + bm = evaluated(hull, only=("Kit Subsurf",)) + check("a mirrored cage closes over its seam: 6 vertices from 5, 8 triangles, the vertex 4 mm off the plane snapped onto it, no boundary edge on the cage or its surface, and its poles reported", + receipt["status"] == "accepted" and (report["cageVerts"], report["cageFaces"], report["triangles"], report["closed"], report["creases"], report["subdividedFaces"]) == (6, 8, 8, True, 4, 8 * 3 * 16) + and abs(hull.data.vertices[1].co.x) < 1e-9 and all(e.is_manifold for e in bm.edges) and len(bm.faces) == 384 and report["poles"] == {}, report) + bm.free() + + # --- rebuild a loft as a free cage ------------------------------------------------------------------------------------- + section("free-cage-rebuild") + receipt, _ = send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(LOFT), thickness=0.03) + plate_obj = bpy.data.objects["Plate"] + plate_obj.data.materials.append(bpy.data.materials.new("Khaki")) + receipt, _ = send("brokkr_kitbash.cut_many", object_name="Plate", cuts=json.dumps([{"name": "PlateLine", "part": "slab", "params": "gap=0.02; length=0.3; depth=0.02", "origin": [0.0, 3.0, 0.3], "direction": [0, -1, 0]}])) + before = (plate_obj.as_pointer(), plate_obj.data.as_pointer(), sorted(c.name for c in plate_obj.children), sorted(o.name for o in plate_obj.modifiers["Kit Difference"].collection.objects), [s.material.name for s in plate_obj.material_slots]) + loft = core.sheet(LOFT) + quads = loft.faces.reshape(-1, 4).tolist() + FREE = {"verts": [[round(c, 6) for c in v] for v in loft.V.tolist()], "faces": quads[:5] + [quads[5][:3], [quads[5][0], quads[5][2], quads[5][3]]], "poles": [7, 10], "creases": [[5, 6, 1.0]]} # the last quad split along its diagonal: two boundary vertices of valence 4 + receipt, report = send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(FREE), thickness=0.03) + again = bpy.data.objects.get("Plate") + after = (again.as_pointer(), again.data.as_pointer(), sorted(c.name for c in again.children), sorted(o.name for o in again.modifiers["Kit Difference"].collection.objects), [s.material.name for s in again.material_slots]) + bm = evaluated(again) + check("a loft shell rebuilt in place as a free cage keeps its object, mesh datablock, cutter, Boolean and material slot; the report says rebuilt, 2 triangles and the cage's poles; the plate is still cut and closed", + receipt["status"] == "accepted" and before == after and before[2:] == (["PlateLine"], ["PlateLine"], ["Khaki"]) and report["rebuilt"] is True and (report["triangles"], report["rings"], report["cageFaces"]) == (2, None, 7) + and report["poles"] == {"4": 2} and report["children"] == ["PlateLine"] and sum(1 for e in bm.edges if not e.is_manifold) == 0 and len(bm.faces) > 2 * report["subdividedFaces"], [receipt["message"], report, before, after]) + bm.free() + + # --- the gate refuses before it writes ------------------------------------------------------------------------------- + section("free-cage-refusals") + for label, name, sheet, expected in ( + ("an undeclared pole, on a shell", "Plate", {**FREE, "poles": [7]}, "sheet.poles lacks vertex 10 (valence 4, on the boundary)"), + ("a declared vertex that is no pole, on a new name", "New", {**TENT, "poles": [1, 2, 0]}, "sheet.poles[2] names vertex 0 (valence 4), which is no pole"), + ("rings with verts", "New", {**TENT, "rings": LOFT["rings"]}, "sheet states both rings and verts"), + ("a face of five sides", "New", {**TENT, "faces": TENT["faces"][:4] + [[2, 1, 5, 6, 3]]}, "sheet.faces[4] must be 3 or 4 vertex indices, not 5"), + ("two faces wound against each other", "Plate", {**FREE, "faces": FREE["faces"][:6] + [FREE["faces"][6][::-1]]}, "the two are wound against each other")): + held = state() + receipt, _ = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(sheet)) + check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and state() == held, [receipt["status"], receipt["message"]]) + check("no refusal made an object", "New" not in bpy.data.objects, None) + + # --- export-score-roundtrip ----------------------------------------------------------------------------------------- + section("export-score-roundtrip") + saved = str(WORK / "scratch.blend") + probe = bpy.data.objects.new("Probe Cage", bpy.data.meshes.new("Probe Cage")) # a cage as a person leaves one: a mesh, a Mirror, creases on edges; made here, no one's file + bpy.context.scene.collection.objects.link(probe) + probe.data.from_pydata(HULL["verts"], [], HULL["faces"]) + probe.data.update(calc_edges=True) + weights = probe.data.attributes.new("crease_edge", "FLOAT", "EDGE") + for e in probe.data.edges: + weights.data[e.index].value = 1.0 if tuple(sorted(e.vertices)) in ((0, 4), (2, 4)) else 0.0 + probe.modifiers.new("Mirror", "MIRROR") + probe.modifiers.new("Subdivision", "SUBSURF") + document = cage_export.export(probe, core) + exported = document["sheet"] + check("cage_export reads a mirrored, creased mesh as the free cage it is: the seam snapped, the creases by vertex pair, mirror set, rim 0, the poles computed, and core.sheet takes it", + exported["verts"][1] == [0.0, 0.0, 0.3] and exported["faces"] == HULL["faces"] and exported["creases"] == [[0, 4, 1.0], [2, 4, 1.0]] and exported["mirror"] is True + and exported["rim"] == 0.0 and exported["poles"] == [] and document["modifiers"] == [["MIRROR", "Mirror"], ["SUBSURF", "Subdivision"]] + and np.array_equal(core.sheet(exported).faces, core.sheet(HULL).faces), document) + bpy.data.objects.remove(probe) + tent_document = {**TENT, "rim": 1.0} + held = state() + same = cage_score.score(tent_document, tent_document, send) + check("cage_score of a cage against itself: equal counts, distance 0, every silhouette IoU 1, crease chamfer 0, and its two shells removed again", + same["agent"] == same["reference"] and same["agent"]["cageVerts"] == 7 and same["distance"]["maxPct"] < SAME / 1.2 and set(same["silhouetteIoU"].values()) == {1.0} + and same["creaseChamferPct"] == 0.0 and state() == held, same) + moved = {**tent_document, "verts": [[0.0, 0.0, 0.5 + 0.05 * 2.0]] + TENT["verts"][1:]} # the apex lifted 5% of the 2 m extent + apart = cage_score.score(moved, tent_document, send) + R["readings"].update({"scoreSameMedianPct": same["distance"]["medianPct"], "scoreMovedMedianPct": apart["distance"]["medianPct"], "scoreMovedIoUy": apart["silhouetteIoU"]["y"], + "scoreMovedChamferPct": apart["creaseChamferPct"]}) + check("cage_score of the cage with one vertex moved 5% of the extent: distance above the bound, a silhouette under 1, a crease chamfer above 0, the counts still equal", + apart["distance"]["medianPct"] > SAME * 1.2 and apart["distance"]["maxPct"] > 1.0 and min(apart["silhouetteIoU"].values()) < 1.0 and apart["creaseChamferPct"] > 0.0 + and apart["agent"] == apart["reference"] and abs(apart["extent"] - same["extent"]) < 1e-9, apart) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file + check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:]) +finally: + R["ok"] = all(c["ok"] for c in R["checks"]) + R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} + Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") + for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) + print("READINGS", R["readings"], flush=True) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_cage.result.json b/surfaces/blender/tests/live/kitbash_cage.result.json new file mode 100644 index 0000000..449043c --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_cage.result.json @@ -0,0 +1,120 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "a cage of 4 triangles and a quad at 1 levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads", + "ok": true, + "detail": null + }, + { + "name": "at 1 levels the wall is closed, twice the surface and a rim, and count_folds counts none folded", + "ok": true, + "detail": null + }, + { + "name": "a cage of 4 triangles and a quad at 2 levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads", + "ok": true, + "detail": null + }, + { + "name": "at 2 levels the wall is closed, twice the surface and a rim, and count_folds counts none folded", + "ok": true, + "detail": null + }, + { + "name": "a cage of 4 triangles and a quad at 3 levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads", + "ok": true, + "detail": null + }, + { + "name": "at 3 levels the wall is closed, twice the surface and a rim, and count_folds counts none folded", + "ok": true, + "detail": null + }, + { + "name": "the report carries the cage's facts: 7 vertices, 5 faces of which 4 triangles, 2 creases, two poles of valence 4, open; rings and points null", + "ok": true, + "detail": null + }, + { + "name": "the cage mesh is core.sheet's, face for face, and kit_shell is the request", + "ok": true, + "detail": null + }, + { + "name": "the creased ridge stays an edge under subdivision: over 34.0 degrees, and under it with crease_edge cleared", + "ok": true, + "detail": null + }, + { + "name": "cut_many cuts a free-cage shell: the Boolean stands after the wall, the plate has more faces than the wall and no non-manifold edge", + "ok": true, + "detail": null + }, + { + "name": "a mirrored cage closes over its seam: 6 vertices from 5, 8 triangles, the vertex 4 mm off the plane snapped onto it, no boundary edge on the cage or its surface, and its poles reported", + "ok": true, + "detail": null + }, + { + "name": "a loft shell rebuilt in place as a free cage keeps its object, mesh datablock, cutter, Boolean and material slot; the report says rebuilt, 2 triangles and the cage's poles; the plate is still cut and closed", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an undeclared pole, on a shell", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a declared vertex that is no pole, on a new name", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: rings with verts", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a face of five sides", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: two faces wound against each other", + "ok": true, + "detail": null + }, + { + "name": "no refusal made an object", + "ok": true, + "detail": null + }, + { + "name": "cage_export reads a mirrored, creased mesh as the free cage it is: the seam snapped, the creases by vertex pair, mirror set, rim 0, the poles computed, and core.sheet takes it", + "ok": true, + "detail": null + }, + { + "name": "cage_score of a cage against itself: equal counts, distance 0, every silhouette IoU 1, crease chamfer 0, and its two shells removed again", + "ok": true, + "detail": null + }, + { + "name": "cage_score of the cage with one vertex moved 5% of the extent: distance above the bound, a silhouette under 1, a crease chamfer above 0, the counts still equal", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "readings": { + "crispDegrees": 71.0, + "crispDegreesK1": 16.0, + "scoreMovedChamferPct": 0.46, + "scoreMovedIoUy": 0.95, + "scoreMovedMedianPct": 0.68, + "scoreSameMedianPct": 0.0 + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/kitbash_faceted.py b/surfaces/blender/tests/live/kitbash_faceted.py index be7a6eb..a7c09ab 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.py +++ b/surfaces/blender/tests/live/kitbash_faceted.py @@ -214,7 +214,8 @@ try: and sorted(stored) == ["bevel", "levels", "offset", "sheet", "thickness"] and stored["sheet"] == PAULDRON and (stored["levels"], stored["offset"]) == (3, -1.0) and abs(stored["thickness"] - WALL) < 1e-7, [receipt["message"], stored]) check("shell reports cage facts: rings, points, quads, creased edges, the subdivided count, an upward facing, no children", - report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "folded", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"] + report and sorted(report) == ["cageFaces", "cageVerts", "children", "closed", "corners", "creases", "facing", "folded", "levels", "object", "offset", "points", "poles", "rebuilt", "rings", "subdividedFaces", "thickness", "triangles"] + and (report["cageVerts"], report["triangles"], report["poles"], report["closed"]) == (36, 0, {}, False) and (report["object"], report["rebuilt"], report["rings"], report["points"], report["cageFaces"], report["creases"], report["corners"], report["subdividedFaces"], report["levels"], report["thickness"], report["offset"], report["children"]) == ("Pauldron", False, 6, 6, 25, 25, 0, 1600, 3, 0.06, -1.0, []) and report["facing"][2] > 0.5 and abs(np.linalg.norm(report["facing"]) - 1.0) < 1e-5, report) diff --git a/surfaces/blender/tools/cage_export.py b/surfaces/blender/tools/cage_export.py new file mode 100644 index 0000000..5798062 --- /dev/null +++ b/surfaces/blender/tools/cage_export.py @@ -0,0 +1,84 @@ +"""Write one object of a .blend as a free cage document, the form brokkr_kitbash.shell's sheet takes. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tools/cage_export.py -- + +For reading a cage a person modelled by hand: its vertex budget, faces, creases and poles, and as the reference +of tools/cage_score.py. is a COPY of the file, made by whoever runs this: the script opens it, reads +one mesh, writes (an absolute path) and nothing else, and never saves a .blend. It refuses to start +unless BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are private (tools/private_dirs.py). + +The document: {"object", "modifiers" (type and name, as stacked), "matrixWorld", "sheet"}. sheet is the cage in +the object's own frame, before any modifier: verts, faces, creases from the crease_edge attribute, corners from +crease_vert, mirror true when the object carries a Mirror across x (any other Mirror is refused), the seam +snapped as core.sheet snaps it (a vertex within SEAM_EPS of x = 0 goes to 0), rim 0 (a boundary edge carries the +crease it was given and no more), and poles as the faces make them (core.poles). The sheet is what core.sheet +accepts: a cage it would refuse (a face of five sides, a fin on the mirror plane) is refused here with its reason. +""" +import importlib.util +import json +import os +import sys +from pathlib import Path + +import bpy + +SURFACE = Path(__file__).resolve().parents[1] + + +def load_core(): + spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_tool", SURFACE / "brokkr_kitbash" / "core.py") + core = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = core + spec.loader.exec_module(core) + return core + + +def export(obj, core) -> dict: + """The document of a mesh object's cage. Raises core.KitError when the cage is none core.sheet takes.""" + if obj.type != "MESH": + raise core.KitError(f"{obj.name!r} is a {obj.type}, not a mesh") + mirrors = [m for m in obj.modifiers if m.type == "MIRROR"] + if len(mirrors) > 1 or mirrors and (tuple(mirrors[0].use_axis) != (True, False, False) or mirrors[0].mirror_object is not None): + raise core.KitError(f"{obj.name!r} is mirrored otherwise than once across its own x: a free cage mirrors across x = 0 only") + mesh = obj.data + verts = [[round(float(c), 6) for c in v.co] for v in mesh.vertices] + if mirrors: + for point in verts: + if abs(point[0]) <= core.SEAM_EPS: + point[0] = 0.0 + creases, corners = mesh.attributes.get("crease_edge"), mesh.attributes.get("crease_vert") + sheet = {"verts": verts, "faces": [list(p.vertices) for p in mesh.polygons], + "creases": sorted([*sorted(e.vertices), round(float(creases.data[e.index].value), 4)] for e in mesh.edges if creases.data[e.index].value > 0) if creases else [], + "corners": [[v.index, round(float(corners.data[v.index].value), 4)] for v in mesh.vertices if corners.data[v.index].value > 0] if corners else [], + "mirror": bool(mirrors), "rim": 0.0} + sheet["poles"] = core.poles(sheet) + core.sheet(sheet) + return {"object": obj.name, "modifiers": [[m.type, m.name] for m in obj.modifiers], "matrixWorld": core.rows(obj.matrix_world), "sheet": sheet} + + +def main() -> int: + sys.path.insert(0, str(Path(__file__).resolve().parent)) + import private_dirs + refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) + if refused: + raise SystemExit(f"cage_export: {refused}") + arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] + if len(arguments) != 3 or not Path(arguments[2]).is_absolute(): + raise SystemExit("usage: blender --background --factory-startup --python cage_export.py -- ") + blend, name, out = arguments + core = load_core() + bpy.ops.wm.open_mainfile(filepath=str(Path(blend).resolve()), load_ui=False, use_scripts=False) + obj = bpy.data.objects.get(name) + if obj is None: + raise SystemExit(f"cage_export: {blend} has no object {name!r}; its meshes: {', '.join(sorted(o.name for o in bpy.data.objects if o.type == 'MESH'))}") + try: + document = export(obj, core) + except core.KitError as error: + raise SystemExit(f"cage_export: {name!r} is no free cage: {error}") from None + Path(out).write_text(json.dumps(document, indent=1), encoding="utf-8") + print("cage_export:", json.dumps({key: core.cage_report(core.sheet(document["sheet"]))[key] for key in ("cageVerts", "cageFaces", "triangles", "creases", "poles", "closed")}), flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/surfaces/blender/tools/cage_score.py b/surfaces/blender/tools/cage_score.py new file mode 100644 index 0000000..72c2cbb --- /dev/null +++ b/surfaces/blender/tools/cage_score.py @@ -0,0 +1,186 @@ +"""Read how close one free cage comes to another: an agent's cage against a reference, both in one frame. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tools/cage_score.py -- + +Each input is a sheet (either form of brokkr_kitbash.shell's) or a cage_export.py document holding one. Both are +built by brokkr_kitbash.shell through the add-on's own agent turn, at three levels, and read with their Kit +Subsurf alone: the tool measures what the tool builds. is an absolute path and the one file written; +no .blend is saved. It refuses to start unless BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and +BLENDER_USER_SCRIPTS are private (tools/private_dirs.py). + +The result is a reading with no pass bar: + + agent, reference each cage's counts as shell reports them: cageVerts, cageFaces, triangles, creases, corners, poles, closed + extent the reference surface's largest extent, metres: the unit of every percentage + distance between the two level-3 surfaces, each one's vertices to the nearest point of the other, pooled: + medianPct, p95Pct, maxPct + silhouetteIoU orthographic silhouettes seen along x, y and z, 512 px across the two surfaces' common box: + intersection over union + creaseChamferPct the creased cage edges (rim included, where its weight is over 0) as they lie on each level-3 + surface, sampled every 1% of extent: the mean distance from each curve's samples to the + other's, averaged both ways; null when either cage has no crease +""" +import importlib.util +import json +import os +import sys +import types +from pathlib import Path + +import bpy +import numpy as np +from mathutils import Vector +from mathutils.bvhtree import BVHTree + +SURFACE = Path(__file__).resolve().parents[1] +LEVELS, PIXELS, SPACING = 3, 512, 0.01 +COUNTS = ("cageVerts", "cageFaces", "triangles", "creases", "corners", "poles", "closed") + + +def surface(obj): + """(V, triangles, creased polylines) of a shell read with its Kit Subsurf alone. A creased cage edge is found on + the subdivided mesh as Blender lays it out: the cage's vertices keep their indices, then each cage edge's 2^L - 1 + inner vertices follow in edge order; the chain is checked edge by edge against the mesh, not assumed.""" + hidden = [m for m in obj.modifiers if m.name != "Kit Subsurf" and m.show_viewport] + for m in hidden: + m.show_viewport = False + try: + bpy.context.view_layer.update() + owner = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()) + mesh = owner.to_mesh() + V = np.array([v.co[:] for v in mesh.vertices], dtype=np.float64) + triangles = np.array([[p.vertices[0], p.vertices[k], p.vertices[k + 1]] for p in mesh.polygons for k in range(1, len(p.vertices) - 1)], dtype=np.int64) + edges = {tuple(sorted(e.vertices)) for e in mesh.edges} + owner.to_mesh_clear() + finally: + for m in hidden: + m.show_viewport = True + bpy.context.view_layer.update() + cage, inner = obj.data, 2 ** obj.modifiers["Kit Subsurf"].levels - 1 + weights = cage.attributes["crease_edge"].data + curves = [] + for e in cage.edges: + if weights[e.index].value <= 0: + continue + between = [len(cage.vertices) + e.index * inner + k for k in range(inner)] + for chain in ([e.vertices[0], *between, e.vertices[1]], [e.vertices[0], *between[::-1], e.vertices[1]]): + if all(tuple(sorted(pair)) in edges for pair in zip(chain, chain[1:])): + curves.append(V[chain]) + break + else: + raise SystemExit(f"cage_score: cage edge {tuple(e.vertices)} of {obj.name!r} is not where the subdivided mesh was expected to carry it; this Blender lays a Subdivision out otherwise") + return V, triangles, curves + + +def nearest(points, V, triangles): + tree = BVHTree.FromPolygons([Vector(v) for v in V], [tuple(int(i) for i in t) for t in triangles]) + return np.array([tree.find_nearest(Vector(p))[3] for p in points]) + + +def silhouette(V, triangles, axis, low, scale): + """A PIXELS-square mask of the triangles seen along `axis`, in the frame (low, scale) both surfaces share.""" + keep = [k for k in range(3) if k != axis] + P = (V[:, keep] - low[keep]) * scale + mask = np.zeros((PIXELS, PIXELS), dtype=bool) + for a, b, c in P[triangles]: + x0, y0 = np.floor(np.minimum(np.minimum(a, b), c)).astype(int).clip(0, PIXELS - 1) + x1, y1 = np.ceil(np.maximum(np.maximum(a, b), c)).astype(int).clip(0, PIXELS - 1) + area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + if abs(area) < 1e-12: + continue + X, Y = np.meshgrid(np.arange(x0, x1 + 1) + 0.5, np.arange(y0, y1 + 1) + 0.5) + u = ((b[0] - X) * (c[1] - Y) - (b[1] - Y) * (c[0] - X)) / area + v = ((c[0] - X) * (a[1] - Y) - (c[1] - Y) * (a[0] - X)) / area + mask[y0:y1 + 1, x0:x1 + 1] |= (u >= 0) & (v >= 0) & (u + v <= 1) + return mask + + +def sampled(curves, step): + points = [] + for curve in curves: + lengths = np.linalg.norm(np.diff(curve, axis=0), axis=1) + along = np.concatenate([[0.0], np.cumsum(lengths)]) + at = np.linspace(0.0, along[-1], max(2, int(np.ceil(along[-1] / step)) + 1)) + points.append(np.stack([np.interp(at, along, curve[:, k]) for k in range(3)], axis=1)) + return np.concatenate(points) if points else np.zeros((0, 3)) + + +def score(agent: dict, reference: dict, send) -> dict: + """The reading of two sheets. send(action, **fields) -> (receipt, report) runs an intent; the two shells it + builds (Cage Score Agent, Cage Score Reference) are removed again.""" + built, reports = {}, {} + try: + for role, sheet in (("agent", agent), ("reference", reference)): + name = f"Cage Score {role.title()}" + receipt, report = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(sheet), levels=LEVELS, thickness=0.001) + if receipt["status"] != "accepted": + raise SystemExit(f"cage_score: the {role} cage was refused: {receipt['message']}") + reports[role] = {key: report[key] for key in COUNTS} + built[role] = surface(bpy.data.objects[name]) + finally: + for role in ("agent", "reference"): + obj = bpy.data.objects.get(f"Cage Score {role.title()}") + if obj is not None: + mesh = obj.data + bpy.data.objects.remove(obj) + bpy.data.meshes.remove(mesh) + (VA, TA, CA), (VB, TB, CB) = built["agent"], built["reference"] + extent = float(np.ptp(VB, axis=0).max()) + d = np.concatenate([nearest(VA, VB, TB), nearest(VB, VA, TA)]) / extent * 100.0 + both = np.concatenate([VA, VB]) + low = both.min(axis=0) + scale = (PIXELS - 1) / float(np.ptp(both, axis=0).max()) + overlap = {} + for axis, label in enumerate("xyz"): + a, b = silhouette(VA, TA, axis, low, scale), silhouette(VB, TB, axis, low, scale) + overlap[label] = round(float((a & b).sum() / max(1, (a | b).sum())), 4) + chamfer = None + if CA and CB: + SA, SB = sampled(CA, SPACING * extent), sampled(CB, SPACING * extent) + away = lambda P, Q: float(np.mean([np.linalg.norm(Q - p, axis=1).min() for p in P])) # noqa: E731 + chamfer = round(0.5 * (away(SA, SB) + away(SB, SA)) / extent * 100.0, 4) + return {"levels": LEVELS, "agent": reports["agent"], "reference": reports["reference"], "extent": round(extent, 6), + "distance": {"medianPct": round(float(np.median(d)), 4), "p95Pct": round(float(np.percentile(d, 95)), 4), "maxPct": round(float(d.max()), 4)}, + "silhouetteIoU": overlap, "creaseChamferPct": chamfer} + + +def main() -> int: + sys.path.insert(0, str(Path(__file__).resolve().parent)) + import private_dirs + refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) + if refused: + raise SystemExit(f"cage_score: {refused}") + arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] + if len(arguments) != 3 or not Path(arguments[2]).is_absolute(): + raise SystemExit("usage: blender --background --factory-startup --python cage_score.py -- ") + sheets = [] + for path in arguments[:2]: + document = json.loads(Path(path).read_text(encoding="utf-8")) + sheets.append(document["sheet"] if "sheet" in document else document) + package = types.ModuleType("brokkr_bridge") + package.__path__ = [str(SURFACE / "brokkr_bridge")] + sys.modules["brokkr_bridge"] = package + blender_target = importlib.import_module("brokkr_bridge.blender_target") + import addon_utils + 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 = blender_target.BrokkrBlenderTarget(bpy) + target.configure_action_dirs("", str(Path(arguments[2]).parent)) + target.reload_host_actions() + count = [0] + + def send(action, **fields): + count[0] += 1 + receipt = target.run_intent(bpy.context, {"commandId": f"cage-score-{count[0]}", "requestedBy": "tools/cage_score", "action": action, **fields}) + return receipt, json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None + + result = score(sheets[0], sheets[1], send) + Path(arguments[2]).write_text(json.dumps(result, indent=1), encoding="utf-8") + print("cage_score:", json.dumps(result), flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 224eefa57bb4a9e60f370f7663a34f436677efdf Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 02:47:00 +0100 Subject: [PATCH 168/223] docs/kitbash.md: A free cage: the form, the mirror seam, the pole gate, triangles, the budget from two hand-modelled cages, and what it gives up Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 81 ++++++++++++++++++++++++++++++-- 1 file changed, 77 insertions(+), 4 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index f82d7c3..b507720 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -450,8 +450,10 @@ and about 0.002 s with them frozen. ## Making a shell `shell` makes an armor plate the way one is modelled by hand: fit a sparse subdivision cage, crease the edges that -are facets' borders, give it a wall, then cut into it. The cage is a **loft**: rings of points with equal counts, -quads between neighbouring rings. The description is a JSON object, `sheet`: +are facets' borders, give it a wall, then cut into it. The description is a JSON object, `sheet`, in one of two +forms, both compiled by `core.sheet` into the same cage: a **loft** (`rings`), below, or a **free cage** (`verts` +and `faces`, [A free cage](#a-free-cage)). A sheet states exactly one of `rings` and `verts`. The loft is rings of +points with equal counts, quads between neighbouring rings: | key | default | what it says | | --- | --- | --- | @@ -550,14 +552,85 @@ the corner. Refused, each before anything is written and naming the field and index: a missing or unknown key; a non-finite number; fewer than 2 or more than 64 rings or points; rings of unequal counts; a quad under 1e-8 m2 (a collapsed corner); a mirrored ring that does not start on x = 0 or has a point behind it; `mirror` with `closed`; a run out -of range or with `from` not under `to`; a weight outside 0 to 1; more than 262144 subdivided faces (cage quads -times 4 to the `levels`). +of range or with `from` not under `to`; a weight outside 0 to 1; more than 262144 subdivided faces (a quad gives +4 to the `levels`, a triangle three quarters of that). On the pauldron (25 cage quads, 1600 subdivided faces, 3360 with the wall), `shell` took 3.5 ms a call with Blender's own update after it, and one whole evaluation of the Subdivision and Solidify 1.7 ms. With six cutters (four panel lines, two insets) and ribs under it, a rebuild took 0.92 s, which is its one Boolean evaluation. Medians of 3, interleaved, Blender 5.3 on Starfire (`tests/live/kitbash_faceted.py`, `costs`). +### A free cage + +A loft is a grid: every vertex off its boundary has four edges, so it cannot state a triangle, a pole, or a crease +that ends inside the surface. A hull modelled by hand uses all three. The bar is the fewest cage vertices that +hold the form, with creases doing the work: a dense cage that only looks smooth after subdivision is the failure. +The free form states the cage directly: + +| key | default | what it says | +| --- | --- | --- | +| `verts` | required | 4 to 256 `[x, y, z]` in the shell's own frame | +| `faces` | required | each 3 or 4 vertex indices, counter-clockwise seen from outside | +| `creases` | `[]` | `[a, b, w]`: the edge between vertices a and b, weight 0 to 1 | +| `corners` | `[]` | `[vertex, w]`: a vertex held as a corner | +| `poles` | `[]` | the vertices of irregular valence, by index: a gate, below | +| `mirror` | `false` | the cage is authored on one side of x = 0 and reflected | +| `rim` | `1` | the weight of every boundary edge no crease names | +| `flip` | `false` | reverse every face | + +```json +{"verts": [[0, 0, 0.5], [1, 0, 0], [0, 1, 0], [-1, 0, 0], [0, -1, 0], [1, 0, -1], [0, 1, -1]], + "faces": [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [2, 1, 5, 6]], + "creases": [[0, 1, 1.0], [0, 3, 1.0]], "poles": [1, 2], "rim": 0} +``` + +**Mirror.** Every vertex stands on one side of x = 0 (either side, all the same). One within 0.005 m of the +plane is on the seam: it is snapped to x = 0 and shared by both halves. The others are reflected (the k-th of +them is vertex `len(verts) + k`), each face gets a reversed twin, and creases, corners and poles land on both +halves. A vertex 0.006 m off the plane is not on the seam: the cage is open there. A face lying on the plane, +and an edge on the plane that two authored faces share (a fin), are refused. + +**The pole gate.** A vertex's valence is the number of cage edges at it, on the cage as built (after the +mirror). A pole is a vertex whose valence is not 4 off the boundary, or not 2 or 3 on it. `poles` must list +exactly the poles the faces make. An undeclared pole and a declared vertex that is none are both refused, naming +the vertex and its valence. The list changes nothing in the mesh: it is there so that no pole is an accident, +since a pole is where a subdivision surface pinches or flattens. Put one where a crease runs through it or a +triangle stands beside it, and where the form turns anyway. + +**Triangles.** A triangle subdivides to three quads, so after one level the surface is all quads, and the wall, +`cut`, `ribs` and `count_folds` take it as any shell. Use one where a crease run ends: the two cage edges +either side of the crease close onto a point instead of carrying a loop across the rest of the form. Faces of +five or more sides are refused. + +**Budget.** Two cages modelled by hand are the measure. A whole ship hull, 1 m long: 46 control vertices (29 +authored under a mirror), 25 faces a side of which 6 are triangles, 9 creased edges a side, every one at weight +1, six poles, each on a crease or beside a triangle. A petal: 10 vertices, 4 quads and 6 triangles, 5 creased +ridges at weight 1, an uncreased outline. In both the creases are full weight and stand only where the form +truly breaks (turns of 40 to 170 degrees); the longest straight silhouette edges are single cage edges; the cage's +vertices stand outside the form, as subdivision shrinks toward the inside. An armour plate should cost about what +the petal does. Add a vertex only where the limit surface cannot otherwise reach the form, and say why. + +**Refused**, before anything is written and naming the field and index: fewer than 4 or more than 256 vertices; +a vertex in no face; a face of other than 3 or 4 indices, with a repeated or out-of-range index, with another +face's vertices, or under 1e-8 m2; an edge in three faces; two faces crossing an edge the same way (wound +against each other); a crease on no cage edge; two weights for one edge or point; a mirrored cage with vertices +on both sides; the pole gate. `closed` and the loft's crease runs belong to the loft and are refused here, as +`poles`, `corners` and `verts` are on a loft. + +**The report** carries, for both forms, `cageVerts`, `cageFaces`, `triangles`, `creases`, `corners`, `poles` +(`{"3": 2, "5": 1}`: valence to how many vertices, on the cage as built) and `closed` (no boundary edge); +`rings` and `points` are null on a free cage. + +**What it gives up.** A free cage is authored by index, by hand or by an agent: nothing derives it from a +silhouette, and a wrong index is caught only where it breaks a rule above, not where it merely makes a worse form. +There are no pentagons. A loft remains the shorter description of anything that is a grid. + +**Reading and scoring a cage.** `tools/cage_export.py` writes an object of a `.blend` copy as a free cage document +(seam snapped, creases from `crease_edge`, poles computed); it writes only that document and never saves the +`.blend`. `tools/cage_score.py` builds two documents through `shell` and reports, raw and with no pass bar, each +one's counts, the distance between their level-3 limit surfaces (median, 95th centile and worst, as a share of +the reference's largest extent), silhouette overlap from +x, +y and +z, and how far apart their creased curves run. + ## Cutting a shell An armor plate is not a kit part: it is any mesh, usually one made by `shell`. `cut` cuts it, or a From 1755ffaada77602626cc13e66fd57794dc4e4504 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 03:49:11 +0100 Subject: [PATCH 169/223] brokkr_kitbash free cage: boundary smoothed as a hand-modelled cage's (Sheet.boundary; All on a free cage, Keep Corners on a loft); the seam relative to extent and read before the side; a pinched vertex refused by its fans; flip and the quad's area pinned cage_export writes vertices as authored (core.sheet owns the seam) and refuses a Subdivision at Keep Corners. cage_score: distance each way with area-weighted mean and Hausdorff; crease agreement read off the surfaces' sharp edges (miss, spur) in place of the cage-tag chamfer; cost = fit + complexity after Hoppe et al. 1994. Live kitbash_cage: the open-plate round trip with its bound, the cost ranking on a creased box, exact wall counts, bounds compared as they stand (lodur:ruling:deterministic-bound-margin). Fix batch h2 for aetheria-release:verdict:cut-kit-minimal-cage.s1. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 2 +- .../brokkr_kitbash/brokkr_actions.json | 2 +- surfaces/blender/brokkr_kitbash/core.py | 48 +++++-- surfaces/blender/docs/kitbash.md | 46 +++++-- surfaces/blender/tests/live/kitbash_cage.py | 129 ++++++++++++++---- .../tests/live/kitbash_cage.result.json | 49 +++++-- surfaces/blender/tests/test_kitbash.py | 27 +++- surfaces/blender/tools/cage_export.py | 22 +-- surfaces/blender/tools/cage_score.py | 114 ++++++++++------ 9 files changed, 321 insertions(+), 118 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index b7c3119..19c7090 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1648,7 +1648,7 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): context.scene.collection.objects.link(obj) smooth = obj.modifiers.get(SUBSURF) or obj.modifiers.new(SUBSURF, "SUBSURF") smooth.levels = smooth.render_levels = self.levels - smooth.subdivision_type, smooth.boundary_smooth, smooth.use_creases = "CATMULL_CLARK", "PRESERVE_CORNERS", True + smooth.subdivision_type, smooth.boundary_smooth, smooth.use_creases = "CATMULL_CLARK", built.boundary, True wall = obj.modifiers.get(SOLIDIFY) or obj.modifiers.new(SOLIDIFY, "SOLIDIFY") wall.thickness, wall.offset, wall.use_even_offset, wall.use_rim = self.thickness, self.offset, True, True sync_bevel(obj, self.bevel) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 3114140..93be89c 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -804,7 +804,7 @@ }, { "name": "brokkr_kitbash.shell", - "doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object in one of two forms, a loft of rings or a free cage; exactly one of rings and verts. The loft: {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The free cage, for a form a few vertices and creases hold: {\"verts\": 4 to 256 [x, y, z]; \"faces\": each 3 or 4 vertex indices, counter-clockwise seen from outside; \"creases\": [[a, b, w]], an edge by its two vertices, weight 0 to 1; \"corners\": [[vertex, w]]; \"poles\": the vertex indices of irregular valence (not 4 off the boundary, not 2 or 3 on it); \"mirror\": every vertex is authored on one side of x = 0, one within 0.005 m of it is on the seam (snapped to x = 0 and shared), the others are reflected with their faces, creases, corners and poles (false); \"rim\" and \"flip\" as on the loft}. The pole gate: poles must equal the poles the faces make, or the sheet is refused naming each undeclared pole and each declared vertex that is none, with its valence. A free cage is also refused for a vertex in no face, a repeated index, a duplicate or collapsed face, an edge in three faces, two faces wound against each other, a crease on no edge, and a face or shared edge lying on the mirror plane. A triangle subdivides to three quads. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. A thickness the cage cannot hold is not refused: the wall folds over itself beside a tight crease or rim corner, and a cut there is unsound. count_folds evaluates the wall alone (Kit Subsurf and Kit Solidify, no Boolean; 4 ms on a plate of 1600 subdivided faces) and counts the folded inner faces; nothing else in the report reads an evaluated mesh, and no figure of the cage bounds the fold. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings and points (null on a free cage), cageVerts, cageFaces, triangles, creases, poles ({valence: how many vertices}, on the cage as built), closed (no boundary edge), folded (null unless count_folds: then the number of the wall's inner faces that fold over, counted on the evaluated wall; 0 is a wall with no folded face, which an Exact Boolean can still fail on just short of a fold: read nonManifoldEdges after cutting), corners, subdividedFaces, facing, thickness, offset, levels and children.", + "doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object in one of two forms, a loft of rings or a free cage; exactly one of rings and verts. The loft: {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The free cage, for a form a few vertices and creases hold: {\"verts\": 4 to 256 [x, y, z]; \"faces\": each 3 or 4 vertex indices, counter-clockwise seen from outside; \"creases\": [[a, b, w]], an edge by its two vertices, weight 0 to 1; \"corners\": [[vertex, w]]; \"poles\": the vertex indices of irregular valence (not 4 off the boundary, not 2 or 3 on it); \"mirror\": every vertex is authored on one side of x = 0, one within 0.005 of the cage's largest extent of it is on the seam (snapped to x = 0 and shared), the others are reflected with their faces, creases, corners and poles (false); \"rim\" and \"flip\" as on the loft}. The pole gate: poles must equal the poles the faces make, or the sheet is refused naming each undeclared pole and each declared vertex that is none, with its valence. A free cage is also refused for a vertex in no face, a repeated index, a duplicate or collapsed face, an edge in three faces, two faces wound against each other, a pinched vertex (its faces meet only at it), a crease on no edge, and a face or shared edge lying on the mirror plane. A triangle subdivides to three quads. The cage is subdivided (Kit Subsurf, creases kept; a loft's boundary keeps its corners, a free cage's is smoothed through every vertex, Boundary Smooth All, so pin a corner with corners) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. A thickness the cage cannot hold is not refused: the wall folds over itself beside a tight crease or rim corner, and a cut there is unsound. count_folds evaluates the wall alone (Kit Subsurf and Kit Solidify, no Boolean; 4 ms on a plate of 1600 subdivided faces) and counts the folded inner faces; nothing else in the report reads an evaluated mesh, and no figure of the cage bounds the fold. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings and points (null on a free cage), cageVerts, cageFaces, triangles, creases, poles ({valence: how many vertices}, on the cage as built), closed (no boundary edge), folded (null unless count_folds: then the number of the wall's inner faces that fold over, counted on the evaluated wall; 0 is a wall with no folded face, which an Exact Boolean can still fail on just short of a fold: read nonManifoldEdges after cutting), corners, subdividedFaces, facing, thickness, offset, levels and children.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index cd0db1c..71f3717 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1029,7 +1029,7 @@ def spans(flags, lengths, closed: bool, bridge: float, clearance: float) -> list SHEET_LIMIT = 64 # rings in a sheet, and authored points in a ring SHEET_AREA = 1e-8 # square metres: a cage quad under this is a collapsed corner MIRROR_EPS = 1e-6 # metres a mirrored ring's point 0 may stand off x = 0, and any of its points behind it -SEAM_EPS = 5e-3 # metres from x = 0 within which a mirrored free cage's vertex is on the seam: snapped to 0 and shared +SEAM_REL = 5e-3 # of a mirrored free cage's largest authored extent: a vertex that near x = 0 is on the seam, snapped to 0 and shared CAGE_VERTS = 256 # authored vertices in a free cage SHEET_KEYS = ("closed", "mirror", "creases", "rim", "flip") CAGE_KEYS = ("creases", "corners", "poles", "mirror", "rim", "flip") @@ -1041,7 +1041,10 @@ class Sheet(NamedTuple): pairs with weights (E,) in (0, 1]; corners (K,) are vertex indices with corner_weights (K,) in (0, 1]. On a loft vertex i * points + j is ring i's point j, of rings rings of points points (2C - 1 when mirrored); on a free cage rings and points are None, the authored vertices keep their indices and a mirror's reflections follow them. - poles (P,) are the cage's vertices of irregular valence, as built; triangles is how many faces have 3 sides.""" + poles (P,) are the cage's vertices of irregular valence, as built; triangles is how many faces have 3 sides. + boundary is the Subdivision's Boundary Smooth, by Blender's name: PRESERVE_CORNERS on a loft (a boundary vertex + of two edges stays a corner), ALL on a free cage (the boundary is smoothed through it unless a corner pins it), + which is how a cage modelled by hand is set.""" V: np.ndarray faces: np.ndarray counts: np.ndarray @@ -1055,6 +1058,7 @@ class Sheet(NamedTuple): points: int | None poles: np.ndarray triangles: int + boundary: str def _index(value: Any, where: str, least: int, most: int) -> int: @@ -1192,7 +1196,7 @@ def sheet(document: Any) -> Sheet: return Sheet(V=V.copy(), faces=quads.ravel().astype(np.int32), counts=np.full(len(quads), 4, dtype=np.int32), smooth=np.ones(len(quads), dtype=bool), sharp=NO_SHARP, creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64), corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N, - poles=np.zeros(0, dtype=np.int64), triangles=0) + poles=np.zeros(0, dtype=np.int64), triangles=0, boundary="PRESERVE_CORNERS") def _cage_facts(vertices: int, faces, counts): @@ -1246,12 +1250,15 @@ def _cage(document: Any, gate: bool = True) -> Sheet: verts: 4 to 256 [x, y, z]. faces: 3 or 4 vertex indices each, wound so the normal (counter-clockwise seen from outside) faces out; flip reverses every face. creases: [a, b, weight], an edge by its two vertices; corners: - [vertex, weight]. rim is the weight of every boundary edge no crease names. mirror: every vertex is authored on - one side of x = 0; one within SEAM_EPS of it is on the seam, snapped to x = 0 and shared; the others are + [vertex, weight]. rim is the weight of every boundary edge no crease names. The boundary is smoothed through + every vertex (Sheet.boundary ALL): a boundary vertex of two edges is a corner only where corners pins it or its + edges are creased apart. mirror: every vertex is authored on one side of x = 0; one within SEAM_REL of the + authored vertices' largest extent of it is on the seam, snapped to x = 0 and shared; the others are reflected (vertex len(verts) + k is the k-th of them), each face gets a reversed twin, and creases, corners and poles land on both halves. poles: the vertices of irregular valence on the cage as built (not 4 off the boundary, not 2 or 3 on it), by authored index. The list is a gate, not a setting: it must equal what the - faces make, so a pole is never an accident.""" + faces make, so a pole is never an accident. A vertex's faces are one fan, each joined to the next by an edge at + the vertex: one whose faces meet only at it (a pinched vertex) is refused.""" _keys(document, "sheet", ("verts", "faces"), CAGE_KEYS) flags = {} for key in ("mirror", "flip"): @@ -1282,12 +1289,13 @@ def _cage(document: Any, gate: bool = True) -> Sheet: V = np.array(verts, dtype=np.float64) seam = np.zeros(A, dtype=bool) if mirror: - if (V[:, 0] < -MIRROR_EPS).any() and (V[:, 0] > MIRROR_EPS).any(): - side = 1.0 if (V[:, 0] > MIRROR_EPS).sum() >= (V[:, 0] < -MIRROR_EPS).sum() else -1.0 + near = SEAM_REL * float(np.ptp(V, axis=0).max()) + seam = np.abs(V[:, 0]) <= near + V[seam, 0] = 0.0 # the seam first: a seam vertex may stand a hair on either side + if (V[:, 0] < 0).any() and (V[:, 0] > 0).any(): + side = 1.0 if (V[:, 0] > 0).sum() >= (V[:, 0] < 0).sum() else -1.0 worst = int((V[:, 0] * side).argmin()) raise KitError(f"sheet.verts[{worst}] has x = {V[worst, 0]:.6g}: a mirrored cage is authored on one side of x = 0, and the others stand on the {'+' if side > 0 else '-'}x side") - seam = np.abs(V[:, 0]) <= SEAM_EPS - V[seam, 0] = 0.0 seen, directed = {}, {} for f, face in enumerate(faces): key = tuple(sorted(face)) @@ -1295,7 +1303,7 @@ def _cage(document: Any, gate: bool = True) -> Sheet: raise KitError(f"sheet.faces[{f}] has the vertices of sheet.faces[{seen[key]}]: a duplicate face") seen[key] = f if mirror and all(seam[v] for v in face): - raise KitError(f"sheet.faces[{f}] lies on the mirror plane (every vertex within {SEAM_EPS:g} m of x = 0): its reflection is itself") + raise KitError(f"sheet.faces[{f}] lies on the mirror plane (every vertex within {near:.3g} m of x = 0, {SEAM_REL:g} of the cage's extent): its reflection is itself") corners = V[face] area = 0.5 * np.linalg.norm(np.cross(corners[1] - corners[0], corners[-1] - corners[0])) if len(face) == 4: @@ -1325,6 +1333,22 @@ def _cage(document: Any, gate: bool = True) -> Sheet: counts = np.array([len(face) for face in built], dtype=np.int32) flat = np.array([v for face in built for v in face], dtype=np.int32) cage_edges, boundary, valences, poles = _cage_facts(len(V), flat, counts) + fans: dict[int, list[tuple[set[int], list[int]]]] = {} # each vertex's faces, grouped while they share an edge at it + for f, face in enumerate(built): + for k, v in enumerate(face): + spokes, members, apart = {face[k - 1], face[(k + 1) % len(face)]}, [f], [] + for others, theirs in fans.get(v, []): + if others & spokes: + spokes, members = spokes | others, members + theirs + else: + apart.append((others, theirs)) + fans[v] = apart + [(spokes, members)] + pinched = min((v for v, parts in fans.items() if len(parts) > 1), default=None) + if pinched is not None: + named = lambda f: str(f) if f < len(faces) else f"{f - len(faces)} mirrored" # noqa: E731 + raise KitError(f"sheet.verts[{pinched}] is pinched: its faces meet only at it, in {len(fans[pinched])} fans (faces " + f"{' | '.join(', '.join(named(f) for f in sorted(theirs)) for _, theirs in sorted(fans[pinched], key=lambda part: min(part[1])))}). " + "A vertex's faces are one fan: join them by a face, or give each fan its own vertex") declared = document.get("poles", []) if gate else [int(v) for v in poles if v < A] if not isinstance(declared, list): @@ -1374,7 +1398,7 @@ def _cage(document: Any, gate: bool = True) -> Sheet: return Sheet(V=V, faces=flat, counts=counts, smooth=np.ones(len(counts), dtype=bool), sharp=NO_SHARP, creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64), corners=np.array([key for key, _ in held], dtype=np.int64), corner_weights=np.array([w for _, w in held], dtype=np.float64), - rings=None, points=None, poles=poles, triangles=int((counts == 3).sum())) + rings=None, points=None, poles=poles, triangles=int((counts == 3).sum()), boundary="ALL") # --- reports ------------------------------------------------------------------------------------------------- diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index b507720..211bf4e 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -584,11 +584,19 @@ The free form states the cage directly: "creases": [[0, 1, 1.0], [0, 3, 1.0]], "poles": [1, 2], "rim": 0} ``` -**Mirror.** Every vertex stands on one side of x = 0 (either side, all the same). One within 0.005 m of the -plane is on the seam: it is snapped to x = 0 and shared by both halves. The others are reflected (the k-th of -them is vertex `len(verts) + k`), each face gets a reversed twin, and creases, corners and poles land on both -halves. A vertex 0.006 m off the plane is not on the seam: the cage is open there. A face lying on the plane, -and an edge on the plane that two authored faces share (a fin), are refused. +**Boundary.** A free cage's open boundary is smoothed through every vertex (Kit Subsurf at Boundary Smooth All), +as the hand-modelled cages are set: an uncreased outline is a soft curve and a plate's tip is round. A boundary +vertex is a corner only where `corners` pins it at weight 1 or its two edges are creased apart by the form. A loft +keeps its corners (Keep Corners), as it always has. With the outline uncreased the two settings differ by 7.7% of +extent on a 3 m plate, so the setting is the form's and not a taste. + +**Mirror.** Every vertex off the seam stands on one side of x = 0 (either side, all the same). One within 0.005 +of the cage's largest authored extent of the plane (5 mm on a 1 m hull) is on the seam, on whichever side it +strays: it is snapped to x = 0 and shared by both halves, so a cage reads the same at any scale. The others are +reflected (the k-th of them is vertex `len(verts) + k`), each face gets a reversed twin, and creases, corners and +poles land on both halves. A vertex further off the plane is not on the seam: the cage is open there, and a face +that then meets its reflection at one vertex alone is refused as pinched. A face lying on the plane, and an edge +on the plane that two authored faces share (a fin), are refused. **The pole gate.** A vertex's valence is the number of cage edges at it, on the cage as built (after the mirror). A pole is a vertex whose valence is not 4 off the boundary, or not 2 or 3 on it. `poles` must list @@ -613,7 +621,8 @@ the petal does. Add a vertex only where the limit surface cannot otherwise reach **Refused**, before anything is written and naming the field and index: fewer than 4 or more than 256 vertices; a vertex in no face; a face of other than 3 or 4 indices, with a repeated or out-of-range index, with another face's vertices, or under 1e-8 m2; an edge in three faces; two faces crossing an edge the same way (wound -against each other); a crease on no cage edge; two weights for one edge or point; a mirrored cage with vertices +against each other); a pinched vertex, whose faces meet only at it and are not one fan, naming the fans; a crease +on no cage edge; two weights for one edge or point; a mirrored cage with vertices on both sides; the pole gate. `closed` and the loft's crease runs belong to the loft and are refused here, as `poles`, `corners` and `verts` are on a loft. @@ -626,10 +635,27 @@ silhouette, and a wrong index is caught only where it breaks a rule above, not w There are no pentagons. A loft remains the shorter description of anything that is a grid. **Reading and scoring a cage.** `tools/cage_export.py` writes an object of a `.blend` copy as a free cage document -(seam snapped, creases from `crease_edge`, poles computed); it writes only that document and never saves the -`.blend`. `tools/cage_score.py` builds two documents through `shell` and reports, raw and with no pass bar, each -one's counts, the distance between their level-3 limit surfaces (median, 95th centile and worst, as a share of -the reference's largest extent), silhouette overlap from +x, +y and +z, and how far apart their creased curves run. +(vertices as authored, creases from `crease_edge`, poles computed); it writes only that document and never saves +the `.blend`. `shell` builds that document as the object's own Subdivision draws it: an open plate with an +uncreased outline to 2e-5% of its extent, a mirrored hull to 0.28% (its seam snap). A Subdivision at Keep Corners +is refused, saying how to state the corners. + +`tools/cage_score.py` builds two documents through `shell` and reports, with no pass bar and every figure a share +of the reference's largest extent: each one's counts; the distance between their level-3 surfaces, whose vertices +lie on the limit surface, each way and together (area-weighted mean, Hausdorff, median, 95th centile); silhouette +overlap along x, y and z; and `crease`, where each surface is sharp (level-3 edges turning 30 degrees or more, +read off the surface, not off the crease weights): `missPct`, how far the reference's sharp features lie from the +agent's, and `spurPct`, the reverse; 100 when one side has them and the other none. The headline is `cost`, after +the energy of Hoppe et al., *Piecewise Smooth Surface Reconstruction* (1994), fit plus complexity: +`fit = meanPct + hausdorffPct + (missPct + spurPct) / 2`, `complexity = 0.01 * cageVerts + 0.002 * creases` of the +agent's cage, a sharp edge a fifth of a vertex as in the paper. Lower is better; a cage against itself costs its +complexity. On the 46-vertex hull: itself 0.50, every vertex 0.5% off 1.26, one vertex moved 5% 1.56, nine more +edges creased 5.49, every edge creased 16.2, no crease 16.6. The median and the silhouettes cannot make that +order: a moved vertex leaves the median at 0 and every silhouette at 1, and the creaseless cage has the lower +median of the two. What the cost gives up: the three fit terms are summed at weight 1 and the vertex price is a +chosen 0.01, knobs and not measurements; the Hausdorff term is one point, so one stray vertex costs as much as +a broad error of the same size; and sharpness is a 30 degree threshold, so a crease softer than that is not a +feature to it. ## Cutting a shell diff --git a/surfaces/blender/tests/live/kitbash_cage.py b/surfaces/blender/tests/live/kitbash_cage.py index b10fe49..e3a2724 100644 --- a/surfaces/blender/tests/live/kitbash_cage.py +++ b/surfaces/blender/tests/live/kitbash_cage.py @@ -1,8 +1,9 @@ """Live proof, in a background Blender, of brokkr_kitbash.shell's free cage through run_intent: a cage of triangles and quads with declared poles becomes a shell whose subdivided face count is the reported one at each level, takes a wall, counts folds and is cut; a mirrored cage closes over its seam; a loft shell is rebuilt in place as a free cage -under its cutters; the pole gate refuses without writing; and tools/cage_export.py and tools/cage_score.py read a -cage back and score it. Not part of the unittest run: it needs Blender. +under its cutters; the pole gate refuses without writing; tools/cage_export.py reads a cage back, an open one +included, as its maker's Subdivision draws it; and tools/cage_score.py ranks a near copy, a moved vertex, an +over-creased and a creaseless cage in that order. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_cage.py -- @@ -10,7 +11,8 @@ Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USE 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 reading and -the least claimed mutant's, both written beside it; the result file carries the readings. The checks run inside +its mutant's, both written beside it, and is compared as it stands; an order between two readings asks 1.2 +between them; the result file carries the readings. The checks run inside one try: an uncaught error is a failed check that names its section, and the result file is always written. """ import importlib.util @@ -61,11 +63,16 @@ COUNT, SECTION = [0], ["setup"] # creased ridge. Shipped 71; least claimed mutant 16 (K1, the free form's creases not written to crease_edge: the # ridge subdivides smooth), read here by clearing the attribute; the geometric mean, separation 2.1 each side. CRISP = 34.0 -# Per cent of the reference's extent: cage_score's median surface distance between the tent and the tent with its apex -# moved 5% of the extent. Shipped (a cage against itself) 0, read as 5e-6 (1e-7 m, what a float32 mesh is good to, of -# a 2 m extent); least claimed mutant 0.68 (the moved apex); the geometric mean, separation 370 each side. The moved -# apex's silhouette reads IoU 0.95 along y, under 1: checked as a strict inequality, not bounded. -SAME = 1.8e-3 +# Per cent of the reference's extent: cage_score's Hausdorff distance. Shipped (the tent against itself) 0, read as +# 5e-5 (the reading is rounded to 1e-4); the mutant is one stated move, the apex lifted 5% of the extent, 3.3; the +# geometric mean, separation 260 each side. A smaller move is not claimed. +SAME = 1.3e-2 +# Per cent of extent: the worst distance, both ways, between an open plate as Blender's Subdivision at Boundary Smooth +# All draws it and as shell builds cage_export's document of it. Shipped 1.7e-5; mutant B1 (the shell's Kit Subsurf at +# Keep Corners, read here by setting it) 7.7; the geometric mean, separation 670 each side. A closed cage does not tell +# the two apart, and a hand-modelled hull's own round trip is 0.28 (its seam snap): the open plate stands inside that. +OPEN = 1.1e-2 + # A tent: four triangles round an apex of valence 4 with two ridges creased, and a quad hung under one edge: 7 # vertices, vertices 1 and 2 boundary poles of valence 4. @@ -145,7 +152,7 @@ try: check(f"a cage of 4 triangles and a quad at {levels} levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads", receipt["status"] == "accepted" and report["subdividedFaces"] == expected == faces and sides == {4}, [receipt["message"], expected, faces, sides]) check(f"at {levels} levels the wall is closed, twice the surface and a rim, and count_folds counts none folded", - closed and walled > 2 * expected and report["folded"] == 0, [closed, walled, report and report["folded"]]) + closed and walled == 2 * expected + 6 * 2 ** levels and report["folded"] == 0, [closed, walled, report and report["folded"]]) # the tent's boundary is 6 cage edges built = core.sheet(TENT) check("the report carries the cage's facts: 7 vertices, 5 faces of which 4 triangles, 2 creases, two poles of valence 4, open; rings and points null", report and {k: report[k] for k in ("rings", "points", "cageVerts", "cageFaces", "triangles", "creases", "corners", "poles", "closed")} @@ -165,16 +172,15 @@ try: attribute.data.foreach_set("value", kept) tent.data.update() R["readings"].update({"crispDegrees": crisp, "crispDegreesK1": soft}) - check(f"the creased ridge stays an edge under subdivision: over {CRISP} degrees, and under it with crease_edge cleared", crisp > CRISP * 1.2 and soft < CRISP / 1.2, [crisp, soft]) + check(f"the creased ridge stays an edge under subdivision: over {CRISP} degrees, and under it with crease_edge cleared", crisp > CRISP and soft < CRISP, [crisp, soft]) # --- cut ------------------------------------------------------------------------------------------------------------- section("live-free-cage-shell") receipt, cut = send("brokkr_kitbash.cut_many", object_name="Tent", cuts=json.dumps(CUTS)) plate = evaluated(tent) - uncut = 2 * (4 ** 3 + 12 * 4 ** 2) - check("cut_many cuts a free-cage shell: the Boolean stands after the wall, the plate has more faces than the wall and no non-manifold edge", - receipt["status"] == "accepted" and [m.name for m in tent.modifiers] == ["Kit Subsurf", "Kit Solidify", "Kit Difference"] and len(plate.faces) > uncut + 20 - and sum(1 for e in plate.edges if not e.is_manifold) == 0, [receipt["message"], len(plate.faces), sum(1 for e in plate.edges if not e.is_manifold)]) + check("cut_many cuts a free-cage shell: the Boolean stands after the wall, the plate has more faces than the wall it was cut from (a Boolean that cut nothing leaves as many) and no non-manifold edge", + receipt["status"] == "accepted" and [m.name for m in tent.modifiers] == ["Kit Subsurf", "Kit Solidify", "Kit Difference"] and len(plate.faces) > walled + and sum(1 for e in plate.edges if not e.is_manifold) == 0, [receipt["message"], len(plate.faces), walled, sum(1 for e in plate.edges if not e.is_manifold)]) plate.free() # --- mirror ---------------------------------------------------------------------------------------------------------- @@ -233,24 +239,95 @@ try: probe.modifiers.new("Subdivision", "SUBSURF") document = cage_export.export(probe, core) exported = document["sheet"] - check("cage_export reads a mirrored, creased mesh as the free cage it is: the seam snapped, the creases by vertex pair, mirror set, rim 0, the poles computed, and core.sheet takes it", - exported["verts"][1] == [0.0, 0.0, 0.3] and exported["faces"] == HULL["faces"] and exported["creases"] == [[0, 4, 1.0], [2, 4, 1.0]] and exported["mirror"] is True + check("cage_export reads a mirrored, creased mesh as the free cage it is: the vertices as authored and the seam snapped when built, the creases by vertex pair, mirror set, rim 0, the poles computed, and core.sheet takes it", + exported["verts"][1] == [0.004, 0.0, 0.3] and core.sheet(exported).V[1].tolist() == [0.0, 0.0, 0.3] and exported["faces"] == HULL["faces"] and exported["creases"] == [[0, 4, 1.0], [2, 4, 1.0]] and exported["mirror"] is True and exported["rim"] == 0.0 and exported["poles"] == [] and document["modifiers"] == [["MIRROR", "Mirror"], ["SUBSURF", "Subdivision"]] and np.array_equal(core.sheet(exported).faces, core.sheet(HULL).faces), document) bpy.data.objects.remove(probe) + # an open plate as a person leaves one: a bulge, one creased ridge, an uncreased outline, Subdivision at Boundary Smooth All + grid = [[i - 1.5, j - 1.5, 0.4 * math.cos(i - 1.5) * math.cos(j - 1.5)] for i in range(4) for j in range(4)] + open_plate = bpy.data.objects.new("Open Plate", bpy.data.meshes.new("Open Plate")) + bpy.context.scene.collection.objects.link(open_plate) + open_plate.data.from_pydata(grid, [], [[4 * i + j, 4 * i + 4 + j, 4 * i + 5 + j, 4 * i + 1 + j] for i in range(3) for j in range(3)]) + open_plate.data.update(calc_edges=True) + weights = open_plate.data.attributes.new("crease_edge", "FLOAT", "EDGE") + for e in open_plate.data.edges: + weights.data[e.index].value = 1.0 if all(v // 4 == 1 for v in e.vertices) else 0.0 + by_hand = open_plate.modifiers.new("Subdivision", "SUBSURF") + by_hand.levels, by_hand.boundary_smooth = 3, "ALL" + bm = evaluated(open_plate) + VH = np.array([v.co[:] for v in bm.verts]) + TH = np.array([[f.verts[0].index, f.verts[k].index, f.verts[k + 1].index] for f in bm.faces for k in (1, 2)]) + bm.free() + document = cage_export.export(open_plate, core) + receipt, report = send("brokkr_kitbash.shell", object_name="Open Shell", sheet=json.dumps(document["sheet"]), levels=3, thickness=0.001) + shell_obj = bpy.data.objects["Open Shell"] + worst = {} + for mode in ("ALL", "PRESERVE_CORNERS"): # the second is B1 + kept, shell_obj.modifiers["Kit Subsurf"].boundary_smooth = shell_obj.modifiers["Kit Subsurf"].boundary_smooth, mode + VS, TS, _, _ = cage_score.surface(shell_obj) + worst[mode] = float(max(cage_score.nearest(VS, VH, TH).max(), cage_score.nearest(VH, VS, TS).max()) / np.ptp(VH, axis=0).max() * 100.0) + shell_obj.modifiers["Kit Subsurf"].boundary_smooth = kept + R["readings"].update({"openRoundTripPct": worst["ALL"], "openRoundTripPctB1": worst["PRESERVE_CORNERS"]}) + check(f"an open cage round-trips: shell builds cage_export's document of a plate with an uncreased outline as its Subdivision (Boundary Smooth All) draws it, under {OPEN}% of extent, and over it at Keep Corners", + receipt["status"] == "accepted" and kept == "ALL" and report["closed"] is False and document["sheet"]["corners"] == [] and worst["ALL"] < OPEN < worst["PRESERVE_CORNERS"], [receipt["message"], worst]) + by_hand.boundary_smooth = "PRESERVE_CORNERS" + try: + cage_export.export(open_plate, core) + said = None + except core.KitError as error: + said = str(error) + check("cage_export refuses a Subdivision at Keep Corners, saying how to state the corners", said is not None and "Boundary Smooth Keep Corners" in said and "vertex crease of 1" in said, said) + bpy.data.objects.remove(shell_obj) + bpy.data.objects.remove(open_plate) + + # --- score-ranks --------------------------------------------------------------------------------------------------- + section("score-ranks") tent_document = {**TENT, "rim": 1.0} held = state() same = cage_score.score(tent_document, tent_document, send) - check("cage_score of a cage against itself: equal counts, distance 0, every silhouette IoU 1, crease chamfer 0, and its two shells removed again", - same["agent"] == same["reference"] and same["agent"]["cageVerts"] == 7 and same["distance"]["maxPct"] < SAME / 1.2 and set(same["silhouetteIoU"].values()) == {1.0} - and same["creaseChamferPct"] == 0.0 and state() == held, same) - moved = {**tent_document, "verts": [[0.0, 0.0, 0.5 + 0.05 * 2.0]] + TENT["verts"][1:]} # the apex lifted 5% of the 2 m extent - apart = cage_score.score(moved, tent_document, send) - R["readings"].update({"scoreSameMedianPct": same["distance"]["medianPct"], "scoreMovedMedianPct": apart["distance"]["medianPct"], "scoreMovedIoUy": apart["silhouetteIoU"]["y"], - "scoreMovedChamferPct": apart["creaseChamferPct"]}) - check("cage_score of the cage with one vertex moved 5% of the extent: distance above the bound, a silhouette under 1, a crease chamfer above 0, the counts still equal", - apart["distance"]["medianPct"] > SAME * 1.2 and apart["distance"]["maxPct"] > 1.0 and min(apart["silhouetteIoU"].values()) < 1.0 and apart["creaseChamferPct"] > 0.0 - and apart["agent"] == apart["reference"] and abs(apart["extent"] - same["extent"]) < 1e-9, apart) + check("cage_score of a cage against itself: equal counts, distance 0, every silhouette IoU 1, no sharp feature missed or spurious, the cost its complexity alone, and its two shells removed again", + same["agent"] == same["reference"] and same["agent"]["cageVerts"] == 7 and same["distance"]["hausdorffPct"] < SAME and set(same["silhouetteIoU"].values()) == {1.0} + and (same["crease"]["missPct"], same["crease"]["spurPct"]) == (0.0, 0.0) and same["crease"]["agentSharp"] == same["crease"]["referenceSharp"] > 0 + and same["cost"]["complexity"] == round(7 * cage_score.C_REP + 8 * cage_score.C_SHARP, 4) and abs(same["cost"]["total"] - same["cost"]["complexity"]) < SAME and state() == held, same) + lifted = cage_score.score({**tent_document, "verts": [[0.0, 0.0, 0.5 + 0.05 * 2.0]] + TENT["verts"][1:]}, tent_document, send) # the apex lifted 5% of the 2 m extent + R["readings"].update({"scoreSameHausdorffPct": same["distance"]["hausdorffPct"], "scoreLiftedHausdorffPct": lifted["distance"]["hausdorffPct"]}) + check("cage_score of the tent with its apex lifted 5% of the extent: Hausdorff distance above the bound, a silhouette under 1, the counts and the extent still the reference's", + lifted["distance"]["hausdorffPct"] > SAME and min(lifted["silhouetteIoU"].values()) < 1.0 and lifted["agent"] == lifted["reference"] and abs(lifted["extent"] - same["extent"]) < 1e-9, lifted) + + # A box of 26 vertices and 24 quads, its lid's outline creased: the reference. Four agents against it. + points = [(x, y, z) for x in (-1, 0, 1) for y in (-1, 0, 1) for z in (-1, 0, 1) if (x, y, z) != (0, 0, 0)] + at = {point: k for k, point in enumerate(points)} + quads = [] + for axis in range(3): + for side in (-1, 1): + for a in (-1, 0): + for b in (-1, 0): + quad = [] + for da, db in ((0, 0), (1, 0), (1, 1), (0, 1)): + point = [0, 0, 0] + point[axis], point[(axis + 1) % 3], point[(axis + 2) % 3] = side, a + da, b + db + quad.append(at[tuple(point)]) + quads.append(quad if side > 0 else quad[::-1]) + cage_edges = sorted({tuple(sorted((q[k], q[k - 1]))) for q in quads for k in range(4)}) + BOX = {"verts": [[0.6 * x, 1.0 * y, 0.4 * z] for x, y, z in points], "faces": quads, + "creases": [[a, b, 1.0] for a, b in cage_edges if points[a][2] == points[b][2] == 1 and (0, 0, 1) not in (points[a], points[b])]} + BOX["poles"] = core.poles(BOX) + shaken = (np.array(BOX["verts"]) + np.random.default_rng(7).normal(size=(26, 3)) * 0.005 * 2.0 / math.sqrt(3)).round(6).tolist() + agents = {"Self": BOX, "Near": {**BOX, "verts": shaken}, # every vertex off by 0.5% of the 2 m extent + "Moved": {**BOX, "verts": [[v[0], v[1] + 0.05 * 2.0, v[2]] if k == at[(1, 1, 1)] else v for k, v in enumerate(BOX["verts"])]}, # one vertex, 5% of the extent + "Over": {**BOX, "creases": [[a, b, 1.0] for a, b in cage_edges]}, # every edge creased: the box as a polyhedron + "Bare": {**BOX, "creases": []}} # no crease: a smooth blob + read = {label: cage_score.score(agent, BOX, send) for label, agent in agents.items()} + cost = {label: reading["cost"]["total"] for label, reading in read.items()} + R["readings"].update({f"cost{label}": value for label, value in cost.items()}) + R["readings"].update({"costMovedHausdorffPct": read["Moved"]["distance"]["hausdorffPct"], "costBareMissPct": read["Bare"]["crease"]["missPct"], "costOverSpurPct": read["Over"]["crease"]["spurPct"]}) + check("the cost ranks: the reference itself is cheapest, and a near copy (every vertex 0.5% off) beats a creaseless cage, each by 1.2 or more", + len(BOX["creases"]) == 8 and cost["Self"] * 1.2 < cost["Near"] and cost["Near"] * 1.2 < cost["Bare"] and read["Bare"]["crease"]["missPct"] > read["Near"]["crease"]["missPct"], [cost, read["Bare"]["crease"]]) + check("one vertex moved 5% of the extent registers: its Hausdorff distance is over the bound and its cost 1.2 over the reference's own, though the median and the silhouettes barely see it", + read["Moved"]["distance"]["hausdorffPct"] > SAME and cost["Self"] * 1.2 < cost["Moved"], read["Moved"]) + check("an over-creased cage costs more than the reference, by its spurious sharp features and its sharp edges' price", + cost["Self"] * 1.2 < cost["Over"] and read["Over"]["crease"]["spurPct"] > 0.0 and read["Over"]["cost"]["complexity"] > read["Self"]["cost"]["complexity"], read["Over"]) except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:]) finally: diff --git a/surfaces/blender/tests/live/kitbash_cage.result.json b/surfaces/blender/tests/live/kitbash_cage.result.json index 449043c..4f40224 100644 --- a/surfaces/blender/tests/live/kitbash_cage.result.json +++ b/surfaces/blender/tests/live/kitbash_cage.result.json @@ -47,7 +47,7 @@ "detail": null }, { - "name": "cut_many cuts a free-cage shell: the Boolean stands after the wall, the plate has more faces than the wall and no non-manifold edge", + "name": "cut_many cuts a free-cage shell: the Boolean stands after the wall, the plate has more faces than the wall it was cut from (a Boolean that cut nothing leaves as many) and no non-manifold edge", "ok": true, "detail": null }, @@ -92,29 +92,62 @@ "detail": null }, { - "name": "cage_export reads a mirrored, creased mesh as the free cage it is: the seam snapped, the creases by vertex pair, mirror set, rim 0, the poles computed, and core.sheet takes it", + "name": "cage_export reads a mirrored, creased mesh as the free cage it is: the vertices as authored and the seam snapped when built, the creases by vertex pair, mirror set, rim 0, the poles computed, and core.sheet takes it", "ok": true, "detail": null }, { - "name": "cage_score of a cage against itself: equal counts, distance 0, every silhouette IoU 1, crease chamfer 0, and its two shells removed again", + "name": "an open cage round-trips: shell builds cage_export's document of a plate with an uncreased outline as its Subdivision (Boundary Smooth All) draws it, under 0.011% of extent, and over it at Keep Corners", "ok": true, "detail": null }, { - "name": "cage_score of the cage with one vertex moved 5% of the extent: distance above the bound, a silhouette under 1, a crease chamfer above 0, the counts still equal", + "name": "cage_export refuses a Subdivision at Keep Corners, saying how to state the corners", + "ok": true, + "detail": null + }, + { + "name": "cage_score of a cage against itself: equal counts, distance 0, every silhouette IoU 1, no sharp feature missed or spurious, the cost its complexity alone, and its two shells removed again", + "ok": true, + "detail": null + }, + { + "name": "cage_score of the tent with its apex lifted 5% of the extent: Hausdorff distance above the bound, a silhouette under 1, the counts and the extent still the reference's", + "ok": true, + "detail": null + }, + { + "name": "the cost ranks: the reference itself is cheapest, and a near copy (every vertex 0.5% off) beats a creaseless cage, each by 1.2 or more", + "ok": true, + "detail": null + }, + { + "name": "one vertex moved 5% of the extent registers: its Hausdorff distance is over the bound and its cost 1.2 over the reference's own, though the median and the silhouettes barely see it", + "ok": true, + "detail": null + }, + { + "name": "an over-creased cage costs more than the reference, by its spurious sharp features and its sharp edges' price", "ok": true, "detail": null } ], "hostErrors": [], "readings": { + "costBare": 58.0, + "costBareMissPct": 100.0, + "costMoved": 3.4, + "costMovedHausdorffPct": 2.7, + "costNear": 1.2, + "costOver": 27.0, + "costOverSpurPct": 22.0, + "costSelf": 0.28, "crispDegrees": 71.0, "crispDegreesK1": 16.0, - "scoreMovedChamferPct": 0.46, - "scoreMovedIoUy": 0.95, - "scoreMovedMedianPct": 0.68, - "scoreSameMedianPct": 0.0 + "openRoundTripPct": 1.7e-05, + "openRoundTripPctB1": 7.7, + "scoreLiftedHausdorffPct": 3.3, + "scoreSameHausdorffPct": 0.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 caa2e05..49d85e2 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -2031,6 +2031,7 @@ class CageTests(unittest.TestCase): for field in ("V", "faces", "counts", "smooth", "creases", "weights", "corners", "corner_weights", "poles"): self.assertEqual(getattr(free, field).tolist(), getattr(loft, field).tolist(), (field, extra)) self.assertEqual((free.rings, free.points, free.triangles, loft.triangles, len(loft.poles)), (None, None, 0, 0, 0)) + self.assertEqual((free.boundary, loft.boundary), ("ALL", "PRESERVE_CORNERS")) # the one field the form decides: a free cage's boundary is smoothed as a hand-modelled cage's self.assertEqual(core.cage_report(free), core.cage_report(loft)) plain = core.sheet({"rings": SheetTests.rings(3, 4)}) # rim defaults to 1 on the boundary edges of either form free = core.sheet({"verts": plain.V.tolist(), "faces": plain.faces.reshape(-1, 4).tolist()}) @@ -2039,12 +2040,19 @@ class CageTests(unittest.TestCase): def test_a_mirrored_cage_shares_its_seam(self): """free-cage-mirror. C2 (the seam duplicated: an open cage; the reflected faces not reversed): seam vertices - within SEAM_EPS are snapped and shared, the rest reflected, and creases, corners and poles land on both halves.""" + within SEAM_REL of the extent are snapped and shared, the rest reflected, and creases, corners and poles land + on both halves. S1 (the seam distance in metres, not of the extent): the same cage at 1% and at 100 times builds alike.""" verts = [[0.0, 0.0, 0.0], [0.004, 0.0, 1.0], [0.5, 0.0, 0.0], [0.5, 0.0, 1.0], [1.0, 0.2, 0.0], [1.0, 0.2, 1.0]] faces = [[0, 1, 3, 2], [2, 3, 5, 4]] # outside is +y built = core.sheet({"verts": verts, "faces": faces, "mirror": True, "creases": [[2, 3, 0.75]], "corners": [[4, 0.5], [0, 1.0]], "rim": 0.0}) self.assertEqual((len(built.V), built.counts.tolist()), (10, [4, 4, 4, 4])) - self.assertEqual(built.V[:2, 0].tolist(), [0.0, 0.0]) # 0.004 is inside SEAM_EPS: snapped + self.assertEqual(built.V[:2, 0].tolist(), [0.0, 0.0]) # 0.004 of an extent of 1 is inside SEAM_REL: snapped + for scale in (0.01, 100.0): # S1: at 1 cm an absolute 5 mm takes face 0 for the plane's; at 100 m it leaves vertex 1 off the seam + scaled = core.sheet({"verts": [[c * scale for c in v] for v in verts], "faces": faces, "mirror": True, "rim": 0.0}) + self.assertEqual((len(scaled.V), scaled.V[:2, 0].tolist(), scaled.faces.tolist()), (10, [0.0, 0.0], built.faces.tolist()), scale) + turned = core.sheet({"verts": verts, "faces": faces, "mirror": True, "flip": True, "rim": 0.0}) # F1 (flip ignored on a free cage): every face reversed, the reflected ones too + self.assertEqual(turned.faces.reshape(-1, 4).tolist(), [[2, 3, 1, 0], [4, 5, 3, 2], [0, 1, 7, 6], [6, 7, 9, 8]]) + self.assertEqual((turned.V.tolist(), SheetTests.weights(turned)), (built.V.tolist(), {})) self.assertEqual(built.V[6:].tolist(), [[-0.5, 0.0, 0.0], [-0.5, 0.0, 1.0], [-1.0, 0.2, 0.0], [-1.0, 0.2, 1.0]]) self.assertEqual(built.faces.reshape(-1, 4).tolist(), [[0, 1, 3, 2], [2, 3, 5, 4], [6, 7, 1, 0], [8, 9, 7, 6]]) V = built.V[built.faces.reshape(-1, 4)] @@ -2053,10 +2061,12 @@ class CageTests(unittest.TestCase): self.assertEqual((built.corners.tolist(), built.corner_weights.tolist()), ([0, 4, 8], [1.0, 0.5, 0.5])) edges, boundary, _, _ = core._cage_facts(len(built.V), built.faces, built.counts) self.assertEqual((edges[(0, 1)], (0, 1) in boundary, len(boundary)), (2, False, 10)) # the seam edge is interior - verts[1][0] = 0.006 # outside SEAM_EPS: reflected, not shared, and vertex 0 now joins four boundary edges - self.refused(r"sheet\.poles lacks vertex 0 \(valence 4, on the boundary\)", verts=verts, faces=faces, mirror=True) - apart = core.sheet({"verts": verts, "faces": faces, "mirror": True, "poles": [0]}) - self.assertEqual((len(apart.V), apart.V[6].tolist(), apart.poles.tolist()), (11, [-0.006, 0.0, 1.0], [0])) + verts[1][0] = 0.006 # outside the seam: reflected, not shared, so face 0 and its reflection meet at vertex 0 alone + self.refused(r"sheet\.verts\[0\] is pinched: its faces meet only at it, in 2 fans \(faces 0 \| 0 mirrored\)", verts=verts, faces=faces, mirror=True, poles=[0]) + verts[0][0] = 0.006 # both off the plane: two halves 12 mm apart, no vertex shared + apart = core.sheet({"verts": verts, "faces": faces, "mirror": True}) + self.assertEqual((len(apart.V), apart.V[6:8].tolist(), apart.poles.tolist()), (12, [[-0.006, 0.0, 0.0], [-0.006, 0.0, 1.0]], [])) + verts[0][0] = 0.0 fan_verts, fan_faces = self.fan(3) aside = core.sheet({"verts": [[x + 2.0, y, z] for x, y, z in fan_verts], "faces": fan_faces, "mirror": True, "poles": [0]}) self.assertEqual((aside.poles.tolist(), core.cage_report(aside)["poles"]), ([0, 7], {"3": 2})) # a pole off the seam stands on both halves @@ -2111,6 +2121,11 @@ class CageTests(unittest.TestCase): self.refused(r"sheet\.faces\[0\] lies on the mirror plane", verts=[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0]], faces=[[0, 1, 2], [0, 3, 1]], mirror=True) self.refused(r"sheet\.faces\[1\] has area 0 m2, under 1e-08: a collapsed face", verts=[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0]], faces=[[0, 1, 2], [1, 3, 4]]) + self.refused(r"sheet\.faces\[0\] has area 0 m2, under 1e-08: a collapsed face", verts=[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0]], faces=[[0, 1, 2, 3]]) + dart = core.sheet({"verts": [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [-1.0, 0.0, 0.0]], "faces": [[0, 1, 2, 3]]}) # Q1 (a quad's area read from its first corner alone): vertex 0 stands on the line from 3 to 1, and the quad has area 1 + self.assertEqual((dart.counts.tolist(), dart.poles.tolist()), ([4], [])) + self.refused(r"sheet\.verts\[2\] is pinched: its faces meet only at it, in 2 fans \(faces 0 \| 1\)\. A vertex's faces are one fan", # P1 (the fan check dropped): its valence 4 declared, it was taken + verts=[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [2.0, 1.0, 0.0], [2.0, 2.0, 0.0], [1.0, 2.0, 0.0]], faces=[[0, 1, 2, 3], [2, 4, 5, 6]], poles=[2]) self.refused(r"sheet states both rings and verts", rings=SheetTests.rings(), **ok) self.refused(r"sheet lacks 'rings' and 'verts'", creases=[]) self.refused(r"sheet\.verts must be 4 to 256 vertices, not 257", verts=[[0.0, 0.0, float(k)] for k in range(257)], faces=faces) diff --git a/surfaces/blender/tools/cage_export.py b/surfaces/blender/tools/cage_export.py index 5798062..2c44131 100644 --- a/surfaces/blender/tools/cage_export.py +++ b/surfaces/blender/tools/cage_export.py @@ -8,11 +8,15 @@ one mesh, writes (an absolute path) and nothing else, and never saves unless BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are private (tools/private_dirs.py). The document: {"object", "modifiers" (type and name, as stacked), "matrixWorld", "sheet"}. sheet is the cage in -the object's own frame, before any modifier: verts, faces, creases from the crease_edge attribute, corners from -crease_vert, mirror true when the object carries a Mirror across x (any other Mirror is refused), the seam -snapped as core.sheet snaps it (a vertex within SEAM_EPS of x = 0 goes to 0), rim 0 (a boundary edge carries the -crease it was given and no more), and poles as the faces make them (core.poles). The sheet is what core.sheet -accepts: a cage it would refuse (a face of five sides, a fin on the mirror plane) is refused here with its reason. +the object's own frame, before any modifier: verts as authored (core.sheet snaps the seam when it builds), faces, +creases from the crease_edge attribute, corners from crease_vert, mirror true when the object carries a Mirror +across x (any other Mirror is refused), rim 0 (a boundary edge carries the crease it was given and no more), and +poles as the faces make them (core.poles). The sheet is what core.sheet accepts: a cage it would refuse (a face of +five sides, a fin on the mirror plane) is refused here with its reason. + +A free cage's boundary is smoothed as Blender's Boundary Smooth: All smooths it (core.Sheet.boundary), the setting +of the hand-modelled cages this was made to read. A Subdivision set to Keep Corners draws another surface from the +same cage, so an object carrying one is refused, saying how to state its corners. """ import importlib.util import json @@ -40,12 +44,12 @@ def export(obj, core) -> dict: mirrors = [m for m in obj.modifiers if m.type == "MIRROR"] if len(mirrors) > 1 or mirrors and (tuple(mirrors[0].use_axis) != (True, False, False) or mirrors[0].mirror_object is not None): raise core.KitError(f"{obj.name!r} is mirrored otherwise than once across its own x: a free cage mirrors across x = 0 only") + kept = [m.name for m in obj.modifiers if m.type == "SUBSURF" and m.boundary_smooth != "ALL"] + if kept: + raise core.KitError(f"{obj.name!r} has its Subdivision {kept[0]!r} at Boundary Smooth Keep Corners, and a free cage smooths its boundary through every vertex: " + "set it to All and give each corner a vertex crease of 1, which draws the same surface") mesh = obj.data verts = [[round(float(c), 6) for c in v.co] for v in mesh.vertices] - if mirrors: - for point in verts: - if abs(point[0]) <= core.SEAM_EPS: - point[0] = 0.0 creases, corners = mesh.attributes.get("crease_edge"), mesh.attributes.get("crease_vert") sheet = {"verts": verts, "faces": [list(p.vertices) for p in mesh.polygons], "creases": sorted([*sorted(e.vertices), round(float(creases.data[e.index].value), 4)] for e in mesh.edges if creases.data[e.index].value > 0) if creases else [], diff --git a/surfaces/blender/tools/cage_score.py b/surfaces/blender/tools/cage_score.py index 72c2cbb..5780fcd 100644 --- a/surfaces/blender/tools/cage_score.py +++ b/surfaces/blender/tools/cage_score.py @@ -1,4 +1,5 @@ -"""Read how close one free cage comes to another: an agent's cage against a reference, both in one frame. +"""Read how close one free cage comes to another, and what it spends to get there: an agent's cage against a +reference, both in one frame. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tools/cage_score.py -- @@ -8,68 +9,78 @@ Subsurf alone: the tool measures what the tool builds. is an absolute no .blend is saved. It refuses to start unless BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are private (tools/private_dirs.py). -The result is a reading with no pass bar: +The result is a reading with no pass bar. Every percentage is of the reference surface's largest extent. agent, reference each cage's counts as shell reports them: cageVerts, cageFaces, triangles, creases, corners, poles, closed - extent the reference surface's largest extent, metres: the unit of every percentage - distance between the two level-3 surfaces, each one's vertices to the nearest point of the other, pooled: - medianPct, p95Pct, maxPct + extent the reference surface's largest extent, metres + distance between the two level-3 surfaces, whose vertices lie on the limit surface. Each one's vertices + to the nearest point of the other: agentToReference and referenceToAgent {meanPct, maxPct}, + the mean weighted by each vertex's share of its surface's area. meanPct is the mean of the two + means, hausdorffPct the larger of the two maxima (one moved vertex shows here), medianPct and + p95Pct the pooled centiles. silhouetteIoU orthographic silhouettes seen along x, y and z, 512 px across the two surfaces' common box: intersection over union - creaseChamferPct the creased cage edges (rim included, where its weight is over 0) as they lie on each level-3 - surface, sampled every 1% of extent: the mean distance from each curve's samples to the - other's, averaged both ways; null when either cage has no crease + crease where each surface is sharp, read off the surface and not off the cage's crease weights: the + level-3 edges between two faces that turn SHARP degrees or more, sampled every 1% of extent. + missPct is the mean distance from the reference's sharp samples to the agent's (a feature the + agent lacks), spurPct the reverse (a feature the reference lacks). A side with sharp samples + against one with none reads 100; two with none read 0. agentSharp and referenceSharp count the + sharp edges. + cost the headline, lower is better, after the energy of Hoppe et al., "Piecewise Smooth Surface + Reconstruction" (SIGGRAPH 1994), E = E_dist + c_rep * vertices + c_sharp * sharp edges: fit is + distance.meanPct + distance.hausdorffPct + the mean of crease.missPct and crease.spurPct; + complexity is C_REP per cage vertex and C_SHARP per creased cage edge of the agent, a sharp + edge a fifth of a vertex as in that paper; total is their sum. C_REP is the fit, in per cent + of extent, that one more cage vertex must buy. """ import importlib.util import json +import math import os import sys import types from pathlib import Path +import bmesh import bpy import numpy as np from mathutils import Vector from mathutils.bvhtree import BVHTree +from mathutils.kdtree import KDTree SURFACE = Path(__file__).resolve().parents[1] LEVELS, PIXELS, SPACING = 3, 512, 0.01 +SHARP = 30.0 # degrees between two level-3 faces at which their edge is a sharp feature +C_REP, C_SHARP = 0.01, 0.002 # per cent of extent: the price of a cage vertex, and of a creased cage edge COUNTS = ("cageVerts", "cageFaces", "triangles", "creases", "corners", "poles", "closed") def surface(obj): - """(V, triangles, creased polylines) of a shell read with its Kit Subsurf alone. A creased cage edge is found on - the subdivided mesh as Blender lays it out: the cage's vertices keep their indices, then each cage edge's 2^L - 1 - inner vertices follow in edge order; the chain is checked edge by edge against the mesh, not assumed.""" + """(V, triangles, area, sharp) of a shell read with its Kit Subsurf alone: area (len(V),) is each vertex's share + of the surface, sharp the (S, 2, 3) end points of the edges between two faces that turn SHARP degrees or more.""" hidden = [m for m in obj.modifiers if m.name != "Kit Subsurf" and m.show_viewport] for m in hidden: m.show_viewport = False try: bpy.context.view_layer.update() owner = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()) - mesh = owner.to_mesh() - V = np.array([v.co[:] for v in mesh.vertices], dtype=np.float64) - triangles = np.array([[p.vertices[0], p.vertices[k], p.vertices[k + 1]] for p in mesh.polygons for k in range(1, len(p.vertices) - 1)], dtype=np.int64) - edges = {tuple(sorted(e.vertices)) for e in mesh.edges} + bm = bmesh.new() + bm.from_mesh(owner.to_mesh()) owner.to_mesh_clear() finally: for m in hidden: m.show_viewport = True bpy.context.view_layer.update() - cage, inner = obj.data, 2 ** obj.modifiers["Kit Subsurf"].levels - 1 - weights = cage.attributes["crease_edge"].data - curves = [] - for e in cage.edges: - if weights[e.index].value <= 0: - continue - between = [len(cage.vertices) + e.index * inner + k for k in range(inner)] - for chain in ([e.vertices[0], *between, e.vertices[1]], [e.vertices[0], *between[::-1], e.vertices[1]]): - if all(tuple(sorted(pair)) in edges for pair in zip(chain, chain[1:])): - curves.append(V[chain]) - break - else: - raise SystemExit(f"cage_score: cage edge {tuple(e.vertices)} of {obj.name!r} is not where the subdivided mesh was expected to carry it; this Blender lays a Subdivision out otherwise") - return V, triangles, curves + bm.normal_update() + V = np.array([v.co[:] for v in bm.verts], dtype=np.float64) + triangles = np.array([[f.verts[0].index, f.verts[k].index, f.verts[k + 1].index] for f in bm.faces for k in range(1, len(f.verts) - 1)], dtype=np.int64) + area = np.zeros(len(V)) + for f in bm.faces: + for v in f.verts: + area[v.index] += f.calc_area() / len(f.verts) + sharp = np.array([[e.verts[0].co[:], e.verts[1].co[:]] for e in bm.edges if len(e.link_faces) == 2 and math.degrees(e.calc_face_angle()) >= SHARP], dtype=np.float64).reshape(-1, 2, 3) + bm.free() + return V, triangles, area, sharp def nearest(points, V, triangles): @@ -95,16 +106,23 @@ def silhouette(V, triangles, axis, low, scale): return mask -def sampled(curves, step): - points = [] - for curve in curves: - lengths = np.linalg.norm(np.diff(curve, axis=0), axis=1) - along = np.concatenate([[0.0], np.cumsum(lengths)]) - at = np.linspace(0.0, along[-1], max(2, int(np.ceil(along[-1] / step)) + 1)) - points.append(np.stack([np.interp(at, along, curve[:, k]) for k in range(3)], axis=1)) +def sampled(segments, step): + """Points along each segment, its ends included, no further apart than step.""" + points = [a + (b - a) * np.linspace(0.0, 1.0, max(2, int(np.ceil(np.linalg.norm(b - a) / step)) + 1))[:, None] for a, b in segments] return np.concatenate(points) if points else np.zeros((0, 3)) +def apart(P, Q, extent): + """The mean distance from P's points to the nearest of Q's, per cent of extent: 0 for no P, 100 for a P against no Q.""" + if not len(P) or not len(Q): + return 100.0 if len(P) else 0.0 + tree = KDTree(len(Q)) + for k, q in enumerate(Q): + tree.insert(q, k) + tree.balance() + return float(np.mean([tree.find(p)[2] for p in P])) / extent * 100.0 + + def score(agent: dict, reference: dict, send) -> dict: """The reading of two sheets. send(action, **fields) -> (receipt, report) runs an intent; the two shells it builds (Cage Score Agent, Cage Score Reference) are removed again.""" @@ -124,9 +142,12 @@ def score(agent: dict, reference: dict, send) -> dict: mesh = obj.data bpy.data.objects.remove(obj) bpy.data.meshes.remove(mesh) - (VA, TA, CA), (VB, TB, CB) = built["agent"], built["reference"] + (VA, TA, WA, SA), (VB, TB, WB, SB) = built["agent"], built["reference"] extent = float(np.ptp(VB, axis=0).max()) - d = np.concatenate([nearest(VA, VB, TB), nearest(VB, VA, TA)]) / extent * 100.0 + to_reference, to_agent = nearest(VA, VB, TB) / extent * 100.0, nearest(VB, VA, TA) / extent * 100.0 + pooled = np.concatenate([to_reference, to_agent]) + means = float(np.average(to_reference, weights=WA)), float(np.average(to_agent, weights=WB)) + mean, hausdorff = 0.5 * (means[0] + means[1]), float(pooled.max()) both = np.concatenate([VA, VB]) low = both.min(axis=0) scale = (PIXELS - 1) / float(np.ptp(both, axis=0).max()) @@ -134,14 +155,17 @@ def score(agent: dict, reference: dict, send) -> dict: for axis, label in enumerate("xyz"): a, b = silhouette(VA, TA, axis, low, scale), silhouette(VB, TB, axis, low, scale) overlap[label] = round(float((a & b).sum() / max(1, (a | b).sum())), 4) - chamfer = None - if CA and CB: - SA, SB = sampled(CA, SPACING * extent), sampled(CB, SPACING * extent) - away = lambda P, Q: float(np.mean([np.linalg.norm(Q - p, axis=1).min() for p in P])) # noqa: E731 - chamfer = round(0.5 * (away(SA, SB) + away(SB, SA)) / extent * 100.0, 4) + PA, PB = sampled(SA, SPACING * extent), sampled(SB, SPACING * extent) + miss, spur = apart(PB, PA, extent), apart(PA, PB, extent) + fit = mean + hausdorff + 0.5 * (miss + spur) + complexity = C_REP * reports["agent"]["cageVerts"] + C_SHARP * reports["agent"]["creases"] return {"levels": LEVELS, "agent": reports["agent"], "reference": reports["reference"], "extent": round(extent, 6), - "distance": {"medianPct": round(float(np.median(d)), 4), "p95Pct": round(float(np.percentile(d, 95)), 4), "maxPct": round(float(d.max()), 4)}, - "silhouetteIoU": overlap, "creaseChamferPct": chamfer} + "distance": {"meanPct": round(mean, 4), "hausdorffPct": round(hausdorff, 4), "medianPct": round(float(np.median(pooled)), 4), "p95Pct": round(float(np.percentile(pooled, 95)), 4), + "agentToReference": {"meanPct": round(means[0], 4), "maxPct": round(float(to_reference.max()), 4)}, + "referenceToAgent": {"meanPct": round(means[1], 4), "maxPct": round(float(to_agent.max()), 4)}}, + "silhouetteIoU": overlap, + "crease": {"sharpDegrees": SHARP, "missPct": round(miss, 4), "spurPct": round(spur, 4), "agentSharp": len(SA), "referenceSharp": len(SB)}, + "cost": {"fit": round(fit, 4), "complexity": round(complexity, 4), "total": round(fit + complexity, 4), "cRep": C_REP, "cSharp": C_SHARP}} def main() -> int: From a038e05520ce621c7904ba5aa49d8a2bc3acde9e Mon Sep 17 00:00:00 2001 From: Eureka Date: Thu, 3 Dec 2026 03:12:57 +0000 Subject: [PATCH 170/223] brokkr_reference: pair, lift_pair and the lift helpers deleted; PR 36 lands as flow_score and the honest lens band Camera-solve honesty, flow_score and hiding margin; lift_pair deleted (ruling lift-pair-held-for-redesign). Co-Authored-By: Claude Opus 5.5 --- surfaces/blender/brokkr_reference/__init__.py | 139 ++++++- .../brokkr_reference/brokkr_actions.json | 53 +++ surfaces/blender/brokkr_reference/core.py | 183 +++++++-- surfaces/blender/docs/reference.md | 105 ++++- .../blender/tests/live/reference.result.json | 10 +- surfaces/blender/tests/live/reference_flow.py | 276 +++++++++++++ .../tests/live/reference_flow.result.json | 385 ++++++++++++++++++ surfaces/blender/tests/test_reference.py | 192 ++++++++- 8 files changed, 1271 insertions(+), 72 deletions(-) create mode 100644 surfaces/blender/tests/live/reference_flow.py create mode 100644 surfaces/blender/tests/live/reference_flow.result.json diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index eb9d58f..4f93a0b 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -1,4 +1,5 @@ -"""Fit a scene to a reference image: the camera a reference view was drawn through, solved from marked points. +"""Fit a scene to a reference image: the camera a reference view was drawn through, solved from marked points, +and traced lines scored against the edges the camera sees on the build. A host add-on for Brokkr beside brokkr_mesh_polish (it imports that package's operator base, and nothing from Brokkr): brokkr_actions.json beside this file lists the operators agents may run (docs/reference.md). The @@ -6,14 +7,18 @@ arithmetic is core.py (numpy, tested without Blender); this file is the bpy arou JSON report to WindowManager.brokkr_mesh_polish_result, as the polish operators do. The camera record core.solve returns is the truth; a Blender camera stood at it is derived by core.blender, and -core.camera_of reads one back. The images, traces and masks a view is marked on stay with whoever marked them: -this package takes points and gives cameras. +core.camera_of reads one back (flow_score takes the camera that way, by its object's name). The images, traces +and masks a view is marked on stay with whoever marked them: this package takes points and lines and gives +cameras and scores. The edges flow_score reads are computed on each call and kept nowhere. """ bl_info = {"name": "Brokkr Reference", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), "category": "Camera", "description": "Solve a reference view's camera from marked points; agent-callable through Brokkr."} +import math + import bpy -from mathutils import Matrix +import numpy as np +from mathutils import Matrix, Vector try: from brokkr_mesh_polish import RESULT, PolishOperator, Refused @@ -75,7 +80,131 @@ class BROKKR_REFERENCE_OT_solve_camera(PolishOperator): return report -classes = (BROKKR_REFERENCE_OT_solve_camera,) +def record(context, name, box): + """The camera record of the scene camera `name` (core.camera_of), the frame being `box` on the image ('' for + the render's own frame from 0, 0).""" + obj = bpy.data.objects.get(name) + if obj is None or obj.type != "CAMERA": + raise Refused(f"{name!r} is not a camera object.") + data, render = obj.data, context.scene.render + if data.type != "PERSP": + raise Refused(f"camera {name!r} is {data.type}; a camera record is a perspective camera's.") + fit = "HORIZONTAL" if data.sensor_fit == "AUTO" and render.resolution_x >= render.resolution_y else data.sensor_fit + place, turn, _ = obj.matrix_world.decompose() # a scaled camera object draws the same picture + return core.camera_of({"matrix_world": [list(row) for row in Matrix.LocRotScale(place, turn, None)], "lens": data.lens, "shift_x": data.shift_x, "shift_y": data.shift_y, + "sensor_width": data.sensor_width, "sensor_fit": fit, "resolution": [render.resolution_x, render.resolution_y]}, + core.numbers(box, 4, "box") if box.strip() else None) + + +HIDE = 1e-3 # of a diagonal: a sight line stops this share of the edge's own piece of mesh short of the edge, so that the edge's own faces do not hide it; a surface nearer the edge than that hides it only from further than this share of its own object + + +def _diagonal(obj, placed, dg): + """The diagonal of an object's evaluated bounding box as `placed` (a world matrix) stands it.""" + return float(np.linalg.norm(np.ptp(np.array([placed @ Vector(corner) for corner in obj.evaluated_get(dg).bound_box]), axis=0))) + + +def built_edges(context, cam, objects, angle): + """The edges a camera record sees on the build as it stands, modifiers evaluated: creases (two faces meeting at + more than `angle` degrees, one of them toward the camera), contours (one face toward the camera, the other + away) and open borders, each kept where two of three points along it are hidden behind nothing: a ray from the + camera toward the point meets no surface nearer it than the hiding margin: HIDE of the diagonal of the edge's + own piece (the connected part of its mesh it lies on: a box joined into one mesh with a ground is still a + box) or of the object met, the smaller of the two, so the margin is the same share of the parts involved at + any scale and whatever else the scene or the mesh holds (a ground plane, a hull). Past the own piece's margin + the ray is cast once more, and the first surface it meets there decides; the object met is measured whole. `objects` are the meshes read; anything the + scene renders hides. Returns {kind: [[u0, v0, u1, v1], ...]} in the record's pixels.""" + scene, dg = context.scene, context.evaluated_depsgraph_get() + eye, out, cos_a = np.array(cam["C"]), {"crease": [], "contour": [], "border": []}, math.cos(math.radians(angle)) + + def hidden(p, short): + d = float(np.linalg.norm(p - eye)) + toward = (p - eye) / d + if scene.ray_cast(dg, Vector(eye), Vector(toward), distance=d - short)[0]: + return True + hit, where, _, _, other, placed = scene.ray_cast(dg, Vector(eye + toward * (d - short)), Vector(toward), distance=short) + return hit and d - float(np.linalg.norm(np.array(where) - eye)) > HIDE * _diagonal(other, placed, dg) + + for obj in objects: + ev = obj.evaluated_get(dg) + me = ev.to_mesh() + nv, ne, nl, nf = len(me.vertices), len(me.edges), len(me.loops), len(me.polygons) + if not nf: + ev.to_mesh_clear() + continue + co, ends, loop_edge, totals, normal, centre = np.empty(nv * 3), np.empty(ne * 2, np.int32), np.empty(nl, np.int32), np.empty(nf, np.int32), np.empty(nf * 3), np.empty(nf * 3) + me.vertices.foreach_get("co", co) + me.edges.foreach_get("vertices", ends) + me.loops.foreach_get("edge_index", loop_edge) + me.polygons.foreach_get("loop_total", totals) + me.polygons.foreach_get("normal", normal) + me.polygons.foreach_get("center", centre) + ev.to_mesh_clear() + world = np.array(obj.matrix_world) + co, centre = co.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3], centre.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3] + normal = normal.reshape(-1, 3) @ np.linalg.inv(world[:3, :3]) + normal /= np.maximum(np.linalg.norm(normal, axis=1), 1e-12)[:, None] + order = np.argsort(loop_edge, kind="stable") + faces, count = np.repeat(np.arange(nf), totals)[order], np.bincount(loop_edge, minlength=ne) + first = np.searchsorted(loop_edge[order], np.arange(ne)) + two = count == 2 + f0, f1 = faces[np.minimum(first, nl - 1)], faces[np.minimum(first + 1, nl - 1)] + toward = ((eye - centre) * normal).sum(1) > 0 + crease = two & ((normal[f0] * normal[f1]).sum(1) < cos_a) & (toward[f0] | toward[f1]) + contour = two & (toward[f0] != toward[f1]) + ends = ends.reshape(-1, 2) + piece, shorts = np.arange(nv), {} # each vertex's connected piece, named by its least vertex + while True: + low = np.minimum(piece[ends[:, 0]], piece[ends[:, 1]]) + spread = piece.copy() + np.minimum.at(spread, ends[:, 0], low) + np.minimum.at(spread, ends[:, 1], low) + spread = spread[spread] + if (spread == piece).all(): + break + piece = spread + for k in np.nonzero(crease | contour | (count == 1))[0]: + a, b = co[ends[k, 0]], co[ends[k, 1]] + if piece[ends[k, 0]] not in shorts: + shorts[piece[ends[k, 0]]] = HIDE * float(np.linalg.norm(np.ptp(co[piece == piece[ends[k, 0]]], axis=0))) + short = shorts[piece[ends[k, 0]]] + if sum(not hidden(a + t * (b - a), short) for t in (0.2, 0.5, 0.8)) >= 2: + (u0, v0), (u1, v1) = core.project(cam, [a, b]) + out["contour" if contour[k] else "crease" if crease[k] else "border"].append([float(u0), float(v0), float(u1), float(v1)]) + return out + + +class BROKKR_REFERENCE_OT_flow_score(PolishOperator): + """Score traced lines against the edges a camera sees on the build: how much of each line has a built crease, + contour or border running along it""" + bl_idname = "brokkr_reference.flow_score" + bl_label = "Flow Score" + camera_name: bpy.props.StringProperty(name="Camera", maxlen=63, description="The camera object the view is seen through (solve_camera stands one)") + box: bpy.props.StringProperty(name="Box", maxlen=120, description="u0,v0,u1,v1: the camera's frame on the image, in the pixels the lines were traced in; empty is the render's own frame") + height: bpy.props.FloatProperty(name="Height", default=0.0, min=0.0, max=1000000.0, description="The figure's height in those pixels: an edge within 1% of it is near; 0 is the box's height") + lines: bpy.props.StringProperty(name="Lines", maxlen=12000, description="tag: u,v u,v ...; tag: u,v u,v ... the traced lines") + objects: bpy.props.StringProperty(name="Objects", maxlen=4000, description="Mesh objects whose edges are read, name; name; ... empty is every mesh the render shows") + angle: bpy.props.FloatProperty(name="Angle", default=18.0, min=1.0, max=179.0, description="Degrees between two faces' normals past which their edge is a crease") + + def work(self, context): + try: + cam = record(context, self.camera_name, self.box) + lines = core.polylines(self.lines, "lines") + except core.ReferenceFitError as refusal: + raise Refused(str(refusal)) from None + names = [name.strip() for name in self.objects.split(";") if name.strip()] + meshes = [bpy.data.objects.get(name) for name in names] if names else [o for o in context.scene.objects if o.type == "MESH" and not o.hide_render] + for name, obj in zip(names, meshes): + if obj is None or obj.type != "MESH" or obj.name not in context.scene.objects: + raise Refused(f"{name!r} is not a mesh object of this scene.") + edges = built_edges(context, cam, meshes, self.angle) + height = self.height or cam["box"][3] - cam["box"][1] + segments = [seg for kind in edges.values() for seg in kind] + return {"lines": {tag: core.along(line, segments, height) for tag, line in lines.items()}, "edges": {kind: len(found) for kind, found in edges.items()}, + "objects": [o.name for o in meshes], "height": height} + + +classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_flow_score) def register(): diff --git a/surfaces/blender/brokkr_reference/brokkr_actions.json b/surfaces/blender/brokkr_reference/brokkr_actions.json index 759504c..9bfe98f 100644 --- a/surfaces/blender/brokkr_reference/brokkr_actions.json +++ b/surfaces/blender/brokkr_reference/brokkr_actions.json @@ -80,6 +80,59 @@ "doc": "pixels across the frame the box becomes when camera_name is given" } ] + }, + { + "name": "brokkr_reference.flow_score", + "doc": "Score traced lines against the edges a camera sees on the evaluated build (creases, contours and open borders, unhidden): per line, the share with a built edge running along it (on), the mean distance to one in % of height (off) and the longest unbroken share (run); and the count of edges by kind (docs/reference.md).", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "camera_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the camera object the view is seen through (solve_camera stands one)" + }, + { + "name": "box", + "type": "string", + "maxLength": 120, + "doc": "u0,v0,u1,v1: the camera's frame on the image, in the pixels the lines were traced in; absent is the render's own frame from 0,0" + }, + { + "name": "height", + "type": "number", + "minimum": 0, + "maximum": 1000000, + "default": 0, + "doc": "the figure's height in those pixels: an edge within 1% of it is near; 0 is the box's height" + }, + { + "name": "lines", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 12000, + "doc": "tag: u,v u,v ...; tag: u,v u,v ... the traced lines" + }, + { + "name": "objects", + "type": "string", + "maxLength": 4000, + "doc": "mesh objects whose edges are read, name; name; ... absent is every mesh the render shows" + }, + { + "name": "angle", + "type": "number", + "minimum": 1, + "maximum": 179, + "default": 18, + "doc": "degrees between two faces' normals past which their edge is a crease" + } + ] } ] } diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index eb3fd63..f5b7fe4 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -23,7 +23,13 @@ focal length trade against each other (a dolly zoom), and "lens_band" says how f blender(cam, width) what a Blender camera takes to be this one, the frame being the box camera_of(params, box) the record of a Blender camera: blender() read back in_frame(cam, pixels, width) image pixels as pixels of the frame blender() renders - points(text, size), numbers(text, count) the action's string fields + points, numbers, polyline, polylines the actions' string fields + +A traced line is pixels; a part's points are given in its frame, a 4 x 4 frame-to-world matrix. + + seen(cam, frame, points) pixels of points of a frame + crease_run(points) where Blender builds the hard crease of a cage column at one level + along(line, segments, height) the flow score: how much of a traced line has a seen edge along it """ from __future__ import annotations @@ -36,6 +42,9 @@ SENSOR = 36.0 # mm, fitted to the box's width LENS_MM = (4.0, 4000.0) # the focal length never leaves this: past 4000 mm a view is orthographic to any marking, and an unbounded solve runs off (docs/reference.md) BAND = 1.1 # lens_band: the lenses whose refitted rms is within this multiple of the best STEP = 0.1 # the band is walked in steps of this in log f +FINE = 1.0 # pixels: no mark is placed truer than this, so the band is never judged against a smaller error (exact marks fit every lens of a flat view to 1e-6 px and would call one of them best) +PLANAR = 0.12 # marks thinner than this share of their spread (their planarity) are near a plane: a band of theirs that is open at one end of LENS_MM is reported open at both. The geometric mean of 0.041, a panel with relief whose band does open at one end, and 0.36, marks with depth: separation 2.9 each side (tests/test_reference.py) +DECIDED = 1.57 # a lens is determined when its band is inside LENS_MM and spans no more than this factor. A band's span is a whole number of STEPs: this is the geometric mean of four steps (1.49, the widest that marks with depth 3 px off read) and five (1.65). An exception to lodur:ruling:deterministic-bound-margin: the two readings are one STEP apart, 1.105, and readings quantised in STEPs have no pair 1.2 apart with nothing between; a host that moves a band by a step fails the span assertion in tests/test_reference.py MODELS = {"upright": (), "rolled": ("roll",), "free": ("roll", "centre"), "square": ("square",)} # what a model solves beyond place, yaw, pitch and focal length; "square" holds the yaw at a quarter turn instead QUARTER = math.pi / 2 @@ -194,24 +203,30 @@ def _left_out(W, P, c0, model, logf, f_fixed, near, turned, pivot): return float(np.sqrt(np.mean(np.square(miss)))) -def _decidable(names, W, P, plane_will_do): +EXACT = 1e-9 # of the marks' extent: under this a set of marks is exactly degenerate (true lines and planes read 1e-16); marks placed by hand are never within 1e-3 + + +def _decidable(names, W, P, model): """Refuses marks that cannot decide a camera, by which they are, before anything is solved: the place is solved in units of the marks' extent, so marks of no extent have no solve at all (a logarithm of zero, a record of - NaN). These are exact degeneracies, to nine digits of the marks' extent; points nearly in a line or a plane are - solved, and what they leave undecided is the band's to say.""" + NaN). These are exact degeneracies, to EXACT of the marks' extent; points nearly in a line or a plane are + solved, and what they leave undecided is the band's to say. Returns (the unit normal of the plane the world + points all lie in, or None; the marks' planarity: their least extent over their greatest, 0 for a plane).""" for what, A in (("world point", W), ("pixel", P)): first = {} twins = [(first[row], k) for k, row in zip(names, map(tuple, A.tolist())) if row in first or first.setdefault(row, k) is None] if len(first) < 6: raise ReferenceFitError(f"{len(first)} different {what}s are marked; six are needed ({twins[0][0]!r} and {twins[0][1]!r} share one)") - flat = lambda A: np.linalg.svd(A - A.mean(0), compute_uv=False) # noqa: E731 the marks' extents along their own axes, widest first - w, p = flat(W), flat(P) - if p[1] <= 1e-9 * p[0]: + (_, w, axes), p = np.linalg.svd(W - W.mean(0), full_matrices=False), np.linalg.svd(P - P.mean(0), compute_uv=False) # the marks' extents along their own axes, widest first + if p[1] <= EXACT * p[0]: raise ReferenceFitError("the pixels lie on one line: marks along a line of the image cannot say how the camera is turned about it") - if w[1] <= 1e-9 * w[0]: + if w[1] <= EXACT * w[0]: raise ReferenceFitError("the world points lie on one line: the camera could stand anywhere round it") - if w[2] <= 1e-9 * w[0] and not plane_will_do: - raise ReferenceFitError("the world points lie in one plane, which does not decide the lens or the centre: mark a point off the plane, or hold `lens` and name a model other than free") + if w[2] > EXACT * w[0]: + return None, float(w[2] / w[0]) + if model == "free": + raise ReferenceFitError("the world points lie in one plane, which does not decide the centre: mark a point off the plane, or name a model other than free") + return axes[2], float(w[2] / w[0]) def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.0)): @@ -227,18 +242,29 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0. torso on its waist ring): the angle is solved with the camera, and "twist" is how far they turn from where they were given. - Returns the camera record: {"C", "R", "f", "c", "box", "lens" (mm), "lens_band" [low, high] (the lenses that - refit within BAND of the best rms, walked out from the best in steps of STEP in log f, about 10%, to the first - that misses: an equal-error band, not a confidence interval, and no finer than its step, so [x, x] says the - band is narrower than one step each way, not that the lens is exact), + Returns the camera record: {"C", "R", "f", "c", "box", "lens" (mm), "lens_band" [low, high] (walked out from the + best lens in steps of STEP in log f, about 10%, to the first lens each way whose refit misses BAND of the best + rms, or of FINE pixels where the marks fit closer than any hand places them: every lens outside it misses, + and its ends are the first that do, so it is an equal-error band no finer than its step, not a confidence + interval. Near a plane (planarity under PLANAR) a band that reaches one end of LENS_MM is the whole of + LENS_MM), "lens_determined" (True when the band is inside LENS_MM and spans no more than DECIDED times; + False when the marks leave the lens open, and the headline lens is then one of many that fit; None when + `lens` was held), "planarity" (the marks' least extent over their greatest: 0 for a plane), "lens_at_bound" (None, or "short" or "long" when the solve stopped at an end of LENS_MM), "rms", "median" (pixels), "worst" [name, pixels], "left_out" (the leave-one-out rms), "model", "tried" {model: rms, left_out, lens}, "azimuth", "elevation" (degrees: where the camera stands round the points' middle), "distance", "roll", - "twist" (degrees), "residuals" {name: [du, dv]}}. Every number in it is finite. + "twist" (degrees), "plane" (None, or when the world points all lie in one plane the degrees between the line + of sight and square-on to it), "residuals" {name: [du, dv]}}. Every number in it is finite. + + World points in or near one plane may not decide the lens: seen obliquely they do, by the plane's + foreshortening; the nearer square-on, the less, and "lens_determined" and the band say so (a headline lens + then sits anywhere in LENS_MM: a tilt of the plane seen through a long lens draws what a short lens draws + square-on, and the marks' error chooses between them). The centre a plane never decides, so "auto" leaves + "free" untried. Refuses with ReferenceFitError, before solving, what cannot decide a camera: fewer than six shared names, or fewer than six different world points or different pixels among them; pixels on one line; world points on one - line; world points in one plane, unless `lens` is held and the model is upright, rolled or square.""" + line; world points in one plane with the model "free".""" if model != "auto" and model not in MODELS: raise ReferenceFitError(f"unknown model {model!r}: one of auto, {', '.join(MODELS)}") box = [float(v) for v in box] @@ -254,43 +280,49 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0. if len(world[k]) != 3 or len(pixels[k]) != 2 or not all(math.isfinite(v) for v in (*world[k], *pixels[k])): raise ReferenceFitError(f"point {k!r} is not three finite world numbers and two finite pixel numbers: {list(world[k])}, {list(pixels[k])}") W, P = np.array([world[k] for k in names], float), np.array([pixels[k] for k in names], float) - _decidable(names, W, P, lens is not None and model not in ("auto", "free")) + normal, planarity = _decidable(names, W, P, model) T = np.array([k in turned for k in names]) c0 = [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2] logf = (math.log(LENS_MM[0] * width / SENSOR), math.log(LENS_MM[1] * width / SENSOR)) fixed = None if lens is None else lens * width / SENSOR tried = {} - for m in (("upright", "rolled", "free") if model == "auto" else (model,)): + for m in ((("upright", "rolled", "free") if normal is None else ("upright", "rolled")) if model == "auto" else (model,)): rms, p, cam, X, angle = _fit(W, P, c0, m, logf, f_fixed=fixed, turned=T, pivot=pivot) tried[m] = (rms, p, cam, X, angle, _left_out(W, P, c0, m, logf, fixed, p, T, pivot)) kind = min(tried, key=lambda k: tried[k][5]) rms, p, cam, X, angle, left = tried[kind] mm = lambda f: min(max(f * SENSOR / width, LENS_MM[0]), LENS_MM[1]) # noqa: E731 an end of the range reads as exactly that end - span, best = [cam["f"]], math.log(cam["f"]) - for way in ((-1, 1) if fixed is None else ()): # walk the lens out each way from the best, each solve started at the last, to the first that misses or to the bound + walked, best = [(cam["f"], True)], math.log(cam["f"]) # (focal length, whether its refit is within the band) + for way in ((-1, 1) if fixed is None else ()): # walk the lens out each way from the best, each solve started at the last q, step = np.delete(p, 5 + ("roll" in MODELS[kind])), 1 while True: at = best + STEP * way * step f = math.exp(min(max(at, logf[0]), logf[1])) r_f, q = _fit(W, P, c0, kind, logf, f_fixed=f, near=q, turned=T, pivot=pivot)[:2] - if r_f > BAND * rms + 1e-9: - break - span.append(f) - if not logf[0] < at < logf[1]: + walked.append((f, r_f <= BAND * max(rms, FINE) + 1e-9)) + if not walked[-1][1] or not logf[0] < at < logf[1]: # marks with depth stop at the first miss; near a plane the error can come back under, so the walk runs to the bound break step += 1 + walked.sort() + within = [k for k, (_, ok) in enumerate(walked) if ok] + span = [walked[max(within[0] - 1, 0)][0], walked[min(within[-1] + 1, len(walked) - 1)][0]] # out to the first miss past each end: the band's end is somewhere in that step, and the band never leaves it out + if fixed is None and planarity < PLANAR and (math.log(walked[within[0]][0]) <= logf[0] + 1e-9 or math.log(walked[within[-1]][0]) >= logf[1] - 1e-9): + span = [math.exp(logf[0]), math.exp(logf[1])] # near a plane, a band open at one end is open at both: what closes the other is a tilt traded for the lens, which the marks' error sets either way off = cam["C"] - X.mean(0) res = project(cam, X) - P if not (math.isfinite(rms) and math.isfinite(left) and np.isfinite(cam["C"]).all() and np.isfinite(res).all()): raise ReferenceFitError("the solve did not come to finite numbers: the marks do not decide a camera") worst = int(np.argmax(np.linalg.norm(res, axis=1))) + band = [float(mm(span[0])), float(mm(span[1]))] edge = None if fixed is not None else "short" if best <= logf[0] + 1e-9 else "long" if best >= logf[1] - 1e-9 else None return {"C": [float(v) for v in cam["C"]], "R": [[float(v) for v in row] for row in cam["R"]], "f": float(cam["f"]), "c": [float(v) for v in cam["c"]], - "box": box, "lens": float(mm(cam["f"])), "lens_band": [float(mm(min(span))), float(mm(max(span)))], "lens_at_bound": edge, + "box": box, "lens": float(mm(cam["f"])), "lens_band": band, "lens_at_bound": edge, "lens_determined": None if fixed is not None else bool(LENS_MM[0] < band[0] and band[1] < LENS_MM[1] and band[1] <= DECIDED * band[0]), + "planarity": planarity, "rms": float(rms), "median": float(np.median(np.linalg.norm(res, axis=1))), "worst": [names[worst], float(np.linalg.norm(res[worst]))], "left_out": left, "model": kind, "tried": {k: {"rms": float(v[0]), "left_out": v[5], "lens": float(mm(v[2]["f"]))} for k, v in tried.items()}, "azimuth": float(math.degrees(math.atan2(-off[0], off[1]))), "elevation": float(math.degrees(math.atan2(off[2], math.hypot(off[0], off[1])))), "distance": float(np.linalg.norm(off)), "roll": float(math.degrees(p[5])) if "roll" in MODELS[kind] else 0.0, "twist": float(math.degrees(angle)), + "plane": None if normal is None else float(math.degrees(math.acos(min(1.0, abs(float(cam["R"][2] @ normal)))))), "residuals": {k: [float(v) for v in r] for k, r in zip(names, res)}} @@ -334,6 +366,81 @@ def in_frame(cam, pixels, width): return (np.asarray(pixels, float) - np.array([u0, v0], float)) * k + np.array([0.0, (round(k * (v1 - v0)) - k * (v1 - v0)) / 2]) +# --- traced lines and built edges ------------------------------------------------------------------------------------- + + +def resampled(points, n): + """A polyline as n points evenly spaced along it.""" + p = np.asarray(points, float) + d = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(p, axis=0), axis=1))]) + t = np.linspace(0, d[-1], n) + return np.stack([np.interp(t, d, p[:, k]) for k in range(p.shape[1])], 1) + + +def seen(cam, frame, points): + """Pixels of points of a frame.""" + F = np.asarray(frame, float) + return project(cam, np.asarray(points, float) @ F[:3, :3].T + F[:3, 3]) + + +def crease_run(points): + """The built edges of a hard crease whose cage column is `points`, after one level of Catmull-Clark as Blender's + Subdivision modifier builds it: each inner cage point moves to (1, 6, 1) / 8 of itself and its neighbours, a + new point stands at each middle, the ends stay; then every point but the ends is set on the limit curve, + (1, 4, 1) / 6 of itself and its new neighbours (the modifier's Limit Surface, on by default; with it off the + crease stands at the first step and this is not it). A polyline of 2n - 1 points; the cage's own points are + its even ones, each at (1, 4, 1) / 6 of the cage.""" + p = np.asarray(points, float) + v = p.copy() + v[1:-1] = (p[:-2] + 6 * p[1:-1] + p[2:]) / 8 + out = np.empty((2 * len(p) - 1, p.shape[1])) + out[0::2], out[1::2] = v, (p[:-1] + p[1:]) / 2 + out[1:-1] = (out[:-2] + 4 * out[1:-1] + out[2:]) / 6 + return out + + +def _off(points, line): + """Per point, its distance to a polyline.""" + p, q = np.asarray(points, float), np.asarray(line, float) + a, d = q[:-1], q[1:] - q[:-1] + t = np.clip(((p[:, None] - a) * d).sum(2) / np.maximum((d * d).sum(1), 1e-18), 0, 1) + return np.linalg.norm(a + t[:, :, None] * d - p[:, None], axis=2).min(1) + + +def along(line, segments, height, near=0.01, turn=20.0, cap=0.05): + """The flow score: how much of a traced line (pixels) has a seen edge running along it. `segments` are + [u0, v0, u1, v1] in the same pixels, `height` the figure's height there. Per point of the line: the distance to + the nearest segment within `turn` degrees of the line's direction. Returns {"on": the share of the line with + such an edge within `near` of the height, "off": the mean distance to one in % of the height, capped at `cap`, + "run": the longest unbroken share that is on}.""" + p = resampled(line, 80) + tan = np.gradient(p, axis=0) + tan /= np.linalg.norm(tan, axis=1)[:, None] + S = np.asarray(segments, float).reshape(-1, 4) + if not len(S): + return {"on": 0.0, "off": 100 * cap, "run": 0.0} + a, d = S[:, :2], S[:, 2:] - S[:, :2] + length = np.maximum(np.linalg.norm(d, axis=1), 1e-9) + u = d / length[:, None] + dist = np.empty(len(p)) + for i, (q, t) in enumerate(zip(p, tan)): + ok = np.abs(u @ t) >= math.cos(math.radians(turn)) + if not ok.any(): + dist[i] = np.inf + continue + s = np.clip(((q - a[ok]) * u[ok]).sum(1), 0, length[ok]) + dist[i] = np.linalg.norm(a[ok] + s[:, None] * u[ok] - q, axis=1).min() + on = dist <= near * height + run = best = 0 + for flag in on: + run = run + 1 if flag else 0 + best = max(best, run) + return {"on": round(float(on.mean()), 3), "off": round(float(100 * np.minimum(dist / height, cap).mean()), 2), "run": round(best / len(on), 3)} + + +# --- fields ---------------------------------------------------------------------------------------------------------- + + def numbers(text, count, what): """'1, 2.5, 3' as `count` finite floats; ReferenceFitError names `what`.""" try: @@ -360,3 +467,29 @@ def points(text, size, what): raise ReferenceFitError(f"{what} names {name!r} twice") out[name] = numbers(values, size, f"{what} point {name!r}:") return out + + +def polyline(text, what): + """'u,v u,v ...' as an (n, 2) array of two or more different points; ReferenceFitError names `what`.""" + line = np.array([numbers(piece, 2, f"{what} point") for piece in text.split()], float).reshape(-1, 2) + if len(line) < 2 or not np.ptp(line, axis=0).max() > 0: + raise ReferenceFitError(f"{what} is {len(line)} points of no length; a traced line is two or more, 'u,v u,v ...'") + return line + + +def polylines(text, what): + """'tag: u,v u,v ...; tag: ...' as {tag: polyline}; a tag given twice is refused.""" + out = {} + for entry in (piece.strip() for piece in text.split(";")): + if not entry: + continue + tag, colon, line = entry.partition(":") + tag = tag.strip() + if not colon or not tag: + raise ReferenceFitError(f"{what} entry {entry[:40]!r} has no tag; it is 'tag: u,v u,v ...'") + if tag in out: + raise ReferenceFitError(f"{what} names {tag!r} twice") + out[tag] = polyline(line, f"{what} line {tag!r}") + if not out: + raise ReferenceFitError(f"{what} holds no line; it is 'tag: u,v u,v ...; tag: ...'") + return out diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index 83e967f..93bdc69 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -1,18 +1,18 @@ -# Reference views: the camera a picture was drawn through +# Reference views: the camera a picture was drawn through, and traced lines scored against the build `surfaces/blender/brokkr_reference` is a Blender add-on that fits a scene to a reference image. A concept sheet, a render or a photograph draws its subject through a camera nobody wrote down; given points whose place in the world is known and the pixel where the image draws each, `solve_camera` finds that camera, so that a render through -it lays over the image pixel for pixel and a line traced on the image can be lifted into the scene. +it lays over the image pixel for pixel and a line traced on the image can be scored against the build's edges. It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish`: it imports that package's operator base and `Refused`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish` first; `brokkr_reference` refuses to register without it. `brokkr_actions.json` beside its `__init__.py` lists the -one operator agents may run; the arithmetic is `core.py` (numpy only, tested without Blender), which a script may +two operators agents may run (`solve_camera`, `flow_score`); the arithmetic is `core.py` (numpy only, tested without Blender), which a script may import directly. The action writes its JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. -The package takes points and gives cameras. The images, the marks on them, traces and masks belong to whoever +The package takes points and traced lines and gives cameras and scores. The images, the marks on them, traces and masks belong to whoever made them; nothing here opens an image. ## Conventions @@ -29,7 +29,7 @@ made them; nothing here opens an image. The record is the truth. A Blender camera stood at it (`core.blender`) is derived, and `core.camera_of` reads one back into a record. -## The action +## solve_camera `brokkr_reference.solve_camera`. Host action fields are scalar, so points go in as text: @@ -63,7 +63,7 @@ proportion. It does not make it the scene's active camera and does not touch `re render through it at 100% is then the image's pixel less the box's corner, times `width` over the box's width (`core.in_frame`; the frame's height is a whole number of pixels, so it can stand half a pixel off the box's). -The report is the camera record: `C`, `R`, `f`, `c`, `box`, `lens`, `lens_band`, `lens_at_bound`, `rms`, `median` +The report is the camera record: `C`, `R`, `f`, `c`, `box`, `lens`, `lens_band`, `lens_at_bound`, `lens_determined`, `planarity`, `plane`, `rms`, `median` and `worst` (`[name, pixels]`), `left_out` (the leave-one-out rms), `model`, `tried` (each model's `rms`, `left_out` and `lens`), `azimuth`, `elevation` and `distance` (where the camera stands round the points' middle), `roll`, `twist`, and `residuals` (`{name: [du, dv]}`, to a hundredth of a pixel in a receipt); plus `camera` (the @@ -72,9 +72,33 @@ object's name or null) and, when a camera was stood, `blender` (what `core.blend Refusals name their cause: fewer than six shared names, a point that is not finite numbers, a name given twice, a box of no width or height, a lens outside 4 to 4000 mm. Marks that cannot decide a camera are refused before any solve: fewer than six different world points or six different pixels among the shared names (the message names two -that share one), pixels all on one line, world points all on one line, and world points all in one plane unless -`lens` is held and the model is `upright`, `rolled` or `square`. These are exact cases; points nearly in a line or -a plane are solved, and the band says what they leave open. A report never holds a number that is not finite. +that share one), pixels all on one line, world points all on one line, and world points all in one plane with the +model `free`. These are exact cases, to a billionth of the marks' extent (`core.EXACT`); points nearly in a line or +a plane are solved, and `lens_determined` and the band say what they leave open. A report never holds a number +that is not finite. + +`planarity` is how flat the marked world points are: their least extent over their greatest, 0 for a plane, 0.3 +for points spread through a box. World points all in one plane (a deck, a wall, a flat sheet of marks) are solved, +and `plane` is then the degrees between the line of sight and square-on to that plane (it is null otherwise). A +plane never decides the centre, so `auto` tries `upright` and `rolled` only. + +Flat marks may not decide the lens, and `lens_determined` says whether these did. Seen obliquely a plane does, by +its foreshortening. Seen square-on it does not: every lens draws it the same from its own distance, and a small +tilt of the plane seen through a long lens draws what a short lens draws square-on, so the marks' error picks the +headline lens. Measured on a plane of thirteen marks through a 50 mm lens, each mark a pixel off, six seeds a tilt: + +| degrees off square-on | headline lens, mm | band, mm | `lens_determined` | +| --- | --- | --- | --- | +| 0 | 4 to 4000 | 4 to 4000 | false, all six | +| 3 | 4 to 90 | 4 to 4000 (one 45 to 134) | false, all six | +| 6 | 42 to 62 | from 13 to 84, one 4 to 4000 | false, all six | +| 9 | 46 to 57 | from 35 to 69 | true in five | +| 15 | 48 to 53 | from 44 to 59 | true, all six | +| 30 | 49 to 51 | from 45 to 57 | true, all six | + +The band held 50 mm in all 36. With marks 3 px off, one band of nine at 5 degrees did not (68 to 152, not +determined). When `lens_determined` is false, do not read `lens` as the lens: hold `lens` from another view, or mark +a point off the plane. ## How far to trust the lens @@ -85,13 +109,21 @@ and focal length trade against each other (a dolly zoom) and the picture barely - The focal length is held inside 4 to 4000 mm. Without a bound the solve ran the focal length to overflow on long views; past 4000 mm a view is orthographic to any marking. `lens_at_bound` is `"long"` or `"short"` when the answer sits at an end: read that as "at least this long", not as a lens. -- `lens_band` is `[low, high]`: the lenses that, held and refitted, come within 1.1 times the best rms, walked out - from the best in steps of a tenth in log f until one misses or the bound is reached. It is an **equal-error - band, not a confidence interval**: it says which lenses the marks cannot tell apart, not where the true lens - lies, and on a probe one such band excluded the true lens. A band that ends at 4000 was stopped by the bound. - The walk's step is the band's resolution: each end is the last step that still fitted, so the true end lies up - to one step (about 10%) further out, and a band of `[x, x]` means the first step each way already missed, that - is, a band narrower than one 10% step each way, not a lens known exactly. +- `lens_band` is `[low, high]`, walked out from the best lens in steps of a tenth in log f (about 10%) to the first + lens each way that, held and refitted, misses 1.1 times the best rms. Every lens outside the band misses; each + end is the first step that did, so the lenses that fit end somewhere in the step before it, and a band is never + narrower than a step each way. The rms the walk is judged against is never taken under 1 pixel (`core.FINE`): + marks placed truer than a hand places them fit every lens of a flat view to a millionth of a pixel, and one of + those would be called best. It is an **equal-error band, not a confidence interval**: it says which lenses the + marks cannot tell apart, and on probes a few such bands excluded the true lens. A band that ends at 4000 or at 4 + was stopped by the bound. +- For flat marks (`planarity` under 0.12, `core.PLANAR`) a band that reaches one end of the range is reported as + the whole range, 4 to 4000. What closes the other end of such a band is a tilt of the plane traded against the + lens, and the marks' error sets that either way: a square-on plane's band read 309 to 4000 mm on one seed with + the true lens at 50. This gives up the one-sided reading ("at least 300 mm") for flat marks; marks with depth + keep it. +- `lens_determined` is true when the band lies inside 4 to 4000 mm and spans no more than 1.57 times + (`core.DECIDED`), false otherwise, and null when `lens` was held. - There is no prior. Where the data cannot decide, the answer is a wide band rather than a plausible-looking 50 mm. - Hold `lens` only when views must agree: two views of one subject solved alone may each sit anywhere in their bands, and a fit rendered from elsewhere than the reference view depends on the lens the band does not fix. @@ -107,6 +139,39 @@ place, not about a lift made in the view's own frame. pseudo-Huber loss; `median` beside it shows when a few points carry the error. A solve with `auto` on 13 points takes several seconds (three models, each from 16 starts, plus a left-out solve per point per model). +## flow_score: traced lines against built edges + +`flow_score` says how much of each traced line the build already carries as an edge. It reads the evaluated meshes +(modifiers applied) and keeps the edges the camera sees: creases (two faces whose normals differ by more than +`angle` degrees, at least one of them facing the camera), contours (one face toward the camera, one away) and open +borders, each where two of three points along it are hidden behind nothing the scene shows. A face that looks away +by its winding does not count as seen, so a cage with flipped normals shows no creases. + +| field | | +| --- | --- | +| `camera_name` | the camera object the view is seen through (`solve_camera` stands one) | +| `box` | `u0,v0,u1,v1`: the camera's frame on the image, in the pixels the lines were traced in; absent is the render's own frame from 0,0 | +| `height` | the figure's height in the box's pixels; an edge within 1% of it is near. 0 (default) is the box's height | +| `lines` | `tag: u,v u,v ...; tag: u,v u,v ...` | +| `objects` | `name; name; ...`, the meshes whose edges are read; absent is every mesh the render shows. Everything the scene shows hides | +| `angle` | degrees (default 18) | + +The report: `lines` (`{tag: {on, off, run}}`), `edges` (the count of seen edges by kind), `objects` and `height`. +`on` is the share of the line with a seen edge within 1% of the height and within 20 degrees of the line's own +direction; `off` the mean distance to such an edge in % of the height, capped at 5; `run` the longest unbroken +share that is on. The edges themselves are not returned and not kept: they are computed on each call. + +The hiding test's sight line stops short of each point by a thousandth (`HIDE`) of the diagonal of the edge's own +piece, the connected part of its mesh that it lies on, so that the edge's own faces do not hide it: a box joined +into one mesh with a ground 200 times its size keeps the box's margin. A surface nearer the edge than that hides +it when it stands further off than a thousandth of the diagonal of the object it belongs to, measured whole: the +margin is the smaller of the two, whatever else the scene holds. A greeble modelled into its hull's own connected +surface has the hull's margin, and a surface nearer it than a thousandth of the hull does not hide it. A strip 0.3% of a box's diagonal in front of an edge hides it at scales 0.01, 1 and +100, and with a ground 20 or 40 times the box among the meshes read; chips a fortieth of a box hide its edge from +0.05% of its diagonal. Past the own object's margin the first surface met decides. Edges read true from cameras to +about 20000 diagonals off, where the ray's own rounding reaches the margin. The action writes nothing to the scene (its row says `changesScene` +because the operator base pushes an undo step). + ## What it cannot do It solves one pinhole camera for one view: no lens distortion, no two views solved together, one turned group and @@ -122,9 +187,13 @@ cam = core.solve(world, pixels, box, model="auto") # dicts by name; the u_v = core.project(cam, points) # where it draws world points origin, direction = core.ray(cam, (u, v)) # a pixel's line of sight point = core.lift(cam, (u, v), plane_point, plane_normal) # a traced pixel on a plane +run = core.crease_run(column) # the hard crease Blender builds from a cage column +score = core.along(line, segments, height) # on, off, run against [u0, v0, u1, v1] segments params = core.blender(cam, 1000) # matrix_world, lens, shifts, resolution cam2 = core.camera_of(params, box) # and back ``` -The tests are `tests/test_reference.py` (no Blender) and `tests/live/reference.py` (a known scene rendered, -solved through the action and rendered again; `reference.result.json` is its last run). +The tests are `tests/test_reference.py` (no Blender), `tests/live/reference.py` (a known scene rendered, solved +through the action and rendered again; `reference.result.json` is its last run) and `tests/live/reference_flow.py` +(`crease_run` against Blender's own subdivision, a box and a folded sheet scored by `flow_score`; +`reference_flow.result.json` is its last run). diff --git a/surfaces/blender/tests/live/reference.result.json b/surfaces/blender/tests/live/reference.result.json index 55664b6..cbe1785 100644 --- a/surfaces/blender/tests/live/reference.result.json +++ b/surfaces/blender/tests/live/reference.result.json @@ -12,7 +12,8 @@ "brokkr_mesh_polish.scrub_markings", "brokkr_mesh_polish.cut_parts", "brokkr_mesh_polish.pick", - "brokkr_reference.solve_camera" + "brokkr_reference.solve_camera", + "brokkr_reference.flow_score" ] }, { @@ -119,13 +120,14 @@ "brokkr_mesh_polish.scrub_markings", "brokkr_mesh_polish.cut_parts", "brokkr_mesh_polish.pick", - "brokkr_reference.solve_camera" + "brokkr_reference.solve_camera", + "brokkr_reference.flow_score" ], "record": { "lens": 50.02266319807241, "lens_band": [ - 50.02266319807241, - 50.02266319807241 + 45.26237741142627, + 61.09781880064287 ], "lens_at_bound": null, "rms": 0.03555833513434369, diff --git a/surfaces/blender/tests/live/reference_flow.py b/surfaces/blender/tests/live/reference_flow.py new file mode 100644 index 0000000..ad03265 --- /dev/null +++ b/surfaces/blender/tests/live/reference_flow.py @@ -0,0 +1,276 @@ +"""Live proof, in a background Blender, of brokkr_reference.flow_score through run_intent, and of core.crease_run +against Blender's own subdivision. + + crease_run a strip of quads with its middle column creased hard, subdivided once by Blender: the built crease + is where core.crease_run says (the numbers printed as BUILT are test_reference.py's fixture) + flow_score a box and, beside it, a folded sheet seen from behind: the box's front edge scores 1, its back edge 0 + (it faces away, so it is never read), and the sheet's fold 0, since neither of its faces is toward + the camera (mutant N5, which counts such creases, reads 1 and four creases). Then the box alone at + scales 0.01, 1 and 100, its front edge seen, and hidden by a strip standing in front of it by + 0.316% of the box's diagonal (mutants O1, nothing hides; O2, a margin of 0.03 units; O3, HIDE ten + times over: each reads the hidden edge as seen. O4, no margin at all, loses seen edges to their + own faces here and at the first box). The margin is the objects' own: a box over a ground 20 and + 40 times its size, a small box over a ground behind a long strip (O7, a share of the largest mesh + read), two chips before a large box (O9, no second cast); a box, a ground and a strip joined + into one mesh, where the margin is the box's own connected piece's (O10, the whole mesh's). + Cameras 30 and 144 diagonals off still read every edge (O5, HIDE at 1e-6, loses four contours + at 144) + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_flow.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). is an absolute path: it writes .result.json and exits 1 when a check failed. Not part +of the unittest run: it needs Blender. +""" +import json +import math +import os +import sys +import tempfile +import time +import traceback +import types +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from bpy_extras.object_utils import world_to_camera_view +from mathutils import Euler, Matrix, Vector + +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 os.path.isabs(OUT): + raise SystemExit(f" must be an absolute path, not {OUT!r}: a relative one lands in Blender's start directory") +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 + +sys.path.append(str(SURFACE)) +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_reference"): + addon_utils.enable(module, default_set=True) +from brokkr_reference import core # noqa: E402 + +target = bt.BrokkrBlenderTarget(bpy) +target.configure_action_dirs("", tempfile.mkdtemp(prefix="brokkr-reference-flow-live-")) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], + "hostRows": [row["name"] for row in target.host_actions()[0]]} +COUNT = [0] +T0 = time.time() +WIDTH, HEIGHT = 800, 600 +COLUMN = [[0.5, 0.0, 0.0], [0.6, 0.2, 1.0], [0.4, 0.1, 2.0], [0.7, -0.2, 3.0], [0.5, 0.0, 4.0]] + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +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 = json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None + print("SEND", f"{time.time() - T0:.1f}s", action, receipt["status"], str(receipt["message"])[:300], flush=True) + return receipt, result + + +def mesh_object(name, verts, faces): + mesh = bpy.data.meshes.new(name) + mesh.from_pydata(verts, [], faces) + obj = bpy.data.objects.new(name, mesh) + bpy.context.scene.collection.objects.link(obj) + return obj + + +def traced(camera, points, scale=1.0, corner=(0.0, 0.0)): + """'u,v u,v ...' where Blender's own projection draws world points, in an image whose pixels are the frame's + times `scale` from `corner`.""" + out = [] + for p in points: + x, y, _ = world_to_camera_view(bpy.context.scene, camera, Vector(p)) + out.append(f"{corner[0] + scale * x * WIDTH:.3f},{corner[1] + scale * (1.0 - y) * HEIGHT:.3f}") + return " ".join(out) + + +try: + check("host file admitted", not R["hostErrors"] and "brokkr_reference.flow_score" in R["hostRows"], R["hostRows"]) + scene = bpy.context.scene + scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage = WIDTH, HEIGHT, 100 + + # --- crease_run is Blender's level-1 subdivision of a hard crease ------------------------------------------------- + col = np.array(COLUMN) + verts = [tuple(p + d) for p in col for d in ((-0.5, 0.3, 0.0), (0.0, 0.0, 0.0), (0.5, -0.3, 0.1))] + strip = mesh_object("Strip", verts, [(3 * i + j, 3 * i + j + 1, 3 * i + j + 4, 3 * i + j + 3) for i in range(4) for j in range(2)]) + sharp = strip.data.attributes.new("crease_edge", "FLOAT", "EDGE") + for edge in strip.data.edges: + sharp.data[edge.index].value = 1.0 if all(v % 3 == 1 for v in edge.vertices) else 0.0 + modifier = strip.modifiers.new("Subdivision", "SUBSURF") + modifier.levels, modifier.subdivision_type, modifier.use_creases = 1, "CATMULL_CLARK", True + bpy.context.view_layer.update() + evaluated = strip.evaluated_get(bpy.context.evaluated_depsgraph_get()) + built_all = np.array([v.co for v in evaluated.data.vertices]) + run = core.crease_run(COLUMN) + nearest = [built_all[np.linalg.norm(built_all - p, axis=1).argmin()] for p in run] + R["BUILT"] = [[round(float(v), 6) for v in p] for p in nearest] + print("BUILT", json.dumps(R["BUILT"]), flush=True) + worst = float(np.abs(np.array(nearest) - run).max()) + # Shipped 4.8e-7 m (Blender's single floats); without the limit step (N3) 0.0208: the bound is their geometric mean. + check("crease_run stands where Blender builds the creased column, within 1e-4 m", len(built_all) == 45 and worst < 1e-4, worst) + strip.hide_render = True + strip.hide_viewport = True + + # --- the camera every flow_score check below is seen through ------------------------------------------------------- + truth = bpy.data.objects.new("Truth", bpy.data.cameras.new("Truth")) + scene.collection.objects.link(truth) + truth.data.lens, truth.data.sensor_width, truth.data.sensor_fit = 50.0, 36.0, "HORIZONTAL" + truth.matrix_world = Matrix.Translation((-6.5, -8.0, 4.6)) @ Euler((1.2, 0.03, -0.72), "XYZ").to_matrix().to_4x4() + bpy.context.view_layer.update() + box = "100,50,1700,1250" # the same view as an image twice the frame's size, its corner at 100, 50 + + # --- flow_score: the edges the camera sees on a box and on a folded sheet seen from behind ------------------------ + bm = bmesh.new() + bmesh.ops.create_cube(bm, size=2.0, matrix=Matrix.Translation((0.0, 0.0, 1.0))) + mesh = bpy.data.meshes.new("Box") + bm.to_mesh(mesh) + bm.free() + scene.collection.objects.link(bpy.data.objects.new("Box", mesh)) + # a valley fold running toward the camera in plan, its faces rising 45 degrees to either side: seen from above, both look down and away + fold, wing = [(2.176, -1.734, 0.5), (2.824, -1.266, 0.5)], np.array([0.1755, -0.2433, 0.3]) + sheet = mesh_object("Sheet", [fold[0], fold[1], tuple(fold[1] - wing * [1, 1, -1]), tuple(fold[0] - wing * [1, 1, -1]), tuple(fold[1] + wing), tuple(fold[0] + wing)], [(0, 1, 2, 3), (1, 0, 5, 4)]) + for polygon in sheet.data.polygons: + if polygon.normal.z > 0: + polygon.flip() + sheet.data.update() + bpy.context.view_layer.update() + eye = np.array(truth.matrix_world.translation) + check("fixture: both of the sheet's faces look away from the camera, and their fold is 90 degrees or so", + all((eye - np.array(p.center)) @ np.array(p.normal) < 0 for p in sheet.data.polygons) and abs(sheet.data.polygons[0].normal @ sheet.data.polygons[1].normal) < 0.5, + [list(p.normal) for p in sheet.data.polygons]) + front, back = [(-1.0, -1.0, 0.0), (-1.0, -1.0, 2.0)], [(1.0, 1.0, 0.0), (1.0, 1.0, 2.0)] + lines = f"front: {traced(truth, front)}; back: {traced(truth, back)}; fold: {traced(truth, fold)}; top: {traced(truth, [(-1.0, -1.0, 2.0), (1.0, -1.0, 2.0), (1.0, 1.0, 2.0)])}" + receipt, flow = send("brokkr_reference.flow_score", camera_name="Truth", lines=lines) + R["flow"] = flow + check("flow_score: accepted; the box shows 3 creases and 6 contours, the sheet 6 borders and no crease", receipt["status"] == "accepted" + and flow["edges"] == {"crease": 3, "contour": 6, "border": 6} and flow["objects"] == ["Box", "Sheet"] and flow["height"] == HEIGHT, [receipt["message"], flow and flow["edges"]]) + check("the box's front edge and the top's two edges score on 1, run 1", flow and flow["lines"]["front"]["on"] == 1.0 and flow["lines"]["front"]["run"] == 1.0 + and flow["lines"]["top"]["on"] > 0.95, flow and flow["lines"]) + check("the box's back edge, both its faces turned away, is not read: on 0", flow and flow["lines"]["back"] == {"on": 0.0, "off": 5.0, "run": 0.0}, flow and flow["lines"]["back"]) + check("the sheet's fold, both faces turned away, scores on 0 (N5 reads 1)", flow and flow["lines"]["fold"]["on"] == 0.0, flow and flow["lines"]["fold"]) + receipt, only = send("brokkr_reference.flow_score", camera_name="Truth", lines=lines, objects="Box", box=box, height=600) + check("objects names the meshes read: the box alone has no border; lines in the frame's pixels miss a box twice its size", + receipt["status"] == "accepted" and only["edges"] == {"crease": 3, "contour": 6, "border": 0} and only["objects"] == ["Box"] and only["lines"]["front"]["on"] == 0.0, [receipt["message"], only]) + for fields, said in (({"objects": "Nobody"}, "not a mesh object"), ({"objects": "Truth"}, "not a mesh object"), ({"lines": "1,2 3,4"}, "no tag"), ({"camera_name": "Box"}, "not a camera")): + receipt, _ = send("brokkr_reference.flow_score", **{"camera_name": "Truth", "lines": lines, **fields}) + check(f"flow_score refuses {next(iter(fields))}: failed, saying '{said}'", receipt["status"] == "failed" and said in receipt["message"], receipt["message"]) + + # --- flow_score: an edge the camera would see, hidden by a nearer surface; the margin is the objects' own ---------- + def stage(half, ground=0.0, far=0.0): + """A box of half-width `half` standing on z = 0, alone or over a square ground `ground` across, and a camera: + the first box's, scaled with the box, or one `far` box diagonals off with the lens grown to match. Returns + the camera, the box's front edge, and its line as the camera draws it.""" + for obj in [o for o in bpy.data.objects if o.type == "MESH"]: + bpy.data.objects.remove(obj) + name = f"Staged {half:g} {ground:g} {far:g}" + staged = bpy.data.objects.new(name, bpy.data.cameras.new(name)) + scene.collection.objects.link(staged) + staged.data.lens, staged.data.sensor_width, staged.data.sensor_fit, staged.data.clip_start, staged.data.clip_end = 50.0 * max(1.0, far / 5.0), 36.0, "HORIZONTAL", 0.01 * half, 1e9 + if far: + centre = Vector((0.0, 0.0, half)) + place = centre + Vector((-0.55, -0.7, 0.4)).normalized() * far * 2.0 * half * math.sqrt(3.0) + staged.matrix_world = Matrix.Translation(place) @ (centre - place).to_track_quat("-Z", "Y").to_matrix().to_4x4() + else: + staged.matrix_world = Matrix.Translation(truth.matrix_world.translation * half) @ truth.matrix_world.to_3x3().to_4x4() + bm = bmesh.new() + bmesh.ops.create_cube(bm, size=2.0 * half, matrix=Matrix.Translation((0.0, 0.0, half))) + mesh = bpy.data.meshes.new("Box") + bm.to_mesh(mesh) + bm.free() + scene.collection.objects.link(bpy.data.objects.new("Box", mesh)) + if ground: + g = ground / 2.0 + mesh_object("Ground", [(-g, -g, -4.0 * half), (g, -g, -4.0 * half), (g, g, -4.0 * half), (-g, g, -4.0 * half)], [(0, 1, 2, 3)]) + bpy.context.view_layer.update() + edge = np.array([(-1.0, -1.0, 0.0), (-1.0, -1.0, 2.0)]) * half + return staged, edge, f"front: {traced(staged, edge)}" + + def screen(staged, name, point, gap, wide, tall): + """An upright quad `wide` by `tall` that every sight line to `point` meets `gap` before it.""" + toward = np.array(staged.matrix_world.translation) - point + toward /= np.linalg.norm(toward) + level = np.array([toward[0], toward[1], 0.0]) / np.hypot(toward[0], toward[1]) + side = np.cross([0.0, 0.0, 1.0], level) + at = point + level * gap * float(toward @ level) + mesh_object(name, [tuple(at + side * a * wide / 2.0 + np.array([0.0, 0.0, b * tall / 2.0])) for a, b in ((-1, -1), (1, -1), (1, 1), (-1, 1))], [(0, 1, 2, 3)]) + bpy.context.view_layer.update() + + def front(staged, line, objects): + receipt, flow = send("brokkr_reference.flow_score", camera_name=staged.name, lines=line, **objects) + return (flow["lines"]["front"]["on"], flow["edges"]["crease"], flow["edges"]["contour"]) if receipt["status"] == "accepted" else receipt["message"] + + DIAGONAL = 2.0 * math.sqrt(3.0) # of a box, in its half-widths + for s in (0.01, 1.0, 100.0): + staged, edge, line = stage(s) + bare = front(staged, line, {"objects": "Box"}) + gap = 3.16e-3 * DIAGONAL * s # of the box's diagonal: the geometric mean of the shipped HIDE, 1e-3, and one ten times it (mutant O3), 3.16 from each + screen(staged, "Wall", edge.mean(0), gap, 0.4 * s, 3.0 * s) + walled = front(staged, line, {"objects": "Box"}) + check(f"at scale {s:g} the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), " + "O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1", bare == (1.0, 3, 6) and walled == (0.0, 2, 6), [bare, walled, gap]) + # a larger mesh in the scene and among the meshes read: the margin stays the box's + for half, ground in ((0.5, 20.0), (0.05, 4.0)): + staged, edge, line = stage(half, ground) + bare = front(staged, line, {}) + screen(staged, "Wall", edge.mean(0), 0.01 * DIAGONAL * half, 0.4 * half, 3.0 * half) + walled = front(staged, line, {}) + check(f"a box {2 * half:g} across over a ground {ground:g} across, every mesh read: its front edge is seen, and a strip 1% of the box's diagonal in front hides it " + f"(a margin of the ground's is {1e-3 * ground * math.sqrt(2.0) / (0.01 * DIAGONAL * half):.1f} times the gap)", bare == (1.0, 3, 6) and walled == (0.0, 2, 6), [bare, walled]) + # the box, the ground and the strip joined into one mesh: the margin is the box's own piece's (O10, the whole mesh's diagonal, reads on 1: the ground's margin is 16 times the gap) + staged, edge, line = stage(0.05, 20.0) + screen(staged, "Wall", edge.mean(0), 0.01 * DIAGONAL * 0.05, 0.02, 0.15) + bm = bmesh.new() + for obj in [o for o in bpy.data.objects if o.type == "MESH"]: + bm.from_mesh(obj.data) + bpy.data.objects.remove(obj) + mesh = bpy.data.meshes.new("Joined") + bm.to_mesh(mesh) + bm.free() + scene.collection.objects.link(bpy.data.objects.new("Joined", mesh)) + bpy.context.view_layer.update() + walled = front(staged, line, {}) + check("a box 0.1 across, a ground 20 across and a strip 1% of the box's diagonal in front of the box's edge, all one mesh: hidden, the margin is the edge's own connected piece's (O10 reads on 1)", walled[0] == 0.0, walled) + # a small box's edge behind a strip far longer than the box, over a ground: the margin is the box's, not the strip's or the ground's (O7, a share of the largest mesh read, reads on 1) + staged, edge, line = stage(0.05, 4.0) + gap = math.sqrt(1e-3 * DIAGONAL * 0.05 * 1e-3 * math.hypot(0.02, 4.0)) # the geometric mean of the box's margin and the strip's, 4.8 from each + screen(staged, "Wall", edge.mean(0), gap, 0.02, 4.0) + walled = front(staged, line, {}) + check("a box 0.1 across over a ground 4 across, with a strip 4 long standing between the two margins in front of its edge: hidden, the margin is the smaller object's (O7 reads on 1)", walled == (0.0, 2, 6), [walled, gap]) + # two chips far smaller than the box, in front of two of the edge's three read points: the margin is the chips' (O9, no second cast, reads on 1) + staged, edge, line = stage(1.0) + gap = math.sqrt(1e-3 * DIAGONAL * 1e-3 * 0.05 * math.sqrt(2.0)) # the geometric mean of the box's margin and a chip's, 7 from each + for t in (0.2, 0.5): + screen(staged, f"Chip {t}", edge[0] + t * (edge[1] - edge[0]), gap, 0.05, 0.05) + chipped = front(staged, line, {"objects": "Box"}) + check("a box 2 across with two chips 0.05 across standing between the two margins in front of its edge: hidden, the margin is the chips' (O9 reads on 1)", chipped == (0.0, 2, 6), [chipped, gap]) + # far cameras: the margin's floor is the ray's rounding (O5, HIDE 1e-6, loses four contours to their own faces at 144 diagonals; at 30 it reads true here) + for far in (30.0, 144.0): + staged, edge, line = stage(1.0, far=far) + bare = front(staged, line, {"objects": "Box"}) + check(f"a camera {far:g} box diagonals off still reads the box's 3 creases and 6 contours and its front edge on 1" + (" (O5 reads 2 contours)" if far == 144.0 else ""), bare == (1.0, 3, 6), bare) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) + +R["ok"] = all(c["ok"] for c in R["checks"]) +for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/reference_flow.result.json b/surfaces/blender/tests/live/reference_flow.result.json new file mode 100644 index 0000000..e382f40 --- /dev/null +++ b/surfaces/blender/tests/live/reference_flow.result.json @@ -0,0 +1,385 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "host file admitted", + "ok": true, + "detail": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick", + "brokkr_reference.solve_camera", + "brokkr_reference.flow_score" + ] + }, + { + "name": "crease_run stands where Blender builds the creased column, within 1e-4 m", + "ok": true, + "detail": 4.76837158203125e-07 + }, + { + "name": "fixture: both of the sheet's faces look away from the camera, and their fold is 90 degrees or so", + "ok": true, + "detail": [ + [ + -0.4140099287033081, + 0.5732445120811462, + -0.7070971727371216 + ], + [ + 0.4140099287033081, + -0.5732445120811462, + -0.7070971727371216 + ] + ] + }, + { + "name": "flow_score: accepted; the box shows 3 creases and 6 contours, the sheet 6 borders and no crease", + "ok": true, + "detail": [ + "Operator brokkr_reference.flow_score finished.", + { + "crease": 3, + "contour": 6, + "border": 6 + } + ] + }, + { + "name": "the box's front edge and the top's two edges score on 1, run 1", + "ok": true, + "detail": { + "front": { + "on": 1.0, + "off": 0.0, + "run": 1.0 + }, + "back": { + "on": 0.0, + "off": 5.0, + "run": 0.0 + }, + "fold": { + "on": 0.0, + "off": 5.0, + "run": 0.0 + }, + "top": { + "on": 0.988, + "off": 0.06, + "run": 0.537 + } + } + }, + { + "name": "the box's back edge, both its faces turned away, is not read: on 0", + "ok": true, + "detail": { + "on": 0.0, + "off": 5.0, + "run": 0.0 + } + }, + { + "name": "the sheet's fold, both faces turned away, scores on 0 (N5 reads 1)", + "ok": true, + "detail": { + "on": 0.0, + "off": 5.0, + "run": 0.0 + } + }, + { + "name": "objects names the meshes read: the box alone has no border; lines in the frame's pixels miss a box twice its size", + "ok": true, + "detail": [ + "Operator brokkr_reference.flow_score finished.", + { + "lines": { + "front": { + "on": 0.0, + "off": 5.0, + "run": 0.0 + }, + "back": { + "on": 0.0, + "off": 5.0, + "run": 0.0 + }, + "fold": { + "on": 0.0, + "off": 5.0, + "run": 0.0 + }, + "top": { + "on": 0.0, + "off": 5.0, + "run": 0.0 + } + }, + "edges": { + "crease": 3, + "contour": 6, + "border": 0 + }, + "objects": [ + "Box" + ], + "height": 600.0 + } + ] + }, + { + "name": "flow_score refuses objects: failed, saying 'not a mesh object'", + "ok": true, + "detail": "Error: 'Nobody' is not a mesh object of this scene." + }, + { + "name": "flow_score refuses objects: failed, saying 'not a mesh object'", + "ok": true, + "detail": "Error: 'Truth' is not a mesh object of this scene." + }, + { + "name": "flow_score refuses lines: failed, saying 'no tag'", + "ok": true, + "detail": "Error: lines entry '1,2 3,4' has no tag; it is 'tag: u,v u,v ...'" + }, + { + "name": "flow_score refuses camera_name: failed, saying 'not a camera'", + "ok": true, + "detail": "Error: 'Box' is not a camera object." + }, + { + "name": "at scale 0.01 the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1", + "ok": true, + "detail": [ + [ + 1.0, + 3, + 6 + ], + [ + 0.0, + 2, + 6 + ], + 0.00010946561103835304 + ] + }, + { + "name": "at scale 1 the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1", + "ok": true, + "detail": [ + [ + 1.0, + 3, + 6 + ], + [ + 0.0, + 2, + 6 + ], + 0.010946561103835304 + ] + }, + { + "name": "at scale 100 the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1", + "ok": true, + "detail": [ + [ + 1.0, + 3, + 6 + ], + [ + 0.0, + 2, + 6 + ], + 1.0946561103835304 + ] + }, + { + "name": "a box 1 across over a ground 20 across, every mesh read: its front edge is seen, and a strip 1% of the box's diagonal in front hides it (a margin of the ground's is 1.6 times the gap)", + "ok": true, + "detail": [ + [ + 1.0, + 3, + 6 + ], + [ + 0.0, + 2, + 6 + ] + ] + }, + { + "name": "a box 0.1 across over a ground 4 across, every mesh read: its front edge is seen, and a strip 1% of the box's diagonal in front hides it (a margin of the ground's is 3.3 times the gap)", + "ok": true, + "detail": [ + [ + 1.0, + 3, + 6 + ], + [ + 0.0, + 2, + 6 + ] + ] + }, + { + "name": "a box 0.1 across, a ground 20 across and a strip 1% of the box's diagonal in front of the box's edge, all one mesh: hidden, the margin is the edge's own connected piece's (O10 reads on 1)", + "ok": true, + "detail": [ + 0.0, + 2, + 6 + ] + }, + { + "name": "a box 0.1 across over a ground 4 across, with a strip 4 long standing between the two margins in front of its edge: hidden, the margin is the smaller object's (O7 reads on 1)", + "ok": true, + "detail": [ + [ + 0.0, + 2, + 6 + ], + 0.000832363492248106 + ] + }, + { + "name": "a box 2 across with two chips 0.05 across standing between the two margins in front of its edge: hidden, the margin is the chips' (O9 reads on 1)", + "ok": true, + "detail": [ + [ + 0.0, + 2, + 6 + ], + 0.0004949232003839765 + ] + }, + { + "name": "a camera 30 box diagonals off still reads the box's 3 creases and 6 contours and its front edge on 1", + "ok": true, + "detail": [ + 1.0, + 3, + 6 + ] + }, + { + "name": "a camera 144 box diagonals off still reads the box's 3 creases and 6 contours and its front edge on 1 (O5 reads 2 contours)", + "ok": true, + "detail": [ + 1.0, + 3, + 6 + ] + } + ], + "hostErrors": [], + "hostRows": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick", + "brokkr_reference.solve_camera", + "brokkr_reference.flow_score" + ], + "BUILT": [ + [ + 0.5, + 0.0, + 0.0 + ], + [ + 0.54375, + 0.09375, + 0.5 + ], + [ + 0.55, + 0.15, + 1.0 + ], + [ + 0.504167, + 0.139583, + 1.5 + ], + [ + 0.483333, + 0.066667, + 2.0 + ], + [ + 0.55, + -0.04375, + 2.5 + ], + [ + 0.616667, + -0.116667, + 3.0 + ], + [ + 0.589583, + -0.089583, + 3.5 + ], + [ + 0.5, + 0.0, + 4.0 + ] + ], + "flow": { + "lines": { + "front": { + "on": 1.0, + "off": 0.0, + "run": 1.0 + }, + "back": { + "on": 0.0, + "off": 5.0, + "run": 0.0 + }, + "fold": { + "on": 0.0, + "off": 5.0, + "run": 0.0 + }, + "top": { + "on": 0.988, + "off": 0.06, + "run": 0.537 + } + }, + "edges": { + "crease": 3, + "contour": 6, + "border": 6 + }, + "objects": [ + "Box", + "Sheet" + ], + "height": 600.0 + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index 18d77e4..56540c8 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -15,6 +15,8 @@ tolerances round a known truth that no mutant claims. The mutants, each run once M6 the turned group is not turned test_a_turned_torso_is_recovered_as_twist M7 square holds the yaw along y only test_square_solves_elevations_along_both_axes M13 the walk stops after 20 steps each way test_a_wide_band_is_walked_to_its_end + G10, G01 core.EXACT ten times looser, ten tighter test_the_exact_gates_sit_at_a_billionth_of_the_marks_extent + PL1, PL3, PL4, PL5 the band and lens_determined test_a_plane_tilted_from_square_on_never_reports_a_lens_it_does_not_decide """ from __future__ import annotations @@ -117,19 +119,20 @@ class SolveTests(unittest.TestCase): self.assertAlmostEqual(s["c"][0], 640.0, delta=5.0) def test_the_band_is_an_equal_error_band(self): - """band-is-equal-error: a build 4 cm off. Every lens in the band refits within BAND of the best rms, and one - step past each end does not.""" + """band-is-equal-error: a build 4 cm off. Every lens inside the band refits within BAND of the best rms; the + band's ends are the first lenses that do not (PL4, a band that stops at the last lens that fits, has ends + that fit).""" world, pixels = marks(self.oblique, self.points, build=0.04) s = core.solve(world, pixels, BOX, model="upright") low, high = s["lens_band"] self.assertLess(low, s["lens"] * 0.95) self.assertGreater(high, s["lens"] * 1.05) - for lens in (low, math.sqrt(low * s["lens"]), math.sqrt(high * s["lens"]), high): + for lens in (low * math.exp(core.STEP), math.sqrt(low * s["lens"]), math.sqrt(high * s["lens"]), high * math.exp(-core.STEP)): self.assertLessEqual(core.solve(world, pixels, BOX, model="upright", lens=lens)["rms"], core.BAND * s["rms"] + 1e-6, lens) - for lens in (low * math.exp(-core.STEP), high * math.exp(core.STEP)): + for lens in (low, high): self.assertGreater(core.solve(world, pixels, BOX, model="upright", lens=lens)["rms"], core.BAND * s["rms"], lens) held = core.solve(world, pixels, BOX, model="upright", lens=low) - self.assertEqual((held["lens"], held["lens_band"], held["lens_at_bound"]), (low, [low, low], None)) + self.assertEqual((held["lens"], held["lens_band"], held["lens_at_bound"], held["lens_determined"]), (low, [low, low], None, None)) def test_the_band_is_walked_from_the_last_solve(self): """M3: each step of the walk is one solve started at the one before; restarting from the grid costs 16 per @@ -211,31 +214,172 @@ class SolveTests(unittest.TestCase): self.assertTrue(issubclass(core.ReferenceFitError, ValueError)) def test_marks_that_decide_no_camera_are_refused(self): - """refusals: marks with no extent, in a line or in a plane are refused by which they are before any solve - (one pixel for every name was a bare ValueError, one world point a record of NaN). A plane is enough once - the lens is held and the centre is not solved.""" + """refusals: marks with no extent or in a line and a plane asked for its centre are refused by which they + are before any solve (one pixel for every name was a bare ValueError, one world point a record of NaN).""" solved, lm = [], core.lm core.lm = lambda *args, **kwargs: solved.append(1) or lm(*args, **kwargs) self.addCleanup(setattr, core, "lm", lm) plane = np.c_[self.points[:, :2], np.zeros(13)] - on_plane = dict(zip(NAMES, plane.tolist())), dict(zip(NAMES, core.project(self.oblique, plane).tolist())) + in_plane = dict(zip(NAMES, plane.tolist())), dict(zip(NAMES, core.project(self.oblique, plane).tolist())) + square_on = in_plane[0], dict(zip(NAMES, core.project(camera(plane, 35, 90, 50), plane).tolist())) line = dict(zip(NAMES, np.outer(np.arange(13.0), [1.0, 2.0, 0.5]).tolist())) cases = (((self.world, {k: [500.0, 400.0] for k in NAMES}), {}, "1 different pixels"), (({k: [1.0, 2.0, 3.0] for k in NAMES}, self.pixels), {}, "1 different world points"), ((self.world, {**self.pixels, **{k: self.pixels["p0"] for k in NAMES[:9]}}), {}, "5 different pixels are marked; six are needed ('p0' and 'p1'"), ((self.world, {k: [100.0 + 10 * i, 200.0 + 5 * i] for i, k in enumerate(NAMES)}), {}, "pixels lie on one line"), ((line, self.pixels), {}, "world points lie on one line"), - (on_plane, {}, "one plane"), (on_plane, {"model": "upright"}, "one plane"), (on_plane, {"model": "free", "lens": 50.0}, "one plane")) + (in_plane, {"model": "free"}, "one plane, which does not decide the centre"), (in_plane, {"model": "free", "lens": 50.0}, "does not decide the centre")) for args, kwargs, said in cases: with self.assertRaises(core.ReferenceFitError) as caught: core.solve(*args, BOX, **kwargs) self.assertIn(said, str(caught.exception)) self.assertEqual(solved, []) - held = core.solve(*on_plane, BOX, model="upright", lens=50.0) + held = core.solve(*square_on, BOX, model="upright", lens=50.0) # with the lens held a plane decides the rest, square-on too self.assertLess(held["rms"], 1e-3) - self.assertAlmostEqual(held["azimuth"], 35.0, delta=0.01) + self.assertAlmostEqual(held["elevation"], 90.0, delta=0.01) + self.assertAlmostEqual(held["plane"], 0.0, delta=0.01) self.assertNotIn("NaN", json.dumps(held)) + def test_a_plane_seen_obliquely_decides_the_lens_and_says_it_is_a_plane(self): + """plane-honest: world points in one plane are solved, not refused: the plane's foreshortening decides the + lens (Zhang's calibration from a plane), "plane" says how far from square-on the view is, and auto leaves + the free model untried, since a plane never decides the centre.""" + plane = np.c_[self.points[:, :2], np.zeros(13)] + world = dict(zip(NAMES, plane.tolist())) + solved = core.solve(world, dict(zip(NAMES, core.project(self.oblique, plane).tolist())), BOX) + self.assertAlmostEqual(solved["lens"], 50.0, delta=0.01) + self.assertAlmostEqual(solved["plane"], 70.0, delta=0.01) + self.assertEqual(sorted(solved["tried"]), ["rolled", "upright"]) + self.assertLess(place_error(solved, self.oblique), 1e-3) + self.assertEqual((solved["planarity"], solved["lens_determined"]), (0.0, True)) + self.assertIsNone(self.auto["plane"]) + self.assertGreater(self.auto["planarity"], core.PLANAR) + self.assertIs(self.auto["lens_determined"], True) + + def test_a_plane_tilted_from_square_on_never_reports_a_lens_it_does_not_decide(self): + """plane-sweep: a plane of thirteen marks seen through a 50 mm lens from square-on to 30 degrees off it, + each mark a pixel off (a second seed at 0 and 3 degrees), and from square-on and a hair off it with exact marks. At every tilt the + band holds 50 mm; where the lens is called determined the headline is within a quarter of 50 mm, and it is + never called determined within 3 degrees of square-on, where the headlines read 4 to 4000 mm; from 15 + degrees on it is. Truth tolerances, no bound a mutant claims by a reading; the mutants die by which + assertion: PL1 (a band open at one end stays closed at the other) at square-on, seed 0, band [309, 4000]; + PL3 (no FINE floor under the band's error) on the exact marks square-on, band [192, 2855]; PL4 (the band + stops at the last lens that fits) at 6 degrees, band [51, 69]; + PL5 (DECIDED 10) at 3 degrees, seed 0, 90 mm called determined.""" + plane = np.c_[self.points[:, :2], np.zeros(13)] + world = dict(zip(NAMES, plane.tolist())) + cases = [(tilt, 1.0, 0) for tilt in (0.0, 3.0, 6.0, 10.0, 15.0, 20.0, 30.0)] + [(0.0, 1.0, 1), (3.0, 1.0, 1), (0.0, 0.0, 0), (1e-5, 0.0, 0)] + for tilt, noise, seed in cases: + drawn = core.project(camera(plane, 35, 90.0 - tilt, 50), plane) + np.random.default_rng(seed).normal(0, noise, (13, 2)) + s = core.solve(world, dict(zip(NAMES, drawn.tolist())), BOX) + said = f"tilt {tilt:g}, noise {noise:g}, seed {seed}: lens {s['lens']:.0f}, band {s['lens_band']}, determined {s['lens_determined']}" + self.assertTrue(s["lens_band"][0] <= 50.0 <= s["lens_band"][1], said) + self.assertNotIn("NaN", json.dumps(s)) + if s["lens_determined"]: + self.assertAlmostEqual(math.log(s["lens"] / 50.0), 0.0, delta=math.log(1.25), msg=said) + self.assertAlmostEqual(s["plane"], tilt, delta=3.0, msg=said) + if tilt <= 3.0: + self.assertIs(s["lens_determined"], False, said) + if tilt < 1.0: + self.assertEqual(s["lens_band"], list(core.LENS_MM), said) + if tilt >= 15.0: + self.assertIs(s["lens_determined"], True, said) + + def test_determined_and_planar_sit_between_readings_either_side(self): + """lens_determined's two thresholds, each between two readings (lodur:ruling:deterministic-bound-margin). + DECIDED: a band spans a whole number of STEPs, so the readings are discrete. Marks with depth seen through + 85 mm, 3 px off, read a band of four steps, 1.4918 times, the widest of 48 such solves, and are called + determined; the same marks 5 px off read five steps, 1.6487, and are not. DECIDED 1.57 is the geometric + mean, 1.05 from each: the readings are one step apart, 1.105, under the ruling's 1.2, and no nearer pair + exists: an exception to the ruling, recorded at core.DECIDED (a band moved one step by a host fails the span + assertion here, loudly). Mutants DECIDED 1.4 and 1.7 die here by which call flips; 2.5 too; 1.5 and 1.6 are + unclaimed, inside the step. PLANAR: a panel with relief (planarity 0.041) seen square-on through 85 mm, + 3 px off, reads a band open at 4000 mm and so is reported open at both ends; marks with depth read 0.36. + PLANAR 0.12 is the geometric mean, 2.9 from each: PLANAR 0.03 leaves the panel's band at [84.4, 4000] and + dies here, as 0.001 and 0.008 do on the flatter panel (0.009); PLANAR 1.0 dies at the oblique view. + Unclaimed: PLANAR 0.3, which differs from shipped in none of 192 solves of panels 0.009 to 0.277 thick.""" + for noise, span, determined in ((3.0, 1.4918, True), (5.0, 1.6487, False)): + drawn = core.project(camera(self.points, 35, 20, 85), self.points) + np.random.default_rng(3).normal(0, noise, (13, 2)) + s = core.solve(dict(zip(NAMES, self.points.tolist())), dict(zip(NAMES, drawn.tolist())), BOX) + self.assertAlmostEqual(s["lens_band"][1] / s["lens_band"][0], span, delta=1e-3) + self.assertIs(s["lens_determined"], determined) + self.assertAlmostEqual(s["planarity"], 0.3615, delta=1e-3) + relief = np.random.default_rng(77).uniform(-1, 1, 13) + for depth, lens, noise, planarity in ((0.01, 50, 1.0, 0.009), (0.045, 85, 3.0, 0.041)): + panel = np.c_[self.points[:, :2], relief / np.ptp(relief) * depth * np.ptp(self.points[:, :2], axis=0).max()] + drawn = core.project(camera(panel, 35, 90.0, lens), panel) + np.random.default_rng(0).normal(0, noise, (13, 2)) + s = core.solve(dict(zip(NAMES, panel.tolist())), dict(zip(NAMES, drawn.tolist())), BOX) + self.assertAlmostEqual(s["planarity"], planarity, delta=5e-4) + self.assertEqual((s["lens_band"], s["lens_determined"]), (list(core.LENS_MM), False)) + + def test_the_exact_gates_sit_at_a_billionth_of_the_marks_extent(self): + """exact-gate: each of _decidable's three tests reads a ratio (the marks' thinnest extent over their + widest) against core.EXACT, 1e-9. Marks at 3.16e-10 are refused + and marks at 3.16e-9 pass: the geometric means of the shipped gate with a gate ten times tighter and ten + times looser, the least mutants claimed (separation 3.16 each side).""" + r = np.random.default_rng(7) + bump = r.normal(0, 1, 13) + plane = np.c_[self.points[:, :2], np.zeros(13)] + line = np.outer(np.linspace(-2, 2, 13), [1.0, 2.0, 0.5]) + across = np.cross([1.0, 2.0, 0.5], [0.0, 0.0, 1.0]) + flat_px, slope = np.c_[np.linspace(200, 900, 13), np.linspace(300, 500, 13)], np.array([-200.0, 700.0]) + thin = lambda A: (lambda s: s[-1] / s[0])(np.linalg.svd(A - A.mean(0), compute_uv=False)) # noqa: E731 + sites = (("pixels lie on one line", lambda t: (self.points, flat_px + t * np.outer(bump, slope)), lambda W, P: thin(P), {}), + ("world points lie on one line", lambda t: (line + t * np.outer(bump, across), np.array(list(self.pixels.values()))), lambda W, P: (lambda s: s[1] / s[0])(np.linalg.svd(W - W.mean(0), compute_uv=False)), {}), + ("does not decide the centre", lambda t: (plane + t * np.outer(bump, [0.0, 0.0, 1.0]), np.array(list(self.pixels.values()))), lambda W, P: thin(W), {"model": "free"})) + for said, make, reading, how in sites: + unit = reading(*make(1e-6)) / 1e-6 # the reading is the offset's size times this, the offset being small + for at, refused in ((3.16e-10, True), (3.16e-9, False)): + W, P = make(at / unit) + self.assertAlmostEqual(reading(W, P) / at, 1.0, delta=0.01, msg=said) + try: + core._decidable(NAMES, W, P, how.get("model", "auto")) + self.assertFalse(refused, f"{said}: marks at {at:g} passed") + except core.ReferenceFitError as refusal: + self.assertTrue(refused, f"{said}: marks at {at:g} were refused: {refusal}") + self.assertIn(said, str(refusal)) + + +@unittest.skipIf(np is None, "numpy") +class FlowTests(unittest.TestCase): + """The crease Blender builds from a cage column, the flow score and the line parsers. Mutants, each run once: + N3 crease_run without the limit step test_crease_run_is_one_level_of_subdivision + N3b its first step weighs (1, 4, 1) / 6 the same + N4 along without the direction test test_along_scores_edges_that_run_with_the_line + N5 (back-facing creases counted) is claimed by tests/live/reference_flow.py.""" + + COLUMN = [[0.5, 0.0, 0.0], [0.6, 0.2, 1.0], [0.4, 0.1, 2.0], [0.7, -0.2, 3.0], [0.5, 0.0, 4.0]] + BUILT = [[0.5, 0.0, 0.0], [0.54375, 0.09375, 0.5], [0.55, 0.15, 1.0], [0.504167, 0.139583, 1.5], [0.483333, 0.066667, 2.0], [0.55, -0.04375, 2.5], + [0.616667, -0.116667, 3.0], [0.589583, -0.089583, 3.5], [0.5, 0.0, 4.0]] # Blender 5.3's level-1 Subdivision of this column creased hard, as tests/live/reference_flow.py printed it + + def test_crease_run_is_one_level_of_subdivision(self): + """crease-run-and-through, N3: against Blender's own numbers, which are the limit curve's (the modifier's + Limit Surface is on unless turned off). Shipped reads 3.3e-7 m, the fixture's rounding; N3b 0.0139 and N3 + 0.0208: the bound is the geometric mean of 3.3e-7 and 0.0139, separation 205 each side.""" + run = core.crease_run(self.COLUMN) + self.assertEqual(run.shape, (9, 3)) + self.assertLess(np.abs(run - np.array(self.BUILT)).max(), 6.8e-5) + + def test_along_scores_edges_that_run_with_the_line(self): + """along-scores, N4: rungs 5 px apart cross the line square-on, each within the 10 px that counts as near.""" + line = [[100.0, 200.0], [500.0, 200.0]] + self.assertEqual(core.along(line, [[80.0, 203.0, 520.0, 203.0]], 1000.0), {"on": 1.0, "off": 0.3, "run": 1.0}) + rungs = [[float(u), 150.0, float(u), 250.0] for u in range(100, 501, 5)] + self.assertEqual(core.along(line, rungs, 1000.0), {"on": 0.0, "off": 5.0, "run": 0.0}) + half = core.along(line, [[100.0, 200.0, 300.0, 200.0]], 1000.0) + self.assertAlmostEqual(half["on"], 0.5, delta=0.03) + self.assertEqual(half["run"], half["on"]) + self.assertEqual(core.along(line, [], 1000.0), {"on": 0.0, "off": 5.0, "run": 0.0}) + + def test_line_parsers(self): + self.assertEqual(core.polyline("1,2 3,4.5", "line_a").tolist(), [[1.0, 2.0], [3.0, 4.5]]) + self.assertEqual({k: v.tolist() for k, v in core.polylines("r: 1,2 3,4; l: 5,6 7,8;", "lines").items()}, {"r": [[1.0, 2.0], [3.0, 4.0]], "l": [[5.0, 6.0], [7.0, 8.0]]}) + for call, text, said in ((core.polyline, "1,2", "no length"), (core.polyline, "1,2 1,2", "no length"), (core.polyline, "1,2 3", "point"), + (core.polylines, "1,2 3,4", "no tag"), (core.polylines, "r: 1,2 3,4; r: 1,2 3,4", "twice"), (core.polylines, " ; ", "no line")): + with self.assertRaises(core.ReferenceFitError) as caught: + call(text, "lines") + self.assertIn(said, str(caught.exception)) + @unittest.skipIf(np is None, "numpy") class CameraTests(unittest.TestCase): @@ -300,13 +444,15 @@ class HostFileTests(unittest.TestCase): def test_the_row_names_the_operator_and_properties_the_add_on_defines(self): source = (SURFACE / "brokkr_reference" / "__init__.py").read_text(encoding="utf-8") - (row,) = self.document["actions"] - self.assertIn(f'bl_idname = "{row["name"]}"', source) - self.assertEqual(row.get("result"), "brokkr_mesh_polish_result") - body = source.split(f'bl_idname = "{row["name"]}"')[1].split("def work")[0] - for field in row["fields"]: - self.assertIn(f" {field['name']}: bpy.props.", body, field["name"]) - self.assertEqual(body.count(": bpy.props."), len(row["fields"])) + self.assertEqual([row["name"] for row in self.document["actions"]], ["brokkr_reference.solve_camera", "brokkr_reference.flow_score"]) + self.assertEqual(source.count("bl_idname = "), 2) + for row in self.document["actions"]: + self.assertIn(f'bl_idname = "{row["name"]}"', source) + self.assertEqual(row.get("result"), "brokkr_mesh_polish_result") + body = source.split(f'bl_idname = "{row["name"]}"')[1].split("def work")[0] + for field in row["fields"]: + self.assertIn(f" {field['name']}: bpy.props.", body, field["name"]) + self.assertEqual(body.count(": bpy.props."), len(row["fields"]), row["name"]) def test_a_valid_intent_is_admitted_and_a_bound_miss_is_refused(self): fields = {"world": "a=0,0,0", "pixels": "a=1,2", "box": "0,0,10,10"} @@ -315,6 +461,11 @@ class HostFileTests(unittest.TestCase): for bad in ({"lens": 4001}, {"model": "fisheye"}, {"width": 8}, {"world": ""}): with self.assertRaises(at.IntentInvalid): at.validate({**self.envelope, **fields, **bad}, self.host) + flow = {**self.envelope, "action": "brokkr_reference.flow_score", "camera_name": "Concept", "lines": "r: 1,2 3,4"} + self.assertEqual((at.validate(flow, self.host)["angle"], at.validate(flow, self.host)["height"]), (18, 0)) + for intent, bad in ((flow, {"angle": 0}), (flow, {"lines": ""}), (flow, {"camera_name": "x" * 64})): + with self.assertRaises(at.IntentInvalid): + at.validate({**intent, **bad}, self.host) class OwnershipTests(unittest.TestCase): @@ -325,9 +476,10 @@ class OwnershipTests(unittest.TestCase): self.assertIsNone(re.search(r"import bpy|mathutils", (SURFACE / "brokkr_reference" / "core.py").read_text(encoding="utf-8"))) def test_the_package_reads_no_image_or_sheet(self): + """Nor does it hold the harness's recipes: the centre plate, the outline descent and their masks stay there.""" for path in (SURFACE / "brokkr_reference").glob("*"): if path.is_file(): - self.assertIsNone(re.search(r"concepts\.json|PIL|Image\.open", path.read_text(encoding="utf-8")), path.name) + self.assertIsNone(re.search(r"concepts\.json|PIL|Image\.open|centre_plate|silhouette|polygon_mask|knotted", path.read_text(encoding="utf-8")), path.name) def test_no_other_package_names_this_one(self): for package in ("brokkr_kitbash", "brokkr_rig", "brokkr_bridge", "brokkr_mesh_polish"): From 968208fd36dd7141276d6688b7c82d60afde2c86 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 04:21:38 +0100 Subject: [PATCH 171/223] brokkr_reference core: fit_runs and fit_sheet, a shell's traced runs fitted through cameras and refused where a trace is not explained The cage points of a loft's traced hard runs move until the runs, as crease_run builds them and the cameras draw them, lie on their traces: analytic Jacobian, Gauss-Newton with LM damping, a prior that holds each point to the sheet as given. A fit is returned only where every point of every trace lies within tol px of its built run; otherwise the refusal names the trace and the span. Per moved point the report says metres per pixel along its sight line and the prior's share of that. Runs crease_run does not build (semi-sharp, a dart end, a point held partway) and free cages are refused before fitting. FitTests with the Orchid c09 fixture (camera record, frame, two hand traces, a blocking column; no mesh). core.seen is pinned against project; _off now serves the explained check (follow-up reference-lift-s5-lows). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/core.py | 273 ++++++++++++++++++ .../tests/fixtures/orchid_c09_traces.json | 224 ++++++++++++++ surfaces/blender/tests/test_reference.py | 220 ++++++++++++++ 3 files changed, 717 insertions(+) create mode 100644 surfaces/blender/tests/fixtures/orchid_c09_traces.json diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index f5b7fe4..5cea4da 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -30,9 +30,18 @@ A traced line is pixels; a part's points are given in its frame, a 4 x 4 frame-t seen(cam, frame, points) pixels of points of a frame crease_run(points) where Blender builds the hard crease of a cage column at one level along(line, segments, height) the flow score: how much of a traced line has a seen edge along it + +A shell's cage (brokkr_kitbash's sheet) is fitted to traces of its hard runs: the cage points of the traced runs +are moved until the runs, as Blender builds them and the cameras draw them, lie on the traces. The fit is returned +only where the built runs explain every trace; docs/reference.md, "fit_shell", says what the answer is worth. + + fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol) the moved cage and the report + fit_sheet(document, cage, frame, traces, cams, share, tol) the same for a sheet's named runs: the fitted sheet """ from __future__ import annotations +import copy +import json import math import numpy as np @@ -438,6 +447,270 @@ def along(line, segments, height, near=0.01, turn=20.0, cap=0.05): return {"on": round(float(on.mean()), 3), "off": round(float(100 * np.minimum(dist / height, cap).mean()), 2), "run": round(best / len(on), 3)} +# --- a shell's traced runs fitted through cameras -------------------------------------------------------------------- + +LEVELS = 2 # crease_run applied this many times gives the samples of a built run the fit draws: 4k - 3 for k cage points +HARD = 1.0 - 1e-9 # a crease weight from here up is hard: the edge stays sharp at every level, which is what crease_run builds +ROUNDS = 60 +RESULT_LIMIT = 16000 # characters of a host result Brokkr copies into a receipt before it truncates (brokkr_bridge's HOST_RESULT_LIMIT; this package imports nothing from Brokkr) + + +def _drawn(cam, frame, X): + """Pixels (n, 2) of points of a frame and their derivative (n, 2, 3) by the points' own coordinates; None where + a point stands behind the camera.""" + F, R, f = np.asarray(frame, float), np.asarray(cam["R"], float), cam["f"] + A = R @ F[:3, :3] + q = (X @ F[:3, :3].T + F[:3, 3] - np.asarray(cam["C"], float)) @ R.T + z = -q[:, 2] + if z.min() <= 1e-6: + return None + u = np.stack([cam["c"][0] + f * q[:, 0] / z, cam["c"][1] - f * q[:, 1] / z], 1) + du = (f / z)[:, None] * A[0] + (f * q[:, 0] / z ** 2)[:, None] * A[2] + dv = -((f / z)[:, None] * A[1] + (f * q[:, 1] / z ** 2)[:, None] * A[2]) + return u, np.stack([du, dv], 1) + + +def _normal(points, line): + """Per point: its distance to a polyline and the unit direction that distance grows along (the nearest + segment's normal; from the segment's end where the point is past it).""" + a, d = line[:-1], line[1:] - line[:-1] + length = np.maximum((d * d).sum(1), 1e-18) + t = np.clip(((points[:, None] - a) * d).sum(2) / length, 0, 1) + off = points[:, None] - (a + t[:, :, None] * d) + dist = np.linalg.norm(off, axis=2) + k, i = dist.argmin(1), np.arange(len(points)) + dist, off = dist[i, k], off[i, k] + on = dist < 1e-9 + n = off / np.maximum(dist, 1e-12)[:, None] + n[on] = (np.stack([-d[k, 1], d[k, 0]], 1) / np.sqrt(length[k])[:, None])[on] + return dist, n + + +def _hard_runs(cage, runs): + """Refuse a run crease_run does not build. Blender builds crease_run where every edge of the run is hard, every + point between its ends has those two sharp edges and no other, and each end holds: a hard corner point, three + or more hard or boundary edges, or, on a cage whose Subdivision preserves corners (a loft's; cage.boundary), a + boundary point of two edges.""" + weight = {(int(min(a, b)), int(max(a, b))): float(w) for (a, b), w in zip(np.asarray(cage.creases).reshape(-1, 2), cage.weights)} + pinned = {int(v): float(w) for v, w in zip(cage.corners, cage.corner_weights)} + loops, sides = np.asarray(cage.faces), [] + for first, size in zip(np.concatenate([[0], np.cumsum(cage.counts)[:-1]]), cage.counts): + face = loops[first:first + size] + sides += [np.sort(np.stack([face, np.roll(face, -1)], 1), axis=1)] + sides = np.concatenate(sides) + pairs, count = np.unique(sides, axis=0, return_counts=True) + at = {} # vertex -> [(weight, on the boundary)] of its edges + for (a, b), faces in zip(pairs, count): + w = weight.get((int(a), int(b)), 0.0) + for v in (int(a), int(b)): + at.setdefault(v, []).append((w, faces == 1)) + for run in runs: + name, chain = run["name"], [int(v) for v in run["chain"]] + if len(chain) < 2 or len(set(chain)) != len(chain): + raise ReferenceFitError(f"{name}: its run must be two or more cage points, none twice (a closed loop has no end to hold)") + for m, (a, b) in enumerate(zip(chain, chain[1:])): + w = weight.get((min(a, b), max(a, b))) + if w is None or w < HARD: + raise ReferenceFitError(f"{name}: the edge after point {m} of its run has crease weight {w or 0:g}. Only a hard run (every edge 1) is built where " + "the fit draws it; a semi-sharp or uncreased edge rounds off by an amount the fit does not model. Crease it 1, or leave the run untraced") + for m, v in enumerate(chain): + sharp = [w for w, rim in at[v] if w > 0 or rim] + if 0 < m < len(chain) - 1: + if len(sharp) != 2 or pinned.get(v, 0.0) > 0: + raise ReferenceFitError(f"{name}: point {m} of its run is held or pulled by more than the run (a corner point, or another crease or the rim " + "meeting it there). Trace the run as two, one each side of that point") + elif not (pinned.get(v, 0.0) >= HARD or sum(1 for w, rim in at[v] if w >= HARD or rim) >= 3 or (len(at[v]) == 2 and cage.boundary == "PRESERVE_CORNERS")): + raise ReferenceFitError(f"{name}: the {'first' if m == 0 else 'last'} end of its run does not hold: it is a dart (the crease dies out into the surface " + "there) or runs on, on a mirrored sheet across the middle. An end holds at a corner point of weight 1, where three or " + "more hard edges meet, or on the rim") + + +def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=3.0): + """Move a cage's points until its hard runs, as built and as cameras draw them, lie on their traces. + + views [(camera record, frame)]: the frame is the 4 x 4 that carries the cage to the world + cage the parsed sheet (brokkr_kitbash.core.Sheet's V, faces, counts, creases, weights, corners, + corner_weights, boundary) + runs [{"name", "chain": cage vertices in order, "view": index into views, "line": [[u, v], ...]}]; the + line is drawn from the chain's first point to its last + movable (vertices, 3) of bool: the coordinates that may move. Only authored vertices move + mirror_of per vertex, the authored vertex it mirrors across x = 0, or itself: a mirrored half is the same + parameters seen again, x negated + share the prior: a move of share x diag from the cage as given costs what one pixel of miss does + tol pixels: every point of every trace must lie this near its built run as drawn + + The residual per run is the pixel distance from each built point (crease_run LEVELS times, drawn through the + run's view) to the trace, and the run's two ends against the trace's; no point of the trace is matched to a + point of the run beyond that. Gauss-Newton with Levenberg-Marquardt damping on the analytic Jacobian. Returns + (V, report): the cage's vertices as fitted and {"traces": [{"miss_px": rms of the built points off the trace, + "unexplained_px": the trace's furthest point from the built run}], "points": [{"vertex", "moved_m", + "m_per_px", "prior_share"}], "rounds"}. m_per_px is how far the point slides along its sight line (the worst + of the views that trace it) per pixel of error in the traces, sqrt(r' S r) with S the point's block of the + inverse of J'J, prior included (Triggs et al. 2000, sections 9 and 10); prior_share is that over share x + diag: near 1 the traces say nothing about the point's depth and it stands where it was blocked. + + Raises ReferenceFitError for a run it cannot model (_hard_runs), and when a trace is not explained: the error + names the trace and the span of it that lies further than tol from the built run, and carries the rows as + .traces. Nothing is returned as a fit then.""" + V0, movable, mirror_of = np.array(cage.V, float), np.asarray(movable, bool), np.asarray(mirror_of, int) + mirrored = mirror_of != np.arange(len(V0)) + if (movable & mirrored[:, None]).any() or not movable.any(): + raise ReferenceFitError("movable must mark authored vertices, and at least one coordinate") + _hard_runs(cage, runs) + index = np.flatnonzero(movable.ravel()) + column = np.full(V0.size, -1) + column[index] = np.arange(len(index)) + flip, prior = np.where(mirrored, -1.0, 1.0), 1.0 / (share * diag) + prepared = [] + for run in runs: + chain, line = np.asarray(run["chain"], int), np.asarray(run["line"], float) + if not 0 <= run["view"] < len(views): + raise ReferenceFitError(f"{run['name']}: view {run['view']} is none of the {len(views)} views") + if line.ndim != 2 or line.shape[1] != 2 or len(line) < 2 or not np.isfinite(line).all() or np.linalg.norm(np.diff(line, axis=0), axis=1).sum() < 1e-9: + raise ReferenceFitError(f"{run['name']}: its line must be two or more [u, v] points, not all in one place") + W = np.eye(len(chain)) + for _ in range(LEVELS): + W = crease_run(W) + source = mirror_of[chain] + prepared.append((run["name"], views[run["view"]], line, W, source, np.stack([flip[chain], np.ones(len(chain)), np.ones(len(chain))], 1), + column.reshape(-1, 3)[source])) # the parameter column of each chain point's coordinate, -1 where held + p0 = V0.ravel()[index] + + def terms(p): + """(residual, Jacobian, each run's built points as drawn) at parameters p.""" + P = V0.copy() + P.ravel()[index] = p + res, rows, drawn = [], [], [] + for name, (cam, frame), line, W, source, sign, cols in prepared: + seen_ = _drawn(cam, frame, W @ (P[source] * sign)) + if seen_ is None: + raise ReferenceFitError(f"{name}: its run stands behind the camera") + u, Ju = seen_ + dist, n = _normal(u, line) + D = np.concatenate([np.einsum("si,sij->sj", n, Ju), Ju[0], Ju[-1]]) # per residual row, its derivative by its own built point + who = np.concatenate([np.arange(len(u)), [0, 0, len(u) - 1, len(u) - 1]]) + block = np.zeros((len(D), len(p))) + for m in range(len(source)): + for c in range(3): + if cols[m, c] >= 0: + block[:, cols[m, c]] += W[who, m] * D[:, c] * sign[m, c] + res += [dist, u[0] - line[0], u[-1] - line[-1]] + rows.append(block) + drawn.append((u, dist)) + return np.concatenate(res + [prior * (p - p0)]), np.vstack(rows + [prior * np.eye(len(p))]), drawn + + p, lam, rounds = p0.copy(), 1e-3, 0 + r, J, drawn = terms(p) + for rounds in range(1, ROUNDS + 1): + A, g = J.T @ J, J.T @ r + for _ in range(12): + step = np.linalg.solve(A + lam * np.diag(np.diag(A)), -g) + try: + r2, J2, drawn2 = terms(p + step) + except ReferenceFitError: + r2 = None + if r2 is not None and r2 @ r2 < r @ r: + p, r, J, drawn, lam = p + step, r2, J2, drawn2, lam / 3 + break + lam *= 4 + else: + break + if np.abs(step).max() < 1e-7: + break + V = V0.copy() + V.ravel()[index] = p + V = V[mirror_of] * np.stack([flip, np.ones(len(V)), np.ones(len(V))], 1) + + traces, refused = [], None + for (name, _, line, *_), (u, dist) in zip(prepared, drawn): + length = np.linalg.norm(np.diff(line, axis=0), axis=1).sum() + dense = resampled(line, int(min(max(length, len(line)), 4000)) + 1) # a point each pixel along it + off = _off(dense, u) + traces.append({"miss_px": round(float(np.sqrt(np.mean(dist ** 2))), 3), "unexplained_px": round(float(off.max()), 3)}) + if off.max() > tol and refused is None: + out = np.flatnonzero(off > tol) * length / (len(dense) - 1) + refused = (f"{name} is not explained: {len(out) * length / (len(dense) - 1):.0f} px of the trace, between {out[0]:.0f} and {out[-1]:.0f} px along it, lie " + f"more than {tol:g} px from the run as built, up to {off.max():.1f} px. Nothing is returned as a fit. The trace draws something this run " + "does not build (an overdrawn or doubled stroke, another edge, a bend the cage has too few points for): redraw it, or give the run more points") + if refused is not None: + error = ReferenceFitError(refused) + error.traces = traces + raise error + S = np.linalg.inv(J.T @ J) + points = [] + for a in np.flatnonzero(movable.any(1)): + cols = column.reshape(-1, 3)[a] + block = np.zeros((3, 3)) + held = cols >= 0 + block[np.ix_(held, held)] = S[np.ix_(cols[held], cols[held])] + worst = 0.0 + for _, (cam, frame), _, _, source, sign, _ in prepared: + for m in np.flatnonzero(source == a): + sight = V[a] * sign[m] - (np.linalg.inv(np.asarray(frame, float)) @ np.r_[np.asarray(cam["C"], float), 1.0])[:3] + sight = sight / np.linalg.norm(sight) * sign[m] # the sight line of the mirrored point, said in the authored point's coordinates + worst = max(worst, float(np.sqrt(sight @ block @ sight))) + points.append({"vertex": int(a), "moved_m": float(np.linalg.norm(V[a] - V0[a])), "m_per_px": worst, "prior_share": worst * prior}) + return V, {"traces": traces, "points": points, "rounds": rounds} + + +def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=3.0): + """fit_runs for a shell's sheet. `document` is the sheet as brokkr_kitbash.shell takes it and `cage` what + brokkr_kitbash.core.sheet parses it to; `frame` carries the shell to the world. `traces` is a list of + {"run": {"ring": i, "from": a, "to": b} or {"column": j, "from": a, "to": b}, "side": 1 or -1, "line": + [[u, v], ...]} (authored indices, as the sheet's creases name runs; side -1 is the mirrored half of a mirrored + sheet; the line is drawn from `from` to `to`), and `cams` the camera record of each. The points of the traced + runs move, a mirrored sheet's point 0 only in its plane. Returns {"sheet": the document with those points + moved, "traces": [{"miss_px", "unexplained_px"}], "points": [{"ring", "point", "moved_m", "m_per_px", + "prior_share"}]}; refuses, before fitting, a result that would pass RESULT_LIMIT characters.""" + mirror, closed = document.get("mirror", False) is True, bool(document.get("closed", False)) + R, N = cage.rings, cage.points + if R is None: + raise ReferenceFitError("the sheet is a free cage: fit_sheet names runs by ring and column, which a loft has and a free cage does not. " + "core.fit_runs takes any cage's vertex chains") + C = (N + 1) // 2 if mirror else N + if not isinstance(traces, list) or not traces: + raise ReferenceFitError("traces must be an array of one or more {camera, box, run, side, line}") + mirror_of = np.arange(R * N) + if mirror: + for i in range(R): + mirror_of[i * N + C - 1 - np.arange(1, C)] = i * N + C - 1 + np.arange(1, C) + movable, runs = np.zeros((R * N, 3), bool), [] + for k, trace in enumerate(traces): + where = f"traces[{k}]" + if not isinstance(trace, dict) or not isinstance(trace.get("run"), dict): + raise ReferenceFitError(f"{where} must be an object with a run") + if cams[k] is None: + raise ReferenceFitError(f"{where}.camera {trace.get('camera')!r} is no camera of this fit") + run, side = trace["run"], trace.get("side", 1) + if side not in (1, -1) or (side == -1 and not mirror): + raise ReferenceFitError(f"{where}.side must be 1, or -1 for the mirrored half of a mirrored sheet, not {side!r}") + ring = "ring" in run + if ring == ("column" in run) or set(run) != {"ring" if ring else "column", "from", "to"}: + raise ReferenceFitError(f"{where}.run must be {{ring, from, to}} or {{column, from, to}}") + across, most = (R, C if closed else C - 1) if ring else (C, R - 1) + numbers_ = [run["ring" if ring else "column"], run["from"], run["to"]] + if any(isinstance(v, bool) or not isinstance(v, int) for v in numbers_) or not (0 <= numbers_[0] < across and 0 <= numbers_[1] < numbers_[2] <= most): + raise ReferenceFitError(f"{where}.run must name a {'ring under ' + str(R) if ring else 'column under ' + str(C)} and from under to, to at most {most}") + fixed, first, last = numbers_ + authored = [(fixed, j % C) if ring else (j, fixed) for j in range(first, last + 1)] + chain = [i * N + ((C - 1 + side * j) if mirror else j) for i, j in authored] + for i, j in authored: + movable[i * N + (C - 1 + j if mirror else j)] = (not (mirror and j == 0), True, True) + runs.append({"name": where, "chain": chain, "view": k, "line": trace.get("line")}) + moved = [(int(v) // N, int(v) % N - (C - 1 if mirror else 0)) for v in np.flatnonzero(movable.any(1))] + size = len(json.dumps(document, separators=(",", ":"))) + 36 * len(moved) + 45 * len(traces) + 95 * len(moved) + 40 + if size > RESULT_LIMIT: + raise ReferenceFitError(f"the fitted sheet and its report would be about {size} characters, over the {RESULT_LIMIT} a receipt carries: nothing was fitted. " + "Fit fewer runs at a time, or a sparser sheet") + V0 = np.array(cage.V, float) + V, report = fit_runs([(cam, frame) for cam in cams], cage, runs, movable, mirror_of, share, float(np.linalg.norm(np.ptp(V0, axis=0))), tol) + out = copy.deepcopy(document) + for i, j in moved: + out["rings"][i][j] = [round(float(x), 6) + 0.0 for x in V[i * N + (C - 1 + j if mirror else j)]] + return {"sheet": out, "traces": report["traces"], "points": [{"ring": i, "point": j, "moved_m": round(row["moved_m"], 4), "m_per_px": round(row["m_per_px"], 4), + "prior_share": round(row["prior_share"], 3)} for (i, j), row in zip(moved, report["points"])]} + + # --- fields ---------------------------------------------------------------------------------------------------------- diff --git a/surfaces/blender/tests/fixtures/orchid_c09_traces.json b/surfaces/blender/tests/fixtures/orchid_c09_traces.json new file mode 100644 index 0000000..b172a7f --- /dev/null +++ b/surfaces/blender/tests/fixtures/orchid_c09_traces.json @@ -0,0 +1,224 @@ +{ + "what": "Orchid concept c09 (one view): the camera record brokkr_reference.solve_camera solved from hand marks, the frame of the ship's mirror plane, the inboard edge of the two upper petals traced by eye (left is the mirrored half), and a blocking column of 8 stations standing up to a tenth of the ship's length off. No mesh and no hull: the sheet the test builds round the column is a strip that exists to carry it.", + "camera": { + "C": [ + -6.168901501633792, + -121.90792252280691, + 2.8948965905734094 + ], + "R": [ + [ + 0.9987259467882663, + -0.05046269128654356, + 0.0 + ], + [ + 0.0009919726785528231, + 0.019632501305770517, + 0.9998067717727681 + ], + [ + -0.05045294047016491, + -0.9985329647440779, + 0.01965754606547003 + ] + ], + "f": 113777.77777777778, + "c": [ + 512.0, + 512.0 + ], + "box": [ + 0.0, + 0.0, + 1024.0, + 1024.0 + ], + "lens": 4000.0 + }, + "frame": [ + [ + 0.7946956336528872, + 0.5885955750367245, + -0.14837148951272178, + 0.03987530991435051 + ], + [ + -0.6006879570259439, + 0.7273858746251298, + -0.3317887395313959, + 0.013782020658254623 + ], + [ + -0.08736605826654754, + 0.35279602951708855, + 0.9316126520286978, + 0.5812516808509827 + ], + [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + ], + "left": [ + [ + 556.3, + 34.2 + ], + [ + 533.3, + 50.0 + ], + [ + 518.8, + 64.6 + ], + [ + 500.0, + 89.6 + ], + [ + 483.3, + 118.8 + ], + [ + 466.7, + 147.9 + ], + [ + 450.0, + 178.3 + ], + [ + 433.3, + 208.3 + ], + [ + 408.3, + 258.3 + ], + [ + 389.6, + 295.8 + ], + [ + 375.0, + 329.2 + ], + [ + 356.3, + 360.4 + ], + [ + 337.5, + 389.6 + ], + [ + 320.8, + 418.8 + ], + [ + 306.3, + 445.8 + ] + ], + "right": [ + [ + 888.8, + 86.7 + ], + [ + 853.3, + 97.9 + ], + [ + 815.8, + 112.5 + ], + [ + 778.3, + 129.2 + ], + [ + 740.8, + 152.1 + ], + [ + 703.3, + 179.2 + ], + [ + 665.8, + 210.4 + ], + [ + 636.7, + 233.3 + ], + [ + 607.5, + 262.5 + ], + [ + 582.5, + 295.8 + ], + [ + 559.6, + 337.5 + ], + [ + 532.5, + 395.8 + ], + [ + 503.3, + 466.7 + ] + ], + "left_side": -1, + "blocking": [ + [ + 0.2278, + 0.3586, + 0.279 + ], + [ + 0.1764, + 0.183, + 0.3436 + ], + [ + 0.1489, + 0.0666, + 0.297 + ], + [ + 0.2226, + 0.1029, + 0.2136 + ], + [ + 0.251, + 0.1112, + 0.0995 + ], + [ + 0.2813, + 0.1228, + 0.0095 + ], + [ + 0.2259, + -0.0472, + 0.0286 + ], + [ + 0.4158, + 0.1062, + -0.1008 + ] + ] +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index 56540c8..23451b0 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -44,6 +44,10 @@ if np is not None: spec = importlib.util.spec_from_file_location("brokkr_reference_core", SURFACE / "brokkr_reference" / "core.py") core = importlib.util.module_from_spec(spec) spec.loader.exec_module(core) + spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_for_reference", SURFACE / "brokkr_kitbash" / "core.py") + kit = importlib.util.module_from_spec(spec) # the sheet's one parser: fit_sheet takes what it parses + sys.modules[spec.name] = kit + spec.loader.exec_module(kit) BOX = [100.0, 50.0, 1100.0, 800.0] NAMES = [f"p{i}" for i in range(13)] @@ -381,6 +385,222 @@ class FlowTests(unittest.TestCase): self.assertIn(said, str(caught.exception)) +FIT_FRAME = [[0.9659258262890683, -0.25881904510252074, 0.0, 0.3], [0.25881904510252074, 0.9659258262890683, 0.0, -0.2], [0.0, 0.0, 1.0, 0.1], [0.0, 0.0, 0.0, 1.0]] # turned 15 degrees about z and moved +FIT_VIEWS = ((35, 20, 50), (-60, 40, 85), (150, 10, 35)) +FIT_K = 10 # cage points in the traced column + + +def crease(A, w, n=400): + """A crease 2 m long on the +x side of a mirror plane, in the shell's frame: the family the fit was mapped on.""" + t = np.linspace(0, 1, n) + return np.stack([0.4 + A * np.sin(w * t), -1.0 + 2.0 * t, 0.5 + 0.3 * t * t], 1) + + +def overdrawn(line, start, stop, off, kind): + """A stroke that runs along `line`, and between two shares of it doubles back and over again, each pass `off` + of the line's extent further to one side: a trace drawn twice over.""" + n = len(line) + i0, i1 = int(start * (n - 1)), int(stop * (n - 1)) + v = line[i1] - line[i0] + d = np.array([-v[1], v[0]]) / np.linalg.norm(v) * off * np.ptp(line, axis=0).max() + forward, back = line[i0:i1 + 1], line[i1:i0 - 1 if i0 > 0 else None:-1] + if kind == "mid": + return np.vstack([line[:i1 + 1], back + d, forward + 2 * d, line[i1 + 1:]]) + if kind == "truth-last": + return np.vstack([line[:i0], forward + d, back + 2 * d, line[i0:]]) + return np.vstack([line[:i0], forward + d, back + 2 * d, forward, line[i1 + 1:]]) + + +def strip(column, weight=1.0, last=None): + """A mirrored sheet three points wide whose column 1 is `column`, creased from ring 0 to `last` (the far rim).""" + return {"mirror": True, "rim": 1.0, "creases": [{"column": 1, "from": 0, "to": len(column) - 1 if last is None else last, "weight": weight}], + "rings": [[[0.0, float(p[1]), float(p[2]) + 0.15], [float(v) for v in p], [float(p[0]) + 0.5, float(p[1]), float(p[2]) - 0.2]] for p in column]} + + +def blocked(A, w, share): + """(the true crease, a strip whose column stands up to `share` of the crease's 2 m off it).""" + truth, t, r = crease(A, w), np.linspace(0, 1, FIT_K), np.random.default_rng(int(A * 100 + w * 10)) + bump = sum(r.normal(0, 1, 3)[None] * np.sin(np.pi * (j + 1) * t)[:, None] for j in range(2)) + return truth, strip(core.resampled(truth, FIT_K) + share * 2.0 * bump / np.abs(bump).max()) + + +def fit_views(truth): + both = np.vstack([truth, truth * [-1, 1, 1]]) @ np.array(FIT_FRAME)[:3, :3].T + np.array(FIT_FRAME)[:3, 3] + return [camera(both, *view) for view in FIT_VIEWS] + + +def pair_traces(a, b=None): + run = {"column": 1, "from": 0, "to": FIT_K - 1} + return [{"camera": "View", "run": run, "side": side, "line": np.asarray(line).tolist()} for side, line in ((1, a), (-1, b)) if line is not None] + + +def fitted(document, traces, cam, **more): + return core.fit_sheet(document, kit.sheet(document), FIT_FRAME, traces, [cam] * len(traces), **more) + + +def off_truth(document, truth): + """The furthest the column's built run stands from the true crease, or the crease's ends from the run.""" + run = core.resampled(core.crease_run(core.crease_run(np.array(document["rings"])[:, 1])), 400) + return max(float(core._off(run, truth).max()), float(core._off(truth[[0, -1]], run).max())) + + +@unittest.skipIf(np is None, "numpy") +class FitTests(unittest.TestCase): + """fit_runs and fit_sheet: a shell's traced runs fitted through cameras, accepted only where the built runs + explain every trace. Bounds follow lodur:ruling:deterministic-bound-margin. Mutants, each run once on a copy: + F1 no explained check test_an_overdrawn_stroke_is_refused_naming_its_trace + F2 sensitivity across the run's tangent, not the ray test_the_sight_line_reading_holds_the_points_slide_along_its_run + F3 the prior left out of S test_one_trace_alone_reads_as_held_by_the_blocking + F4 no end terms test_a_mirrored_column_is_recovered_from_a_blocking_well_off + F5 a semi-sharp run admitted test_refusals_name_their_field_before_fitting + F6 (the Jacobian by differences) costs time only: tests/live/reference_fit.py's header says how much.""" + + @classmethod + def setUpClass(cls): + cls.orchid = json.loads((Path(__file__).resolve().parent / "fixtures" / "orchid_c09_traces.json").read_text(encoding="utf-8")) + + def test_the_projection_derivative_is_the_projections(self): + cam, X = camera(cloud(), 35, 20, 50), cloud() + u, J = core._drawn(cam, FIT_FRAME, X) + self.assertLess(np.abs(u - core.seen(cam, FIT_FRAME, X)).max(), 1e-9) + self.assertLess(np.abs(core.seen(cam, FIT_FRAME, X) - core.project(cam, X @ np.array(FIT_FRAME)[:3, :3].T + np.array(FIT_FRAME)[:3, 3])).max(), 1e-9) # seen is project past the frame + for c in range(3): + step = np.zeros(3) + step[c] = 1e-6 + numeric = (core.seen(cam, FIT_FRAME, X + step) - core.seen(cam, FIT_FRAME, X - step)) / 2e-6 + self.assertLess(np.abs(numeric - J[:, :, c]).max(), 1e-4 * np.abs(J).max()) + self.assertIsNone(core._drawn(cam, np.eye(4), np.array([cam["C"]]) - np.array(cam["R"])[2] * -1.0)) # a point behind it + + def test_a_mirrored_column_is_recovered_from_a_blocking_well_off(self): + """fit-recovers, F4: each of three views alone, both halves traced, from blockings 0.10 m and 0.30 m off. + Shipped: the built run ends within 0.67 mm of the true crease (the 3 mm asked is a tolerance round a known + truth) and the worst trace is explained within 0.196 px. F4 (no end terms): the run stops short of its + traces, three fits are refused at 3.6 px and up, and the worst it explains reads 2.06 px: the bound is the + geometric mean of 0.196 and 2.06, separation 3.2 each side.""" + worst = 0.0 + for A, w in ((0.2, 2.5), (0.1, 5.0), (0.4, 1.0)): + for share in (0.05, 0.15): + truth, document = blocked(A, w, share) + self.assertGreater(off_truth(document, truth), 0.09) + for cam in fit_views(truth): + out = fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1])), cam) + worst = max(worst, off_truth(out["sheet"], truth)) + self.assertLess(max(row["unexplained_px"] for row in out["traces"]), 0.64) + self.assertEqual(len(out["points"]), FIT_K) + self.assertLess(worst, 0.003) + + def test_an_overdrawn_stroke_is_refused_naming_its_trace(self): + """overdraw-refused, F1: the mirrored half's trace doubled back over part of itself 3% of its extent off. + All 27 are refused, naming the trace and the span that no built run draws; the least unexplained reads + 8.98 px against the 3 asked, separation 3.0. F1 returns all 27 as fits, the worst 0.104 m off the truth.""" + truth, document = blocked(0.2, 2.5, 0.05) + least = 1e9 + for cam in fit_views(truth): + a, b = core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1]) + for start, stop in ((0.1, 0.3), (0.3, 0.7), (0.6, 1.0)): + for kind in ("mid", "truth-last", "truth-first"): + with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[[01]\] is not explained: \d+ px of the trace, between \d+ and \d+ px along it") as caught: + fitted(document, pair_traces(a, overdrawn(b, start, stop, 0.03, kind)), cam) + least = min(least, max(row["unexplained_px"] for row in caught.exception.traces)) + self.assertGreater(least, 3.0 * 1.2) # lodur:ruling:deterministic-bound-margin's least separation + + def test_an_accepted_fit_is_within_its_own_reported_reach(self): + """accepted-bounded: the same strokes 0.2% off pass as explained (they are under 3 px from one line), and + every accepted fit stands within tol x the worst m_per_px it reports of the truth: all 27 are accepted, + the worst 8.9 mm off, 0.024 of that reach (F2 reads 0.27 of its own). No mutant claims this bound.""" + truth, document = blocked(0.2, 2.5, 0.05) + accepted, most = 0, 0.0 + for cam in fit_views(truth): + a, b = core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1]) + for start, stop in ((0.1, 0.3), (0.3, 0.7), (0.6, 1.0)): + for kind in ("mid", "truth-last", "truth-first"): + try: + out = fitted(document, pair_traces(a, overdrawn(b, start, stop, 0.002, kind)), cam) + except core.ReferenceFitError: + continue + accepted += 1 + most = max(most, off_truth(out["sheet"], truth) / (3.0 * max(row["m_per_px"] for row in out["points"]))) + self.assertEqual(accepted, 27) + self.assertLess(most, 1.0) + + def test_one_trace_alone_reads_as_held_by_the_blocking(self): + """F3: one half traced in one view decides nothing along the sight line, and the prior is all that holds + each point there: prior_share reads 1.0, its ceiling. F3 (the prior left out of S) reads 771366.""" + truth, document = blocked(0.2, 2.5, 0.05) + cam = fit_views(truth)[0] + shares = [row["prior_share"] for row in fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth)), cam)["points"]] + self.assertEqual((min(shares), max(shares)), (1.0, 1.0)) + + def test_the_sight_line_reading_holds_the_points_slide_along_its_run(self): + """F2: m_per_px is along the sight line whole. This column recedes along the view (its tangent 24 to 38 + degrees off the sight line), so with both halves traced, which decide the built run to 0.2 mm, an inner + cage point still slides along its own run on the prior alone and reads a prior_share of 0.633 to 0.88; the + ends, which hold, read 0.024 and under. F2 (the ray's part across the tangent) reads the inner points 0.039 + at most: the bound is the geometric mean of 0.633 and 0.039, separation 4.0 each side.""" + truth, document = blocked(0.2, 2.5, 0.05) + cam = fit_views(truth)[0] + shares = [row["prior_share"] for row in fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1])), cam)["points"]] + self.assertGreater(min(shares[1:-1]), 0.157) + self.assertLess(max(shares[0], shares[-1]), 0.157) + self.assertLessEqual(max(shares), 1.0) + + def orchid_strip(self): + return strip(np.array(self.orchid["blocking"])) + + def orchid_fit(self, lines, tol): + document, run = self.orchid_strip(), {"column": 1, "from": 0, "to": 7} + traces = [{"camera": "Concept", "run": run, "side": side, "line": line} for side, line in lines] + return core.fit_sheet(document, kit.sheet(document), self.orchid["frame"], traces, [self.orchid["camera"]] * len(traces), tol=tol) + + ORCHID_TOL = 18.5 # px: the geometric mean of 9.2, the pair's unexplained reading as drawn, and 37.3, its reading with the right trace moved 40 px: separation 2.0 each side + + def test_orchid_c09_hand_traces(self): + """orchid-c09: the inboard edges of two petals traced by hand on one concept view, through a camera solved + from hand marks (13 px rms). At the default 3 px the pair is refused: the left trace's first 10 px stand up + to 9.2 px off the built run, because the two traces' tips are not one point and its mirror image through + that camera (the right trace reads 2.4 px). Asked at ORCHID_TOL the pair is explained, and the worst + prior_share of its points is 0.119 (0.024 m per px); either trace alone reads 1.0 on every point: the bound + is the geometric mean of 0.119 and 1.0, separation 2.9 each side. The right trace moved 40 px is refused.""" + left, right, side = self.orchid["left"], self.orchid["right"], self.orchid["left_side"] + with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[0\] is not explained: 11 px of the trace, between 0 and 10 px along it, .* up to 9\.2 px"): + self.orchid_fit([(side, left), (-side, right)], 3.0) + pair = self.orchid_fit([(side, left), (-side, right)], self.ORCHID_TOL) + self.assertLess(max(row["unexplained_px"] for row in pair["traces"]), self.ORCHID_TOL / 2.0) + self.assertLess(max(row["prior_share"] for row in pair["points"]), 0.345) + self.assertEqual(pair["sheet"]["rings"][3][0], self.orchid_strip()["rings"][3][0]) # only the traced column moves + for alone in ([(side, left)], [(-side, right)]): + self.assertGreater(min(row["prior_share"] for row in self.orchid_fit(alone, self.ORCHID_TOL)["points"]), 0.345) + with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[0\] is not explained") as caught: + self.orchid_fit([(side, left), (-side, (np.array(right) + [0.0, 40.0]).tolist())], self.ORCHID_TOL) + self.assertGreater(max(row["unexplained_px"] for row in caught.exception.traces), self.ORCHID_TOL * 2.0) + + def test_refusals_name_their_field_before_fitting(self): + """refusals, F5 (which takes the semi-sharp run as far as its end and refuses it there for another cause).""" + truth, document = blocked(0.2, 2.5, 0.05) + cam = fit_views(truth)[0] + a = core.seen(cam, FIT_FRAME, truth) + column = np.array(document["rings"])[:, 1] + crossed = strip(column) + crossed["creases"].append({"ring": 4, "from": 0, "to": 2, "weight": 1.0}) + big = strip(core.resampled(column, 64)) + big["rings"] = [[ring[0]] + [[ring[1][0] + 0.01 * j, ring[1][1], ring[1][2]] for j in range(30)] for ring in big["rings"]] + whole = {"column": 1, "from": 0, "to": 63} + for sheet_, traces, cams, message in ( + (strip(column, weight=0.6), pair_traces(a), [cam], r"^traces\[0\]: the edge after point 0 of its run has crease weight 0\.6"), + (strip(column, last=FIT_K - 2), [dict(pair_traces(a)[0], run={"column": 1, "from": 0, "to": FIT_K - 2})], [cam], r"^traces\[0\]: the last end of its run does not hold: it is a dart"), + (strip(column, last=FIT_K - 2), pair_traces(a), [cam], r"^traces\[0\]: the edge after point 8 of its run has crease weight 0\b"), + (crossed, pair_traces(a), [cam], r"^traces\[0\]: point 4 of its run is held or pulled by more than the run"), + (document, pair_traces(a), [None], r"^traces\[0\]\.camera 'View' is no camera"), + (document, [dict(pair_traces(a)[0], line=[[10.0, 20.0]])], [cam], r"^traces\[0\]: its line must be two or more"), + (document, [dict(pair_traces(a)[0], side=2)], [cam], r"^traces\[0\]\.side must be 1"), + (document, [dict(pair_traces(a)[0], run={"column": 3, "from": 0, "to": 2})], [cam], r"^traces\[0\]\.run must name a column under 3"), + (document, [dict(pair_traces(a)[0], run={"ring": 0, "from": 0, "to": 2})], [cam], r"^traces\[0\]: the first end of its run does not hold"), + ({"verts": [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], "faces": [[0, 1, 2, 3]]}, pair_traces(a), [cam], r"^the sheet is a free cage"), + (big, [dict(pair_traces(a)[0], run=whole)], [cam], r"would be about \d+ characters, over the 16000 a receipt carries: nothing was fitted")): + with self.assertRaisesRegex(core.ReferenceFitError, message): + core.fit_sheet(sheet_, kit.sheet(sheet_), FIT_FRAME, traces, cams) + + @unittest.skipIf(np is None, "numpy") class CameraTests(unittest.TestCase): CAM = {"C": [3.0, -7.0, 2.5], "f": 1400.0, "c": [640.0, 395.0], "box": BOX} From 617233f5671a36995f9a9ac5963fc455f7060f2a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 04:22:23 +0100 Subject: [PATCH 172/223] brokkr_reference.fit_shell: the action over core.fit_sheet; reads the shell's request through brokkr_kitbash's parser and writes nothing Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/__init__.py | 64 ++++++++++++++++++- .../brokkr_reference/brokkr_actions.json | 41 ++++++++++++ surfaces/blender/tests/test_reference.py | 17 ++++- 3 files changed, 117 insertions(+), 5 deletions(-) diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index 4f93a0b..d6c31d6 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -1,5 +1,6 @@ """Fit a scene to a reference image: the camera a reference view was drawn through, solved from marked points, -and traced lines scored against the edges the camera sees on the build. +traced lines scored against the edges the camera sees on the build, and a kitbash shell's sheet fitted to traces of +its hard runs. A host add-on for Brokkr beside brokkr_mesh_polish (it imports that package's operator base, and nothing from Brokkr): brokkr_actions.json beside this file lists the operators agents may run (docs/reference.md). The @@ -9,12 +10,17 @@ JSON report to WindowManager.brokkr_mesh_polish_result, as the polish operators The camera record core.solve returns is the truth; a Blender camera stood at it is derived by core.blender, and core.camera_of reads one back (flow_score takes the camera that way, by its object's name). The images, traces and masks a view is marked on stay with whoever marked them: this package takes points and lines and gives -cameras and scores. The edges flow_score reads are computed on each call and kept nowhere. +cameras, scores and a fitted sheet. The edges flow_score reads are computed on each call and kept nowhere. + +fit_shell reads a shell's request through brokkr_kitbash (the sheet's one parser) and returns a sheet; it writes +nothing. brokkr_kitbash.shell is the cage's one writer: the caller applies the fitted sheet with it. """ bl_info = {"name": "Brokkr Reference", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), "category": "Camera", "description": "Solve a reference view's camera from marked points; agent-callable through Brokkr."} +import json import math +import time import bpy import numpy as np @@ -204,7 +210,59 @@ class BROKKR_REFERENCE_OT_flow_score(PolishOperator): "objects": [o.name for o in meshes], "height": height} -classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_flow_score) +class BROKKR_REFERENCE_OT_fit_shell(PolishOperator): + """Fit a kitbash shell's sheet to traces of its hard runs through solved cameras, and return the fitted sheet + only where the built runs explain every trace; nothing is written""" + bl_idname = "brokkr_reference.fit_shell" + bl_label = "Fit Shell To Traces" + object_name: bpy.props.StringProperty(name="Object", maxlen=63, description="A loft shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame") + traces: bpy.props.StringProperty(name="Traces", maxlen=12000, description="A JSON array of {camera, box, run: {ring|column, from, to}, side, line: [[u, v], ...]}") + share: bpy.props.FloatProperty(name="Share", default=0.1, min=0.001, max=10.0, description="A move of this share of the sheet's diagonal from the sheet as it stands costs what one pixel of miss does") + tol: bpy.props.FloatProperty(name="Tolerance", default=3.0, min=0.1, max=100.0, description="Pixels: every point of every trace must lie this near its built run, or the fit is refused") + + def work(self, context): + try: + import brokkr_kitbash + except ImportError as error: + raise Refused(f"fit_shell needs the brokkr_kitbash add-on beside this one ({error}).") from None + obj = bpy.data.objects.get(self.object_name) + if obj is None or obj.type != "MESH" or brokkr_kitbash.SHELL not in obj: + raise Refused(f"{self.object_name!r} is not a shell brokkr_kitbash.shell made (a mesh carrying {brokkr_kitbash.SHELL}).") + if max(abs(v - 1.0) for v in obj.matrix_world.to_scale()) > 1e-6: + raise Refused(f"{obj.name!r} is scaled {tuple(round(v, 6) for v in obj.matrix_world.to_scale())}: a sheet is in metres of the shell's own frame. Apply or clear the scale.") + try: + document = json.loads(obj[brokkr_kitbash.SHELL])["sheet"] + cage = brokkr_kitbash.core.sheet(document) + except (ValueError, KeyError, TypeError, brokkr_kitbash.core.KitError) as error: + raise Refused(f"{obj.name!r} carries a request its own parser does not take ({error}).") from None + try: + traces = json.loads(self.traces) + except ValueError as error: + raise Refused(f"traces is not JSON ({error}).") from None + if not isinstance(traces, list) or not all(isinstance(trace, dict) for trace in traces): + raise Refused("traces must be a JSON array of objects {camera, box, run, side, line}.") + cams = [] + for k, trace in enumerate(traces): + if set(trace) - {"camera", "box", "run", "side", "line"}: + raise Refused(f"traces[{k}] has {sorted(set(trace) - {'camera', 'box', 'run', 'side', 'line'})}: a trace is {{camera, box, run, side, line}}.") + box = trace.get("box") + if box is not None and not (isinstance(box, list) and len(box) == 4 and all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in box)): + raise Refused(f"traces[{k}].box must be [u0, v0, u1, v1], or absent for the render's own frame.") + if not isinstance(trace.get("camera"), str): + raise Refused(f"traces[{k}].camera must name a camera object.") + try: + cams.append(record(context, trace["camera"], "" if box is None else ",".join(repr(float(v)) for v in box))) + except (Refused, core.ReferenceFitError) as refusal: + raise Refused(f"traces[{k}]: {refusal}") from None + started = time.perf_counter() + try: + out = core.fit_sheet(document, cage, [list(row) for row in obj.matrix_world], traces, cams, share=self.share, tol=self.tol) + except core.ReferenceFitError as refusal: + raise Refused(f"{refusal}. Nothing changed.") from None + return {"object": obj.name, **out, "seconds": round(time.perf_counter() - started, 3)} + + +classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_flow_score, BROKKR_REFERENCE_OT_fit_shell) def register(): diff --git a/surfaces/blender/brokkr_reference/brokkr_actions.json b/surfaces/blender/brokkr_reference/brokkr_actions.json index 9bfe98f..6822511 100644 --- a/surfaces/blender/brokkr_reference/brokkr_actions.json +++ b/surfaces/blender/brokkr_reference/brokkr_actions.json @@ -133,6 +133,47 @@ "doc": "degrees between two faces' normals past which their edge is a crease" } ] + }, + { + "name": "brokkr_reference.fit_shell", + "doc": "Fit a kitbash loft shell's sheet to traces of its hard crease and rim runs, each seen through a scene camera: the traced runs' cage points move until the runs as built draw on the traces. Returns the fitted sheet for brokkr_kitbash.shell only where every point of every trace lies within tol px of its built run; otherwise it is refused naming the trace and the span. Writes nothing. Per moved point: metres per pixel along its sight line and the prior's share of that (docs/reference.md).", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "a loft shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame" + }, + { + "name": "traces", + "type": "string", + "required": true, + "minLength": 2, + "maxLength": 12000, + "doc": "a JSON array of {camera, box, run, side, line}: camera a camera object's name; box [u0,v0,u1,v1], its frame on the image, absent for the render's own; run {ring, from, to} or {column, from, to} in authored indices, as the sheet's creases name runs; side 1, or -1 for the mirrored half; line [[u,v],...] drawn from `from` to `to`" + }, + { + "name": "share", + "type": "number", + "minimum": 0.001, + "maximum": 10, + "default": 0.1, + "doc": "the prior: a move of this share of the sheet's diagonal from the sheet as it stands costs what one pixel of miss does" + }, + { + "name": "tol", + "type": "number", + "minimum": 0.1, + "maximum": 100, + "default": 3, + "doc": "pixels: every point of every trace must lie this near its built run, or the fit is refused" + } + ] } ] } diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index 23451b0..eaacde6 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -664,8 +664,8 @@ class HostFileTests(unittest.TestCase): def test_the_row_names_the_operator_and_properties_the_add_on_defines(self): source = (SURFACE / "brokkr_reference" / "__init__.py").read_text(encoding="utf-8") - self.assertEqual([row["name"] for row in self.document["actions"]], ["brokkr_reference.solve_camera", "brokkr_reference.flow_score"]) - self.assertEqual(source.count("bl_idname = "), 2) + self.assertEqual([row["name"] for row in self.document["actions"]], ["brokkr_reference.solve_camera", "brokkr_reference.flow_score", "brokkr_reference.fit_shell"]) + self.assertEqual(source.count("bl_idname = "), 3) for row in self.document["actions"]: self.assertIn(f'bl_idname = "{row["name"]}"', source) self.assertEqual(row.get("result"), "brokkr_mesh_polish_result") @@ -686,6 +686,11 @@ class HostFileTests(unittest.TestCase): for intent, bad in ((flow, {"angle": 0}), (flow, {"lines": ""}), (flow, {"camera_name": "x" * 64})): with self.assertRaises(at.IntentInvalid): at.validate({**intent, **bad}, self.host) + fit = {**self.envelope, "action": "brokkr_reference.fit_shell", "object_name": "Plate", "traces": "[{}]"} + self.assertEqual((at.validate(fit, self.host)["share"], at.validate(fit, self.host)["tol"]), (0.1, 3)) + for bad in ({"tol": 0}, {"share": 11}, {"traces": ""}, {"object_name": "x" * 64}): + with self.assertRaises(at.IntentInvalid): + at.validate({**fit, **bad}, self.host) class OwnershipTests(unittest.TestCase): @@ -701,6 +706,14 @@ class OwnershipTests(unittest.TestCase): if path.is_file(): self.assertIsNone(re.search(r"concepts\.json|PIL|Image\.open|centre_plate|silhouette|polygon_mask|knotted", path.read_text(encoding="utf-8")), path.name) + def test_fit_shell_never_writes_the_request_and_nothing_here_searches_a_correspondence(self): + """The cut's negative patterns: brokkr_kitbash.shell is the cage's one writer, and no point's depth is + decided by matching trace points to each other.""" + for path in (SURFACE / "brokkr_reference").glob("*.py"): + text = path.read_text(encoding="utf-8") + self.assertIsNone(re.search(r"def pair|_smoothest|cage_through|on_plane", text), path.name) + self.assertIsNone(re.search(r"SHELL\] *=|kit_shell\"\] *=|\.data\.vertices|foreach_set|from_pydata", text), path.name) + def test_no_other_package_names_this_one(self): for package in ("brokkr_kitbash", "brokkr_rig", "brokkr_bridge", "brokkr_mesh_polish"): for path in (SURFACE / package).rglob("*.py"): From cad1a69def7ed3d0715f3700be7f6829da756a73 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 04:29:14 +0100 Subject: [PATCH 173/223] tests/live/reference_fit.py: fit_shell through run_intent on a mirrored shell, applied by brokkr_kitbash.shell and scored by flow_score fit_shell's float bounds stand just under the row's (a float property rounds 0.001 and 0.1 up). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/__init__.py | 5 +- surfaces/blender/tests/live/reference_fit.py | 219 ++++++++++++++++++ .../tests/live/reference_fit.result.json | 184 +++++++++++++++ 3 files changed, 406 insertions(+), 2 deletions(-) create mode 100644 surfaces/blender/tests/live/reference_fit.py create mode 100644 surfaces/blender/tests/live/reference_fit.result.json diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index d6c31d6..ad652d6 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -217,9 +217,10 @@ class BROKKR_REFERENCE_OT_fit_shell(PolishOperator): bl_label = "Fit Shell To Traces" object_name: bpy.props.StringProperty(name="Object", maxlen=63, description="A loft shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame") traces: bpy.props.StringProperty(name="Traces", maxlen=12000, description="A JSON array of {camera, box, run: {ring|column, from, to}, side, line: [[u, v], ...]}") - share: bpy.props.FloatProperty(name="Share", default=0.1, min=0.001, max=10.0, description="A move of this share of the sheet's diagonal from the sheet as it stands costs what one pixel of miss does") - tol: bpy.props.FloatProperty(name="Tolerance", default=3.0, min=0.1, max=100.0, description="Pixels: every point of every trace must lie this near its built run, or the fit is refused") + share: bpy.props.FloatProperty(name="Share", default=0.1, min=0.0009, max=10.0, description="A move of this share of the sheet's diagonal from the sheet as it stands costs what one pixel of miss does") + tol: bpy.props.FloatProperty(name="Tolerance", default=3.0, min=0.09, max=100.0, description="Pixels: every point of every trace must lie this near its built run, or the fit is refused") + # the action table states share from 0.001 and tol from 0.1: a float property rounds those up, so its bounds stand just under def work(self, context): try: import brokkr_kitbash diff --git a/surfaces/blender/tests/live/reference_fit.py b/surfaces/blender/tests/live/reference_fit.py new file mode 100644 index 0000000..a88935e --- /dev/null +++ b/surfaces/blender/tests/live/reference_fit.py @@ -0,0 +1,219 @@ +"""Live proof, in a background Blender, of brokkr_reference.fit_shell through run_intent. + +A mirrored loft shell made by brokkr_kitbash.shell stands turned and moved in the world: a hard crease column and +the rim's outer column on each half. A camera looks at it from the side, and the four runs are traced where +Blender's own projection draws them on the shell as designed. Then: + + blocked the shell is rebuilt from a sheet whose two traced columns stand up to 0.12 m off: flow_score reads + the four traced lines against the build, and little of them is on a built edge + fit_shell from that shell and the traces: every trace explained, the request and the mesh untouched + applied brokkr_kitbash.shell rebuilds the shell from the returned sheet; flow_score reads every traced line + on a built edge (the bound sits between the mean of this reading and of the blocked build's, as CHECK prints) + crease_run the fitted shell at one level: the rim run and the crease stand where core.crease_run says + refusals a trace doubled back over itself, an unknown camera, a scaled shell and a mesh that is no shell, + each a failed receipt naming its cause, the shell unchanged + +The Jacobian by differences (mutant F6: core.lm on the same residual) costs time only: the mirrored column of +tests/test_reference.py, views one at a time, medians of 3 interleaved runs on Starfire, read +SECONDS_ANALYTIC against SECONDS_DIFFERENCES below. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_fit.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). is an absolute path: it writes .result.json and exits 1 when a check failed. Not part +of the unittest run: it needs Blender. +""" +import json +import math +import os +import sys +import tempfile +import time +import traceback +import types +from pathlib import Path + +import bpy +import numpy as np +from bpy_extras.object_utils import world_to_camera_view +from mathutils import Euler, Matrix, Vector + +SECONDS_ANALYTIC, SECONDS_DIFFERENCES = (0.07, 0.21), (2.3, 3.9) # least and most of the three views, 2026-12-03; the fitted cages agree within 0.11 mm + +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 os.path.isabs(OUT): + raise SystemExit(f" must be an absolute path, not {OUT!r}: a relative one lands in Blender's start directory") +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 + +sys.path.append(str(SURFACE)) +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_kitbash", "brokkr_reference"): + addon_utils.enable(module, default_set=True) +from brokkr_reference import core # noqa: E402 + +target = bt.BrokkrBlenderTarget(bpy) +target.configure_action_dirs("", tempfile.mkdtemp(prefix="brokkr-reference-fit-live-")) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], + "hostRows": [row["name"] for row in target.host_actions()[0]]} +COUNT = [0] +T0 = time.time() +WIDTH, HEIGHT = 800, 600 +RINGS, CREASE, RIM = 6, 1, 3 # the sheet's rings, and its two traced columns + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +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 = json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None + print("SEND", f"{time.time() - T0:.1f}s", action, receipt["status"], str(receipt["message"])[:400], flush=True) + return receipt, result + + +def designed(): + """The sheet as designed: six rings from y -1 to 1, each from the middle out and down, a fold at column 1.""" + rings = [] + for i in range(RINGS): + t = i / (RINGS - 1) + y, lift = -1.0 + 2.0 * t, 0.12 * math.sin(math.pi * t) + rings.append([[0.0, y, 0.55 + lift], [0.42 + 0.08 * math.sin(2.5 * t), y, 0.5 + lift], [0.8 + 0.05 * t, y, 0.12 + lift], [1.05 + 0.12 * math.sin(3.0 * t), y, -0.3 + 0.1 * t]]) + return {"mirror": True, "rim": 1.0, "creases": [{"column": CREASE, "from": 0, "to": RINGS - 1, "weight": 1.0}], "rings": rings} + + +def blocking(sheet): + """The designed sheet with its two traced columns pushed off by smooth bumps, up to 0.12 m.""" + out, r, t = json.loads(json.dumps(sheet)), np.random.default_rng(5), np.linspace(0, 1, RINGS) + for column in (CREASE, RIM): + bump = sum(r.normal(0, 1, 3)[None] * np.sin(np.pi * (j + 1) * t + 0.4)[:, None] for j in range(2)) + bump *= 0.12 / np.abs(bump).max() + for i in range(RINGS): + out["rings"][i][column] = [round(float(v + d), 6) for v, d in zip(sheet["rings"][i][column], bump[i])] + return out + + +def run_of(sheet, column, side): + """A column's built run in the shell's frame, as core.crease_run builds it twice over.""" + return core.crease_run(core.crease_run(np.array(sheet["rings"])[:, column] * [side, 1, 1])) + + +def pixels(camera, shell, points): + out = [] + for p in points: + x, y, _ = world_to_camera_view(bpy.context.scene, camera, shell.matrix_world @ Vector(p)) + out.append([round(x * WIDTH, 3), round((1.0 - y) * HEIGHT, 3)]) + return out + + +def flow(lines, shell): + _, result = send("brokkr_reference.flow_score", camera_name="View", objects=shell.name, + lines="; ".join(f"{tag}: " + " ".join(f"{u},{v}" for u, v in line) for tag, line in lines.items())) + return {tag: row["on"] for tag, row in result["lines"].items()} if result else None + + +def state(shell): + return shell["kit_shell"], [tuple(round(c, 7) for c in v.co) for v in shell.data.vertices] + + +try: + check("host files admitted with the fit_shell row", not R["hostErrors"] and "brokkr_reference.fit_shell" in R["hostRows"], R["hostErrors"] or R["hostRows"]) + scene = bpy.context.scene + scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage = WIDTH, HEIGHT, 100 + truth = designed() + send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(truth), thickness=0.03, levels=2) + shell = bpy.data.objects["Plate"] + shell.matrix_world = Matrix.Translation((0.3, -0.2, 0.1)) @ Euler((0.0, 0.0, math.radians(15.0))).to_matrix().to_4x4() + camera = bpy.data.objects.new("View", bpy.data.cameras.new("View")) + scene.collection.objects.link(camera) + camera.data.lens, camera.data.sensor_fit = 50.0, "HORIZONTAL" + camera.location = (3.2, -3.0, 5.2) + camera.rotation_euler = (Vector((0.3, -0.1, 0.25)) - camera.location).to_track_quat("-Z", "Y").to_euler() + bpy.context.view_layer.update() + runs = {"crease": (CREASE, 1), "crease_m": (CREASE, -1), "rim": (RIM, 1), "rim_m": (RIM, -1)} + lines = {tag: pixels(camera, shell, core.resampled(run_of(truth, column, side), 40)) for tag, (column, side) in runs.items()} + inside = all(0 <= u <= WIDTH and 0 <= v <= HEIGHT for line in lines.values() for u, v in line) + designed_on = flow(lines, shell) + check("the designed shell: the camera frames all four runs, and flow_score reads each traced line on a built edge", inside and designed_on and min(designed_on.values()) >= 0.9, designed_on) + + # --- blocked: the shell rebuilt from a sheet whose traced columns stand off --------------------------------------- + blocked = blocking(truth) + send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(blocked), thickness=0.03, levels=2) + bpy.context.view_layer.update() + blocked_on = flow(lines, shell) + before = state(shell) + + # --- fit_shell ----------------------------------------------------------------------------------------------------- + traces = [{"camera": "View", "run": {"column": column, "from": 0, "to": RINGS - 1}, "side": side, "line": lines[tag]} for tag, (column, side) in runs.items()] + receipt, fit = send("brokkr_reference.fit_shell", object_name="Plate", traces=json.dumps(traces, separators=(",", ":"))) + ok = receipt["status"] == "accepted" and fit is not None + check("fit_shell returns a sheet with every trace explained within 3 px, and a row for each of the 12 moved points", + ok and max(row["unexplained_px"] for row in fit["traces"]) <= 3.0 and len(fit["points"]) == 2 * RINGS and len(receipt["hostResult"]) < 16000, + fit and {"traces": fit["traces"], "seconds": fit["seconds"], "chars": len(receipt["hostResult"])}) + check("fit_shell wrote nothing: the shell's request and its cage are as they were", state(shell) == before) + if ok: + gap, off = (max(float(core._off(core.resampled(run_of(sheet, column, 1), 200), run_of(truth, column, 1)).max()) for column in (CREASE, RIM)) for sheet in (fit["sheet"], blocked)) + check("the fitted runs stand within 5 mm of the designed ones, from a blocking over 0.05 m off them", gap < 0.005 and off > 0.05, [gap, off]) + shares = {(row["ring"], row["point"]): row["prior_share"] for row in fit["points"]} + check("every moved point reports metres per pixel and a prior share from 0 to 1", all(0.0 <= row["prior_share"] <= 1.0 and row["m_per_px"] >= 0.0 for row in fit["points"]), shares and max(shares.values())) + + # --- applied: brokkr_kitbash.shell is the writer --------------------------------------------------------------- + applied, _ = send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(fit["sheet"]), thickness=0.03, levels=2) + bpy.context.view_layer.update() + fitted_on = flow(lines, shell) + low, high = sum(blocked_on.values()) / 4, sum(fitted_on.values()) / 4 + bound = math.sqrt(low * high) + check(f"applied with brokkr_kitbash.shell, flow_score reads the four traced lines on a built edge over {bound:.3f} in the mean: the geometric mean of the fitted build's " + f"reading ({high:.3f}) and the blocked build's ({low:.3f}), separation {high / bound:.2f} each side; no fitted line reads under 0.9", + applied["status"] == "accepted" and high / bound >= 1.2 and min(fitted_on.values()) >= 0.9, {"blocked": blocked_on, "fitted": fitted_on}) + + # --- crease_run is what Blender builds of both runs ---------------------------------------------------------------- + send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(fit["sheet"]), thickness=0.03, levels=1) + wall = shell.modifiers["Kit Solidify"] + wall.show_viewport = False + mesh = shell.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh() + built = np.array([v.co for v in mesh.vertices]) + wall.show_viewport = True + worst = {tag: max(float(np.linalg.norm(built - p, axis=1).min()) for p in core.crease_run(np.array(fit["sheet"]["rings"])[:, column] * [side, 1, 1])) for tag, (column, side) in runs.items()} + check("at one level Blender builds the rim run and the crease, on both halves, where core.crease_run says, within 1e-4 m", max(worst.values()) < 1e-4, worst) + send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(blocked), thickness=0.03, levels=2) + + # --- refusals ---------------------------------------------------------------------------------------------------------- + before = state(shell) + line = np.array(lines["crease_m"]) + doubled = np.vstack([line[:25], line[24:9:-1] + [0.0, 14.0], line[10:25] + [0.0, 28.0], line[25:]]).round(3).tolist() + receipt, _ = send("brokkr_reference.fit_shell", object_name="Plate", traces=json.dumps([traces[0], dict(traces[1], line=doubled)], separators=(",", ":"))) + check("a trace doubled back over itself is refused, naming the trace and the span no built run draws", receipt["status"] == "failed" and "traces[1] is not explained" in receipt["message"] and "px along it" in receipt["message"], receipt["message"]) + receipt, _ = send("brokkr_reference.fit_shell", object_name="Plate", traces=json.dumps([dict(traces[0], camera="Nobody")])) + check("an unknown camera is refused naming the trace", receipt["status"] == "failed" and "traces[0]" in receipt["message"] and "Nobody" in receipt["message"], receipt["message"]) + receipt, _ = send("brokkr_reference.fit_shell", object_name="View", traces=json.dumps(traces[:1])) + check("an object that is no shell is refused", receipt["status"] == "failed" and "is not a shell" in receipt["message"], receipt["message"]) + shell.scale = (2.0, 2.0, 2.0) + bpy.context.view_layer.update() + receipt, _ = send("brokkr_reference.fit_shell", object_name="Plate", traces=json.dumps(traces[:1])) + shell.scale = (1.0, 1.0, 1.0) + bpy.context.view_layer.update() + check("a scaled shell is refused", receipt["status"] == "failed" and "is scaled" in receipt["message"], receipt["message"]) + check("no refusal changed the shell", state(shell) == before) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) + +R["ok"] = all(c["ok"] for c in R["checks"]) +for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/reference_fit.result.json b/surfaces/blender/tests/live/reference_fit.result.json new file mode 100644 index 0000000..cc4d101 --- /dev/null +++ b/surfaces/blender/tests/live/reference_fit.result.json @@ -0,0 +1,184 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "host files admitted with the fit_shell row", + "ok": true, + "detail": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick", + "brokkr_kitbash.place_part", + "brokkr_kitbash.set_params", + "brokkr_kitbash.describe", + "brokkr_kitbash.report", + "brokkr_kitbash.attach", + "brokkr_kitbash.detach", + "brokkr_kitbash.roll", + "brokkr_kitbash.aim", + "brokkr_kitbash.reach", + "brokkr_kitbash.joint", + "brokkr_kitbash.slide", + "brokkr_kitbash.joints", + "brokkr_kitbash.close", + "brokkr_kitbash.boolean", + "brokkr_kitbash.cut", + "brokkr_kitbash.cut_many", + "brokkr_kitbash.freeze", + "brokkr_kitbash.thaw", + "brokkr_kitbash.ribs", + "brokkr_kitbash.shell", + "brokkr_kitbash.hose", + "brokkr_reference.solve_camera", + "brokkr_reference.flow_score", + "brokkr_reference.fit_shell" + ] + }, + { + "name": "the designed shell: the camera frames all four runs, and flow_score reads each traced line on a built edge", + "ok": true, + "detail": { + "crease": 1.0, + "crease_m": 1.0, + "rim": 1.0, + "rim_m": 0.963 + } + }, + { + "name": "fit_shell returns a sheet with every trace explained within 3 px, and a row for each of the 12 moved points", + "ok": true, + "detail": { + "traces": [ + { + "miss_px": 0.004, + "unexplained_px": 0.021 + }, + { + "miss_px": 0.008, + "unexplained_px": 0.082 + }, + { + "miss_px": 0.005, + "unexplained_px": 0.071 + }, + { + "miss_px": 0.003, + "unexplained_px": 0.055 + } + ], + "seconds": 0.12, + "chars": 2059 + } + }, + { + "name": "fit_shell wrote nothing: the shell's request and its cage are as they were", + "ok": true, + "detail": null + }, + { + "name": "the fitted runs stand within 5 mm of the designed ones, from a blocking over 0.05 m off them", + "ok": true, + "detail": [ + 0.0006199003550468113, + 0.132354157889395 + ] + }, + { + "name": "every moved point reports metres per pixel and a prior share from 0 to 1", + "ok": true, + "detail": 0.617 + }, + { + "name": "applied with brokkr_kitbash.shell, flow_score reads the four traced lines on a built edge over 0.747 in the mean: the geometric mean of the fitted build's reading (0.991) and the blocked build's (0.563), separation 1.33 each side; no fitted line reads under 0.9", + "ok": true, + "detail": { + "blocked": { + "crease": 0.713, + "crease_m": 0.613, + "rim": 0.138, + "rim_m": 0.787 + }, + "fitted": { + "crease": 1.0, + "crease_m": 1.0, + "rim": 1.0, + "rim_m": 0.963 + } + } + }, + { + "name": "at one level Blender builds the rim run and the crease, on both halves, where core.crease_run says, within 1e-4 m", + "ok": true, + "detail": { + "crease": 1.341720156294607e-07, + "crease_m": 1.341720156294607e-07, + "rim": 1.6729111618262465e-07, + "rim_m": 1.6729111618262465e-07 + } + }, + { + "name": "a trace doubled back over itself is refused, naming the trace and the span no built run draws", + "ok": true, + "detail": "Error: traces[1] is not explained: 281 px of the trace, between 110 and 466 px along it, lie more than 3 px from the run as built, up to 15.7 px. Nothing is returned as a fit. The trace draws something this run does not build (an overdrawn or doubled stroke, another edge, a bend the cage has too few points for): redraw it, or give the run more points. Nothing changed." + }, + { + "name": "an unknown camera is refused naming the trace", + "ok": true, + "detail": "Error: traces[0]: 'Nobody' is not a camera object." + }, + { + "name": "an object that is no shell is refused", + "ok": true, + "detail": "Error: 'View' is not a shell brokkr_kitbash.shell made (a mesh carrying kit_shell)." + }, + { + "name": "a scaled shell is refused", + "ok": true, + "detail": "Error: 'Plate' is scaled (2.0, 2.0, 2.0): a sheet is in metres of the shell's own frame. Apply or clear the scale." + }, + { + "name": "no refusal changed the shell", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "hostRows": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick", + "brokkr_kitbash.place_part", + "brokkr_kitbash.set_params", + "brokkr_kitbash.describe", + "brokkr_kitbash.report", + "brokkr_kitbash.attach", + "brokkr_kitbash.detach", + "brokkr_kitbash.roll", + "brokkr_kitbash.aim", + "brokkr_kitbash.reach", + "brokkr_kitbash.joint", + "brokkr_kitbash.slide", + "brokkr_kitbash.joints", + "brokkr_kitbash.close", + "brokkr_kitbash.boolean", + "brokkr_kitbash.cut", + "brokkr_kitbash.cut_many", + "brokkr_kitbash.freeze", + "brokkr_kitbash.thaw", + "brokkr_kitbash.ribs", + "brokkr_kitbash.shell", + "brokkr_kitbash.hose", + "brokkr_reference.solve_camera", + "brokkr_reference.flow_score", + "brokkr_reference.fit_shell" + ], + "ok": true +} \ No newline at end of file From f00a5a247d44382f94f398d30385e5cf6c793379 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 04:29:15 +0100 Subject: [PATCH 174/223] docs/reference.md: fit_shell, what its acceptance and its per-point readings are worth, and what it gives up Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/reference.md | 88 ++++++++++++++++++++++++++++-- 1 file changed, 84 insertions(+), 4 deletions(-) diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index 93bdc69..3617042 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -1,4 +1,4 @@ -# Reference views: the camera a picture was drawn through, and traced lines scored against the build +# Reference views: the camera a picture was drawn through, traced lines scored against the build, and a shell fitted to them `surfaces/blender/brokkr_reference` is a Blender add-on that fits a scene to a reference image. A concept sheet, a render or a photograph draws its subject through a camera nobody wrote down; given points whose place in the @@ -8,11 +8,11 @@ it lays over the image pixel for pixel and a line traced on the image can be sco It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish`: it imports that package's operator base and `Refused`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish` first; `brokkr_reference` refuses to register without it. `brokkr_actions.json` beside its `__init__.py` lists the -two operators agents may run (`solve_camera`, `flow_score`); the arithmetic is `core.py` (numpy only, tested without Blender), which a script may +three operators agents may run (`solve_camera`, `flow_score`, `fit_shell`); the arithmetic is `core.py` (numpy only, tested without Blender), which a script may import directly. The action writes its JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. -The package takes points and traced lines and gives cameras and scores. The images, the marks on them, traces and masks belong to whoever +The package takes points and traced lines and gives cameras, scores and a fitted sheet. The images, the marks on them, traces and masks belong to whoever made them; nothing here opens an image. ## Conventions @@ -172,6 +172,83 @@ surface has the hull's margin, and a surface nearer it than a thousandth of the about 20000 diagonals off, where the ray's own rounding reaches the margin. The action writes nothing to the scene (its row says `changesScene` because the operator base pushes an undo step). +## fit_shell: a shell's sheet fitted to traces of its hard runs + +A kitbash shell (`kitbash.md`, "Making a shell") is blocked in by eye; `fit_shell` moves the cage points of its +traced runs until the runs, as Blender builds them and the cameras draw them, lie on the traces. A run is a hard +crease or rim run of a loft, named as the sheet's creases name runs. The unknowns are the authored points on the +traced runs; a mirrored sheet is one set of points seen twice, so a trace of each half through one camera is two +views of the run (Francois et al. 2003), and that is where depth comes from in a single picture. Each built point +of a run is pulled onto its trace along the trace's normal, and the run's two ends onto the trace's ends; no +point of a trace is matched to a point of the run or of another trace (after Debevec's Facade and Drummond and +Cipolla's edge tracker). A prior holds every point to the sheet as it stands: a move of `share` of the sheet's +diagonal costs what one pixel of miss does. + +```json +{"action": "brokkr_reference.fit_shell", "object_name": "Pauldron", "tol": 3, + "traces": "[{\"camera\": \"Concept\", \"box\": [0, 0, 1024, 1024], \"run\": {\"column\": 3, \"from\": 0, \"to\": 5}, \"side\": 1, \"line\": [[412.5, 96.0], [431.0, 180.2], [440.8, 266.0]]}, {\"camera\": \"Concept\", \"box\": [0, 0, 1024, 1024], \"run\": {\"column\": 3, \"from\": 0, \"to\": 5}, \"side\": -1, \"line\": [[612.0, 90.5], [590.2, 176.0], [583.1, 262.4]]}]"} +``` + +| field | | +| --- | --- | +| `object_name` | a loft shell made by `brokkr_kitbash.shell`, unscaled; its place in the world is the sheet's frame | +| `traces` | a JSON array, up to 12000 characters, of `{camera, box, run, side, line}` | +| `share` | the prior (default 0.1) | +| `tol` | pixels (default 3): every point of every trace must lie this near its built run | + +In a trace, `camera` names a camera object (`solve_camera` stands one) and `box` is its frame on the image, absent +for the render's own; `run` is `{"ring": i, "from": a, "to": b}` or `{"column": j, "from": a, "to": b}` in authored +indices; `side` is 1, or -1 for the mirrored half of a mirrored sheet; `line` is `[[u, v], ...]` in the box's +pixels, drawn from the run's `from` end to its `to` end. + +**It returns a fit only where the built runs explain every trace.** After the fit, each trace is walked a pixel +at a time, and every point of it must lie within `tol` of its run as built and drawn. Otherwise the action is +refused, naming the trace, how much of it is unexplained, where along it and by how much, and nothing is returned +as a fit. The fit's own residual is no such test: on strokes doubled back over part of themselves 3% of the view +off, every fit converged and without this check all of them came back, up to 0.10 m wrong on a 2 m crease; with +it every one is refused (the least reads 9 px against the 3 asked). The check also binds the ends: a trace that +runs on past where its run ends, or two traces of a mirrored pair whose tips are not one point and its mirror +image through the camera, are refused at the tip. + +**It writes nothing.** The report carries `sheet`, the shell's own request with the traced points moved, ready +for `brokkr_kitbash.shell`, which is the cage's one writer; `flow_score` on the rebuilt shell is the score. The +rest of the report: `traces` (`[{miss_px, unexplained_px}]`: the root mean square distance of the built points +from the trace, and the trace's furthest point from the built run), `points` (`[{ring, point, moved_m, m_per_px, +prior_share}]`, one per moved point) and `seconds`. + +`m_per_px` says how far a point slides along its line of sight per pixel of error in the traces (the worst of +the views that trace it), from the inverse of the fit's normal matrix, prior included (Triggs et al. 2000, +sections 9 and 10). `prior_share` is that over `share` x the diagonal: at 1 the traces say nothing about the +point along the sight line and it stands where the blocking put it. Read it per point: + +- A run traced on one half only, in one view, reads 1.0 on every point: its depth is the blocking's. +- A mirrored pair reads low where the mirror plane stands well off the sight line. On the Orchid's concept c09 + (plane 34 degrees off, a nearly orthographic camera) the pair's points read 0.12 at most, 0.024 m per px on a + ship one unit long. +- The sight line is taken whole. Where a run recedes along the view, a cage point's slide along its own run is + in the reading: the traces do not decide that slide and it does not move the built run. A column 24 to 38 + degrees off the sight line, both halves traced and its built run right to 0.2 mm, reads 0.63 to 0.88 on its + inner points. A high reading on such a run is not a depth error. +- A run on the mirror plane itself (a spine, a keel) has no partner and reads 1.0. + +What it refuses before fitting, naming the trace: a run with an edge under weight 1 (a semi-sharp edge rounds +off by an amount the fit does not model), a run whose end does not hold (a dart; a ring run from point 0 of a +mirrored sheet, which runs on across the middle), a run with a point held partway (a corner point or a crossing +crease: trace it as two), a closed loop, an unknown camera, a line of fewer than two points, a free cage (it has +no rings or columns; `core.fit_runs` takes vertex chains), a scaled shell, and a result that would pass the +16000 characters a receipt carries. + +Measured (Blender 5.3 and Python 3.13 on Starfire): a mirrored column of 10 points traced in one view at a time, +from blockings 0.10 m and 0.30 m off a 2 m crease, came back within 0.7 mm in 0.1 to 0.6 s. The Orchid's c09 +petal edges, traced by hand through a camera solved from hand marks (13 px rms), are refused at 3 px: the left +trace's first 10 px stand up to 9.2 px off the built run. At 18.5 px they fit in 0.2 s, and from blockings 5%, +10% and 20% of the ship's length off the built run lands in one place, 2.0% of the length from a stand-in mesh +in the mean and 3.4% at worst. A trace drawn by hand through a camera solved by hand wants a `tol` near that +camera's own `rms`, and the acceptance is then that much weaker. + +What it gives up: it fits hard runs of a loft only. Silhouettes of the smooth surface, semi-sharp creases and +free cages are not fitted; a run's depth with no mirror partner and no second view is the blocking's. + ## What it cannot do It solves one pinhole camera for one view: no lens distortion, no two views solved together, one turned group and @@ -188,6 +265,7 @@ u_v = core.project(cam, points) # where it draws wor origin, direction = core.ray(cam, (u, v)) # a pixel's line of sight point = core.lift(cam, (u, v), plane_point, plane_normal) # a traced pixel on a plane run = core.crease_run(column) # the hard crease Blender builds from a cage column +fit = core.fit_sheet(sheet, cage, frame, traces, cams) # the fitted sheet and its report; cage is brokkr_kitbash.core.sheet(sheet) score = core.along(line, segments, height) # on, off, run against [u0, v0, u1, v1] segments params = core.blender(cam, 1000) # matrix_world, lens, shifts, resolution cam2 = core.camera_of(params, box) # and back @@ -196,4 +274,6 @@ cam2 = core.camera_of(params, box) # and back The tests are `tests/test_reference.py` (no Blender), `tests/live/reference.py` (a known scene rendered, solved through the action and rendered again; `reference.result.json` is its last run) and `tests/live/reference_flow.py` (`crease_run` against Blender's own subdivision, a box and a folded sheet scored by `flow_score`; -`reference_flow.result.json` is its last run). +`reference_flow.result.json` is its last run) and `tests/live/reference_fit.py` (a mirrored shell blocked off its +design, fitted through the action, rebuilt by `brokkr_kitbash.shell` and scored; `reference_fit.result.json` is +its last run). From ff6bf588d59b618fda03c6811664c96952d8e585 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 05:22:49 +0100 Subject: [PATCH 175/223] brokkr_kitbash Sheet.mirror_of: per vertex, the authored vertex it reflects, from the parser that makes the reflections (a loft's and a free cage's) Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/core.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 71f3717..e68c566 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1044,7 +1044,8 @@ class Sheet(NamedTuple): poles (P,) are the cage's vertices of irregular valence, as built; triangles is how many faces have 3 sides. boundary is the Subdivision's Boundary Smooth, by Blender's name: PRESERVE_CORNERS on a loft (a boundary vertex of two edges stays a corner), ALL on a free cage (the boundary is smoothed through it unless a corner pins it), - which is how a cage modelled by hand is set.""" + which is how a cage modelled by hand is set. mirror_of (V,) is, per vertex, the authored vertex it reflects + across x = 0, or itself: an authored vertex, one on the mirror plane, every vertex of a sheet not mirrored.""" V: np.ndarray faces: np.ndarray counts: np.ndarray @@ -1059,6 +1060,7 @@ class Sheet(NamedTuple): poles: np.ndarray triangles: int boundary: str + mirror_of: np.ndarray def _index(value: Any, where: str, least: int, most: int) -> int: @@ -1130,6 +1132,9 @@ def sheet(document: Any) -> Sheet: vertex = lambda i, j: i * N + j % N # noqa: E731 quads = np.array([[vertex(i, j), vertex(i, j + 1), vertex(i + 1, j + 1), vertex(i + 1, j)] for i in range(R - 1) for j in range(wrap)], dtype=np.int32) V = P.reshape(-1, 3) + mirror_of = np.arange(R * N).reshape(R, N) + if mirror: + mirror_of[:, :C - 1] = mirror_of[:, :C - 1:-1] corners = V[quads] areas = 0.5 * (np.linalg.norm(np.cross(corners[:, 1] - corners[:, 0], corners[:, 3] - corners[:, 0]), axis=1) + np.linalg.norm(np.cross(corners[:, 3] - corners[:, 2], corners[:, 1] - corners[:, 2]), axis=1)) @@ -1196,7 +1201,7 @@ def sheet(document: Any) -> Sheet: return Sheet(V=V.copy(), faces=quads.ravel().astype(np.int32), counts=np.full(len(quads), 4, dtype=np.int32), smooth=np.ones(len(quads), dtype=bool), sharp=NO_SHARP, creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64), corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N, - poles=np.zeros(0, dtype=np.int64), triangles=0, boundary="PRESERVE_CORNERS") + poles=np.zeros(0, dtype=np.int64), triangles=0, boundary="PRESERVE_CORNERS", mirror_of=mirror_of.ravel()) def _cage_facts(vertices: int, faces, counts): @@ -1321,6 +1326,7 @@ def _cage(document: Any, gate: bool = True) -> Sheet: if mirror and seam[a] and seam[b] and len(both) == 2: raise KitError(f"sheet.faces[{both[0]}] and sheet.faces[{both[1]}] share the edge between vertices {min(a, b)} and {max(a, b)}, which lies on the mirror plane: " "with their reflections that edge is in four faces (a fin on the plane)") + mirror_of = np.concatenate([np.arange(A), np.flatnonzero(~seam)]) if mirror else np.arange(A) twin = np.arange(A) if mirror: twin[~seam] = A + np.arange(int((~seam).sum())) @@ -1398,7 +1404,7 @@ def _cage(document: Any, gate: bool = True) -> Sheet: return Sheet(V=V, faces=flat, counts=counts, smooth=np.ones(len(counts), dtype=bool), sharp=NO_SHARP, creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64), corners=np.array([key for key, _ in held], dtype=np.int64), corner_weights=np.array([w for _, w in held], dtype=np.float64), - rings=None, points=None, poles=poles, triangles=int((counts == 3).sum()), boundary="ALL") + rings=None, points=None, poles=poles, triangles=int((counts == 3).sum()), boundary="ALL", mirror_of=mirror_of) # --- reports ------------------------------------------------------------------------------------------------- From 5b460c5394eac8a4c4d6d5bf56cc48d37d22a757 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 05:22:49 +0100 Subject: [PATCH 176/223] brokkr_reference fit: a trace is asked at its 90th percentile past 5% at each end (tol 5), the reading is depth across the run, and a free cage is fitted by its vertex chains The gate on a trace's worst point read the Orchid pair's tip (9.20 px) and its least 1% overdraw (9.12) alike; the trimmed percentile reads them 0.69 and 4.27, and the pair is accepted at the default. TRIM, PART and TOL are pinned from Soul's 296 fits by lodur:ruling:deterministic-bound-margin (FitTests' docstring states the sets, and what the default does not separate). m_per_px leaves a point's slide along its own run out: pairs read 0.080 at most, a single trace's inner points 0.503 and up. fit_sheet takes {verts: [...]} runs on a free cage through Sheet.mirror_of; miss_px is gone, worst_px is reported beside the reading. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/__init__.py | 6 +- .../brokkr_reference/brokkr_actions.json | 10 +- surfaces/blender/brokkr_reference/core.py | 126 +++++---- surfaces/blender/tests/test_reference.py | 252 +++++++++++++----- 4 files changed, 266 insertions(+), 128 deletions(-) diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index ad652d6..96d6dab 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -215,10 +215,10 @@ class BROKKR_REFERENCE_OT_fit_shell(PolishOperator): only where the built runs explain every trace; nothing is written""" bl_idname = "brokkr_reference.fit_shell" bl_label = "Fit Shell To Traces" - object_name: bpy.props.StringProperty(name="Object", maxlen=63, description="A loft shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame") - traces: bpy.props.StringProperty(name="Traces", maxlen=12000, description="A JSON array of {camera, box, run: {ring|column, from, to}, side, line: [[u, v], ...]}") + object_name: bpy.props.StringProperty(name="Object", maxlen=63, description="A shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame") + traces: bpy.props.StringProperty(name="Traces", maxlen=12000, description="A JSON array of {camera, box, run: {ring|column, from, to} on a loft or {verts: [v, ...]} on a free cage, side, line: [[u, v], ...]}") share: bpy.props.FloatProperty(name="Share", default=0.1, min=0.0009, max=10.0, description="A move of this share of the sheet's diagonal from the sheet as it stands costs what one pixel of miss does") - tol: bpy.props.FloatProperty(name="Tolerance", default=3.0, min=0.09, max=100.0, description="Pixels: every point of every trace must lie this near its built run, or the fit is refused") + tol: bpy.props.FloatProperty(name="Tolerance", default=core.TOL, min=0.09, max=100.0, description="Pixels: nine tenths of every trace, its ends apart, must lie this near its built run, or the fit is refused") # the action table states share from 0.001 and tol from 0.1: a float property rounds those up, so its bounds stand just under def work(self, context): diff --git a/surfaces/blender/brokkr_reference/brokkr_actions.json b/surfaces/blender/brokkr_reference/brokkr_actions.json index 6822511..aa4f7e2 100644 --- a/surfaces/blender/brokkr_reference/brokkr_actions.json +++ b/surfaces/blender/brokkr_reference/brokkr_actions.json @@ -136,7 +136,7 @@ }, { "name": "brokkr_reference.fit_shell", - "doc": "Fit a kitbash loft shell's sheet to traces of its hard crease and rim runs, each seen through a scene camera: the traced runs' cage points move until the runs as built draw on the traces. Returns the fitted sheet for brokkr_kitbash.shell only where every point of every trace lies within tol px of its built run; otherwise it is refused naming the trace and the span. Writes nothing. Per moved point: metres per pixel along its sight line and the prior's share of that (docs/reference.md).", + "doc": "Fit a kitbash shell's sheet (a loft or a free cage) to traces of its hard crease and rim runs, each seen through a scene camera: the traced runs' cage points move until the runs as built draw on the traces. Returns the fitted sheet for brokkr_kitbash.shell only where nine tenths of every trace, 5% left out at each end, lies within tol px of its built run; otherwise it is refused naming the trace, its reading and the span. A very unsteady hand and a 1 to 2% overdraw read alike: each trace's reading (unexplained_px) and worst point (worst_px) are in the report to judge by. Writes nothing. Per moved point: metres of depth across its run per pixel, and the prior's share of that: under 0.2 the traces decide the point, over it the blocking holds it (docs/reference.md).", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -147,7 +147,7 @@ "required": true, "minLength": 1, "maxLength": 63, - "doc": "a loft shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame" + "doc": "a shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame" }, { "name": "traces", @@ -155,7 +155,7 @@ "required": true, "minLength": 2, "maxLength": 12000, - "doc": "a JSON array of {camera, box, run, side, line}: camera a camera object's name; box [u0,v0,u1,v1], its frame on the image, absent for the render's own; run {ring, from, to} or {column, from, to} in authored indices, as the sheet's creases name runs; side 1, or -1 for the mirrored half; line [[u,v],...] drawn from `from` to `to`" + "doc": "a JSON array of {camera, box, run, side, line}: camera a camera object's name; box [u0,v0,u1,v1], its frame on the image, absent for the render's own; run {ring, from, to} or {column, from, to} on a loft, {verts: [v, ...]} on a free cage, in authored indices, as the sheet's creases name runs; side 1, or -1 for the mirrored half; line [[u,v],...] drawn from the run's first point to its last" }, { "name": "share", @@ -170,8 +170,8 @@ "type": "number", "minimum": 0.1, "maximum": 100, - "default": 3, - "doc": "pixels: every point of every trace must lie this near its built run, or the fit is refused" + "default": 5, + "doc": "pixels: nine tenths of every trace, its ends apart, must lie this near its built run, or the fit is refused" } ] } diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index 5cea4da..bb27391 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -452,6 +452,9 @@ def along(line, segments, height, near=0.01, turn=20.0, cap=0.05): LEVELS = 2 # crease_run applied this many times gives the samples of a built run the fit draws: 4k - 3 for k cage points HARD = 1.0 - 1e-9 # a crease weight from here up is hard: the edge stays sharp at every level, which is what crease_run builds ROUNDS = 60 +TRIM = 0.05 # of a trace's length, left out at each end where a trace is asked whether its run explains it: a hand trace's tip is where two traces cannot agree +PART = 90 # the percentile of the rest of the trace's distances from its built run that fit_runs reads against tol +TOL = 5.0 # pixels. tests/test_reference.py FitTests states the sets TRIM, PART and TOL were read from, and what they do not separate RESULT_LIMIT = 16000 # characters of a host result Brokkr copies into a receipt before it truncates (brokkr_bridge's HOST_RESULT_LIMIT; this package imports nothing from Brokkr) @@ -525,7 +528,7 @@ def _hard_runs(cage, runs): "more hard edges meet, or on the rim") -def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=3.0): +def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL): """Move a cage's points until its hard runs, as built and as cameras draw them, lie on their traces. views [(camera record, frame)]: the frame is the 4 x 4 that carries the cage to the world @@ -537,21 +540,24 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=3.0): mirror_of per vertex, the authored vertex it mirrors across x = 0, or itself: a mirrored half is the same parameters seen again, x negated share the prior: a move of share x diag from the cage as given costs what one pixel of miss does - tol pixels: every point of every trace must lie this near its built run as drawn + tol pixels: of each trace less TRIM of its length at each end, PART in a hundred must lie this near its + built run as drawn The residual per run is the pixel distance from each built point (crease_run LEVELS times, drawn through the run's view) to the trace, and the run's two ends against the trace's; no point of the trace is matched to a point of the run beyond that. Gauss-Newton with Levenberg-Marquardt damping on the analytic Jacobian. Returns - (V, report): the cage's vertices as fitted and {"traces": [{"miss_px": rms of the built points off the trace, - "unexplained_px": the trace's furthest point from the built run}], "points": [{"vertex", "moved_m", - "m_per_px", "prior_share"}], "rounds"}. m_per_px is how far the point slides along its sight line (the worst - of the views that trace it) per pixel of error in the traces, sqrt(r' S r) with S the point's block of the - inverse of J'J, prior included (Triggs et al. 2000, sections 9 and 10); prior_share is that over share x - diag: near 1 the traces say nothing about the point's depth and it stands where it was blocked. + (V, report): the cage's vertices as fitted and {"traces": [{"unexplained_px": the reading tol is asked of, + "worst_px": the whole trace's furthest point from the built run}], "points": [{"vertex", "moved_m", "m_per_px", + "prior_share"}], "rounds"}. m_per_px is how far the point slides in depth across its run per pixel of error in + the traces: along the part of its sight line that stands across the run's tangent there (the worst of the + traces that draw it), sqrt(r' S r) with S the point's block of the inverse of J'J, prior included (Triggs et + al. 2000, sections 9 and 10). A point's slide along its own run is left out: the traces do not decide it and it + does not move the built run. prior_share is m_per_px over share x diag: near 1 the traces say nothing about + the point's depth and it stands where it was blocked. Raises ReferenceFitError for a run it cannot model (_hard_runs), and when a trace is not explained: the error - names the trace and the span of it that lies further than tol from the built run, and carries the rows as - .traces. Nothing is returned as a fit then.""" + names the trace, its reading and the span of it that lies further than tol from the built run, and carries the + rows as .traces. Nothing is returned as a fit then.""" V0, movable, mirror_of = np.array(cage.V, float), np.asarray(movable, bool), np.asarray(mirror_of, int) mirrored = mirror_of != np.arange(len(V0)) if (movable & mirrored[:, None]).any() or not movable.any(): @@ -626,12 +632,16 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=3.0): length = np.linalg.norm(np.diff(line, axis=0), axis=1).sum() dense = resampled(line, int(min(max(length, len(line)), 4000)) + 1) # a point each pixel along it off = _off(dense, u) - traces.append({"miss_px": round(float(np.sqrt(np.mean(dist ** 2))), 3), "unexplained_px": round(float(off.max()), 3)}) - if off.max() > tol and refused is None: - out = np.flatnonzero(off > tol) * length / (len(dense) - 1) + ends = int(TRIM * len(dense)) + reading = float(np.percentile(off[ends:len(dense) - ends], PART)) + traces.append({"unexplained_px": round(reading, 3), "worst_px": round(float(off.max()), 3)}) + if reading > tol and refused is None: + out = (ends + np.flatnonzero(off[ends:len(dense) - ends] > tol)) * length / (len(dense) - 1) refused = (f"{name} is not explained: {len(out) * length / (len(dense) - 1):.0f} px of the trace, between {out[0]:.0f} and {out[-1]:.0f} px along it, lie " - f"more than {tol:g} px from the run as built, up to {off.max():.1f} px. Nothing is returned as a fit. The trace draws something this run " - "does not build (an overdrawn or doubled stroke, another edge, a bend the cage has too few points for): redraw it, or give the run more points") + f"more than {tol:g} px from the run as built ({reading:.1f} px at the {PART}th of a hundred, {TRIM:.0%} of the trace left out at each end; up to " + f"{off.max():.1f} px). Nothing is returned as a fit. The trace draws something this run does not build (an overdrawn or doubled stroke, another " + "edge, a bend the cage has too few points for): redraw it, or give the run more points. A very unsteady hand reads the same as a slight " + "overdraw: if the trace is one clean stroke, ask again with tol over this reading") if refused is not None: error = ReferenceFitError(refused) error.traces = traces @@ -645,36 +655,37 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=3.0): block[np.ix_(held, held)] = S[np.ix_(cols[held], cols[held])] worst = 0.0 for _, (cam, frame), _, _, source, sign, _ in prepared: + run = V[source] * sign for m in np.flatnonzero(source == a): - sight = V[a] * sign[m] - (np.linalg.inv(np.asarray(frame, float)) @ np.r_[np.asarray(cam["C"], float), 1.0])[:3] - sight = sight / np.linalg.norm(sight) * sign[m] # the sight line of the mirrored point, said in the authored point's coordinates - worst = max(worst, float(np.sqrt(sight @ block @ sight))) + sight = run[m] - (np.linalg.inv(np.asarray(frame, float)) @ np.r_[np.asarray(cam["C"], float), 1.0])[:3] + along = run[min(m + 1, len(run) - 1)] - run[max(m - 1, 0)] + sight = sight - (sight @ along) / (along @ along) * along + if np.linalg.norm(sight) > 1e-9: # a run seen end on has no depth across itself + sight = sight / np.linalg.norm(sight) * sign[m] # said in the authored point's coordinates + worst = max(worst, float(np.sqrt(sight @ block @ sight))) points.append({"vertex": int(a), "moved_m": float(np.linalg.norm(V[a] - V0[a])), "m_per_px": worst, "prior_share": worst * prior}) return V, {"traces": traces, "points": points, "rounds": rounds} -def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=3.0): +def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=TOL): """fit_runs for a shell's sheet. `document` is the sheet as brokkr_kitbash.shell takes it and `cage` what brokkr_kitbash.core.sheet parses it to; `frame` carries the shell to the world. `traces` is a list of - {"run": {"ring": i, "from": a, "to": b} or {"column": j, "from": a, "to": b}, "side": 1 or -1, "line": - [[u, v], ...]} (authored indices, as the sheet's creases name runs; side -1 is the mirrored half of a mirrored - sheet; the line is drawn from `from` to `to`), and `cams` the camera record of each. The points of the traced - runs move, a mirrored sheet's point 0 only in its plane. Returns {"sheet": the document with those points - moved, "traces": [{"miss_px", "unexplained_px"}], "points": [{"ring", "point", "moved_m", "m_per_px", + {"run", "side": 1 or -1, "line": [[u, v], ...]} and `cams` the camera record of each. A loft's run is {"ring": + i, "from": a, "to": b} or {"column": j, "from": a, "to": b}, a free cage's {"verts": [v, ...]}: authored + indices, as the sheet's creases name runs. Side -1 is the mirrored half of a mirrored sheet (cage.mirror_of); + the line is drawn from the run's first point to its last. The points of the traced runs move, one on the + mirror plane only in it. Returns {"sheet": the document with those points moved, "traces": [{"unexplained_px", + "worst_px"}], "points": [{"ring", "point" (a loft) or "vertex" (a free cage), "moved_m", "m_per_px", "prior_share"}]}; refuses, before fitting, a result that would pass RESULT_LIMIT characters.""" mirror, closed = document.get("mirror", False) is True, bool(document.get("closed", False)) - R, N = cage.rings, cage.points - if R is None: - raise ReferenceFitError("the sheet is a free cage: fit_sheet names runs by ring and column, which a loft has and a free cage does not. " - "core.fit_runs takes any cage's vertex chains") - C = (N + 1) // 2 if mirror else N + R, N, mirror_of = cage.rings, cage.points, np.asarray(cage.mirror_of) + loft, authored = R is not None, np.flatnonzero(mirror_of == np.arange(len(mirror_of))) + twin = np.arange(len(mirror_of)) # an authored vertex's reflection: itself on the mirror plane + twin[mirror_of[mirror_of != twin]] = np.flatnonzero(mirror_of != twin) + C = ((N + 1) // 2 if mirror else N) if loft else None if not isinstance(traces, list) or not traces: raise ReferenceFitError("traces must be an array of one or more {camera, box, run, side, line}") - mirror_of = np.arange(R * N) - if mirror: - for i in range(R): - mirror_of[i * N + C - 1 - np.arange(1, C)] = i * N + C - 1 + np.arange(1, C) - movable, runs = np.zeros((R * N, 3), bool), [] + movable, runs = np.zeros((len(mirror_of), 3), bool), [] for k, trace in enumerate(traces): where = f"traces[{k}]" if not isinstance(trace, dict) or not isinstance(trace.get("run"), dict): @@ -684,31 +695,40 @@ def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=3.0): run, side = trace["run"], trace.get("side", 1) if side not in (1, -1) or (side == -1 and not mirror): raise ReferenceFitError(f"{where}.side must be 1, or -1 for the mirrored half of a mirrored sheet, not {side!r}") - ring = "ring" in run - if ring == ("column" in run) or set(run) != {"ring" if ring else "column", "from", "to"}: - raise ReferenceFitError(f"{where}.run must be {{ring, from, to}} or {{column, from, to}}") - across, most = (R, C if closed else C - 1) if ring else (C, R - 1) - numbers_ = [run["ring" if ring else "column"], run["from"], run["to"]] - if any(isinstance(v, bool) or not isinstance(v, int) for v in numbers_) or not (0 <= numbers_[0] < across and 0 <= numbers_[1] < numbers_[2] <= most): - raise ReferenceFitError(f"{where}.run must name a {'ring under ' + str(R) if ring else 'column under ' + str(C)} and from under to, to at most {most}") - fixed, first, last = numbers_ - authored = [(fixed, j % C) if ring else (j, fixed) for j in range(first, last + 1)] - chain = [i * N + ((C - 1 + side * j) if mirror else j) for i, j in authored] - for i, j in authored: - movable[i * N + (C - 1 + j if mirror else j)] = (not (mirror and j == 0), True, True) - runs.append({"name": where, "chain": chain, "view": k, "line": trace.get("line")}) - moved = [(int(v) // N, int(v) % N - (C - 1 if mirror else 0)) for v in np.flatnonzero(movable.any(1))] + if loft: + ring = "ring" in run + if ring == ("column" in run) or set(run) != {"ring" if ring else "column", "from", "to"}: + raise ReferenceFitError(f"{where}.run must be {{ring, from, to}} or {{column, from, to}}: the sheet is a loft") + across, most = (R, C if closed else C - 1) if ring else (C, R - 1) + numbers_ = [run["ring" if ring else "column"], run["from"], run["to"]] + if any(isinstance(v, bool) or not isinstance(v, int) for v in numbers_) or not (0 <= numbers_[0] < across and 0 <= numbers_[1] < numbers_[2] <= most): + raise ReferenceFitError(f"{where}.run must name a {'ring under ' + str(R) if ring else 'column under ' + str(C)} and from under to, to at most {most}") + fixed, first, last = numbers_ + chain = [i * N + (C - 1 if mirror else 0) + j for i, j in ((fixed, j % C) if ring else (j, fixed) for j in range(first, last + 1))] + else: + chain = run.get("verts") + if set(run) != {"verts"} or not isinstance(chain, list) or any(isinstance(v, bool) or not isinstance(v, int) or not 0 <= v < len(authored) for v in chain): + raise ReferenceFitError(f"{where}.run must be {{verts: [v, ...]}}, authored vertices under {len(authored)} in the run's order: the sheet is a free cage") + for v in chain: + movable[v] = (twin[v] != v or not mirror, True, True) + runs.append({"name": where, "chain": chain if side == 1 else [int(twin[v]) for v in chain], "view": k, "line": trace.get("line")}) + moved = [int(v) for v in np.flatnonzero(movable.any(1))] size = len(json.dumps(document, separators=(",", ":"))) + 36 * len(moved) + 45 * len(traces) + 95 * len(moved) + 40 if size > RESULT_LIMIT: raise ReferenceFitError(f"the fitted sheet and its report would be about {size} characters, over the {RESULT_LIMIT} a receipt carries: nothing was fitted. " "Fit fewer runs at a time, or a sparser sheet") V0 = np.array(cage.V, float) V, report = fit_runs([(cam, frame) for cam in cams], cage, runs, movable, mirror_of, share, float(np.linalg.norm(np.ptp(V0, axis=0))), tol) - out = copy.deepcopy(document) - for i, j in moved: - out["rings"][i][j] = [round(float(x), 6) + 0.0 for x in V[i * N + (C - 1 + j if mirror else j)]] - return {"sheet": out, "traces": report["traces"], "points": [{"ring": i, "point": j, "moved_m": round(row["moved_m"], 4), "m_per_px": round(row["m_per_px"], 4), - "prior_share": round(row["prior_share"], 3)} for (i, j), row in zip(moved, report["points"])]} + out, points = copy.deepcopy(document), [] + for v, row in zip(moved, report["points"]): + place = {"ring": v // N, "point": v % N - (C - 1 if mirror else 0)} if loft else {"vertex": v} + point = [round(float(x), 6) + 0.0 for x in V[v]] + if loft: + out["rings"][place["ring"]][place["point"]] = point + else: + out["verts"][v] = point + points.append({**place, "moved_m": round(row["moved_m"], 4), "m_per_px": round(row["m_per_px"], 4), "prior_share": round(row["prior_share"], 3)}) + return {"sheet": out, "traces": report["traces"], "points": points} # --- fields ---------------------------------------------------------------------------------------------------------- diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index eaacde6..72d19d1 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -20,6 +20,7 @@ tolerances round a known truth that no mutant claims. The mutants, each run once """ from __future__ import annotations +import copy import importlib.util import json import math @@ -444,16 +445,59 @@ def off_truth(document, truth): return max(float(core._off(run, truth).max()), float(core._off(truth[[0, -1]], run).max())) +def hand(line, sigma, rng, corr=30.0, jitter=0.7, tip=6.0): + """`line` as a hand draws it: a wander of `sigma` px that holds over `corr` px, a jitter on every point, and + each tip (its 10 px) set off whole by about `tip` px.""" + s = np.r_[0, np.cumsum(np.linalg.norm(np.diff(line, axis=0), axis=1))] + grid = np.arange(0, s[-1] + corr, corr / 2) + wander = rng.normal(0, 1, (len(grid), 2)) + out = line + sigma * np.stack([np.interp(s, grid, wander[:, k]) for k in range(2)], 1) + rng.normal(0, jitter, line.shape) + out[s < 10] += rng.normal(0, 1, 2) * tip + out[s > s[-1] - 10] += rng.normal(0, 1, 2) * tip + return out + + +def free_strip(points=6): + """A mirrored free cage three columns wide (x 0 on the mirror plane, 0.5, 1) whose middle column is a hard + crease, and that column's vertices in order.""" + verts = [[x, -1 + 2 * i / (points - 1), 0.5 - x * x + 0.1 * math.sin(3 * i / (points - 1)) * (c == 1)] for c, x in enumerate((0.0, 0.5, 1.0)) for i in range(points)] + faces = [[c * points + i, c * points + i + 1, c * points + i + 1 + points, c * points + i + points] for c in range(2) for i in range(points - 1)] + chain = list(range(points, 2 * points)) + return {"verts": verts, "faces": faces, "creases": [[a, b, 1.0] for a, b in zip(chain, chain[1:])], "mirror": True, "rim": 1.0}, chain + + @unittest.skipIf(np is None, "numpy") class FitTests(unittest.TestCase): """fit_runs and fit_sheet: a shell's traced runs fitted through cameras, accepted only where the built runs - explain every trace. Bounds follow lodur:ruling:deterministic-bound-margin. Mutants, each run once on a copy: + explain the traces. Bounds follow lodur:ruling:deterministic-bound-margin. Mutants, each run once on a copy: F1 no explained check test_an_overdrawn_stroke_is_refused_naming_its_trace - F2 sensitivity across the run's tangent, not the ray test_the_sight_line_reading_holds_the_points_slide_along_its_run F3 the prior left out of S test_one_trace_alone_reads_as_held_by_the_blocking F4 no end terms test_a_mirrored_column_is_recovered_from_a_blocking_well_off F5 a semi-sharp run admitted test_refusals_name_their_field_before_fitting - F6 (the Jacobian by differences) costs time only: tests/live/reference_fit.py's header says how much.""" + G1 m_per_px along the sight line whole test_a_mirrored_column_is_recovered_from_a_blocking_well_off + G2 the gate on the trace's worst point (PART 100) test_hand_traces_are_explained_at_the_default + G3 a point on the mirror plane free to leave it test_a_spine_on_the_mirror_plane_stays_on_it + G4 a run's last index allowed one past the sheet test_refusals_name_their_field_before_fitting + G5 the prior's share not scaled by the diagonal test_one_trace_alone_reads_as_held_by_the_blocking + G6 the gate at 1.2 x tol test_an_overdrawn_stroke_is_refused_naming_its_trace + G7 a free cage's mirrored half read as the authored test_a_free_cage_is_fitted_by_its_vertex_chains + G8 the prior in the Jacobian and not the residual test_one_trace_alone_reads_as_held_by_the_blocking + + core.TRIM, core.PART and core.TOL were read from 296 fits kept outside the suite (108 hand traces by `hand`, + wander 1, 2 and 4 px; 108 strokes by `overdrawn` 1, 2, 3 and 5% off; the Orchid pair, moved and overdrawn). + Read as the PART-th percentile past TRIM at each end, the traces to accept read 3.26 px at most (the 72 hand + traces of wander 1 and 2 px; the Orchid pair 0.69) and the least to refuse 7.65 (the Orchid's traces overdrawn + 2%; the strokes 3% off 7.83): TOL is their geometric mean, separation 1.53 each side. The trace's worst point, + which that reading replaces, read 9.20 on the Orchid pair against 9.12 on its least 1% overdraw. What TOL does + not separate: 31 of the 36 hand traces of wander 4 px are accepted (they read up to 5.96), 9 of 27 strokes 1% + off and 3 of 18 Orchid 1% overdraws are accepted (from 2.63 and 4.27), and the strokes 2% off are refused from + 5.34 with no margin. A very unsteady hand and a slight overdraw read alike; the report carries the reading. + + Unclaimed, with readings: TRIM 0 (the hand traces read 3.76 against 3.26, the Orchid 0.80 against 0.69: + separation 1.15); F6, the Jacobian by differences (time only: tests/live/reference_fit.py's header); + the least, in place of the worst, of the traces that draw a point (the 18 pairs' greatest prior_share reads 0.060 + against 0.080, both under PAIR_FROM_SINGLE; one point's two readings differ up to 4.3 times); the guard on a run + seen end on (the reading is dropped either way).""" @classmethod def setUpClass(cls): @@ -471,28 +515,56 @@ class FitTests(unittest.TestCase): self.assertLess(np.abs(numeric - J[:, :, c]).max(), 1e-4 * np.abs(J).max()) self.assertIsNone(core._drawn(cam, np.eye(4), np.array([cam["C"]]) - np.array(cam["R"])[2] * -1.0)) # a point behind it - def test_a_mirrored_column_is_recovered_from_a_blocking_well_off(self): - """fit-recovers, F4: each of three views alone, both halves traced, from blockings 0.10 m and 0.30 m off. - Shipped: the built run ends within 0.67 mm of the true crease (the 3 mm asked is a tolerance round a known - truth) and the worst trace is explained within 0.196 px. F4 (no end terms): the run stops short of its - traces, three fits are refused at 3.6 px and up, and the worst it explains reads 2.06 px: the bound is the - geometric mean of 0.196 and 2.06, separation 3.2 each side.""" - worst = 0.0 + def families(self): for A, w in ((0.2, 2.5), (0.1, 5.0), (0.4, 1.0)): for share in (0.05, 0.15): truth, document = blocked(A, w, share) - self.assertGreater(off_truth(document, truth), 0.09) for cam in fit_views(truth): - out = fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1])), cam) - worst = max(worst, off_truth(out["sheet"], truth)) - self.assertLess(max(row["unexplained_px"] for row in out["traces"]), 0.64) - self.assertEqual(len(out["points"]), FIT_K) + yield truth, document, cam + + PAIR_FROM_SINGLE = 0.2 # prior_share: the geometric mean of 0.080, the most any point of the 18 mirrored pairs reads, and 0.503, the least an inner point of the 18 single traces reads: separation 2.5 each side + + def test_a_mirrored_column_is_recovered_from_a_blocking_well_off(self): + """fit-recovers, F4 and G1: each of three views alone, both halves traced, from blockings 0.10 m and 0.30 m + off. Shipped: the built run ends within 0.67 mm of the true crease (the 3 mm asked is a tolerance round a + known truth) and the worst point of any trace stands 0.196 px off its run. F4 (no end terms): the run stops + short of its traces and the worst reads 2.06 px and up: the bound is the geometric mean of 0.196 and 2.06, + separation 3.2 each side. Every point reads a prior_share under PAIR_FROM_SINGLE: the pair decides it. G1 + (the sight line whole, a point's slide along its own run counted in) reads inner points up to 0.95.""" + worst = 0.0 + for truth, document, cam in self.families(): + self.assertGreater(off_truth(document, truth), 0.09) + out = fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1])), cam) + worst = max(worst, off_truth(out["sheet"], truth)) + self.assertLess(max(row["worst_px"] for row in out["traces"]), 0.64) + self.assertEqual(len(out["points"]), FIT_K) + self.assertLess(max(row["prior_share"] for row in out["points"]), self.PAIR_FROM_SINGLE) self.assertLess(worst, 0.003) + def test_one_trace_alone_reads_as_held_by_the_blocking(self): + """F3, G5, G8: one half traced in one view decides nothing along the sight line. The same 18 fits with one + trace end 17.6 to 355 mm off the truth (G8, the prior left out of the residual, lets the nearest drift to 11.2: + the bound is their geometric mean, separation 1.25 each side), and every inner point reads a prior_share over PAIR_FROM_SINGLE + (0.503 to 1.0, the sine of the angle its run stands off the sight line; an end seen along its run reads + down to 0.005, and its depth across the run is decided). F3 (the prior left out of S) reads 771366 where + the ceiling is 1. m_per_px is prior_share x share x the sheet's diagonal (2.77 m here); G5 leaves the + diagonal out.""" + for truth, document, cam in self.families(): + out = fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth)), cam) + shares = [row["prior_share"] for row in out["points"]] + self.assertGreater(min(shares[1:-1]), self.PAIR_FROM_SINGLE) + self.assertLessEqual(max(shares), 1.0) + self.assertGreater(off_truth(out["sheet"], truth), 0.014) + diagonal = float(np.linalg.norm(np.ptp(kit.sheet(document).V, axis=0))) + for row in out["points"][1:-1]: + self.assertAlmostEqual(row["m_per_px"] / row["prior_share"], 0.1 * diagonal, delta=0.01 * diagonal) + def test_an_overdrawn_stroke_is_refused_naming_its_trace(self): - """overdraw-refused, F1: the mirrored half's trace doubled back over part of itself 3% of its extent off. - All 27 are refused, naming the trace and the span that no built run draws; the least unexplained reads - 8.98 px against the 3 asked, separation 3.0. F1 returns all 27 as fits, the worst 0.104 m off the truth.""" + """overdraw-refused, F1 and G6: the mirrored half's trace doubled back over part of itself 3% of its extent + off. All 27 are refused, naming the trace and the span that no built run draws; the least reads 7.83 px + against core.TOL, separation 1.57. F1 returns all 27 as fits, the worst 0.104 m off the truth. Asked with + tol 1.1 times its own reading a stroke is accepted, and with tol that reading over 1.1 refused: tol is what + the reading is held to (G6 holds it to 1.2 x tol).""" truth, document = blocked(0.2, 2.5, 0.05) least = 1e9 for cam in fit_views(truth): @@ -501,78 +573,119 @@ class FitTests(unittest.TestCase): for kind in ("mid", "truth-last", "truth-first"): with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[[01]\] is not explained: \d+ px of the trace, between \d+ and \d+ px along it") as caught: fitted(document, pair_traces(a, overdrawn(b, start, stop, 0.03, kind)), cam) + self.assertEqual(set(caught.exception.traces[0]), {"unexplained_px", "worst_px"}) least = min(least, max(row["unexplained_px"] for row in caught.exception.traces)) - self.assertGreater(least, 3.0 * 1.2) # lodur:ruling:deterministic-bound-margin's least separation + self.assertGreater(least, core.TOL * 1.2) # lodur:ruling:deterministic-bound-margin's least separation + traces = pair_traces(a, overdrawn(b, 0.3, 0.7, 0.03, "mid")) + with self.assertRaises(core.ReferenceFitError) as caught: + fitted(document, traces, cam) + reading = max(row["unexplained_px"] for row in caught.exception.traces) + self.assertAlmostEqual(max(row["unexplained_px"] for row in fitted(document, traces, cam, tol=reading * 1.1)["traces"]), reading, delta=0.002) + with self.assertRaises(core.ReferenceFitError): + fitted(document, traces, cam, tol=reading / 1.1) - def test_an_accepted_fit_is_within_its_own_reported_reach(self): - """accepted-bounded: the same strokes 0.2% off pass as explained (they are under 3 px from one line), and - every accepted fit stands within tol x the worst m_per_px it reports of the truth: all 27 are accepted, - the worst 8.9 mm off, 0.024 of that reach (F2 reads 0.27 of its own). No mutant claims this bound.""" + def test_hand_traces_are_explained_at_the_default(self): + """G2: both halves traced by `hand` (wander 2 px, tips 6 px off), each of three views. All three are + accepted at core.TOL, reading 2.97 px at most (TOL over 1.68), while the worst point of a trace stands 6.94 + px off its run and, the tips left out, still 5.82 to 6.94: G2, which holds that point to TOL, refuses all + three. The fits end 20 to 64 mm off the true crease, up to 1.36 times TOL x the m_per_px they report: + m_per_px is what one pixel of error on a single point moves, and a wander that holds over 30 px moves + more.""" + truth, document = blocked(0.2, 2.5, 0.05) + rng, most = np.random.default_rng(1), 0.0 + for cam in fit_views(truth): + a, b = hand(core.seen(cam, FIT_FRAME, truth), 2.0, rng), hand(core.seen(cam, FIT_FRAME, truth * [-1, 1, 1]), 2.0, rng) + out = fitted(document, pair_traces(a, b), cam) + self.assertLess(max(row["unexplained_px"] for row in out["traces"]), core.TOL / 1.2) + most = max(most, max(row["worst_px"] for row in out["traces"])) + self.assertGreater(most, core.TOL * 1.2) + + def test_a_clean_fit_is_within_its_own_reported_reach(self): + """accepted-bounded, on clean strokes only: strokes doubled back 0.2% off pass as explained, and each + accepted fit stands within core.TOL x the worst m_per_px it reports of the truth: all 27 are accepted, the + worst 8.9 mm off, 0.161 of that reach. No mutant claims this bound, and hand traces pass it + (test_hand_traces_are_explained_at_the_default).""" truth, document = blocked(0.2, 2.5, 0.05) accepted, most = 0, 0.0 for cam in fit_views(truth): a, b = core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1]) for start, stop in ((0.1, 0.3), (0.3, 0.7), (0.6, 1.0)): for kind in ("mid", "truth-last", "truth-first"): - try: - out = fitted(document, pair_traces(a, overdrawn(b, start, stop, 0.002, kind)), cam) - except core.ReferenceFitError: - continue + out = fitted(document, pair_traces(a, overdrawn(b, start, stop, 0.002, kind)), cam) accepted += 1 - most = max(most, off_truth(out["sheet"], truth) / (3.0 * max(row["m_per_px"] for row in out["points"]))) + most = max(most, off_truth(out["sheet"], truth) / (core.TOL * max(row["m_per_px"] for row in out["points"]))) self.assertEqual(accepted, 27) self.assertLess(most, 1.0) - def test_one_trace_alone_reads_as_held_by_the_blocking(self): - """F3: one half traced in one view decides nothing along the sight line, and the prior is all that holds - each point there: prior_share reads 1.0, its ceiling. F3 (the prior left out of S) reads 771366.""" - truth, document = blocked(0.2, 2.5, 0.05) - cam = fit_views(truth)[0] - shares = [row["prior_share"] for row in fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth)), cam)["points"]] - self.assertEqual((min(shares), max(shares)), (1.0, 1.0)) + def test_a_spine_on_the_mirror_plane_stays_on_it(self): + """G3: a mirrored sheet's column 0 is on the mirror plane and has no partner; the plane decides its depth. + Traced in one view from a blocking 0.07 m off, its points keep x = 0 and the built run ends 0.15 mm + from the true spine, every point reading a prior_share of 0.019 or under. G3 (x free there) leaves the run as far off as a single trace is.""" + t = np.linspace(0, 1, FIT_K) + spine = np.stack([0 * t, -1 + 2 * t, 0.5 + 0.3 * t * t], 1) + sheet_ = {"mirror": True, "rim": 1.0, "creases": [{"column": 0, "from": 0, "to": FIT_K - 1, "weight": 1.0}], + "rings": [[[0.0, float(p[1]) + 0.05, float(p[2]) + 0.05], [0.4, float(p[1]), float(p[2]) - 0.1], [0.9, float(p[1]), float(p[2]) - 0.3]] for p in spine]} + built = core.crease_run(core.crease_run(spine)) + cam = fit_views(built)[0] + out = fitted(sheet_, [{"camera": "View", "run": {"column": 0, "from": 0, "to": FIT_K - 1}, "side": 1, "line": core.seen(cam, FIT_FRAME, built).tolist()}], cam) + column = np.array(out["sheet"]["rings"])[:, 0] + self.assertEqual(float(np.abs(column[:, 0]).max()), 0.0) + self.assertLess(float(core._off(core.resampled(core.crease_run(core.crease_run(column)), 400), built).max()), 0.001) + self.assertLess(max(row["prior_share"] for row in out["points"]), self.PAIR_FROM_SINGLE) - def test_the_sight_line_reading_holds_the_points_slide_along_its_run(self): - """F2: m_per_px is along the sight line whole. This column recedes along the view (its tangent 24 to 38 - degrees off the sight line), so with both halves traced, which decide the built run to 0.2 mm, an inner - cage point still slides along its own run on the prior alone and reads a prior_share of 0.633 to 0.88; the - ends, which hold, read 0.024 and under. F2 (the ray's part across the tangent) reads the inner points 0.039 - at most: the bound is the geometric mean of 0.633 and 0.039, separation 4.0 each side.""" - truth, document = blocked(0.2, 2.5, 0.05) - cam = fit_views(truth)[0] - shares = [row["prior_share"] for row in fitted(document, pair_traces(core.seen(cam, FIT_FRAME, truth), core.seen(cam, FIT_FRAME, truth * [-1, 1, 1])), cam)["points"]] - self.assertGreater(min(shares[1:-1]), 0.157) - self.assertLess(max(shares[0], shares[-1]), 0.157) - self.assertLessEqual(max(shares), 1.0) + def test_a_free_cage_is_fitted_by_its_vertex_chains(self): + """free-cage, G7: a mirrored free cage's crease, six vertices, both halves traced in one view from a + blocking 0.057 m off: the built run ends 0.45 mm from the true one, the six traced vertices are the only + ones moved, each with a row naming its vertex and a prior_share under PAIR_FROM_SINGLE (0.036 at most). The + mirrored half is the reflections the cage's own parser lists (Sheet.mirror_of); G7 reads it as the authored + half and the fit is refused, the second trace unexplained.""" + truth, chain = free_strip() + run = core.crease_run(core.crease_run(np.array(truth["verts"])[chain])) + cam = fit_views(run)[0] + document, bump = copy.deepcopy(truth), np.random.default_rng(1).normal(0, 0.06, (len(chain), 3)) + for v, d in zip(chain, bump): + document["verts"][v] = [float(x) for x in np.array(truth["verts"][v]) + d] + off = lambda sheet_: float(core._off(core.resampled(core.crease_run(core.crease_run(np.array(sheet_["verts"])[chain])), 400), run).max()) # noqa: E731 + traces = [{"camera": "View", "run": {"verts": chain}, "side": side, "line": core.seen(cam, FIT_FRAME, run * [side, 1, 1]).tolist()} for side in (1, -1)] + out = fitted(document, traces, cam) + self.assertGreater(off(document), 0.05) + self.assertLess(off(out["sheet"]), 0.001) + self.assertEqual([row["vertex"] for row in out["points"]], chain) + self.assertLess(max(row["prior_share"] for row in out["points"]), self.PAIR_FROM_SINGLE) + self.assertTrue(all(out["sheet"]["verts"][v] == document["verts"][v] for v in range(len(document["verts"])) if v not in chain)) + self.assertTrue(np.array_equal(kit.sheet(document).mirror_of, np.r_[np.arange(18), np.arange(6, 18)])) # the six on the mirror plane are shared, the twelve others reflected after them def orchid_strip(self): return strip(np.array(self.orchid["blocking"])) - def orchid_fit(self, lines, tol): + def orchid_fit(self, lines): document, run = self.orchid_strip(), {"column": 1, "from": 0, "to": 7} traces = [{"camera": "Concept", "run": run, "side": side, "line": line} for side, line in lines] - return core.fit_sheet(document, kit.sheet(document), self.orchid["frame"], traces, [self.orchid["camera"]] * len(traces), tol=tol) - - ORCHID_TOL = 18.5 # px: the geometric mean of 9.2, the pair's unexplained reading as drawn, and 37.3, its reading with the right trace moved 40 px: separation 2.0 each side + return core.fit_sheet(document, kit.sheet(document), self.orchid["frame"], traces, [self.orchid["camera"]] * len(traces)) def test_orchid_c09_hand_traces(self): """orchid-c09: the inboard edges of two petals traced by hand on one concept view, through a camera solved - from hand marks (13 px rms). At the default 3 px the pair is refused: the left trace's first 10 px stand up - to 9.2 px off the built run, because the two traces' tips are not one point and its mirror image through - that camera (the right trace reads 2.4 px). Asked at ORCHID_TOL the pair is explained, and the worst - prior_share of its points is 0.119 (0.024 m per px); either trace alone reads 1.0 on every point: the bound - is the geometric mean of 0.119 and 1.0, separation 2.9 each side. The right trace moved 40 px is refused.""" + from hand marks (13 px rms). At the default the pair is explained: its traces read 0.69 and 0.64 px (TOL + over 7.2), though the left trace's first 10 px stand up to 9.2 px off the built run, because the two + traces' tips are not one point and its mirror image through that camera; the gate on the worst point + refused the pair for that. Its points read a prior_share of 0.018 at most; either trace alone reads 0.271 + and up on every point: the bound is their geometric mean, separation 3.9 each side. The right trace + overdrawn 2% of its extent is refused nine ways of nine, reading 7.65 px and up.""" left, right, side = self.orchid["left"], self.orchid["right"], self.orchid["left_side"] - with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[0\] is not explained: 11 px of the trace, between 0 and 10 px along it, .* up to 9\.2 px"): - self.orchid_fit([(side, left), (-side, right)], 3.0) - pair = self.orchid_fit([(side, left), (-side, right)], self.ORCHID_TOL) - self.assertLess(max(row["unexplained_px"] for row in pair["traces"]), self.ORCHID_TOL / 2.0) - self.assertLess(max(row["prior_share"] for row in pair["points"]), 0.345) + pair = self.orchid_fit([(side, left), (-side, right)]) + self.assertLess(max(row["unexplained_px"] for row in pair["traces"]), core.TOL / 1.2) + self.assertGreater(pair["traces"][0]["worst_px"], core.TOL * 1.2) + self.assertLess(max(row["prior_share"] for row in pair["points"]), 0.07) self.assertEqual(pair["sheet"]["rings"][3][0], self.orchid_strip()["rings"][3][0]) # only the traced column moves for alone in ([(side, left)], [(-side, right)]): - self.assertGreater(min(row["prior_share"] for row in self.orchid_fit(alone, self.ORCHID_TOL)["points"]), 0.345) - with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[0\] is not explained") as caught: - self.orchid_fit([(side, left), (-side, (np.array(right) + [0.0, 40.0]).tolist())], self.ORCHID_TOL) - self.assertGreater(max(row["unexplained_px"] for row in caught.exception.traces), self.ORCHID_TOL * 2.0) + self.assertGreater(min(row["prior_share"] for row in self.orchid_fit(alone)["points"]), 0.07) + least = 1e9 + for start, stop in ((0.1, 0.3), (0.3, 0.7), (0.6, 1.0)): + for kind in ("mid", "truth-last", "truth-first"): + with self.assertRaisesRegex(core.ReferenceFitError, r"^traces\[1\] is not explained") as caught: + self.orchid_fit([(side, left), (-side, overdrawn(np.array(right), start, stop, 0.02, kind))]) + least = min(least, caught.exception.traces[1]["unexplained_px"]) + self.assertGreater(least, core.TOL * 1.2) def test_refusals_name_their_field_before_fitting(self): """refusals, F5 (which takes the semi-sharp run as far as its end and refuses it there for another cause).""" @@ -595,7 +708,12 @@ class FitTests(unittest.TestCase): (document, [dict(pair_traces(a)[0], side=2)], [cam], r"^traces\[0\]\.side must be 1"), (document, [dict(pair_traces(a)[0], run={"column": 3, "from": 0, "to": 2})], [cam], r"^traces\[0\]\.run must name a column under 3"), (document, [dict(pair_traces(a)[0], run={"ring": 0, "from": 0, "to": 2})], [cam], r"^traces\[0\]: the first end of its run does not hold"), - ({"verts": [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], "faces": [[0, 1, 2, 3]]}, pair_traces(a), [cam], r"^the sheet is a free cage"), + (document, [dict(pair_traces(a)[0], run={"column": 1, "from": 0, "to": FIT_K})], [cam], r"^traces\[0\]\.run must name a column under 3 and from under to, to at most 9$"), + (document, [dict(pair_traces(a)[0], run={"ring": 0, "from": 0, "to": 3})], [cam], r"^traces\[0\]\.run must name a ring under 10 and from under to, to at most 2$"), + (document, [dict(pair_traces(a)[0], run={"verts": [0, 1]})], [cam], r"^traces\[0\]\.run must be \{ring, from, to\} or \{column, from, to\}: the sheet is a loft"), + (free_strip()[0], pair_traces(a), [cam], r"^traces\[0\]\.run must be \{verts: \[v, \.\.\.\]\}, authored vertices under 18 in the run's order: the sheet is a free cage"), + (free_strip()[0], [dict(pair_traces(a)[0], run={"verts": [6, 18]})], [cam], r"^traces\[0\]\.run must be \{verts"), + (free_strip()[0], [dict(pair_traces(a)[0], run={"verts": [0, 6]})], [cam], r"^traces\[0\]: the first end of its run does not hold"), # a rim run from the mirror plane runs on across it (big, [dict(pair_traces(a)[0], run=whole)], [cam], r"would be about \d+ characters, over the 16000 a receipt carries: nothing was fitted")): with self.assertRaisesRegex(core.ReferenceFitError, message): core.fit_sheet(sheet_, kit.sheet(sheet_), FIT_FRAME, traces, cams) @@ -687,7 +805,7 @@ class HostFileTests(unittest.TestCase): with self.assertRaises(at.IntentInvalid): at.validate({**intent, **bad}, self.host) fit = {**self.envelope, "action": "brokkr_reference.fit_shell", "object_name": "Plate", "traces": "[{}]"} - self.assertEqual((at.validate(fit, self.host)["share"], at.validate(fit, self.host)["tol"]), (0.1, 3)) + self.assertEqual((at.validate(fit, self.host)["share"], at.validate(fit, self.host)["tol"]), (0.1, core.TOL)) for bad in ({"tol": 0}, {"share": 11}, {"traces": ""}, {"object_name": "x" * 64}): with self.assertRaises(at.IntentInvalid): at.validate({**fit, **bad}, self.host) From 54781f45dadf5bf7a42e62393df9b65a7cbcb242 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 05:24:51 +0100 Subject: [PATCH 177/223] tests/live/reference_fit.py: a mirrored free cage fitted through fit_shell by its vertex chains, rebuilt by brokkr_kitbash.shell and read against Blender's build Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/reference_fit.py | 57 ++++++++++++++++++- .../tests/live/reference_fit.result.json | 54 +++++++++++++----- 2 files changed, 96 insertions(+), 15 deletions(-) diff --git a/surfaces/blender/tests/live/reference_fit.py b/surfaces/blender/tests/live/reference_fit.py index a88935e..86130f6 100644 --- a/surfaces/blender/tests/live/reference_fit.py +++ b/surfaces/blender/tests/live/reference_fit.py @@ -12,6 +12,9 @@ Blender's own projection draws them on the shell as designed. Then: crease_run the fitted shell at one level: the rim run and the crease stand where core.crease_run says refusals a trace doubled back over itself, an unknown camera, a scaled shell and a mesh that is no shell, each a failed receipt naming its cause, the shell unchanged + free cage a mirrored free cage with one hard crease, blocked off its design and traced on both halves: fit_shell + takes the run as {verts}, brokkr_kitbash.shell rebuilds it, and Blender builds the crease on both + halves where core.crease_run says The Jacobian by differences (mutant F6: core.lm on the same residual) costs time only: the mirrored column of tests/test_reference.py, views one at a time, medians of 3 interleaved runs on Starfire, read @@ -107,6 +110,15 @@ def blocking(sheet): return out +def free_cage(points=6): + """A mirrored free cage three columns wide (x 0 on the mirror plane, 0.5, 1) whose middle column is a hard crease, + and that column's vertices in order.""" + verts = [[x, -1 + 2 * i / (points - 1), 0.5 - x * x + 0.1 * math.sin(3 * i / (points - 1)) * (c == 1)] for c, x in enumerate((0.0, 0.5, 1.0)) for i in range(points)] + faces = [[c * points + i, c * points + i + 1, c * points + i + 1 + points, c * points + i + points] for c in range(2) for i in range(points - 1)] + chain = list(range(points, 2 * points)) + return {"verts": verts, "faces": faces, "creases": [[a, b, 1.0] for a, b in zip(chain, chain[1:])], "mirror": True, "rim": 1.0}, chain + + def run_of(sheet, column, side): """A column's built run in the shell's frame, as core.crease_run builds it twice over.""" return core.crease_run(core.crease_run(np.array(sheet["rings"])[:, column] * [side, 1, 1])) @@ -161,8 +173,8 @@ try: traces = [{"camera": "View", "run": {"column": column, "from": 0, "to": RINGS - 1}, "side": side, "line": lines[tag]} for tag, (column, side) in runs.items()] receipt, fit = send("brokkr_reference.fit_shell", object_name="Plate", traces=json.dumps(traces, separators=(",", ":"))) ok = receipt["status"] == "accepted" and fit is not None - check("fit_shell returns a sheet with every trace explained within 3 px, and a row for each of the 12 moved points", - ok and max(row["unexplained_px"] for row in fit["traces"]) <= 3.0 and len(fit["points"]) == 2 * RINGS and len(receipt["hostResult"]) < 16000, + check(f"fit_shell returns a sheet with every trace explained within {core.TOL:g} px, and a row for each of the 12 moved points", + ok and max(row["unexplained_px"] for row in fit["traces"]) <= core.TOL and len(fit["points"]) == 2 * RINGS and len(receipt["hostResult"]) < 16000, fit and {"traces": fit["traces"], "seconds": fit["seconds"], "chars": len(receipt["hostResult"])}) check("fit_shell wrote nothing: the shell's request and its cage are as they were", state(shell) == before) if ok: @@ -209,6 +221,47 @@ try: bpy.context.view_layer.update() check("a scaled shell is refused", receipt["status"] == "failed" and "is scaled" in receipt["message"], receipt["message"]) check("no refusal changed the shell", state(shell) == before) + + # --- a free cage, by its vertex chains --------------------------------------------------------------------------------- + design, chain = free_cage() + + def crease(sheet, side, levels=core.LEVELS): + run = np.array(sheet["verts"])[chain] * [side, 1, 1] + for _ in range(levels): + run = core.crease_run(run) + return run + + send("brokkr_kitbash.shell", object_name="Free", sheet=json.dumps(design), thickness=0.03, levels=2) + free = bpy.data.objects["Free"] + free.matrix_world = shell.matrix_world.copy() + bpy.context.view_layer.update() + free_lines = {side: pixels(camera, free, core.resampled(crease(design, side), 120)) for side in (1, -1)} + rough, bump = json.loads(json.dumps(design)), np.random.default_rng(1).normal(0, 0.06, (len(chain), 3)) + for v, d in zip(chain, bump): + rough["verts"][v] = [round(float(x + y), 6) for x, y in zip(design["verts"][v], d)] + send("brokkr_kitbash.shell", object_name="Free", sheet=json.dumps(rough), thickness=0.03, levels=2) + bpy.context.view_layer.update() + before = state(free) + receipt, fit = send("brokkr_reference.fit_shell", object_name="Free", + traces=json.dumps([{"camera": "View", "run": {"verts": chain}, "side": side, "line": free_lines[side]} for side in (1, -1)], separators=(",", ":"))) + ok = receipt["status"] == "accepted" and fit is not None + if ok: + gap, off = (float(core._off(core.resampled(crease(sheet, 1), 200), crease(design, 1)).max()) for sheet in (fit["sheet"], rough)) + check("a mirrored free cage's crease, traced on both halves and named {verts}, is fitted within 1 mm of the designed run from a blocking over 0.05 m off: " + "a row for each of its six vertices and no other, every trace explained, nothing written", + gap < 0.001 and off > 0.05 and [row["vertex"] for row in fit["points"]] == chain and max(row["unexplained_px"] for row in fit["traces"]) <= core.TOL + and all(0 <= u <= WIDTH and 0 <= v <= HEIGHT for line in free_lines.values() for u, v in line) and state(free) == before, + {"gap": gap, "off": off, "traces": fit["traces"], "prior_share": max(row["prior_share"] for row in fit["points"]), "seconds": fit["seconds"]}) + applied, _ = send("brokkr_kitbash.shell", object_name="Free", sheet=json.dumps(fit["sheet"]), thickness=0.03, levels=1) + wall = free.modifiers["Kit Solidify"] + wall.show_viewport = False + built = np.array([v.co for v in free.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh().vertices]) + wall.show_viewport = True + worst = {side: max(float(np.linalg.norm(built - p, axis=1).min()) for p in crease(fit["sheet"], side, 1)) for side in (1, -1)} + check("brokkr_kitbash.shell takes the fitted free cage, and at one level Blender builds its crease on both halves where core.crease_run says, within 1e-4 m", + applied["status"] == "accepted" and max(worst.values()) < 1e-4, worst) + else: + check("fit_shell fits a mirrored free cage by its vertex chains", False, receipt["message"]) except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) diff --git a/surfaces/blender/tests/live/reference_fit.result.json b/surfaces/blender/tests/live/reference_fit.result.json index cc4d101..17094d0 100644 --- a/surfaces/blender/tests/live/reference_fit.result.json +++ b/surfaces/blender/tests/live/reference_fit.result.json @@ -49,29 +49,29 @@ } }, { - "name": "fit_shell returns a sheet with every trace explained within 3 px, and a row for each of the 12 moved points", + "name": "fit_shell returns a sheet with every trace explained within 5 px, and a row for each of the 12 moved points", "ok": true, "detail": { "traces": [ { - "miss_px": 0.004, - "unexplained_px": 0.021 + "unexplained_px": 0.01, + "worst_px": 0.021 }, { - "miss_px": 0.008, - "unexplained_px": 0.082 + "unexplained_px": 0.058, + "worst_px": 0.082 }, { - "miss_px": 0.005, - "unexplained_px": 0.071 + "unexplained_px": 0.053, + "worst_px": 0.071 }, { - "miss_px": 0.003, - "unexplained_px": 0.055 + "unexplained_px": 0.037, + "worst_px": 0.055 } ], - "seconds": 0.12, - "chars": 2059 + "seconds": 0.138, + "chars": 2066 } }, { @@ -90,7 +90,7 @@ { "name": "every moved point reports metres per pixel and a prior share from 0 to 1", "ok": true, - "detail": 0.617 + "detail": 0.069 }, { "name": "applied with brokkr_kitbash.shell, flow_score reads the four traced lines on a built edge over 0.747 in the mean: the geometric mean of the fitted build's reading (0.991) and the blocked build's (0.563), separation 1.33 each side; no fitted line reads under 0.9", @@ -123,7 +123,7 @@ { "name": "a trace doubled back over itself is refused, naming the trace and the span no built run draws", "ok": true, - "detail": "Error: traces[1] is not explained: 281 px of the trace, between 110 and 466 px along it, lie more than 3 px from the run as built, up to 15.7 px. Nothing is returned as a fit. The trace draws something this run does not build (an overdrawn or doubled stroke, another edge, a bend the cage has too few points for): redraw it, or give the run more points. Nothing changed." + "detail": "Error: traces[1] is not explained: 239 px of the trace, between 124 and 461 px along it, lie more than 5 px from the run as built (12.1 px at the 90th of a hundred, 5% of the trace left out at each end; up to 15.7 px). Nothing is returned as a fit. The trace draws something this run does not build (an overdrawn or doubled stroke, another edge, a bend the cage has too few points for): redraw it, or give the run more points. A very unsteady hand reads the same as a slight overdraw: if the trace is one clean stroke, ask again with tol over this reading. Nothing changed." }, { "name": "an unknown camera is refused naming the trace", @@ -144,6 +144,34 @@ "name": "no refusal changed the shell", "ok": true, "detail": null + }, + { + "name": "a mirrored free cage's crease, traced on both halves and named {verts}, is fitted within 1 mm of the designed run from a blocking over 0.05 m off: a row for each of its six vertices and no other, every trace explained, nothing written", + "ok": true, + "detail": { + "gap": 0.00042547668113367745, + "off": 0.055743395392436126, + "traces": [ + { + "unexplained_px": 0.013, + "worst_px": 0.022 + }, + { + "unexplained_px": 0.02, + "worst_px": 0.032 + } + ], + "prior_share": 0.06, + "seconds": 0.022 + } + }, + { + "name": "brokkr_kitbash.shell takes the fitted free cage, and at one level Blender builds its crease on both halves where core.crease_run says, within 1e-4 m", + "ok": true, + "detail": { + "1": 1.305964704160048e-07, + "-1": 1.305964704160048e-07 + } } ], "hostErrors": [], From 272a761892683ca7834e1ca5a0c4eb9f2f2e3ac6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 05:24:51 +0100 Subject: [PATCH 178/223] docs/reference.md: fit_shell's reading of a trace and what it does not separate, depth across the run and the 0.2 line, free cages, and that a spine is decided by its plane Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/reference.md | 110 ++++++++++++++++++----------- 1 file changed, 67 insertions(+), 43 deletions(-) diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index 3617042..31cfb89 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -176,7 +176,7 @@ because the operator base pushes an undo step). A kitbash shell (`kitbash.md`, "Making a shell") is blocked in by eye; `fit_shell` moves the cage points of its traced runs until the runs, as Blender builds them and the cameras draw them, lie on the traces. A run is a hard -crease or rim run of a loft, named as the sheet's creases name runs. The unknowns are the authored points on the +crease or rim run of a loft or of a free cage, named as the sheet's creases name runs. The unknowns are the authored points on the traced runs; a mirrored sheet is one set of points seen twice, so a trace of each half through one camera is two views of the run (Francois et al. 2003), and that is where depth comes from in a single picture. Each built point of a run is pulled onto its trace along the trace's normal, and the run's two ends onto the trace's ends; no @@ -185,69 +185,93 @@ Cipolla's edge tracker). A prior holds every point to the sheet as it stands: a diagonal costs what one pixel of miss does. ```json -{"action": "brokkr_reference.fit_shell", "object_name": "Pauldron", "tol": 3, +{"action": "brokkr_reference.fit_shell", "object_name": "Pauldron", "traces": "[{\"camera\": \"Concept\", \"box\": [0, 0, 1024, 1024], \"run\": {\"column\": 3, \"from\": 0, \"to\": 5}, \"side\": 1, \"line\": [[412.5, 96.0], [431.0, 180.2], [440.8, 266.0]]}, {\"camera\": \"Concept\", \"box\": [0, 0, 1024, 1024], \"run\": {\"column\": 3, \"from\": 0, \"to\": 5}, \"side\": -1, \"line\": [[612.0, 90.5], [590.2, 176.0], [583.1, 262.4]]}]"} ``` | field | | | --- | --- | -| `object_name` | a loft shell made by `brokkr_kitbash.shell`, unscaled; its place in the world is the sheet's frame | +| `object_name` | a shell made by `brokkr_kitbash.shell`, unscaled; its place in the world is the sheet's frame | | `traces` | a JSON array, up to 12000 characters, of `{camera, box, run, side, line}` | | `share` | the prior (default 0.1) | -| `tol` | pixels (default 3): every point of every trace must lie this near its built run | +| `tol` | pixels (default 5): nine tenths of every trace, 5% of it left out at each end, must lie this near its built run | In a trace, `camera` names a camera object (`solve_camera` stands one) and `box` is its frame on the image, absent -for the render's own; `run` is `{"ring": i, "from": a, "to": b}` or `{"column": j, "from": a, "to": b}` in authored -indices; `side` is 1, or -1 for the mirrored half of a mirrored sheet; `line` is `[[u, v], ...]` in the box's -pixels, drawn from the run's `from` end to its `to` end. +for the render's own; `run` is `{"ring": i, "from": a, "to": b}` or `{"column": j, "from": a, "to": b}` on a loft and +`{"verts": [v, ...]}`, the run's vertices in order, on a free cage, all in authored indices; `side` is 1, or -1 +for the mirrored half of a mirrored sheet (the reflections `brokkr_kitbash`'s parser makes: `Sheet.mirror_of`); +`line` is `[[u, v], ...]` in the box's pixels, drawn from the run's first point to its last. **It returns a fit only where the built runs explain every trace.** After the fit, each trace is walked a pixel -at a time, and every point of it must lie within `tol` of its run as built and drawn. Otherwise the action is -refused, naming the trace, how much of it is unexplained, where along it and by how much, and nothing is returned -as a fit. The fit's own residual is no such test: on strokes doubled back over part of themselves 3% of the view -off, every fit converged and without this check all of them came back, up to 0.10 m wrong on a 2 m crease; with -it every one is refused (the least reads 9 px against the 3 asked). The check also binds the ends: a trace that -runs on past where its run ends, or two traces of a mirrored pair whose tips are not one point and its mirror -image through the camera, are refused at the tip. +at a time and each point's distance from its run, as built and drawn, is taken. The trace's reading, +`unexplained_px`, is the 90th percentile of those distances with 5% of the trace left out at each end; over `tol` +the action is refused, naming the trace, its reading, how much of it lies past `tol` and where, and nothing is +returned as a fit. `worst_px` is the furthest any point of the whole trace stands, ends included. The fit's own +residual is no such test: on strokes doubled back over part of themselves 3% of the view off, every fit converged +and without this check all of them came back, up to 0.10 m wrong on a 2 m crease. + +The ends are left out and the reading is not the worst point because a hand trace's tip is where two traces +cannot agree: the Orchid's hand-traced pair reads 0.69 px, with one tip 9.2 px off its run, and that pair's least +1% overdraw has a worst point of 9.1 px. The percentile, the 5% and the default were read from 296 fits and set +by the margin rule (`tests/test_reference.py`, `FitTests`): what should pass reads 3.26 px at most (hand traces +wandering 1 and 2 px), what should not reads 7.65 and up (the Orchid's traces overdrawn 2% of their extent, +synthetic strokes 3% off), and 5 sits 1.53 from each. + +**A very unsteady hand and a slight overdraw are not told apart.** Hand traces wandering 4 px read up to 5.96 +(31 of 36 pass the default); strokes overdrawn 1% read from 2.63 (12 of 45 pass) and 2% from 5.34 (none pass, with +no margin). The reading orders 99.8% of hand trace against 2 to 3% overdraw pairs rightly, but no threshold +stands 1.2 from both the 4 px hand traces and the 2% overdraws. So the reading is in the report of every accepted fit and in every refusal: near 5, look at the trace. An accepted trace +reading 3 to 5 px may be a 1% overdraw; a refused one reading 5 to 6 may be a clean stroke from an unsteady hand, +and asking again with `tol` over its reading is the caller's judgement. A doubled stretch shorter than a tenth of +the trace, or one inside the 5% at an end, does not move the reading: `worst_px` shows it. **It writes nothing.** The report carries `sheet`, the shell's own request with the traced points moved, ready for `brokkr_kitbash.shell`, which is the cage's one writer; `flow_score` on the rebuilt shell is the score. The -rest of the report: `traces` (`[{miss_px, unexplained_px}]`: the root mean square distance of the built points -from the trace, and the trace's furthest point from the built run), `points` (`[{ring, point, moved_m, m_per_px, -prior_share}]`, one per moved point) and `seconds`. +rest of the report: `traces` (`[{unexplained_px, worst_px}]`), `points` (`[{ring, point, moved_m, m_per_px, +prior_share}]` on a loft, `[{vertex, ...}]` on a free cage, one per moved point) and `seconds`. -`m_per_px` says how far a point slides along its line of sight per pixel of error in the traces (the worst of -the views that trace it), from the inverse of the fit's normal matrix, prior included (Triggs et al. 2000, -sections 9 and 10). `prior_share` is that over `share` x the diagonal: at 1 the traces say nothing about the -point along the sight line and it stands where the blocking put it. Read it per point: +`m_per_px` says how far a point slides in depth across its run per pixel of error in the traces: along the part +of its line of sight that stands across the run there (the worst of the traces that draw it), from the inverse +of the fit's normal matrix, prior included (Triggs et al. 2000, sections 9 and 10). A point's slide along its own +run is left out: the traces do not decide it and it does not move the built run. `prior_share` is `m_per_px` over +`share` x the diagonal: near 1 the traces say nothing about the point's depth and it stands where the blocking +put it. Read it per point against 0.2: -- A run traced on one half only, in one view, reads 1.0 on every point: its depth is the blocking's. -- A mirrored pair reads low where the mirror plane stands well off the sight line. On the Orchid's concept c09 - (plane 34 degrees off, a nearly orthographic camera) the pair's points read 0.12 at most, 0.024 m per px on a - ship one unit long. -- The sight line is taken whole. Where a run recedes along the view, a cage point's slide along its own run is - in the reading: the traces do not decide that slide and it does not move the built run. A column 24 to 38 - degrees off the sight line, both halves traced and its built run right to 0.2 mm, reads 0.63 to 0.88 on its - inner points. A high reading on such a run is not a depth error. -- A run on the mirror plane itself (a spine, a keel) has no partner and reads 1.0. +- **Under 0.2 the traces decide the point.** A mirrored pair traced in one view: over 18 fits every point reads + 0.080 or under and the built run is right to 0.7 mm. The Orchid's concept c09 pair reads 0.018 at most. +- **Over 0.2 the blocking holds it.** One half traced in one view: over the same 18 fits every inner point reads + 0.50 to 1.0 (the sine of the angle its run stands off the line of sight) and the built run is 18 to 355 mm + wrong. Either Orchid trace alone reads 0.27 and up on every point. 0.2 is the geometric mean of 0.080 and + 0.50, 2.5 from each. +- A run's end seen along the run reads low even on a single trace (down to 0.005): there the line of sight is + the run's own direction, and the depth across the run is decided. +- A run on the mirror plane (a spine, a keel) has no partner and needs none: its points stay on the plane, which + decides their depth. A spine traced once read 0.019 at most and came back within 0.15 mm. + +`m_per_px` is what one pixel of error on one point moves, not a bound on the fit's error. Clean strokes came back +within 0.16 of `tol` x the worst `m_per_px` they report. Hand traces whose wander holds over 30 px did not: of 24 +fitted (wander 2 and 4 px), 13 ended further off than that, up to 2.5 times (20 to 87 mm on a 2 m crease), while +every point read a `prior_share` under 0.05. A low reading says the traces decide the point; how well they decide it +is as good as the traces are. What it refuses before fitting, naming the trace: a run with an edge under weight 1 (a semi-sharp edge rounds off by an amount the fit does not model), a run whose end does not hold (a dart; a ring run from point 0 of a mirrored sheet, which runs on across the middle), a run with a point held partway (a corner point or a crossing -crease: trace it as two), a closed loop, an unknown camera, a line of fewer than two points, a free cage (it has -no rings or columns; `core.fit_runs` takes vertex chains), a scaled shell, and a result that would pass the -16000 characters a receipt carries. +crease: trace it as two), a closed loop, an unknown camera, a line of fewer than two points, a run named in the +other form's words (`verts` on a loft, a ring or column on a free cage), a scaled shell, and a result that would +pass the 16000 characters a receipt carries. Measured (Blender 5.3 and Python 3.13 on Starfire): a mirrored column of 10 points traced in one view at a time, from blockings 0.10 m and 0.30 m off a 2 m crease, came back within 0.7 mm in 0.1 to 0.6 s. The Orchid's c09 -petal edges, traced by hand through a camera solved from hand marks (13 px rms), are refused at 3 px: the left -trace's first 10 px stand up to 9.2 px off the built run. At 18.5 px they fit in 0.2 s, and from blockings 5%, -10% and 20% of the ship's length off the built run lands in one place, 2.0% of the length from a stand-in mesh -in the mean and 3.4% at worst. A trace drawn by hand through a camera solved by hand wants a `tol` near that -camera's own `rms`, and the acceptance is then that much weaker. +petal edges, traced by hand through a camera solved from hand marks (13 px rms), are accepted at the default, +reading 0.69 and 0.64 px, in 0.2 s; from blockings 5%, 10% and 20% of the ship's length off the built run lands +in one place, 2.0% of the length from a stand-in mesh in the mean and 3.4% at worst. A mirrored free cage's +crease of six vertices, blocked 0.056 m off, came back within 0.43 mm through the action in 0.02 s. -What it gives up: it fits hard runs of a loft only. Silhouettes of the smooth surface, semi-sharp creases and -free cages are not fitted; a run's depth with no mirror partner and no second view is the blocking's. +What it gives up: it fits hard runs only. Silhouettes of the smooth surface and semi-sharp creases are not +fitted; a run's depth with no mirror partner, no second view and no mirror plane under it is the blocking's. +The acceptance reads nine tenths of a trace: it passes a short doubled stretch and a tip that stands off, and +reports both as `worst_px`. ## What it cannot do @@ -274,6 +298,6 @@ cam2 = core.camera_of(params, box) # and back The tests are `tests/test_reference.py` (no Blender), `tests/live/reference.py` (a known scene rendered, solved through the action and rendered again; `reference.result.json` is its last run) and `tests/live/reference_flow.py` (`crease_run` against Blender's own subdivision, a box and a folded sheet scored by `flow_score`; -`reference_flow.result.json` is its last run) and `tests/live/reference_fit.py` (a mirrored shell blocked off its -design, fitted through the action, rebuilt by `brokkr_kitbash.shell` and scored; `reference_fit.result.json` is -its last run). +`reference_flow.result.json` is its last run) and `tests/live/reference_fit.py` (a mirrored loft and a mirrored +free cage, each blocked off its design, fitted through the action and rebuilt by `brokkr_kitbash.shell`; +`reference_fit.result.json` is its last run). From 0c0dc87e504f6979529bfaa752df9a4add341da9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 05:32:27 +0100 Subject: [PATCH 179/223] brokkr_reference fit: the trim deleted, a trace asked at its untrimmed 90th percentile (tol 5.2); m_per_px stated as a depth sensitivity, not an error bound No test claimed the trim (hand traces 3.76 against 3.26, the Orchid 0.80 against 0.69). Untrimmed, the traces to accept read 3.76 at most and the least to refuse 7.27: TOL 5.2, separation 1.39 each side. The clean-stroke test is named for the sensitivity it reads; fit_runs' docstring states the hand-trace overshoot (13 of 24, up to 2.45 times). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/__init__.py | 2 +- .../brokkr_reference/brokkr_actions.json | 6 +-- surfaces/blender/brokkr_reference/core.py | 29 +++++++------ surfaces/blender/tests/test_reference.py | 42 +++++++++---------- 4 files changed, 38 insertions(+), 41 deletions(-) diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index 96d6dab..d106882 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -218,7 +218,7 @@ class BROKKR_REFERENCE_OT_fit_shell(PolishOperator): object_name: bpy.props.StringProperty(name="Object", maxlen=63, description="A shell made by brokkr_kitbash.shell, unscaled; its place in the world is the sheet's frame") traces: bpy.props.StringProperty(name="Traces", maxlen=12000, description="A JSON array of {camera, box, run: {ring|column, from, to} on a loft or {verts: [v, ...]} on a free cage, side, line: [[u, v], ...]}") share: bpy.props.FloatProperty(name="Share", default=0.1, min=0.0009, max=10.0, description="A move of this share of the sheet's diagonal from the sheet as it stands costs what one pixel of miss does") - tol: bpy.props.FloatProperty(name="Tolerance", default=core.TOL, min=0.09, max=100.0, description="Pixels: nine tenths of every trace, its ends apart, must lie this near its built run, or the fit is refused") + tol: bpy.props.FloatProperty(name="Tolerance", default=core.TOL, min=0.09, max=100.0, description="Pixels: nine tenths of every trace must lie this near its built run, or the fit is refused") # the action table states share from 0.001 and tol from 0.1: a float property rounds those up, so its bounds stand just under def work(self, context): diff --git a/surfaces/blender/brokkr_reference/brokkr_actions.json b/surfaces/blender/brokkr_reference/brokkr_actions.json index aa4f7e2..a1d4856 100644 --- a/surfaces/blender/brokkr_reference/brokkr_actions.json +++ b/surfaces/blender/brokkr_reference/brokkr_actions.json @@ -136,7 +136,7 @@ }, { "name": "brokkr_reference.fit_shell", - "doc": "Fit a kitbash shell's sheet (a loft or a free cage) to traces of its hard crease and rim runs, each seen through a scene camera: the traced runs' cage points move until the runs as built draw on the traces. Returns the fitted sheet for brokkr_kitbash.shell only where nine tenths of every trace, 5% left out at each end, lies within tol px of its built run; otherwise it is refused naming the trace, its reading and the span. A very unsteady hand and a 1 to 2% overdraw read alike: each trace's reading (unexplained_px) and worst point (worst_px) are in the report to judge by. Writes nothing. Per moved point: metres of depth across its run per pixel, and the prior's share of that: under 0.2 the traces decide the point, over it the blocking holds it (docs/reference.md).", + "doc": "Fit a kitbash shell's sheet (a loft or a free cage) to traces of its hard crease and rim runs, each seen through a scene camera: the traced runs' cage points move until the runs as built draw on the traces. Returns the fitted sheet for brokkr_kitbash.shell only where nine tenths of every trace lies within tol px of its built run; otherwise it is refused naming the trace, its reading and the span. A very unsteady hand and a 1 to 2% overdraw read alike: each trace's reading (unexplained_px) and worst point (worst_px) are in the report to judge by. Writes nothing. Per moved point: its depth sensitivity (metres one pixel of trace error moves it along its sight line, across its run; a sensitivity, not an error bound) and the prior's share of that: under 0.2 the traces decide the point, over it the blocking holds it (docs/reference.md).", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -170,8 +170,8 @@ "type": "number", "minimum": 0.1, "maximum": 100, - "default": 5, - "doc": "pixels: nine tenths of every trace, its ends apart, must lie this near its built run, or the fit is refused" + "default": 5.2, + "doc": "pixels: nine tenths of every trace must lie this near its built run, or the fit is refused" } ] } diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index bb27391..69549b4 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -452,9 +452,8 @@ def along(line, segments, height, near=0.01, turn=20.0, cap=0.05): LEVELS = 2 # crease_run applied this many times gives the samples of a built run the fit draws: 4k - 3 for k cage points HARD = 1.0 - 1e-9 # a crease weight from here up is hard: the edge stays sharp at every level, which is what crease_run builds ROUNDS = 60 -TRIM = 0.05 # of a trace's length, left out at each end where a trace is asked whether its run explains it: a hand trace's tip is where two traces cannot agree -PART = 90 # the percentile of the rest of the trace's distances from its built run that fit_runs reads against tol -TOL = 5.0 # pixels. tests/test_reference.py FitTests states the sets TRIM, PART and TOL were read from, and what they do not separate +PART = 90 # the percentile of a trace's distances from its built run that fit_runs reads against tol: a hand trace's tip is where two traces cannot agree, and a tenth of it may stand off +TOL = 5.2 # pixels. tests/test_reference.py FitTests states the sets PART and TOL were read from, and what they do not separate RESULT_LIMIT = 16000 # characters of a host result Brokkr copies into a receipt before it truncates (brokkr_bridge's HOST_RESULT_LIMIT; this package imports nothing from Brokkr) @@ -540,20 +539,21 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL): mirror_of per vertex, the authored vertex it mirrors across x = 0, or itself: a mirrored half is the same parameters seen again, x negated share the prior: a move of share x diag from the cage as given costs what one pixel of miss does - tol pixels: of each trace less TRIM of its length at each end, PART in a hundred must lie this near its - built run as drawn + tol pixels: PART in a hundred of each trace must lie this near its built run as drawn The residual per run is the pixel distance from each built point (crease_run LEVELS times, drawn through the run's view) to the trace, and the run's two ends against the trace's; no point of the trace is matched to a point of the run beyond that. Gauss-Newton with Levenberg-Marquardt damping on the analytic Jacobian. Returns (V, report): the cage's vertices as fitted and {"traces": [{"unexplained_px": the reading tol is asked of, "worst_px": the whole trace's furthest point from the built run}], "points": [{"vertex", "moved_m", "m_per_px", - "prior_share"}], "rounds"}. m_per_px is how far the point slides in depth across its run per pixel of error in - the traces: along the part of its sight line that stands across the run's tangent there (the worst of the - traces that draw it), sqrt(r' S r) with S the point's block of the inverse of J'J, prior included (Triggs et - al. 2000, sections 9 and 10). A point's slide along its own run is left out: the traces do not decide it and it - does not move the built run. prior_share is m_per_px over share x diag: near 1 the traces say nothing about - the point's depth and it stands where it was blocked. + "prior_share"}], "rounds"}. m_per_px is the point's depth sensitivity: how many metres one pixel of error in + the traces moves that point along its sight line, taken on the part of the sight line that stands across the + run's tangent there (the worst of the traces that draw it), sqrt(r' S r) with S the point's block of the + inverse of J'J, prior included (Triggs et al. 2000, sections 9 and 10). A point's slide along its own run is + left out: the traces do not decide it and it does not move the built run. It is a sensitivity to one pixel on + one point and no bound on the fit's error: of 24 fits to hand traces whose wander holds over 30 px, 13 ended + further from the truth than tol x m_per_px, up to 2.45 times. prior_share is m_per_px over share x diag: near + 1 the traces say nothing about the point's depth and it stands where it was blocked. Raises ReferenceFitError for a run it cannot model (_hard_runs), and when a trace is not explained: the error names the trace, its reading and the span of it that lies further than tol from the built run, and carries the @@ -632,13 +632,12 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL): length = np.linalg.norm(np.diff(line, axis=0), axis=1).sum() dense = resampled(line, int(min(max(length, len(line)), 4000)) + 1) # a point each pixel along it off = _off(dense, u) - ends = int(TRIM * len(dense)) - reading = float(np.percentile(off[ends:len(dense) - ends], PART)) + reading = float(np.percentile(off, PART)) traces.append({"unexplained_px": round(reading, 3), "worst_px": round(float(off.max()), 3)}) if reading > tol and refused is None: - out = (ends + np.flatnonzero(off[ends:len(dense) - ends] > tol)) * length / (len(dense) - 1) + out = np.flatnonzero(off > tol) * length / (len(dense) - 1) refused = (f"{name} is not explained: {len(out) * length / (len(dense) - 1):.0f} px of the trace, between {out[0]:.0f} and {out[-1]:.0f} px along it, lie " - f"more than {tol:g} px from the run as built ({reading:.1f} px at the {PART}th of a hundred, {TRIM:.0%} of the trace left out at each end; up to " + f"more than {tol:g} px from the run as built ({reading:.1f} px at the {PART}th of a hundred; up to " f"{off.max():.1f} px). Nothing is returned as a fit. The trace draws something this run does not build (an overdrawn or doubled stroke, another " "edge, a bend the cage has too few points for): redraw it, or give the run more points. A very unsteady hand reads the same as a slight " "overdraw: if the trace is one clean stroke, ask again with tol over this reading") diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index 72d19d1..db8af73 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -483,18 +483,17 @@ class FitTests(unittest.TestCase): G7 a free cage's mirrored half read as the authored test_a_free_cage_is_fitted_by_its_vertex_chains G8 the prior in the Jacobian and not the residual test_one_trace_alone_reads_as_held_by_the_blocking - core.TRIM, core.PART and core.TOL were read from 296 fits kept outside the suite (108 hand traces by `hand`, + core.PART and core.TOL were read from 296 fits kept outside the suite (108 hand traces by `hand`, wander 1, 2 and 4 px; 108 strokes by `overdrawn` 1, 2, 3 and 5% off; the Orchid pair, moved and overdrawn). - Read as the PART-th percentile past TRIM at each end, the traces to accept read 3.26 px at most (the 72 hand - traces of wander 1 and 2 px; the Orchid pair 0.69) and the least to refuse 7.65 (the Orchid's traces overdrawn - 2%; the strokes 3% off 7.83): TOL is their geometric mean, separation 1.53 each side. The trace's worst point, + Read at the PART-th percentile, the traces to accept read 3.76 px at most (the 72 hand traces of wander 1 and + 2 px; the Orchid pair 0.80) and the least to refuse 7.27 (the Orchid's traces overdrawn 2%; the strokes 3% off + 7.70): TOL is their geometric mean, separation 1.39 each side. The trace's worst point, which that reading replaces, read 9.20 on the Orchid pair against 9.12 on its least 1% overdraw. What TOL does - not separate: 31 of the 36 hand traces of wander 4 px are accepted (they read up to 5.96), 9 of 27 strokes 1% - off and 3 of 18 Orchid 1% overdraws are accepted (from 2.63 and 4.27), and the strokes 2% off are refused from - 5.34 with no margin. A very unsteady hand and a slight overdraw read alike; the report carries the reading. + not separate: 31 of the 36 hand traces of wander 4 px are accepted (they read up to 5.84), 9 of 27 strokes 1% + off and 2 of 18 Orchid 1% overdraws are accepted (from 2.57 and 4.25), and of the strokes 2% off, which read + from 5.10, 2 of 27 are accepted. A very unsteady hand and a slight overdraw read alike; the report carries the reading. - Unclaimed, with readings: TRIM 0 (the hand traces read 3.76 against 3.26, the Orchid 0.80 against 0.69: - separation 1.15); F6, the Jacobian by differences (time only: tests/live/reference_fit.py's header); + Unclaimed, with readings: F6, the Jacobian by differences (time only: tests/live/reference_fit.py's header); the least, in place of the worst, of the traces that draw a point (the 18 pairs' greatest prior_share reads 0.060 against 0.080, both under PAIR_FROM_SINGLE; one point's two readings differ up to 4.3 times); the guard on a run seen end on (the reading is dropped either way).""" @@ -561,8 +560,8 @@ class FitTests(unittest.TestCase): def test_an_overdrawn_stroke_is_refused_naming_its_trace(self): """overdraw-refused, F1 and G6: the mirrored half's trace doubled back over part of itself 3% of its extent - off. All 27 are refused, naming the trace and the span that no built run draws; the least reads 7.83 px - against core.TOL, separation 1.57. F1 returns all 27 as fits, the worst 0.104 m off the truth. Asked with + off. All 27 are refused, naming the trace and the span that no built run draws; the least reads 7.70 px + against core.TOL, separation 1.48. F1 returns all 27 as fits, the worst 0.104 m off the truth. Asked with tol 1.1 times its own reading a stroke is accepted, and with tol that reading over 1.1 refused: tol is what the reading is held to (G6 holds it to 1.2 x tol).""" truth, document = blocked(0.2, 2.5, 0.05) @@ -586,11 +585,10 @@ class FitTests(unittest.TestCase): def test_hand_traces_are_explained_at_the_default(self): """G2: both halves traced by `hand` (wander 2 px, tips 6 px off), each of three views. All three are - accepted at core.TOL, reading 2.97 px at most (TOL over 1.68), while the worst point of a trace stands 6.94 - px off its run and, the tips left out, still 5.82 to 6.94: G2, which holds that point to TOL, refuses all - three. The fits end 20 to 64 mm off the true crease, up to 1.36 times TOL x the m_per_px they report: - m_per_px is what one pixel of error on a single point moves, and a wander that holds over 30 px moves - more.""" + accepted at core.TOL, reading 2.99 px at most (TOL over 1.74), while the worst point of each stands 6.08 to + 6.94 px off its run: G2, which holds that point to TOL, refuses all three. The fits end 20 to 64 mm off the + true crease, up to 1.3 times TOL x the m_per_px they report: m_per_px is a sensitivity, what one pixel of + error on a single point moves, and a wander that holds over 30 px moves more.""" truth, document = blocked(0.2, 2.5, 0.05) rng, most = np.random.default_rng(1), 0.0 for cam in fit_views(truth): @@ -600,10 +598,10 @@ class FitTests(unittest.TestCase): most = max(most, max(row["worst_px"] for row in out["traces"])) self.assertGreater(most, core.TOL * 1.2) - def test_a_clean_fit_is_within_its_own_reported_reach(self): - """accepted-bounded, on clean strokes only: strokes doubled back 0.2% off pass as explained, and each + def test_a_clean_fit_moves_less_than_its_reported_sensitivity(self): + """m_per_px as a sensitivity, on clean strokes only: strokes doubled back 0.2% off pass as explained, and each accepted fit stands within core.TOL x the worst m_per_px it reports of the truth: all 27 are accepted, the - worst 8.9 mm off, 0.161 of that reach. No mutant claims this bound, and hand traces pass it + worst 8.9 mm off, 0.16 of that. It is no error bound: no mutant claims it, and hand traces end past it (test_hand_traces_are_explained_at_the_default).""" truth, document = blocked(0.2, 2.5, 0.05) accepted, most = 0, 0.0 @@ -665,12 +663,12 @@ class FitTests(unittest.TestCase): def test_orchid_c09_hand_traces(self): """orchid-c09: the inboard edges of two petals traced by hand on one concept view, through a camera solved - from hand marks (13 px rms). At the default the pair is explained: its traces read 0.69 and 0.64 px (TOL - over 7.2), though the left trace's first 10 px stand up to 9.2 px off the built run, because the two + from hand marks (13 px rms). At the default the pair is explained: its traces read 0.80 and 0.68 px (TOL + over 6.5), though the left trace's first 10 px stand up to 9.2 px off the built run, because the two traces' tips are not one point and its mirror image through that camera; the gate on the worst point refused the pair for that. Its points read a prior_share of 0.018 at most; either trace alone reads 0.271 and up on every point: the bound is their geometric mean, separation 3.9 each side. The right trace - overdrawn 2% of its extent is refused nine ways of nine, reading 7.65 px and up.""" + overdrawn 2% of its extent is refused nine ways of nine, reading 7.27 px and up.""" left, right, side = self.orchid["left"], self.orchid["right"], self.orchid["left_side"] pair = self.orchid_fit([(side, left), (-side, right)]) self.assertLess(max(row["unexplained_px"] for row in pair["traces"]), core.TOL / 1.2) From 23ebf4dd1845d3e1bdde169b7dfe88b2b21e6615 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 05:37:03 +0100 Subject: [PATCH 180/223] docs/reference.md: the untrimmed 90th percentile at 5.2 px and what it does not separate; m_per_px as a depth sensitivity with the measured hand-trace overshoot; reference_fit's last run Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/reference.md | 55 ++++++++++--------- .../tests/live/reference_fit.result.json | 14 ++--- 2 files changed, 35 insertions(+), 34 deletions(-) diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index 31cfb89..bbde414 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -194,7 +194,7 @@ diagonal costs what one pixel of miss does. | `object_name` | a shell made by `brokkr_kitbash.shell`, unscaled; its place in the world is the sheet's frame | | `traces` | a JSON array, up to 12000 characters, of `{camera, box, run, side, line}` | | `share` | the prior (default 0.1) | -| `tol` | pixels (default 5): nine tenths of every trace, 5% of it left out at each end, must lie this near its built run | +| `tol` | pixels (default 5.2): nine tenths of every trace must lie this near its built run | In a trace, `camera` names a camera object (`solve_camera` stands one) and `box` is its frame on the image, absent for the render's own; `run` is `{"ring": i, "from": a, "to": b}` or `{"column": j, "from": a, "to": b}` on a loft and @@ -204,35 +204,36 @@ for the mirrored half of a mirrored sheet (the reflections `brokkr_kitbash`'s pa **It returns a fit only where the built runs explain every trace.** After the fit, each trace is walked a pixel at a time and each point's distance from its run, as built and drawn, is taken. The trace's reading, -`unexplained_px`, is the 90th percentile of those distances with 5% of the trace left out at each end; over `tol` -the action is refused, naming the trace, its reading, how much of it lies past `tol` and where, and nothing is -returned as a fit. `worst_px` is the furthest any point of the whole trace stands, ends included. The fit's own -residual is no such test: on strokes doubled back over part of themselves 3% of the view off, every fit converged -and without this check all of them came back, up to 0.10 m wrong on a 2 m crease. +`unexplained_px`, is the 90th percentile of those distances; over `tol` the action is refused, naming the trace, +its reading, how much of it lies past `tol` and where, and nothing is returned as a fit. `worst_px` is the +furthest any point of the trace stands. The fit's own residual is no such test: on strokes doubled back over +part of themselves 3% of the view off, every fit converged and without this check all of them came back, up to +0.10 m wrong on a 2 m crease. -The ends are left out and the reading is not the worst point because a hand trace's tip is where two traces -cannot agree: the Orchid's hand-traced pair reads 0.69 px, with one tip 9.2 px off its run, and that pair's least -1% overdraw has a worst point of 9.1 px. The percentile, the 5% and the default were read from 296 fits and set -by the margin rule (`tests/test_reference.py`, `FitTests`): what should pass reads 3.26 px at most (hand traces -wandering 1 and 2 px), what should not reads 7.65 and up (the Orchid's traces overdrawn 2% of their extent, -synthetic strokes 3% off), and 5 sits 1.53 from each. +The reading is not the worst point because a hand trace's tip is where two traces cannot agree: the Orchid's +hand-traced pair reads 0.80 px, with one tip 9.2 px off its run, and that pair's least 1% overdraw has a worst +point of 9.1 px. The percentile and the default were read from 296 fits and set by the margin rule +(`tests/test_reference.py`, `FitTests`): what should pass reads 3.76 px at most (hand traces wandering 1 and 2 +px), what should not reads 7.27 and up (the Orchid's traces overdrawn 2% of their extent; synthetic strokes 3% +off read 7.70), and 5.2 sits 1.39 from each. -**A very unsteady hand and a slight overdraw are not told apart.** Hand traces wandering 4 px read up to 5.96 -(31 of 36 pass the default); strokes overdrawn 1% read from 2.63 (12 of 45 pass) and 2% from 5.34 (none pass, with -no margin). The reading orders 99.8% of hand trace against 2 to 3% overdraw pairs rightly, but no threshold -stands 1.2 from both the 4 px hand traces and the 2% overdraws. So the reading is in the report of every accepted fit and in every refusal: near 5, look at the trace. An accepted trace -reading 3 to 5 px may be a 1% overdraw; a refused one reading 5 to 6 may be a clean stroke from an unsteady hand, -and asking again with `tol` over its reading is the caller's judgement. A doubled stretch shorter than a tenth of -the trace, or one inside the 5% at an end, does not move the reading: `worst_px` shows it. +**A very unsteady hand and a slight overdraw are not told apart.** Hand traces wandering 4 px read up to 5.84 +(31 of 36 pass the default); strokes overdrawn 1% read from 2.57 (11 of 45 pass) and 2% from 5.10 (2 of 45 +pass). The reading orders 99.6% of hand trace against 2 to 3% overdraw pairs rightly, but no threshold stands 1.2 +from both the 4 px hand traces and the 2% overdraws. So the reading is in the report of every accepted fit and +in every refusal: near 5, look at the trace. An accepted trace reading 3 to 5 px may be a 1 or 2% overdraw; a +refused one reading 5 to 6 may be a clean stroke from an unsteady hand, and asking again with `tol` over its +reading is the caller's judgement. A doubled stretch shorter than a tenth of the trace does not move the +reading: `worst_px` shows it. **It writes nothing.** The report carries `sheet`, the shell's own request with the traced points moved, ready for `brokkr_kitbash.shell`, which is the cage's one writer; `flow_score` on the rebuilt shell is the score. The rest of the report: `traces` (`[{unexplained_px, worst_px}]`), `points` (`[{ring, point, moved_m, m_per_px, prior_share}]` on a loft, `[{vertex, ...}]` on a free cage, one per moved point) and `seconds`. -`m_per_px` says how far a point slides in depth across its run per pixel of error in the traces: along the part -of its line of sight that stands across the run there (the worst of the traces that draw it), from the inverse -of the fit's normal matrix, prior included (Triggs et al. 2000, sections 9 and 10). A point's slide along its own +`m_per_px` is a point's depth sensitivity: how many metres one pixel of error in the traces moves that point +along its line of sight, taken on the part of the line of sight that stands across the run there (the worst of +the traces that draw it), from the inverse of the fit's normal matrix, prior included (Triggs et al. 2000, sections 9 and 10). A point's slide along its own run is left out: the traces do not decide it and it does not move the built run. `prior_share` is `m_per_px` over `share` x the diagonal: near 1 the traces say nothing about the point's depth and it stands where the blocking put it. Read it per point against 0.2: @@ -248,10 +249,10 @@ put it. Read it per point against 0.2: - A run on the mirror plane (a spine, a keel) has no partner and needs none: its points stay on the plane, which decides their depth. A spine traced once read 0.019 at most and came back within 0.15 mm. -`m_per_px` is what one pixel of error on one point moves, not a bound on the fit's error. Clean strokes came back +`m_per_px` is a sensitivity, and `tol` x `m_per_px` is no bound on the fit's error. Clean strokes came back within 0.16 of `tol` x the worst `m_per_px` they report. Hand traces whose wander holds over 30 px did not: of 24 -fitted (wander 2 and 4 px), 13 ended further off than that, up to 2.5 times (20 to 87 mm on a 2 m crease), while -every point read a `prior_share` under 0.05. A low reading says the traces decide the point; how well they decide it +fitted (wander 2 and 4 px), 13 ended further off than that, up to 2.45 times (20 to 87 mm on a 2 m crease), +while every point read a `prior_share` under 0.05. A low reading says the traces decide the point; how well they decide it is as good as the traces are. What it refuses before fitting, naming the trace: a run with an edge under weight 1 (a semi-sharp edge rounds @@ -264,14 +265,14 @@ pass the 16000 characters a receipt carries. Measured (Blender 5.3 and Python 3.13 on Starfire): a mirrored column of 10 points traced in one view at a time, from blockings 0.10 m and 0.30 m off a 2 m crease, came back within 0.7 mm in 0.1 to 0.6 s. The Orchid's c09 petal edges, traced by hand through a camera solved from hand marks (13 px rms), are accepted at the default, -reading 0.69 and 0.64 px, in 0.2 s; from blockings 5%, 10% and 20% of the ship's length off the built run lands +reading 0.80 and 0.68 px, in 0.2 s; from blockings 5%, 10% and 20% of the ship's length off the built run lands in one place, 2.0% of the length from a stand-in mesh in the mean and 3.4% at worst. A mirrored free cage's crease of six vertices, blocked 0.056 m off, came back within 0.43 mm through the action in 0.02 s. What it gives up: it fits hard runs only. Silhouettes of the smooth surface and semi-sharp creases are not fitted; a run's depth with no mirror partner, no second view and no mirror plane under it is the blocking's. The acceptance reads nine tenths of a trace: it passes a short doubled stretch and a tip that stands off, and -reports both as `worst_px`. +reports both as `worst_px`. `m_per_px` is a sensitivity to one pixel, not an error bound. ## What it cannot do diff --git a/surfaces/blender/tests/live/reference_fit.result.json b/surfaces/blender/tests/live/reference_fit.result.json index 17094d0..9d3a687 100644 --- a/surfaces/blender/tests/live/reference_fit.result.json +++ b/surfaces/blender/tests/live/reference_fit.result.json @@ -49,7 +49,7 @@ } }, { - "name": "fit_shell returns a sheet with every trace explained within 5 px, and a row for each of the 12 moved points", + "name": "fit_shell returns a sheet with every trace explained within 5.2 px, and a row for each of the 12 moved points", "ok": true, "detail": { "traces": [ @@ -58,19 +58,19 @@ "worst_px": 0.021 }, { - "unexplained_px": 0.058, + "unexplained_px": 0.054, "worst_px": 0.082 }, { - "unexplained_px": 0.053, + "unexplained_px": 0.052, "worst_px": 0.071 }, { - "unexplained_px": 0.037, + "unexplained_px": 0.036, "worst_px": 0.055 } ], - "seconds": 0.138, + "seconds": 0.176, "chars": 2066 } }, @@ -123,7 +123,7 @@ { "name": "a trace doubled back over itself is refused, naming the trace and the span no built run draws", "ok": true, - "detail": "Error: traces[1] is not explained: 239 px of the trace, between 124 and 461 px along it, lie more than 5 px from the run as built (12.1 px at the 90th of a hundred, 5% of the trace left out at each end; up to 15.7 px). Nothing is returned as a fit. The trace draws something this run does not build (an overdrawn or doubled stroke, another edge, a bend the cage has too few points for): redraw it, or give the run more points. A very unsteady hand reads the same as a slight overdraw: if the trace is one clean stroke, ask again with tol over this reading. Nothing changed." + "detail": "Error: traces[1] is not explained: 235 px of the trace, between 126 and 461 px along it, lie more than 5.2 px from the run as built (11.6 px at the 90th of a hundred; up to 15.7 px). Nothing is returned as a fit. The trace draws something this run does not build (an overdrawn or doubled stroke, another edge, a bend the cage has too few points for): redraw it, or give the run more points. A very unsteady hand reads the same as a slight overdraw: if the trace is one clean stroke, ask again with tol over this reading. Nothing changed." }, { "name": "an unknown camera is refused naming the trace", @@ -162,7 +162,7 @@ } ], "prior_share": 0.06, - "seconds": 0.022 + "seconds": 0.027 } }, { From 9815bad8d1233c625670765d44236fc8c3977872 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 06:26:59 +0100 Subject: [PATCH 181/223] brokkr_kitbash.ram: solids welds before it reads edges and signs by the winding before each face; a mirrored shell is placed by its matrix solids read topology by vertex index and inversion by a solid's volume, and both failed on real meshes (verdict cut-kit-ram-lows.s3). - weld: vertices within WELD (3e-4 of the extent) are one vertex to the open check, so a seam of coincident vertices is no hole. - A face is turned where the winding number NUDGE before its centroid is under -0.5. The region before the turned faces is measured along their normals, and a part is refused where it holds THIN (1.1e-4 of the extent cubed) or more. A turned solid welded to a whole one is refused; a cavity and a sliver pass. - placed: a shell may carry its matrix; a mirrored one has its faces turned back. - tests.test_ram.Corpus: every kit part at the corners of its params (316), and tests/fixtures/ram_meshes.npz, 33 mech meshes: the 21 refused inside out, three open, and the passing parts nearest each bound. - live ram_knee: a hollow mass and a mirrored shell are read; outside is to the nearest face of all; plates 1e-5 of the extent apart are two surfaces; a turned cube's faces are all exposed. 24 checks. Over the 1,832 mech meshes: 1,790 pass, 21 open, 21 inside out (the 17 of s3, walker's two guns, seraph's two Torso.LowerIn plates). Kits: 3,224 of 3,224 pass. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/ram.py | 118 ++++++++++--- surfaces/blender/docs/kitbash.md | 57 +++++-- .../blender/tests/fixtures/ram_meshes.npz | Bin 0 -> 273401 bytes surfaces/blender/tests/live/ram_knee.py | 59 ++++++- .../blender/tests/live/ram_knee.result.json | 59 ++++++- surfaces/blender/tests/test_ram.py | 161 ++++++++++++++++-- 6 files changed, 389 insertions(+), 65 deletions(-) create mode 100644 surfaces/blender/tests/fixtures/ram_meshes.npz diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py index d5fa6f5..dd250a4 100644 --- a/surfaces/blender/brokkr_kitbash/ram.py +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -27,6 +27,7 @@ the coupler bar at c's, the ram at a's plus each of `offsets`. winding(vertices, triangles, points) the generalized winding number of a triangle soup about points inside(vertices, triangles, points) whether points are inside it: the number is 0.5 or more solids(part, vertices, faces) the closed, outward wound solids of a part, or the refusal + placed(vertices, faces, matrix) a local mesh carried by a matrix, turned back where it mirrors Signed(shells, cap) the distance oracle over meshes, signed by the winding number Clearance. The record names the mechanism's `parts`, each a piece of one body (part -> the body whose rest frame @@ -60,6 +61,7 @@ between two points. A RamError of a gate (assembly, stroke, toggle, arm, load, clash) names the angle and the pin; one of the record or of a call (an unknown kind, a range, a grid over the limit, a version) names the pin or the field it refuses. """ +import itertools import math from dataclasses import dataclass, field, fields, replace @@ -81,6 +83,9 @@ GATES = ("assembly", "stroke", "toggle", "arm", "load", "clash") SCHEMA, VERSION = "brokkr.ram", 2 ZONE = ("part", "pin", "radius", "depth") # a zone of `touch`, as the record writes it BAND = 1e-9 # the loop is refused within this of a dead centre of the rocker and coupler +WELD = 3e-4 # of a part's extent: vertices this near along every axis are one vertex to `solids` +NUDGE = 1e-6 # of a part's extent: how far off a face's centroid its two sides are read +THIN = 1.1e-4 # of a part's extent cubed: a region winding -1 that holds less is not read as the part turned over FINE = 64 # in a zone a segment between samples is halved down to spacing / FINE @@ -782,12 +787,33 @@ def inside(vertices, triangles, points): return winding(vertices, triangles, points) >= 0.5 -def solids(part, vertices, faces): - """The solid each face of a part belongs to (faces joined across an edge are one solid), or a RamError where - the part has no inside to sign: a solid with an edge no face runs the other way (a boundary edge, or two faces - wound against each other across it) is open, and a closed solid of negative volume is wound inside out. - Nothing is repaired. A cavity cut as its own inward shell is such a solid and is refused with the rest.""" +def weld(vertices, tolerance): + """The vertex each of `vertices` is read as: one index for all that stand within `tolerance` of one another + along every axis, and for a chain of such. Each is found by the cell it falls in on eight grids of twice the + tolerance, each half a cell off the last along some axes: two points that near share a cell of one.""" v = np.asarray(vertices, dtype=float).reshape(-1, 3) + label = np.arange(len(v)) + if not len(v) or not tolerance > 0.0: + return label + cells = [np.unique(np.floor(v / (2.0 * tolerance) + shift).astype(np.int64), axis=0, return_inverse=True)[1].reshape(-1) for shift in itertools.product((0.0, 0.5), repeat=3)] + while True: + before = label + for cell in cells: + least = np.full(int(cell.max()) + 1, len(v)) + np.minimum.at(least, cell, label) + label = least[cell] + if (label == before).all(): + return label + + +def _read(part, vertices, faces): + """`solids`, and with each face's solid the fan of triangles, the faces of some area and the winding number + before each of those: what Signed keeps.""" + v = np.asarray(vertices, dtype=float).reshape(-1, 3) + face_of = np.repeat(np.arange(len(faces)), [len(face) - 2 for face in faces]) + fan = np.array([(face[0], face[k], face[k + 1]) for face in faces for k in range(1, len(face) - 1)], dtype=int).reshape(-1, 3) + extent = float(np.linalg.norm(np.ptp(v, axis=0))) if len(v) else 0.0 + one = weld(v, WELD * extent) owner, edges = list(range(len(faces))), {} def root(k): @@ -796,10 +822,12 @@ def solids(part, vertices, faces): return k for k, face in enumerate(faces): - for i, j in zip(face, tuple(face[1:]) + tuple(face[:1])): - there = edges.setdefault((min(i, j), max(i, j)), [k, 0]) - there[1] += 1 if i < j else -1 - owner[root(k)] = root(there[0]) + face = [int(one[i]) for i in face] + for i, j in zip(face, face[1:] + face[:1]): + if i != j: + there = edges.setdefault((min(i, j), max(i, j)), [k, 0]) + there[1] += 1 if i < j else -1 + owner[root(k)] = root(there[0]) of = np.array([root(k) for k in range(len(faces))], dtype=int) names = {r: n for n, r in enumerate(dict.fromkeys(of.tolist()))} # solids numbered in the order of their first faces unmatched = {} @@ -809,22 +837,64 @@ def solids(part, vertices, faces): for n, count in sorted(unmatched.items()): raise RamError("mesh", "signed", f"part {part!r} is open: solid {n} of {len(names)} has {count} edge{'s' if count > 1 else ''} no face runs the other way") of = np.array([names[r] for r in of.tolist()], dtype=int) - fan = np.array([(k, face[0], face[n], face[n + 1]) for k, face in enumerate(faces) for n in range(1, len(face) - 1)], dtype=int).reshape(-1, 4) - volume = np.bincount(of[fan[:, 0]], (v[fan[:, 1]] * np.cross(v[fan[:, 2]], v[fan[:, 3]])).sum(axis=1) / 6.0, len(names)) - for n in np.flatnonzero(volume < 0.0): - raise RamError("mesh", "signed", f"part {part!r} is wound inside out: solid {n} of {len(names)} ({int((of == n).sum())} faces from face {int(np.flatnonzero(of == n)[0])}) has volume {volume[n]:.3g}") - return of + normal = np.zeros((len(faces), 3)) + np.add.at(normal, face_of, np.cross(v[fan[:, 1]] - v[fan[:, 0]], v[fan[:, 2]] - v[fan[:, 0]])) + size = np.linalg.norm(normal, axis=1) + flat = np.flatnonzero(size > 0.0) # a face of no area has no side to be read on + centre = np.array([v[list(faces[k])].mean(axis=0) for k in flat]).reshape(-1, 3) + before = winding(v, fan, centre + NUDGE * extent * normal[flat] / size[flat, None]) + turned = np.flatnonzero(before < -0.5) + if len(turned): + unit, rungs = normal[flat[turned]] / size[flat[turned], None], NUDGE * 10.0 ** (np.arange(25) / 4.0) # the nudge to the whole extent, four to a decade + still = winding(v, fan, (centre[turned][:, None, :] + (rungs[1:] * extent)[None, :, None] * unit[:, None, :]).reshape(-1, 3)).reshape(len(turned), -1) < -0.5 + held = float((0.5 * size[flat[turned]] * rungs[np.cumprod(still, axis=1).sum(axis=1)]).sum()) / extent ** 2 + if held >= THIN: + k = int(flat[turned[0]]) + raise RamError("mesh", "signed", f"part {part!r} is wound inside out: {len(turned)} faces, from face {k} of solid {int(of[k])} of {len(names)}, stand before a region that winds {float(before[turned[0]]):.3g} and holds {held:.3g} of the part's extent cubed") + return of, fan, flat, before + + +def solids(part, vertices, faces): + """The solid each face of a part belongs to (faces joined across an edge are one solid), or a RamError where + the part has no inside to sign. Nothing is repaired. + + Vertices within WELD of the part's extent (its box's diagonal) of one another are read as one, so a seam of + coincident vertices is no hole. A solid with an edge no face runs the other way (a boundary edge, or two faces + wound against each other across it) is open. + + A face is read NUDGE of the extent before its centroid, along its normal. Before a face of a whole solid the + winding number is 0, or more where another solid covers it. A face is turned where the number there is under + -0.5: it stands before a region that winds -1, the inside of a solid wound inside out. That region is measured: + each turned face's area by how far out along its normal the number stays under -0.5 (the nudge, then four rungs + to a decade up to the extent), summed. A part whose region holds THIN of its extent cubed or more is wound + inside out, whether the turned solid stands free or is welded to a whole one. Less is the crossing of a bevel + or of a lathe's profile and is let be: there the part reads outside in what its author took for inside. A + cavity cut as its own inward shell has the cavity before its faces, which winds 0, and passes; so does a + sliver, two sheets back to back, with nothing between them to wind.""" + return _read(part, vertices, faces)[0] + + +def placed(vertices, faces, matrix): + """A local mesh in the frame a 4 by 4 `matrix` carries it to: the vertices carried, and each face turned back + where the matrix mirrors (its determinant is negative), so a part mirrored by a negative scale is wound as its + own mesh is.""" + m = np.asarray(matrix, dtype=float).reshape(4, 4) + v = np.asarray(vertices, dtype=float).reshape(-1, 3) @ m[:3, :3].T + m[:3, 3] + return v, [tuple(face)[::-1] if np.linalg.det(m[:3, :3]) < 0.0 else tuple(face) for face in faces] class Signed: """The distance oracle over meshes: distance(part, points) is the distance to the part's surface, negative where the point is inside the part (its depth), capped at `cap` outside only. shells: part -> [(vertices (N, 3), faces)], in the rest frame of the part's body. Every solid of a part (`solids`) is closed and wound - counterclockwise seen from outside: a part with an open or an inside-out solid is refused when the oracle is - made, by a RamError that names the part, the solid and the edge count or the volume. Inside is where `inside` + counterclockwise seen from outside: a part that is open or wound inside out is refused when the oracle is + made, by a RamError that names the part, the solid and the edge count or the turned faces and their region. A + shell may be (vertices, faces, matrix), a local mesh and the 4 by 4 that carries it to the body's rest frame: + it is read as `placed` gives it, the faces of a mirrored one (a negative scale) turned back, so a caller hands + a mirrored object's own mesh and its matrix and never a mesh it carried itself. Inside is where `inside` says, by the winding number of all the part's faces (a face of more than three corners as a fan): solids that overlap, in one mesh or several, welded or not, read inside wherever any is. The depth is to the nearest - exposed face: one whose centroid, set 1e-6 of the part's extent off the face along its normal, is not inside + exposed face: one whose centroid, set NUDGE of the part's extent off the face along its normal, is not inside the part. A face buried in another solid is not the part's surface and is left out. A face that crosses another solid is taken whole by where its centroid is: left out, the depth by it reads greater than it is; kept, a point by its buried stretch reads shallower than the part's surface is. Outside, the distance is to @@ -836,20 +906,14 @@ class Signed: self.cap, self.asked, self.vector, self.parts = cap, 0, Vector, {} for part, made in shells.items(): verts, faces, at = [], [], 0 - for v, f in made: - v = np.asarray(v, dtype=float).reshape(-1, 3) + for v, f, *matrix in made: + v, f = placed(v, f, *matrix) if matrix else (np.asarray(v, dtype=float).reshape(-1, 3), f) verts.append(v) faces += [tuple(at + int(i) for i in face) for face in f] at += len(v) verts = np.concatenate(verts) - solids(part, verts, faces) - fan = np.array([(face[0], face[k], face[k + 1]) for face in faces for k in range(1, len(face) - 1)], dtype=int) - normal = np.zeros((len(faces), 3)) - np.add.at(normal, np.repeat(np.arange(len(faces)), [len(face) - 2 for face in faces]), np.cross(verts[fan[:, 1]] - verts[fan[:, 0]], verts[fan[:, 2]] - verts[fan[:, 0]])) - size = np.linalg.norm(normal, axis=1) - flat = np.flatnonzero(size > 0.0) # a face of no area has no side to be exposed on - off = np.array([verts[list(faces[k])].mean(axis=0) for k in flat]) + 1e-6 * np.linalg.norm(np.ptp(verts, axis=0)) * normal[flat] / size[flat, None] - exposed = [faces[k] for k in flat[~inside(verts, fan, off)]] + _, fan, flat, before = _read(part, verts, faces) + exposed = [faces[k] for k in flat[before < 0.5]] if not exposed: raise RamError("mesh", "signed", f"part {part!r} has no exposed face") self.parts[part] = (BVHTree.FromPolygons(verts.tolist(), faces, epsilon=0.0), BVHTree.FromPolygons(verts.tolist(), exposed, epsilon=0.0), verts, fan) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 1f974ed..91669fe 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1039,20 +1039,56 @@ inside them, 13 inside two bars): each reads inside, as does the overlap of two staircase prism a line crosses six times. `Signed` checks what the winding number needs before it answers, and refuses a part by its reason when the oracle is -made (`ram.solids`, a `RamError` at gate `signed`). A part's faces fall into solids, the faces joined across an -edge. Every solid is closed: each edge one face runs is run the other way by another, and a solid with an edge -that is not (a boundary edge, or two faces wound against each other) is refused with the count of such edges. Every -solid is wound counterclockwise seen from outside: one of negative volume is refused with its number, its first -face and its volume, a turned-over bar beside a whole cube included, whose volume in all is positive. Nothing is -repaired or guessed. The shipped plates are four closed solids of 84 faces each, and the 12 parts of both R-3 knees -pass. What it gives up: a part exported open is capped before it is given, a part mirrored by a negative scale has -its faces turned back, and a cavity cut as its own inward shell is refused with the inside-out solids. +made (`ram.solids`, a `RamError` at gate `signed`). Nothing is repaired or guessed. The checks read the mesh as the +winding number does, by where its faces are and not by how its vertices are numbered. + +Open. Vertices within `WELD` (3e-4) of the part's extent of one another along every axis are one vertex +(`ram.weld`), so a seam of coincident vertices is no hole. A part's faces fall into solids, the faces joined across +an edge, and every solid is closed: each edge one face runs is run the other way by another. A solid with an edge +that is not (a boundary edge, or two faces wound against each other) is refused with the count of such edges. + +Inside out. Each face is read `NUDGE` (1e-6) of the extent before its centroid, along its normal. Before a face of +a whole solid the number is 0, or more where another solid covers it. A face is turned where the number there is +under -0.5: it stands before a region that winds -1. That region is measured, each turned face's area by how far out +along its normal the number stays under -0.5, and a part whose region holds `THIN` (1.1e-4) of its extent cubed or +more is refused with the count of turned faces, the first, its solid, the number and the share. A turned-over bar is +refused beside a whole cube and welded to one, where the volume in all is positive. A hollow mass, its cavity an +inward shell, has the cavity before those faces, which winds 0, and passes; so does a sliver of two sheets back to +back. + +Mirrored. A shell may be `(vertices, faces, matrix)`: the object's own mesh and the 4 by 4 that carries it to the +body's rest frame. `ram.placed` carries the vertices and turns each face back where the matrix mirrors, so a part +mirrored by a negative scale reads as its own mesh does. A caller that carries a mirrored mesh itself and keeps the +winding hands over a part wound inside out. + +The bounds stand on real meshes, and the unit suite holds them there (`tests.test_ram.Corpus`). Every part the kits +build passes at the corners of its params (316 here; 3,224 over the kits of ten other trees). Of the 1,832 mesh objects the +mech experiments make (r3, mcr3, seraph, spectre, walker, chimera, paladin, kestrel), 42 are refused and 1,790 +pass, the 115 mirrored ones the same in their own frame and placed. 21 are open: marks, recesses and plates with a +hole. 21 are wound inside out: 17 lathe and ball bodies; walker's two guns, whose turned barrel is welded into a +whole solid; and seraph's two Torso.LowerIn plates. `tests/fixtures/ram_meshes.npz` holds those 21 and the parts +nearest each bound. + +| bound | nearest below | nearest above | +| --- | --- | --- | +| `WELD` 3e-4 | a plate's seam closes at 3.7e-5 (seraph Torso.SideBlockR; thirteen more from 7.8e-8 up) | a real hole closes at 2.2e-3 (seraph PauldronR.Outer) | +| `THIN` 1.1e-4 | 6.7e-5 held and let be (chimera CannonBody.gunmetal, 178 turned faces at a bevel's crossings) | 1.88e-4 held and refused (seraph Torso.LowerInL) | +| `NUDGE` 1e-6 | a turned cube's faces are held to 1e-8 and four are lost at 1e-9 | plates 1e-5 apart read as one at 1e-4 | + +What it gives up. A part exported open is capped before it is given. Two sheets nearer than `WELD` are one seam to +the open check, and a hole that narrow is not seen. A region winding -1 that holds under `THIN` is let be: 198 of the +1,790 passing mech parts have one, the crossing of a bevel or of a lathe's profile, and there the part reads outside +in what its author took for inside (the phalanges' 10 of 82 faces, 3e-6 to 3e-5 held). What a region holds is +measured along its faces' normals, not counted: by 60,000 sampled points the region is 2.4e-4 of the extent cubed in +Torso.LowerInL, 2.7e-4 in walker's gun (2.2e-3 held), 1.7e-3 in the Ankle root (1.4e-3 held) and 1.2e-5 in +CannonBody. A solid turned over inside a whole one is a cavity to the winding number and reads so, whatever its +author meant. With every solid closed the number is whole, so `ram.inside` reads the same at any bound over 0 and up to 1; 0.5 is pinned in the unit suite on a test-only open cube, where the number is 0.527 under the hole and 0.473 over it. Outside, the distance is to the nearest face of all. Inside, the depth is to the nearest exposed face: one whose -centroid, set 1e-6 of the part's extent off the face along its normal, is not inside the part. A face buried in +centroid, set `NUDGE` of the part's extent off the face along its normal, is not inside the part. A face buried in another of the part's solids is left out, so a pin sunk 0.056 into a slab with a thin sheet buried along it reads 0.056 and is refused by a zone of depth 0.01. A face that crosses another solid is kept or left whole by where its centroid is, not split: left out, the depth by it reads greater than it is, which the gate takes as a refusal; @@ -1079,7 +1115,8 @@ worlds 34.5 and 38.5 s (two runs) on a quiet machine. With the angles in double 47.9 s (three runs). The live result reports the search's seconds as a reading and no check holds it: beside other agents' Blenders at full load the same search took 61 to 94 s. With the refusals and the exposed faces found as each of its 22 worlds is made it took 66.8 s, run after 59.3 s for the oracle before -them under that load (one pair); finding the solids of a 336-face part takes 1.6 ms. +them under that load (one pair). With the vertices welded and every face read before its centroid it took 45 to 81 s +under such load (five runs), and reading a 336-face part takes 27 to 37 ms. ## The actions diff --git a/surfaces/blender/tests/fixtures/ram_meshes.npz b/surfaces/blender/tests/fixtures/ram_meshes.npz new file mode 100644 index 0000000000000000000000000000000000000000..f5a339e8337d0f762e4831a25b6eafa7801b574a GIT binary patch literal 273401 zcmY&<3tWr+`~O48ISEOJNl2n0N@|;g9>UN=C=F4lWJRZ~-AF1Orb4JT6%uNQ4yvtm z(s82mY1OJ#tJcov`~Kf~p6~DV`tS9sZTI2x`P|p%y584yy{~J>oiyfb{p+v4=EHx+ zeA9EJXS&Hrn~U;chU0TwrIhRphF*{*z4#J#q$Z5hm&A;5TEeaR z1*I@n?6Y$^`)Ehv;NN;L)5Uf_;o&4DBqsGapgaN;8e$OMiKM8Q#G=(I=0s zkN2UW> zH&Ys9$>#)myFy-luWAH=Vqi~oX7zK|7)NZ+S7`dJ2%#?Zt+?VnJQ%|$4BSfja{W{y zvwNA5uMK-B|85BvBNKiN{tTYn`| ztd@913P>8?4cYG)6~Y)NiHHzrzlpb+spldGMbc*w&`J943}5c;#C~l@|KS+x75g5{ zyo%n=#7^2IPXD7a7M|Y+)+s+hmC&H04|E|YwBtdkDVkBZo{9fQ zzVyCrl%E@>?_5v88(9>wF8H22fGMQ53RL^#UxmoANYyPdX-j8?oW{S@gZwPV@glEm zP+?s9w%dK7@`nUNA3hp6H?z&qZ!w;3!n>2W6kK{q2P2=pPadUSR`6Q(67Y{t8TW#+ z)HXLVsA|OaTyQ|I#Catnd$53UYrV#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ll)%^_zpTxCAR5EeK)!wTzZhOo%ldzug%h#~CoVD_Fy>GU*1Smf+I%_o5T*@m#d zmu1^su%J?j;4`yQ73`)N!Xg)^cEl6GAh2k!z;A6x1xQb2*daok(=Bd3X!vUV-?M8v zAuu_Zfk!^NdRhFEFDNK*keO}RVk0og5H`!SZ^vK3_cS5(0+WL^_$-S@eDw&RQr0N^ z?xpJ+1OP+WVS=_}k01wBCN#yJS)tP3ry0T`H;#Q3&j!>QSO4y%C%UE>!UAV!cyx4{ zAuN))zG8_xh=)tSO*r#DqyeO-3hbCh=kSvvd%)27Up>wJ@hOJz$a9LhR9ApX`d3f0 zlR3!{9ymM0Hr5nFc;v6oU}iG(Whi_fIi|1@d9j6X6+7T%TqLi{x$?ejx!mj8nj8W_oGX4TvG^FyURkoQVT) zm$QK7Ooj`BrWwK_dp?lD)`5HQE68i6mnH+`&o+bwLOTsYy9oZRDJ*byhJTGtGlWG#;;&bA09b7Ll>brKid!<2+3ZYVB4@#c$y(> zVP|hc-+2&2*kQu#48=sI8NwoGXZRc-e|RZ;me2|hVRJk4-2OCb>b`1o#s|F(lQ Lr4(?UkMF+$=QvlF literal 0 HcmV?d00001 diff --git a/surfaces/blender/tests/live/ram_knee.py b/surfaces/blender/tests/live/ram_knee.py index d503e2c..a8d31b9 100644 --- a/surfaces/blender/tests/live/ram_knee.py +++ b/surfaces/blender/tests/live/ram_knee.py @@ -12,8 +12,9 @@ without them). is an absolute path; writes .result.json and .r3_ The oracle is ram.Signed: a point is inside a part where the winding number of the part's faces about it is 0.5 or more. tests/fixtures/ram_plates.json holds the rocker plates as Imagination's jointlib builds them, four closed bars joined into one mesh, a side's two overlapping, and 29 points inside them: none reads outside. Nor does a point where -two welded boxes overlap. A part that is open or wound inside out is refused when the oracle is made, and the depth -is to the part's surface: a face buried in another of the part's solids is not read. +two welded boxes overlap. A part that is open or wound inside out is refused when the oracle is made, a hollow mass +and a part mirrored by its matrix are read, and the depth is to the part's surface: a face buried in another of the +part's solids is not read, and outside the distance is to the nearest face of all. A clearance verdict is a sign, the gate's own. FLAT follows lodur:ruling:deterministic-bound-margin. The checks run inside one try: an uncaught error is a failed check that names its section, and the result file is always written. @@ -344,22 +345,62 @@ try: [int((plates >= 0).sum()), int(both.sum()), int((got != truth).sum())]) # a part with no inside to sign is refused when the oracle is made, by its reason: a cube with its top off, or - # two adjacent faces off, is open; a cube turned over, mirrored, or a turned-over bar beside a whole cube (a - # positive volume in all) is wound inside out. Every part of both knees made here passed the same two checks + # two adjacent faces off, is open; a cube turned over, mirrored with its winding kept, or a turned-over bar beside + # a whole cube or welded to one along an edge (a positive volume in all) is wound inside out. What has an inside + # is read: a mirrored cube handed as its own mesh and its matrix, and a hollow mass, its cavity an inward shell + def one(*meshes): + at, faces = {}, [] + for v, f in meshes: + index = [at.setdefault(tuple(float(x) for x in q), len(at)) for q in v] + faces += [tuple(index[i] for i in face) for face in f] + return np.array(list(at)), faces + turned = [face[::-1] for face in f1] + rail = wound((1, 0, -0.2), (1.2, 1, 0)) said = {} for name, made in (("top off", [(v1, [face for face in f1 if face != (1, 5, 7, 3)])]), ("two faces off", [(v1, [face for face in f1 if face not in ((1, 5, 7, 3), (2, 3, 7, 6))])]), - ("turned over", [(v1, turned)]), ("mirrored", [(v1 * (-1, 1, 1), f1)]), ("a turned-over bar beside a cube", [(v1, f1), (v2 + (0, 2, 0), [face[::-1] for face in f2])])): + ("turned over", [(v1, turned)]), ("mirrored", [(v1 * (-1, 1, 1), f1)]), ("a turned-over bar beside a cube", [(v1, f1), (v2 + (0, 2, 0), [face[::-1] for face in f2])]), + ("a turned-over bar welded to a cube", [one((v1, f1), (rail[0], [face[::-1] for face in rail[1]]))])): try: Signed({"cube": made}) said[name] = None except R.RamError as error: said[name] = str(error) RES["refusals"] = said - want = {"top off": "is open: solid 0 of 1 has 4 edges", "two faces off": "is open: solid 0 of 1 has 6 edges", "turned over": "is wound inside out: solid 0 of 1 (6 faces from face 0) has volume -1", - "mirrored": "is wound inside out: solid 0 of 1 (6 faces from face 0) has volume -1", "a turned-over bar beside a cube": "is wound inside out: solid 1 of 2 (6 faces from face 6) has volume -0.5"} - check("no-inside-is-refused: an open part is refused by its solid and edge count, an inside-out one by its solid and volume, a turned-over bar beside a whole cube included", - all(said[name] is not None and "part 'cube' " + text in said[name] for name, text in want.items()), said) + want = {"top off": "is open: solid 0 of 1 has 4 edges", "two faces off": "is open: solid 0 of 1 has 6 edges", "turned over": "is wound inside out: 6 faces, from face 0 of solid 0 of 1, stand before a region that winds -1", + "mirrored": "is wound inside out: 6 faces, from face 0 of solid 0 of 1, stand before a region that winds -1", "a turned-over bar beside a cube": "is wound inside out: 6 faces, from face 6 of solid 1 of 2, stand before a region that winds -1", + "a turned-over bar welded to a cube": "is wound inside out: 6 faces, from face 6 of solid 0 of 1, stand before a region that winds -1"} + check("no-inside-is-refused: an open part is refused by its solid and edge count, an inside-out one by its turned faces and their region, a turned-over bar beside a whole cube or welded to it included", + len(one((v1, f1), rail)[0]) == 14 and all(said[name] is not None and "part 'cube' " + text in said[name] for name, text in want.items()), said) + hollow = [wound((-1, -1, -1), (1, 1, 1)), (lambda v, f: (v, [face[::-1] for face in f]))(*wound((0.4, 0.4, 0.4), (0.6, 0.6, 0.6)))] + at = np.array([(0.5, 0.5, 0.5), (0.0, 0.0, 0.0), (0.5, 0.5, 0.95), (1.2, 0.0, 0.0)]) + left = np.array([(-0.5, 0.5, 0.5), (0.5, 0.5, 0.5), (-0.5, 0.5, 0.9)]) + cavity, mirrored = Signed({"p": hollow})("p", at), Signed({"p": [(v1, f1, np.diag((-1.0, 1.0, 1.0, 1.0)))]})("p", left) + RES["readings"]["hollow mass: in the cavity, in the wall by it, under the outer face, outside"] = cavity.tolist() + RES["readings"]["mirrored cube by its matrix: inside, across the mirror, under its top"] = mirrored.tolist() + check("an-inside-is-read: a cavity reads outside and the wall about it by its depth to the cavity; a cube mirrored by its matrix reads as the cube it is", + float(np.abs(cavity - (0.1, -0.4 * math.sqrt(3.0), -0.05, 0.2)).max()) < FLAT and float(np.abs(mirrored - (-0.5, 0.5, -0.1)).max()) < FLAT, [cavity.tolist(), mirrored.tolist()]) + + # the exposed faces, where a reading turns on them. Outside, the distance is to the nearest face of all: a slab + # with a boss through its middle has its two great faces left out (their centroids are in the boss), and points + # off them read 0.05 and 0.02, not the 0.206 and 0.4 to the nearest exposed face. Two plates stacked 1e-5 of the + # extent apart are two surfaces: under the lower one's top the depth is 0.02, where a nudge of 1e-4 reads that + # face buried in the upper plate and the depth 0.08 to the bottom. A cube turned 0.3, 0.5 and 0.7 radians about + # x, y and z has no face along an axis: its six sides are held at 1e-6 and to 1e-8 (the corners' offsets are + # single precision), and at 1e-9 four read buried + slab = [wound((-1, -1, -0.1), (1, 1, 0.1)), wound((-0.2, -0.2, -0.5), (0.2, 0.2, 0.5))] + off = Signed({"p": slab})("p", np.array([(0.8, 0.0, 0.15), (0.6, 0.6, 0.12), (0.0, 0.0, 0.7), (0.5, 0.0, -0.3)])) + gap = 1e-5 * math.sqrt(2.0 + 0.2 ** 2) + stacked = Signed({"p": [wound((0, 0, 0), (1, 1, 0.1)), wound((0, 0, 0.1 + gap), (1, 1, 0.2 + gap))]})("p", np.array([(0.5, 0.5, 0.08), (0.5, 0.5, 0.12 + gap), (0.5, 0.5, 0.1 + 0.5 * gap)])) + (ca, sa), (cb, sb), (cc, sc) = ((math.cos(t), math.sin(t)) for t in (0.3, 0.5, 0.7)) + spin = np.array([[1, 0, 0], [0, ca, -sa], [0, sa, ca]]) @ np.array([[cb, 0, sb], [0, 1, 0], [-sb, 0, cb]]) @ np.array([[cc, -sc, 0], [sc, cc, 0], [0, 0, 1]]) + under = 0.9 * np.array([(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)], float) + spun = Signed({"p": [(cube_v @ spin.T, cube_f) for cube_v, cube_f in [wound((-1, -1, -1), (1, 1, 1))]]})("p", under @ spin.T) + RES["readings"]["slab with a boss through it: off its faces (0.05, 0.02), off the boss's end (0.2), under it (0.2)"] = off.tolist() + RES["readings"]["plates stacked 1e-5 of the extent apart: under the lower's top (0.02), over the upper's bottom (0.02), between them"] = stacked.tolist() + RES["readings"]["a turned cube: 0.1 under each face"] = spun.tolist() + check("exposed-faces-are-read-where-they-are: outside is to the nearest face of all, plates 1e-5 of the extent apart are two surfaces, and a turned cube's six faces are all its surface", + float(np.abs(off - (0.05, 0.02, 0.2, 0.2)).max()) < FLAT and float(np.abs(stacked - (-0.02, -0.02, 0.5 * gap)).max()) < FLAT and float(np.abs(spun + 0.1).max()) < FLAT, [off.tolist(), stacked.tolist(), spun.tolist()]) # the depth is to the part's surface, not to a face buried in another of its solids: a cube of half side 1 with a # box of side 0.2 buried about (0.5, 0.5, 0.5) reads its own depth by the box and at its centre (the nearest face diff --git a/surfaces/blender/tests/live/ram_knee.result.json b/surfaces/blender/tests/live/ram_knee.result.json index 6935ca7..5c63306 100644 --- a/surfaces/blender/tests/live/ram_knee.result.json +++ b/surfaces/blender/tests/live/ram_knee.result.json @@ -22,7 +22,17 @@ "detail": null }, { - "name": "no-inside-is-refused: an open part is refused by its solid and edge count, an inside-out one by its solid and volume, a turned-over bar beside a whole cube included", + "name": "no-inside-is-refused: an open part is refused by its solid and edge count, an inside-out one by its turned faces and their region, a turned-over bar beside a whole cube or welded to it included", + "ok": true, + "detail": null + }, + { + "name": "an-inside-is-read: a cavity reads outside and the wall about it by its depth to the cavity; a cube mirrored by its matrix reads as the cube it is", + "ok": true, + "detail": null + }, + { + "name": "exposed-faces-are-read-where-they-are: outside is to the nearest face of all, plates 1e-5 of the extent apart are two surfaces, and a turned cube's six faces are all its surface", "ok": true, "detail": null }, @@ -114,11 +124,19 @@ ], "readings": { "FLAT": 8.34e-09, + "a turned cube: 0.1 under each face": [ + -0.09999994188547134, + -0.09999997913837433, + -0.09999998658895493, + -0.09999998658895493, + -0.10000001639127731, + -0.10000001639127731 + ], "bell crank: least margin of a pair with no zone, 251 steps uncapped": 0.0336, "bell crank: least margin of a zoned pair, 251 steps uncapped": 0.000118, "bell crank: pairs": 60, "bell crank: pairs refused with nothing let": 19, - "bell crank: seconds, 49 steps capped": 1.34, + "bell crank: seconds, 49 steps capped": 1.52, "bell crank: zoned pairs": 20, "boss through a wall (faces that cross a solid are kept or left whole): in both (the surface is 0.502 off), in the wall (0.583), in the boss (0.2), off it (0.1)": [ -0.5, @@ -134,24 +152,47 @@ 0.20000004768371582 ], "four bar: barrel inside the shin's clearance": -0.122, + "hollow mass: in the cavity, in the wall by it, under the outer face, outside": [ + 0.09999999403953552, + -0.6928203105926514, + -0.050000011920928955, + 0.20000004768371582 + ], "jointlib plates: inside points read outside, of 29": 0, + "mirrored cube by its matrix: inside, across the mirror, under its top": [ + -0.5, + 0.5, + -0.10000002384185791 + ], "moved x: both": -0.0543, "moved x: the coupler at x 0.25, inside the horn's 0.23..0.31": -0.02, "moved x: the rocker at x 0.25, inside the bracket's 0.13..0.35": -0.0543, + "plates stacked 1e-5 of the extent apart: under the lower's top (0.02), over the upper's bottom (0.02), between them": [ + -0.020000003278255463, + -0.019999995827674866, + 7.137656211853027e-06 + ], "search: candidates": 13824, "search: pass the gates before clearance": 78, "search: refused on their own parts": 21, - "search: seconds": 66.8, + "search: seconds": 73.9, "search: worlds built": 22, + "slab with a boss through it: off its faces (0.05, 0.02), off the boss's end (0.2), under it (0.2)": [ + 0.05000000447034836, + 0.019999995827674866, + 0.19999998807907104, + 0.20000001788139343 + ], "the base clevis's foot inside the thigh": -0.01, "welded boxes: points missigned, of 6000 (91 in the overlap)": 0 }, "refusals": { "top off": "mesh ram: signed: part 'cube' is open: solid 0 of 1 has 4 edges no face runs the other way", "two faces off": "mesh ram: signed: part 'cube' is open: solid 0 of 1 has 6 edges no face runs the other way", - "turned over": "mesh ram: signed: part 'cube' is wound inside out: solid 0 of 1 (6 faces from face 0) has volume -1", - "mirrored": "mesh ram: signed: part 'cube' is wound inside out: solid 0 of 1 (6 faces from face 0) has volume -1", - "a turned-over bar beside a cube": "mesh ram: signed: part 'cube' is wound inside out: solid 1 of 2 (6 faces from face 6) has volume -0.5" + "turned over": "mesh ram: signed: part 'cube' is wound inside out: 6 faces, from face 0 of solid 0 of 1, stand before a region that winds -1.01 and holds 1.12 of the part's extent cubed", + "mirrored": "mesh ram: signed: part 'cube' is wound inside out: 6 faces, from face 0 of solid 0 of 1, stand before a region that winds -1.01 and holds 1.12 of the part's extent cubed", + "a turned-over bar beside a cube": "mesh ram: signed: part 'cube' is wound inside out: 6 faces, from face 6 of solid 1 of 2, stand before a region that winds -1 and holds 0.0605 of the part's extent cubed", + "a turned-over bar welded to a cube": "mesh ram: signed: part 'cube' is wound inside out: 6 faces, from face 6 of solid 0 of 1, stand before a region that winds -1 and holds 0.0271 of the part's extent cubed" }, "zones": { "barrel[0] | parent.seat": { @@ -525,9 +566,9 @@ } }, "renders": [ - "F:/aeth-wt/fable-ramlows/scratch/out/live_h4b.r3_0.png", - "F:/aeth-wt/fable-ramlows/scratch/out/live_h4b.r3_62p5.png", - "F:/aeth-wt/fable-ramlows/scratch/out/live_h4b.r3_125.png" + "F:/aeth-wt/fable-ramlows/scratch/h5/out/live_shipped2/knee.r3_0.png", + "F:/aeth-wt/fable-ramlows/scratch/h5/out/live_shipped2/knee.r3_62p5.png", + "F:/aeth-wt/fable-ramlows/scratch/h5/out/live_shipped2/knee.r3_125.png" ], "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py index 3cb02f5..6bf64bc 100644 --- a/surfaces/blender/tests/test_ram.py +++ b/surfaces/blender/tests/test_ram.py @@ -543,6 +543,10 @@ WHOLE = 3.8e-4 # a winding number against the count or share a hand val SPAN_RAM = 0.848 # the ram's span with its base 0.1 from the rocker's pivot: shipped 0.5390 (about that pivot), the span about the knee's pivot 1.3347, separation 1.57 each side +SMALL = (0.05, 0.06) # the sides of a turned-over cube beside a unit cube that hold 7.5e-5 and 1.9e-4 of the extent cubed: THIN, 1.1e-4, is 1.5 and 1.7 from them +KIT_VARIANTS = 316 # kit parts built over the corners of their params + + @unittest.skipIf(np is None, "numpy is not installed") class DeepKnee(unittest.TestCase): """The R-3 knee over 0..-125 (probes P1 to P3).""" @@ -1392,21 +1396,96 @@ class Refusals(unittest.TestCase): self.assertEqual(caught.exception.gate, "signed", name) self.assertIn(f"part 'cube' is open: {solid} has {count} edges no face runs the other way", str(caught.exception), name) - def test_an_inside_out_solid_is_refused_by_name(self): - # a cube with every face turned over, or mirrored with its winding kept, has volume -1. A cube with a bar - # of half its volume turned over beside it has a positive volume in all: the bar is refused as its solid + def test_a_seam_of_coincident_vertices_is_no_hole(self): + # a cube whose every triangle has its own three vertices is closed to the eye and to the winding number, and + # is one solid. Its top stood off by a third of WELD of the extent is a seam and closes; by 3.4 times WELD + # (past the two cells' width, where no grid joins them) it is a hole of 4 edges on the box and 4 on the lid + verts, tris = block((0, 0, 0), (1, 1, 1)) + soup = verts[tris].reshape(-1, 3) + self.assertEqual(R.solids("soup", soup, np.arange(36).reshape(-1, 3)).tolist(), [0] * 12) + top = np.flatnonzero((verts[tris][:, :, 2] == 1.0).all(axis=1)) + for gap, closes in ((R.WELD / 3.0, True), (R.WELD * 3.4, False)): + lifted = soup.copy() + lifted[(3 * top[:, None] + np.arange(3)).ravel(), 2] += gap * math.sqrt(3.0) + if closes: + self.assertEqual(R.solids("lid", lifted, np.arange(36).reshape(-1, 3)).tolist(), [0] * 12) + else: + with self.assertRaises(R.RamError) as caught: + R.solids("lid", lifted, np.arange(36).reshape(-1, 3)) + self.assertIn("part 'lid' is open: solid 0 of 2 has 4 edges no face runs the other way", str(caught.exception)) + # weld alone: the nearest are one, a chain is one, and nothing is joined at no tolerance + row = np.array([(0, 0, 0), (0.5, 0, 0), (9, 0, 0), (9, 0.9, 0), (9, 1.8, 0), (20, 0, 0)], float) * 1e-3 + self.assertEqual(R.weld(row, 1e-3).tolist(), [0, 0, 2, 2, 2, 5]) + self.assertEqual(R.weld(row, 0.0).tolist(), [0, 1, 2, 3, 4, 5]) + + def test_an_inside_out_solid_is_refused_by_its_region(self): + # a cube with every face turned over, or mirrored with its winding kept, winds -1 inside: every face stands + # before that region verts, tris = block((0, 0, 0), (1, 1, 1)) for name, v, t in (("turned over", verts, tris[:, ::-1]), ("mirrored", verts * (-1, 1, 1), tris)): with self.assertRaises(R.RamError, msg=name) as caught: R.solids("cube", v, t) - self.assertIn("part 'cube' is wound inside out: solid 0 of 1 (12 faces from face 0) has volume -1", str(caught.exception), name) - bar_v, bar_t = block((2, 0, 0), (3, 1, 0.5)) - mixed = joined((verts, tris), (bar_v, bar_t[:, ::-1]), False) - self.assertAlmostEqual(sum(float(mixed[0][a] @ np.cross(mixed[0][b], mixed[0][c])) / 6.0 for a, b, c in mixed[1]), 0.5, places=12) + self.assertEqual(caught.exception.gate, "signed", name) + self.assertIn("part 'cube' is wound inside out: 12 faces, from face 0 of solid 0 of 1, stand before a region that winds -1 and holds ", str(caught.exception), name) + # a bar turned over is refused beside the cube, welded to it along an edge and welded to it on a face (there + # the volume of the one solid is positive: 0.96 and 0.8), and the same bars wound outward pass. On the face + # the cube's own face lies on the bar's and stands before the bar with it: 14 faces, the cube's two first + for name, bar, weld, said in (("beside", block((2, 0, 0), (3, 1, 0.5)), False, "12 faces, from face 12 of solid 1 of 2"), ("on an edge", block((1, 0, -0.2), (1.2, 1, 0)), True, "12 faces, from face 12 of solid 0 of 1"), + ("on a face", block((1, 0, 0), (1.2, 1, 1)), True, "14 faces, from face 2 of solid 0 of 1")): + with self.assertRaises(R.RamError, msg=name) as caught: + R.solids("pair", *joined((verts, tris), (bar[0], bar[1][:, ::-1]), weld)) + self.assertIn(f"part 'pair' is wound inside out: {said}, stand before a region that winds -1 and holds ", str(caught.exception), name) + self.assertEqual(len(R.solids("pair", *joined((verts, tris), bar, weld))), 24, name) + + def test_a_cavity_and_a_sliver_are_not_turned_over(self): + # a cube of half side 1 with a cube of half side 0.5 turned over in it is a hollow mass: the winding number + # is 0 in the cavity, 1 in the wall and 0 outside, before every face of the inner shell is the cavity, and + # the part passes as two solids + hollow = joined(block((-1, -1, -1), (1, 1, 1)), (lambda v, t: (v, t[:, ::-1]))(*block((-0.5, -0.5, -0.5), (0.5, 0.5, 0.5))), False) + self.assertEqual(R.solids("hollow", *hollow).tolist(), [0] * 12 + [1] * 12) + self.assertLess(float(np.abs(R.winding(*hollow, [(0, 0, 0), (0.75, 0, 0), (0, 0.75, 0.75), (1.5, 0, 0)]) - (0, 1, 1, 0)).max()), WHOLE) + # a sliver is two sheets back to back, a closed solid of no volume: before either sheet is the outside, and + # it passes alone, beside a cube and sharing a corner of one + sheet = np.array([(0, 0, 0), (1, 0, 0), (0, 1, 0)], float), np.array([(0, 1, 2), (0, 2, 1)]) + self.assertEqual(R.solids("sliver", *sheet).tolist(), [0, 0]) + self.assertEqual(R.solids("beside", *joined(block((2, 0, 0), (3, 1, 1)), sheet, False)).tolist(), [0] * 12 + [1] * 2) + self.assertEqual(R.solids("welded", *joined(block((-1, -1, -1), (0, 0, 0)), sheet, True)).tolist(), [0] * 12 + [1] * 2) + + def test_a_turned_region_is_read_by_what_it_holds(self): + # THIN, by a cube of side s turned over beside a unit cube (extent about 1.4 + s): its six faces stand before + # a region measured by the rungs their normals reach. Side 0.05 holds 7.5e-5 and passes; side 0.06 holds 1.9e-4 + # and is refused. So a bound of 7.5e-5 or of 1.9e-4 is seen, as near THIN as the mech parts either side of it + verts, tris = block((0, 0, 0), (1, 1, 1)) + small = lambda s: joined((verts, tris), (lambda v, t: (v, t[:, ::-1]))(*block((1.2, 0, 0), (1.2 + s, s, s))), False) + self.assertEqual(len(R.solids("small", *small(SMALL[0]))), 24) with self.assertRaises(R.RamError) as caught: - R.solids("pair", *mixed) - self.assertIn("part 'pair' is wound inside out: solid 1 of 2 (12 faces from face 12) has volume -0.5", str(caught.exception)) - self.assertEqual(R.solids("pair", *joined((bar_v, bar_t), (verts, tris), False)).tolist(), [0] * 12 + [1] * 12) + R.solids("small", *small(SMALL[1])) + self.assertIn("part 'small' is wound inside out: 12 faces, from face 12 of solid 1 of 2, stand before a region that winds -1 and holds ", str(caught.exception)) + held = float(str(caught.exception).split("holds ")[1].split(" of")[0]) + self.assertTrue(1.8e-4 < held < 2.0e-4, held) + # the nudge, from below: a cube turned over and turned 0.3, 0.5 and 0.7 radians about x, y and z has no face + # along an axis. Its sides are held at 1e-6 of the extent and to 1e-8; at 1e-9 they are not and it would pass + (ca, sa), (cb, sb), (cc, sc) = ((math.cos(t), math.sin(t)) for t in (0.3, 0.5, 0.7)) + spin = np.array([[1, 0, 0], [0, ca, -sa], [0, sa, ca]]) @ np.array([[cb, 0, sb], [0, 1, 0], [-sb, 0, cb]]) @ np.array([[cc, -sc, 0], [sc, cc, 0], [0, 0, 1]]) + with self.assertRaises(R.RamError): + R.solids("spun", (verts - 0.5) @ spin.T, tris[:, ::-1]) + + def test_a_mirrored_mesh_is_placed_turned_back(self): + # a part mirrored by a negative scale is wound as its own mesh is: placed by its matrix the faces are turned + # back and it passes; carried with its winding kept it is the mirrored cube above. A matrix that does not + # mirror keeps every face, and the vertices are carried either way + verts, tris = block((0, 0, 0), (1, 1, 1)) + faces = [tuple(int(i) for i in t) for t in tris] + mirror, shift = np.diag((-1.0, 1.0, 1.0, 1.0)), np.eye(4) + mirror[:3, 3] = shift[:3, 3] = (3.0, 0.0, 0.5) + v, f = R.placed(verts, faces, mirror) + self.assertEqual(np.abs(v - (verts * (-1, 1, 1) + (3.0, 0.0, 0.5))).max(), 0.0) + self.assertEqual(f, [face[::-1] for face in faces]) + self.assertEqual(R.solids("left", v, f).tolist(), [0] * 12) + with self.assertRaises(R.RamError): + R.solids("left", v, faces) + v, f = R.placed(verts, faces, shift) + self.assertEqual((np.abs(v - (verts + (3.0, 0.0, 0.5))).max(), f), (0.0, faces)) def test_no_blender(self): source = (SURFACE / "brokkr_kitbash" / "ram.py").read_text(encoding="utf-8") @@ -1417,5 +1496,67 @@ class Refusals(unittest.TestCase): self.assertEqual(source.count("\nclass Signed:"), 1) +@unittest.skipIf(np is None, "numpy is not installed") +class Corpus(unittest.TestCase): + """The refusals against meshes nobody made for them: every part the kits build, and a sample of the 1,832 mesh + objects the mech experiments make (r3, mcr3, seraph, spectre, walker, chimera, paladin, kestrel, as Blender + evaluates them, each in its own frame with its world matrix). Of the 1,832, solids refuses 42: 21 open (marks, + recesses, plates with a hole) and 21 wound inside out (17 lathe and ball bodies; walker's two guns, whose + turned barrel is welded into a whole solid; seraph's two Torso.LowerIn plates). The sample is those 21, the + open and the passing parts nearest each bound, and three mirrored parts. + + WELD 3e-4 seams close up to 3.7e-5 of the extent (seraph Torso.SideBlockR; r3 Prow.Upper 2.3e-6, chimera + Pauldron.Band 4.1e-7); the least hole closes at 2.2e-3 (seraph PauldronR.Outer): 8 and 7 apart + THIN 1.1e-4 the least region refused holds 1.88e-4 (seraph Torso.LowerInL; by 60,000 sampled points 2.4e-4 + of its extent cubed winds -1, as 2.7e-4 of walker's gun does); the greatest let be holds 6.7e-5 + (chimera CannonBody.gunmetal, 178 faces at a bevel's crossings, 1.2e-5 sampled): 1.68 each side""" + + def test_every_kit_part_is_accepted(self): + # every part of every kit, at its defaults, all params at min, all at max, and each param at min and at max + spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_ram", SURFACE / "brokkr_kitbash" / "core.py") + core = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = core + spec.loader.exec_module(core) + built, refused = 0, [] + for name in core.kit_names(): + for part_name, part in core.load_kit(name)["parts"].items(): + params = part["params"] + variants = {"default": {}, "min": {p["name"]: p["min"] for p in params}, "max": {p["name"]: p["max"] for p in params}} + for p in params: + variants.update({p["name"] + " min": {p["name"]: p["min"]}, p["name"] + " max": {p["name"]: p["max"]}}) + for variant, given in variants.items(): + try: + made = core.build(part, given) + except core.KitError: + continue # a corner of the params the kit itself refuses + ends = np.cumsum(made.counts) + built += 1 + try: + R.solids(f"{name}.{part_name}", made.V, [tuple(int(i) for i in made.faces[a:b]) for a, b in zip(ends - made.counts, ends)]) + except R.RamError as error: + refused.append((name, part_name, variant, str(error))) + self.assertEqual(refused, []) + self.assertEqual(built, KIT_VARIANTS) + + def test_the_mech_sample_reads_as_recorded(self): + # each mesh in its own frame, and placed by its world matrix (three are mirrored and pass both ways; r3's + # Hand.palm is mirrored and inside out both ways) + sample = np.load(SURFACE / "tests" / "fixtures" / "ram_meshes.npz") + rows = json.loads(str(sample["rows"])) + got = {} + for n, row in enumerate(rows): + ends = np.cumsum(sample[f"counts{n}"]) + faces = [tuple(int(i) for i in sample[f"loops{n}"][a:b]) for a, b in zip(ends - sample[f"counts{n}"], ends)] + for frame, mesh in (("own", (sample[f"v{n}"], faces)), ("placed", R.placed(sample[f"v{n}"], faces, sample[f"matrix{n}"]))): + try: + R.solids(row["name"], *mesh) + got[row["name"], frame] = "pass" + except R.RamError as error: + got[row["name"], frame] = "open" if " is open: " in str(error) else "inside out" if " is wound inside out: " in str(error) else str(error) + self.assertEqual(got, {(row["name"], frame): row["reads"] for row in rows for frame in ("own", "placed")}) + reads = [row["reads"] for row in rows] + self.assertEqual((reads.count("inside out"), reads.count("open"), reads.count("pass"), sum(row["mirrored"] for row in rows)), (21, 3, 9, 7)) + + if __name__ == "__main__": unittest.main() From 2ffb3b6460c5ab3da161266a847697ffa0a32d66 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 08:04:53 +0100 Subject: [PATCH 182/223] brokkr_kitbash.ram: inside out is a solid's negative volume, a crossing is refused under its own name, and weld joins at the tolerance and no farther Verdict cut-kit-ram-lows.s4 and ruling ram-refuses-crossing-not-inverted. - Inside out: a solid with a turned face whose exact signed volume is negative, with a zero bound. A turned 0.2 cube by a 6 m bar and a turned plate 1e-5 thick are refused (both passed under THIN). A cavity's inward shell has no turned face and passes; a solid the weld closes up to a point or a line has no volume to read. - Crossing: turned faces where no solid's volume is negative, holding THIN or more, are refused as "crosses itself" with the region's centre and reach, never as inside out. A turned piece welded into a whole solid reads so too. - weld: one grid of the tolerance, each vertex compared with its own cell and those about it. A pair 0.99 of the tolerance apart joins and one 1.01 apart does not, at any placement (the cells of twice the tolerance joined pairs up to 2x by where they fell). - tests: the two s4 constructions; the weld pair at 100 placements; THIN pinned on a welded bar (6.75e-5 let, 1.93e-4 refused); Exposed, a stub mathutils that kills no-exposed-refusal and zero-area-kept without Blender; a cavity beside a let crossing. - tests/fixtures/ram_meshes.npz: 113 rows. The four crossing parts renamed, and ten passing parts of each mech drawn by a seeded generator: 89 pass. Over the 1,832 mech meshes: 1,790 pass, 21 open, 17 inside out, 4 crossing (walker GunL/GunR.gunmetal, seraph Torso.LowerInL/R). Kits: 3,224 of 3,224 pass, 3,540 of 3,540 with lows. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/ram.py | 88 +++++++--- surfaces/blender/docs/kitbash.md | 62 ++++--- .../blender/tests/fixtures/ram_meshes.npz | Bin 273401 -> 412714 bytes surfaces/blender/tests/test_ram.py | 162 ++++++++++++++---- 4 files changed, 235 insertions(+), 77 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/ram.py b/surfaces/blender/brokkr_kitbash/ram.py index dd250a4..22c8e10 100644 --- a/surfaces/blender/brokkr_kitbash/ram.py +++ b/surfaces/blender/brokkr_kitbash/ram.py @@ -26,6 +26,7 @@ the coupler bar at c's, the ram at a's plus each of `offsets`. swept(fit, body, ...) points of the swept ram's surface in a body's rest frame winding(vertices, triangles, points) the generalized winding number of a triangle soup about points inside(vertices, triangles, points) whether points are inside it: the number is 0.5 or more + weld(vertices, tolerance) the vertex each vertex is read as: those within the tolerance are one solids(part, vertices, faces) the closed, outward wound solids of a part, or the refusal placed(vertices, faces, matrix) a local mesh carried by a matrix, turned back where it mirrors Signed(shells, cap) the distance oracle over meshes, signed by the winding number @@ -83,9 +84,9 @@ GATES = ("assembly", "stroke", "toggle", "arm", "load", "clash") SCHEMA, VERSION = "brokkr.ram", 2 ZONE = ("part", "pin", "radius", "depth") # a zone of `touch`, as the record writes it BAND = 1e-9 # the loop is refused within this of a dead centre of the rocker and coupler -WELD = 3e-4 # of a part's extent: vertices this near along every axis are one vertex to `solids` +WELD = 3e-4 # of a part's extent: vertices no farther apart than this along every axis are one vertex to `solids` NUDGE = 1e-6 # of a part's extent: how far off a face's centroid its two sides are read -THIN = 1.1e-4 # of a part's extent cubed: a region winding -1 that holds less is not read as the part turned over +THIN = 1.1e-4 # of a part's extent cubed: a region winding -1 where no solid's volume is negative is let be when it holds less FINE = 64 # in a zone a segment between samples is halved down to spacing / FINE @@ -788,20 +789,33 @@ def inside(vertices, triangles, points): def weld(vertices, tolerance): - """The vertex each of `vertices` is read as: one index for all that stand within `tolerance` of one another - along every axis, and for a chain of such. Each is found by the cell it falls in on eight grids of twice the - tolerance, each half a cell off the last along some axes: two points that near share a cell of one.""" + """The vertex each of `vertices` is read as: one index, the least, for all that stand within `tolerance` of one + another along every axis, and for a chain of such. Two vertices are joined where no coordinate of theirs differs + by more than the tolerance, and only there, wherever the mesh stands: each vertex is compared with those of its + own cell and of the cells about it on one grid of the tolerance, and the grid only finds the pairs.""" v = np.asarray(vertices, dtype=float).reshape(-1, 3) label = np.arange(len(v)) if not len(v) or not tolerance > 0.0: return label - cells = [np.unique(np.floor(v / (2.0 * tolerance) + shift).astype(np.int64), axis=0, return_inverse=True)[1].reshape(-1) for shift in itertools.product((0.0, 0.5), repeat=3)] + cell = np.floor((v - v.min(axis=0)) / (tolerance * (1.0 + 1e-9))).astype(np.int64) # two within the tolerance are in one cell or in two that touch + about = [step for step in itertools.product((-1, 0, 1), repeat=3) if step >= (0, 0, 0)] # a cell and half the 26 about it: each pair of cells once + at = np.unique(np.concatenate([cell + step for step in about]), axis=0, return_inverse=True)[1].reshape(len(about), len(v)) + order, count = np.argsort(at[0], kind="stable"), np.bincount(at[0], minlength=int(at.max()) + 1) + start, first, second = np.cumsum(count) - count, [], [] + for there in at: + n = count[there] + i = np.repeat(label, n) + j = order[np.repeat(start[there], n) + np.arange(int(n.sum())) - np.repeat(np.cumsum(n) - n, n)] + near = (np.abs(v[i] - v[j]) <= tolerance).all(axis=1) + first.append(i[near]) + second.append(j[near]) + first, second = np.concatenate(first), np.concatenate(second) while True: - before = label - for cell in cells: - least = np.full(int(cell.max()) + 1, len(v)) - np.minimum.at(least, cell, label) - label = least[cell] + before, least = label, label.copy() + low = np.minimum(label[first], label[second]) + np.minimum.at(least, first, low) + np.minimum.at(least, second, low) + label = least[least] if (label == before).all(): return label @@ -814,7 +828,7 @@ def _read(part, vertices, faces): fan = np.array([(face[0], face[k], face[k + 1]) for face in faces for k in range(1, len(face) - 1)], dtype=int).reshape(-1, 3) extent = float(np.linalg.norm(np.ptp(v, axis=0))) if len(v) else 0.0 one = weld(v, WELD * extent) - owner, edges = list(range(len(faces))), {} + owner, edges, seam = list(range(len(faces))), {}, np.zeros(len(faces), dtype=bool) def root(k): while owner[k] != k: @@ -823,6 +837,7 @@ def _read(part, vertices, faces): for k, face in enumerate(faces): face = [int(one[i]) for i in face] + seam[k] = len(set(face)) < 3 # the weld leaves it a point or a line for i, j in zip(face, face[1:] + face[:1]): if i != j: there = edges.setdefault((min(i, j), max(i, j)), [k, 0]) @@ -845,12 +860,22 @@ def _read(part, vertices, faces): before = winding(v, fan, centre + NUDGE * extent * normal[flat] / size[flat, None]) turned = np.flatnonzero(before < -0.5) if len(turned): + mid = v.mean(axis=0) + cone = np.einsum("ij,ij->i", v[fan[:, 0]] - mid, np.cross(v[fan[:, 1]] - mid, v[fan[:, 2]] - mid)) / 6.0 + for n in dict.fromkeys(of[flat[turned]].tolist()): # the solids with a turned face, in the order of those faces + volume = math.fsum(cone[of[face_of] == n].tolist()) + if volume < 0.0 and not seam[of == n].all(): # faces the weld closes up alone hold nothing: their sum is no volume + mine = flat[turned[of[flat[turned]] == n]] + raise RamError("mesh", "signed", f"part {part!r} is wound inside out: solid {n} of {len(names)} has a volume of {volume / extent ** 3:.3g} of the part's extent cubed, and {len(mine)} of its faces, from face {int(mine[0])}, stand before a region that winds {float(before[turned[of[flat[turned]] == n][0]]):.3g}") unit, rungs = normal[flat[turned]] / size[flat[turned], None], NUDGE * 10.0 ** (np.arange(25) / 4.0) # the nudge to the whole extent, four to a decade still = winding(v, fan, (centre[turned][:, None, :] + (rungs[1:] * extent)[None, :, None] * unit[:, None, :]).reshape(-1, 3)).reshape(len(turned), -1) < -0.5 held = float((0.5 * size[flat[turned]] * rungs[np.cumprod(still, axis=1).sum(axis=1)]).sum()) / extent ** 2 if held >= THIN: - k = int(flat[turned[0]]) - raise RamError("mesh", "signed", f"part {part!r} is wound inside out: {len(turned)} faces, from face {k} of solid {int(of[k])} of {len(names)}, stand before a region that winds {float(before[turned[0]]):.3g} and holds {held:.3g} of the part's extent cubed") + k, area = int(flat[turned[0]]), size[flat[turned]] + about = (centre[turned] * area[:, None]).sum(axis=0) / area.sum() + reach = float(np.linalg.norm(centre[turned] - about, axis=1).max()) + raise RamError("mesh", "signed", f"part {part!r} crosses itself: {len(turned)} faces, from face {k} of solid {int(of[k])} of {len(names)}, stand before a region that winds {float(before[turned[0]]):.3g} and holds {held:.3g} of the part's extent cubed, " + f"about ({about[0]:.4g}, {about[1]:.4g}, {about[2]:.4g}) and within {reach:.3g} of it, and no solid there has a negative volume: its surfaces cut through one another (cutters never joined, a fold), or a turned piece is welded into a whole one") return of, fan, flat, before @@ -858,19 +883,29 @@ def solids(part, vertices, faces): """The solid each face of a part belongs to (faces joined across an edge are one solid), or a RamError where the part has no inside to sign. Nothing is repaired. - Vertices within WELD of the part's extent (its box's diagonal) of one another are read as one, so a seam of - coincident vertices is no hole. A solid with an edge no face runs the other way (a boundary edge, or two faces - wound against each other across it) is open. + Open. Vertices within WELD of the part's extent (its box's diagonal) of one another along every axis are read + as one (`weld`), so a seam of coincident vertices is no hole. A solid with an edge no face runs the other way (a + boundary edge, or two faces wound against each other across it) is open. A face is read NUDGE of the extent before its centroid, along its normal. Before a face of a whole solid the winding number is 0, or more where another solid covers it. A face is turned where the number there is under - -0.5: it stands before a region that winds -1, the inside of a solid wound inside out. That region is measured: - each turned face's area by how far out along its normal the number stays under -0.5 (the nudge, then four rungs - to a decade up to the extent), summed. A part whose region holds THIN of its extent cubed or more is wound - inside out, whether the turned solid stands free or is welded to a whole one. Less is the crossing of a bevel - or of a lathe's profile and is let be: there the part reads outside in what its author took for inside. A - cavity cut as its own inward shell has the cavity before its faces, which winds 0, and passes; so does a - sliver, two sheets back to back, with nothing between them to wind.""" + -0.5: it stands before a region that winds -1. + + Inside out. A solid with a turned face whose signed volume (the sum of a . (b x c) / 6 over its triangles, summed + exactly) is negative is wound inside out, however little it holds: the bound is zero. A solid whose every face + the weld closes up to a point or a line is a seam's leftover and has no volume to read. The turned face tells it + from a cavity cut as its own inward shell, whose volume is negative too but whose faces have the cavity before + them, which winds 0: that passes. So does a sliver, two sheets back to back, with no volume and nothing between + the sheets to wind. + + Crossing. Turned faces where no solid's volume is negative stand before a region where the part's surfaces cut + through one another: two cutters taken out of one solid and never joined, a bevel folded over a corner, a + lathe's profile crossing itself, or a turned piece welded into a whole one, which the volume of the one solid + hides. The region is measured: each turned face's area by how far out along its normal the number stays under + -0.5 (the nudge, then four rungs to a decade up to the extent), summed. A part whose region holds THIN of its + extent cubed or more is refused as crossing itself, with the faces, the region and where it lies (the turned + faces' centre by area, in the frame the vertices are given in, and how far the farthest is from it). Less is + let be: there the part reads outside in what its author took for inside.""" return _read(part, vertices, faces)[0] @@ -887,8 +922,9 @@ class Signed: """The distance oracle over meshes: distance(part, points) is the distance to the part's surface, negative where the point is inside the part (its depth), capped at `cap` outside only. shells: part -> [(vertices (N, 3), faces)], in the rest frame of the part's body. Every solid of a part (`solids`) is closed and wound - counterclockwise seen from outside: a part that is open or wound inside out is refused when the oracle is - made, by a RamError that names the part, the solid and the edge count or the turned faces and their region. A + counterclockwise seen from outside: a part that is open, wound inside out or crossing itself is refused when + the oracle is made, by a RamError that names the part and the solid with its edge count or its negative volume, + or the turned faces, their region and where it lies. A shell may be (vertices, faces, matrix), a local mesh and the 4 by 4 that carries it to the body's rest frame: it is read as `placed` gives it, the faces of a mirrored one (a negative scale) turned back, so a caller hands a mirrored object's own mesh and its matrix and never a mesh it carried itself. Inside is where `inside` diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 91669fe..c6cea31 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1042,19 +1042,32 @@ staircase prism a line crosses six times. made (`ram.solids`, a `RamError` at gate `signed`). Nothing is repaired or guessed. The checks read the mesh as the winding number does, by where its faces are and not by how its vertices are numbered. -Open. Vertices within `WELD` (3e-4) of the part's extent of one another along every axis are one vertex -(`ram.weld`), so a seam of coincident vertices is no hole. A part's faces fall into solids, the faces joined across -an edge, and every solid is closed: each edge one face runs is run the other way by another. A solid with an edge -that is not (a boundary edge, or two faces wound against each other) is refused with the count of such edges. +Open. Vertices no farther apart than `WELD` (3e-4) of the part's extent along every axis are one vertex +(`ram.weld`), and a chain of such is one, so a seam of coincident vertices is no hole. The tolerance is the same +wherever the part stands: a pair 0.99 of it apart is joined and a pair 1.01 apart is not. A part's faces fall into +solids, the faces joined across an edge, and every solid is closed: each edge one face runs is run the other way by +another. A solid with an edge that is not (a boundary edge, or two faces wound against each other) is refused with +the count of such edges. -Inside out. Each face is read `NUDGE` (1e-6) of the extent before its centroid, along its normal. Before a face of -a whole solid the number is 0, or more where another solid covers it. A face is turned where the number there is -under -0.5: it stands before a region that winds -1. That region is measured, each turned face's area by how far out -along its normal the number stays under -0.5, and a part whose region holds `THIN` (1.1e-4) of its extent cubed or -more is refused with the count of turned faces, the first, its solid, the number and the share. A turned-over bar is -refused beside a whole cube and welded to one, where the volume in all is positive. A hollow mass, its cavity an -inward shell, has the cavity before those faces, which winds 0, and passes; so does a sliver of two sheets back to -back. +Each face is read `NUDGE` (1e-6) of the extent before its centroid, along its normal. Before a face of a whole solid +the number is 0, or more where another solid covers it. A face is turned where the number there is under -0.5: it +stands before a region that winds -1. Two things put a face there, and they are refused under two names. + +Inside out. A solid with a turned face whose signed volume is negative (the sum of `a . (b x c) / 6` over its +triangles, summed exactly) is wound inside out, and is refused with the solid, its volume and its turned faces. The +bound is zero: a cube of side 0.2 turned over beside a 6 m bar and a turned plate 1e-5 thick are refused as a whole +part turned over is. A hollow mass, its cavity an inward shell, holds a negative volume there too, but the cavity is +before those faces and winds 0, and it passes; so does a sliver of two sheets back to back. A solid whose every face +the weld closes up to a point or a line is a seam's leftover with no volume to read. + +Crossing. Turned faces where no solid's volume is negative stand where the part's surfaces cut through one another: +cutters taken out of one solid and never joined, a bevel folded over a corner, a lathe's profile crossing itself, or +a turned piece welded into a whole one, which the one solid's volume hides. That region is measured, each turned +face's area by how far out along its normal the number stays under -0.5, and a part whose region holds `THIN` +(1.1e-4) of its extent cubed or more is refused as crossing itself: the count of turned faces, the first, its solid, +the number, the share, and where the region lies (the turned faces' centre by area, in the frame the mesh was given +in, and how far the farthest stands from it). The message never calls such a part inside out: its winding is right +and its cut is not. A member cannot be seated against it honestly, so it stays refused until its builder is fixed. Mirrored. A shell may be `(vertices, faces, matrix)`: the object's own mesh and the 4 by 4 that carries it to the body's rest frame. `ram.placed` carries the vertices and turns each face back where the matrix mirrors, so a part @@ -1065,24 +1078,29 @@ The bounds stand on real meshes, and the unit suite holds them there (`tests.tes build passes at the corners of its params (316 here; 3,224 over the kits of ten other trees). Of the 1,832 mesh objects the mech experiments make (r3, mcr3, seraph, spectre, walker, chimera, paladin, kestrel), 42 are refused and 1,790 pass, the 115 mirrored ones the same in their own frame and placed. 21 are open: marks, recesses and plates with a -hole. 21 are wound inside out: 17 lathe and ball bodies; walker's two guns, whose turned barrel is welded into a -whole solid; and seraph's two Torso.LowerIn plates. `tests/fixtures/ram_meshes.npz` holds those 21 and the parts -nearest each bound. +hole. 17 are wound inside out: lathe and ball bodies, the least a solid of -1.4e-3 of the extent cubed (paladin +Waist.torso). 4 cross themselves with every solid's volume positive: walker's two guns, a box whose bore and cross +slots were cut and never joined (242 pairs of faces cross), and seraph's two Torso.LowerIn plates, folded at one +corner by a bevel over a boolean. `tests/fixtures/ram_meshes.npz` holds those 21, three of the open, the parts +nearest each bound and ten passing parts of each mech drawn at random: 89 that pass, so a change that refuses +passing parts is seen. | bound | nearest below | nearest above | | --- | --- | --- | | `WELD` 3e-4 | a plate's seam closes at 3.7e-5 (seraph Torso.SideBlockR; thirteen more from 7.8e-8 up) | a real hole closes at 2.2e-3 (seraph PauldronR.Outer) | -| `THIN` 1.1e-4 | 6.7e-5 held and let be (chimera CannonBody.gunmetal, 178 turned faces at a bevel's crossings) | 1.88e-4 held and refused (seraph Torso.LowerInL) | +| `THIN` 1.1e-4 | 6.7e-5 held and let be (chimera CannonBody.gunmetal, 178 turned faces at a bevel's crossings) | 1.88e-4 held and refused as crossing (seraph Torso.LowerInL) | | `NUDGE` 1e-6 | a turned cube's faces are held to 1e-8 and four are lost at 1e-9 | plates 1e-5 apart read as one at 1e-4 | What it gives up. A part exported open is capped before it is given. Two sheets nearer than `WELD` are one seam to -the open check, and a hole that narrow is not seen. A region winding -1 that holds under `THIN` is let be: 198 of the +the open check, and a hole that narrow is not seen. A crossing whose region holds under `THIN` is let be: 198 of the 1,790 passing mech parts have one, the crossing of a bevel or of a lathe's profile, and there the part reads outside -in what its author took for inside (the phalanges' 10 of 82 faces, 3e-6 to 3e-5 held). What a region holds is -measured along its faces' normals, not counted: by 60,000 sampled points the region is 2.4e-4 of the extent cubed in -Torso.LowerInL, 2.7e-4 in walker's gun (2.2e-3 held), 1.7e-3 in the Ankle root (1.4e-3 held) and 1.2e-5 in -CannonBody. A solid turned over inside a whole one is a cavity to the winding number and reads so, whatever its -author meant. +in what its author took for inside (the phalanges' 10 of 82 faces, 3e-6 to 3e-5 held). `THIN` is on crossings alone: +a turned piece welded into a whole solid is one solid of positive volume, so it is read as a crossing and one under +`THIN` passes (a turned plate 1e-4 thick welded to a cube along an edge). What a region holds is measured along its +faces' normals, not counted: by 60,000 sampled points the region is 2.4e-4 of the extent cubed in Torso.LowerInL, +2.7e-4 in walker's gun (2.2e-3 held) and 1.2e-5 in CannonBody. A solid turned over inside a whole one is a cavity to +the winding number and reads so, whatever its author meant. The four crossing parts cannot carry a ram's seat until +their builders join the gun's cutters and unfold the plate's corner. With every solid closed the number is whole, so `ram.inside` reads the same at any bound over 0 and up to 1; 0.5 is pinned in the unit suite on a test-only open cube, where the number is 0.527 under the hole and 0.473 over it. diff --git a/surfaces/blender/tests/fixtures/ram_meshes.npz b/surfaces/blender/tests/fixtures/ram_meshes.npz index f5a339e8337d0f762e4831a25b6eafa7801b574a..a60cb44326d1ec223dc9537cc8bf4de448e38f8c 100644 GIT binary patch delta 117347 zcmeFZcUV*1)-MVopdv*P0R@86tn^+*R6x22s8j)|(wo#JA_9V-^p129Fd!l|q4(Z9 zp@$wIKnQ{4#uq_f_q(5a?mpi>&;8>B)(RvmW6U{zqs=kL3VML*b2L4msz7x7CIJD# z3H))1V3V%!8Sdxf1i?81dm9%APHS6NLINs+HDCNC_=hdY!ShOjmCcACRfCNU>S_>V z{nT;q>2HIo%S!RNE2`kF(c^X8r@f~$>718ueZA;-SE>$bdv^vqA>Z$FQz7vVFTt6| zQ_~%?z{aXvGY(RQO+^j3Yz9F2WsQJ&0e!*P3LV_ulxwzYx0$l$`0&LWHk#vRIZTiX zH}>poVHFp}gM2!qB*n}f!1@gz?#ye5~D)w5IvDke6R?+h_D(A!FSDeg1vlyD`sh_9Bc zGWkU`x}0mWxx6^#5D&gwkrE9#)B2FHw3XEAv8||+O}i`kj$1v-hQ$M!7iY)l0cEm_ zC4oaG5t$TV!WZ{&&0?q-P(q|H(%A@j8Dn2b0xPc5&;Bwd38 z@kzS2r6O=}cXCLI-u0?yb?Xnur0n)Yx4HzRMi{(}U(-b_cg+trU&s`k-N z!^6Q!6OS}2B2RZEDLs3XaRWN*Xk_o8sCIg6FSJdqo!*RkF-dUX(}s3DRB3jEL!-A4 z`PJdOu2%*KjSXs%2J`}V(H<+sZ$=7$KqbE9m3-b7E%iD{y;=r!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#{PXfI4iK_FC$3(k_Z);_y{BRM#Dt~Cd}z1_4~n! zQ;hiMF0fD{X(us|50ps8D^ZLX0pdloFk-Yhp6p~fFtP~hDQG*H@WXC6iMF%ZpT zeKna#fqWk8%V+GoY^X##S&xmVJtDn>c4JOWGMEmdIh6WP~Z|hND!~!FHaE5Ldtf1Zb zRSkL$&(F+%3kSudp9^wmPxAS*f}d$GI`%nR8hZ)YqRh9I`~k667V46~0S;24X(;E= zUR3im(*^;FtH(Tve&|`%S{8>NJ9vDDd`EM%pg`o#?@w{HZa786ow#2}>ES t3eplUKorPQJ}8Z7Pe;>5M!GqlX!h$K9`FWR#f39`}aSL^V_#a~n0nGpa diff --git a/surfaces/blender/tests/test_ram.py b/surfaces/blender/tests/test_ram.py index 6bf64bc..a0cc7b4 100644 --- a/surfaces/blender/tests/test_ram.py +++ b/surfaces/blender/tests/test_ram.py @@ -9,6 +9,7 @@ import importlib.util import json import math import sys +import types import unittest from dataclasses import replace from pathlib import Path @@ -543,7 +544,8 @@ WHOLE = 3.8e-4 # a winding number against the count or share a hand val SPAN_RAM = 0.848 # the ram's span with its base 0.1 from the rocker's pivot: shipped 0.5390 (about that pivot), the span about the knee's pivot 1.3347, separation 1.57 each side -SMALL = (0.05, 0.06) # the sides of a turned-over cube beside a unit cube that hold 7.5e-5 and 1.9e-4 of the extent cubed: THIN, 1.1e-4, is 1.5 and 1.7 from them +SMALL = (0.009, 0.015) # the sides of a turned-over bar welded along a unit cube's edge whose regions hold 6.75e-5 and 1.93e-4 of the extent cubed: THIN, 1.1e-4, is 1.63 and 1.75 from them +MECH_SAMPLE = (17, 4, 3, 89, 12) # the mech sample's rows: inside out, crossing, open, pass; and the mirrored among them KIT_VARIANTS = 316 # kit parts built over the corners of their params @@ -1399,7 +1401,7 @@ class Refusals(unittest.TestCase): def test_a_seam_of_coincident_vertices_is_no_hole(self): # a cube whose every triangle has its own three vertices is closed to the eye and to the winding number, and # is one solid. Its top stood off by a third of WELD of the extent is a seam and closes; by 3.4 times WELD - # (past the two cells' width, where no grid joins them) it is a hole of 4 edges on the box and 4 on the lid + # it is a hole of 4 edges on the box and 4 on the lid verts, tris = block((0, 0, 0), (1, 1, 1)) soup = verts[tris].reshape(-1, 3) self.assertEqual(R.solids("soup", soup, np.arange(36).reshape(-1, 3)).tolist(), [0] * 12) @@ -1418,24 +1420,72 @@ class Refusals(unittest.TestCase): self.assertEqual(R.weld(row, 1e-3).tolist(), [0, 0, 2, 2, 2, 5]) self.assertEqual(R.weld(row, 0.0).tolist(), [0, 1, 2, 3, 4, 5]) - def test_an_inside_out_solid_is_refused_by_its_region(self): - # a cube with every face turned over, or mirrored with its winding kept, winds -1 inside: every face stands - # before that region + def test_weld_joins_within_the_tolerance_and_no_farther_wherever_it_stands(self): + # a pair 0.99 of the tolerance apart is one vertex and a pair 1.01 apart is two, at 100 places beside a + # vertex that stands still (so the pair falls anywhere in a cell), along each axis and along all three: the + # tolerance is along every axis, and a pair 0.99 apart on all three (1.71 in all) is one + tolerance, still = 1e-3, (-7.0, -7.0, -7.0) + places = np.random.default_rng(11).uniform(-5.0, 5.0, (100, 3)) + for step in ((1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 1), (-1, 1, -1)): + for at in places: + for share, reads in ((0.99, [0, 1, 1]), (1.01, [0, 1, 2])): + self.assertEqual(R.weld([still, at, at + share * tolerance * np.array(step)], tolerance).tolist(), reads, (step, at.tolist(), share)) + # one axis past the tolerance parts a pair the other two hold together + for at in places: + self.assertEqual(R.weld([still, at, at + tolerance * np.array((0.99, 1.01, 0.99))], tolerance).tolist(), [0, 1, 2]) + + def test_an_inside_out_solid_is_refused_by_its_volume(self): + # a cube with every face turned over, or mirrored with its winding kept, holds a negative volume (-1 of an + # extent cubed of 3 sqrt 3) and winds -1 inside: every face stands before that region verts, tris = block((0, 0, 0), (1, 1, 1)) for name, v, t in (("turned over", verts, tris[:, ::-1]), ("mirrored", verts * (-1, 1, 1), tris)): with self.assertRaises(R.RamError, msg=name) as caught: R.solids("cube", v, t) self.assertEqual(caught.exception.gate, "signed", name) - self.assertIn("part 'cube' is wound inside out: 12 faces, from face 0 of solid 0 of 1, stand before a region that winds -1 and holds ", str(caught.exception), name) - # a bar turned over is refused beside the cube, welded to it along an edge and welded to it on a face (there - # the volume of the one solid is positive: 0.96 and 0.8), and the same bars wound outward pass. On the face - # the cube's own face lies on the bar's and stands before the bar with it: 14 faces, the cube's two first - for name, bar, weld, said in (("beside", block((2, 0, 0), (3, 1, 0.5)), False, "12 faces, from face 12 of solid 1 of 2"), ("on an edge", block((1, 0, -0.2), (1.2, 1, 0)), True, "12 faces, from face 12 of solid 0 of 1"), - ("on a face", block((1, 0, 0), (1.2, 1, 1)), True, "14 faces, from face 2 of solid 0 of 1")): + self.assertIn("part 'cube' is wound inside out: solid 0 of 1 has a volume of -0.192 of the part's extent cubed, and 12 of its faces, from face 0, stand before a region that winds -1", str(caught.exception), name) + # a bar turned over beside the cube is a solid of its own, of negative volume, and the same bar wound outward + # passes + bar = block((2, 0, 0), (3, 1, 0.5)) + with self.assertRaises(R.RamError) as caught: + R.solids("pair", *joined((verts, tris), (bar[0], bar[1][:, ::-1]), False)) + self.assertIn("part 'pair' is wound inside out: solid 1 of 2 has a volume of -0.0137 of the part's extent cubed, and 12 of its faces, from face 12, stand before a region that winds -1", str(caught.exception)) + self.assertEqual(len(R.solids("pair", *joined((verts, tris), bar, False))), 24) + + def test_the_least_turned_solid_is_refused(self): + # the bound on a turned solid's volume is zero (verdict cut-kit-ram-lows.s4, thin-hides-small-inversions): a + # cube of side 0.2 turned over beside a whole bar 6 by 0.3 by 0.3 holds 2.1e-5 of the extent cubed, a plate 1 + # by 1 by 1e-5 turned over holds 3.5e-6, and a cube of side 0.01 by the bar 2.9e-9: each is under THIN and + # each is wound inside out. The same wound outward pass + bar = block((0, 0, 0), (6, 0.3, 0.3)) + over = lambda mesh: (mesh[0], mesh[1][:, ::-1]) + for name, whole, turned, said, first in (("a cube by a bar", joined(bar, block((7, 0, 0), (7.2, 0.2, 0.2)), False), joined(bar, over(block((7, 0, 0), (7.2, 0.2, 0.2))), False), "solid 1 of 2 has a volume of -2.13e-05", 12), + ("a plate", block((0, 0, 0), (1, 1, 1e-5)), over(block((0, 0, 0), (1, 1, 1e-5))), "solid 0 of 1 has a volume of -3.54e-06", 0), + ("a speck by a bar", joined(bar, block((7, 0, 0), (7.01, 0.01, 0.01)), False), joined(bar, over(block((7, 0, 0), (7.01, 0.01, 0.01))), False), "solid 1 of 2 has a volume of -2.89e-09", 12)): + self.assertEqual(len(R.solids("least", *whole)), len(whole[1]), name) with self.assertRaises(R.RamError, msg=name) as caught: - R.solids("pair", *joined((verts, tris), (bar[0], bar[1][:, ::-1]), weld)) - self.assertIn(f"part 'pair' is wound inside out: {said}, stand before a region that winds -1 and holds ", str(caught.exception), name) - self.assertEqual(len(R.solids("pair", *joined((verts, tris), bar, weld))), 24, name) + R.solids("least", *turned) + self.assertIn(f"part 'least' is wound inside out: {said} of the part's extent cubed, and 12 of its faces, from face {first}, stand before a region that winds -1", str(caught.exception), name) + + def test_a_part_that_crosses_itself_is_refused_by_its_region_and_where(self): + # a bar turned over and welded to the cube along an edge or on a face is one solid with it, of positive + # volume (0.96 and 0.8): no solid is inside out, and the faces before the region that winds -1 are named as + # the part crossing itself, with the region's centre and reach. On the face the cube's own face lies on the + # bar's and stands before the bar with it: 14 faces, the cube's two first. The same bars wound outward pass + verts, tris = block((0, 0, 0), (1, 1, 1)) + for name, bar, said, about in (("on an edge", block((1, 0, -0.2), (1.2, 1, 0)), "12 faces, from face 12 of solid 0 of 1", (1.1, 0.5, -0.1)), ("on a face", block((1, 0, 0), (1.2, 1, 1)), "14 faces, from face 2 of solid 0 of 1", None)): + with self.assertRaises(R.RamError, msg=name) as caught: + R.solids("pair", *joined((verts, tris), (bar[0], bar[1][:, ::-1]), True)) + self.assertEqual(caught.exception.gate, "signed", name) + self.assertIn(f"part 'pair' crosses itself: {said}, stand before a region that winds -1 and holds ", str(caught.exception), name) + self.assertIn("and no solid there has a negative volume", str(caught.exception), name) + self.assertNotIn("inside out", str(caught.exception), name) + centre = [float(x) for x in str(caught.exception).split("about (")[1].split(")")[0].split(", ")] + reach = float(str(caught.exception).split("and within ")[1].split(" of it")[0]) + inside_bar = all(lo - 1e-9 <= x <= hi + 1e-9 for x, lo, hi in zip(centre, bar[0].min(axis=0), bar[0].max(axis=0))) + self.assertTrue(inside_bar and 0.5 <= reach <= 0.55, (name, centre, reach)) # the bar is 1 long: its end faces' centres are 0.5 from the middle + if about: + self.assertLess(max(abs(a - b) for a, b in zip(centre, about)), 1e-3, name) + self.assertEqual(len(R.solids("pair", *joined((verts, tris), bar, True))), 24, name) def test_a_cavity_and_a_sliver_are_not_turned_over(self): # a cube of half side 1 with a cube of half side 0.5 turned over in it is a hollow mass: the winding number @@ -1444,6 +1494,10 @@ class Refusals(unittest.TestCase): hollow = joined(block((-1, -1, -1), (1, 1, 1)), (lambda v, t: (v, t[:, ::-1]))(*block((-0.5, -0.5, -0.5), (0.5, 0.5, 0.5))), False) self.assertEqual(R.solids("hollow", *hollow).tolist(), [0] * 12 + [1] * 12) self.assertLess(float(np.abs(R.winding(*hollow, [(0, 0, 0), (0.75, 0, 0), (0, 0.75, 0.75), (1.5, 0, 0)]) - (0, 1, 1, 0)).max()), WHOLE) + # the inner shell's volume is negative and none of its faces is turned. With a crossing the part is let (a bar + # of side SMALL[0] turned over and welded along the outer cube's edge) it is a cavity still, and passes + bar = block((1, -1, -1 - SMALL[0]), (1 + SMALL[0], 1, -1)) + self.assertEqual(R.solids("hollow", *joined(hollow, (bar[0], bar[1][:, ::-1]), True)).tolist(), [0] * 12 + [1] * 12 + [0] * 12) # a sliver is two sheets back to back, a closed solid of no volume: before either sheet is the outside, and # it passes alone, beside a cube and sharing a corner of one sheet = np.array([(0, 0, 0), (1, 0, 0), (0, 1, 0)], float), np.array([(0, 1, 2), (0, 2, 1)]) @@ -1451,18 +1505,19 @@ class Refusals(unittest.TestCase): self.assertEqual(R.solids("beside", *joined(block((2, 0, 0), (3, 1, 1)), sheet, False)).tolist(), [0] * 12 + [1] * 2) self.assertEqual(R.solids("welded", *joined(block((-1, -1, -1), (0, 0, 0)), sheet, True)).tolist(), [0] * 12 + [1] * 2) - def test_a_turned_region_is_read_by_what_it_holds(self): - # THIN, by a cube of side s turned over beside a unit cube (extent about 1.4 + s): its six faces stand before - # a region measured by the rungs their normals reach. Side 0.05 holds 7.5e-5 and passes; side 0.06 holds 1.9e-4 - # and is refused. So a bound of 7.5e-5 or of 1.9e-4 is seen, as near THIN as the mech parts either side of it + def test_a_crossing_is_read_by_what_its_region_holds(self): + # THIN, by a bar of side s and length 1 turned over and welded along a unit cube's edge (one solid of positive + # volume, extent about 1.74): its faces stand before a region measured by the rungs their normals reach. Side + # 0.009 holds 6.75e-5 and passes; side 0.015 holds 1.93e-4 and is refused. So a bound of 6.75e-5 or of + # 1.93e-4 is seen, as near THIN as the mech parts either side of it verts, tris = block((0, 0, 0), (1, 1, 1)) - small = lambda s: joined((verts, tris), (lambda v, t: (v, t[:, ::-1]))(*block((1.2, 0, 0), (1.2 + s, s, s))), False) + small = lambda s: joined((verts, tris), (lambda v, t: (v, t[:, ::-1]))(*block((1, 0, -s), (1 + s, 1, 0))), True) self.assertEqual(len(R.solids("small", *small(SMALL[0]))), 24) with self.assertRaises(R.RamError) as caught: R.solids("small", *small(SMALL[1])) - self.assertIn("part 'small' is wound inside out: 12 faces, from face 12 of solid 1 of 2, stand before a region that winds -1 and holds ", str(caught.exception)) + self.assertIn("part 'small' crosses itself: 12 faces, from face 12 of solid 0 of 1, stand before a region that winds -1 and holds ", str(caught.exception)) held = float(str(caught.exception).split("holds ")[1].split(" of")[0]) - self.assertTrue(1.8e-4 < held < 2.0e-4, held) + self.assertTrue(1.83e-4 < held < 2.03e-4, held) # the nudge, from below: a cube turned over and turned 0.3, 0.5 and 0.7 radians about x, y and z has no face # along an axis. Its sides are held at 1e-6 of the extent and to 1e-8; at 1e-9 they are not and it would pass (ca, sa), (cb, sb), (cc, sc) = ((math.cos(t), math.sin(t)) for t in (0.3, 0.5, 0.7)) @@ -1496,18 +1551,66 @@ class Refusals(unittest.TestCase): self.assertEqual(source.count("\nclass Signed:"), 1) +class Tree: + """Blender's BVHTree as Signed makes it, keeping only the faces it was given.""" + made = [] + + @classmethod + def FromPolygons(cls, verts, faces, epsilon=0.0): + cls.made.append([tuple(face) for face in faces]) + return cls() + + +@unittest.skipIf(np is None, "numpy is not installed") +class Exposed(unittest.TestCase): + """What Signed hands its trees, under a stand-in mathutils that records the polygons: the faces of all, then the + exposed ones (verdict cut-kit-ram-lows.s4, survivors-killable-by-stub). The distances are the live suite's.""" + + def setUp(self): + mathutils, bvhtree = types.ModuleType("mathutils"), types.ModuleType("mathutils.bvhtree") + mathutils.Vector, bvhtree.BVHTree, Tree.made = tuple, Tree, [] + self.kept = {name: sys.modules.get(name) for name in ("mathutils", "mathutils.bvhtree")} + sys.modules.update({"mathutils": mathutils, "mathutils.bvhtree": bvhtree}) + + def tearDown(self): + for name, module in self.kept.items(): + if module is None: + sys.modules.pop(name, None) + else: + sys.modules[name] = module + + # two triangles of no area on one line, wound both ways: closed, and with no side to be read on + LINE = [(5.0, 0.0, 0.0), (6.0, 0.0, 0.0), (7.0, 0.0, 0.0)], [(0, 1, 2), (0, 2, 1)] + + def test_a_part_with_no_exposed_face_is_refused(self): + with self.assertRaises(R.RamError) as caught: + R.Signed({"line": [self.LINE]}) + self.assertEqual((caught.exception.gate, str(caught.exception)), ("signed", "mesh ram: signed: part 'line' has no exposed face")) + self.assertEqual(Tree.made, []) + + def test_a_face_of_no_area_is_not_exposed(self): + verts, tris = block((0, 0, 0), (1, 1, 1)) + cube = [tuple(int(i) for i in t) for t in tris] + R.Signed({"p": [(verts, cube), self.LINE]}) + every, exposed = Tree.made + self.assertEqual((len(every), exposed), (14, cube)) # the cube's twelve are its surface; the two of no area are not + + @unittest.skipIf(np is None, "numpy is not installed") class Corpus(unittest.TestCase): """The refusals against meshes nobody made for them: every part the kits build, and a sample of the 1,832 mesh objects the mech experiments make (r3, mcr3, seraph, spectre, walker, chimera, paladin, kestrel, as Blender evaluates them, each in its own frame with its world matrix). Of the 1,832, solids refuses 42: 21 open (marks, - recesses, plates with a hole) and 21 wound inside out (17 lathe and ball bodies; walker's two guns, whose - turned barrel is welded into a whole solid; seraph's two Torso.LowerIn plates). The sample is those 21, the - open and the passing parts nearest each bound, and three mirrored parts. + recesses, plates with a hole), 17 wound inside out (lathe and ball bodies, each with a solid of negative volume, + -1.4e-3 of the extent cubed at the least) and 4 that cross themselves, every solid of positive volume: walker's + two guns, a box whose bore and cross slots were cut and never joined, and seraph's two Torso.LowerIn plates, + folded at a corner by a bevel over a boolean. The sample is those 21, three open, the passing parts nearest + each bound, three mirrored parts, and ten passing parts of each mech drawn by a seeded generator from those of + 400 faces or fewer: 89 pass, so a change that refuses one passing part in twenty fails here 99 times in 100. WELD 3e-4 seams close up to 3.7e-5 of the extent (seraph Torso.SideBlockR; r3 Prow.Upper 2.3e-6, chimera Pauldron.Band 4.1e-7); the least hole closes at 2.2e-3 (seraph PauldronR.Outer): 8 and 7 apart - THIN 1.1e-4 the least region refused holds 1.88e-4 (seraph Torso.LowerInL; by 60,000 sampled points 2.4e-4 + THIN 1.1e-4 the least crossing refused holds 1.88e-4 (seraph Torso.LowerInL; by 60,000 sampled points 2.4e-4 of its extent cubed winds -1, as 2.7e-4 of walker's gun does); the greatest let be holds 6.7e-5 (chimera CannonBody.gunmetal, 178 faces at a bevel's crossings, 1.2e-5 sampled): 1.68 each side""" @@ -1539,8 +1642,8 @@ class Corpus(unittest.TestCase): self.assertEqual(built, KIT_VARIANTS) def test_the_mech_sample_reads_as_recorded(self): - # each mesh in its own frame, and placed by its world matrix (three are mirrored and pass both ways; r3's - # Hand.palm is mirrored and inside out both ways) + # each mesh in its own frame, and placed by its world matrix: the twelve mirrored ones read the same both + # ways, pass or inside out (r3's Hand.palm) sample = np.load(SURFACE / "tests" / "fixtures" / "ram_meshes.npz") rows = json.loads(str(sample["rows"])) got = {} @@ -1552,10 +1655,11 @@ class Corpus(unittest.TestCase): R.solids(row["name"], *mesh) got[row["name"], frame] = "pass" except R.RamError as error: - got[row["name"], frame] = "open" if " is open: " in str(error) else "inside out" if " is wound inside out: " in str(error) else str(error) + got[row["name"], frame] = "open" if " is open: " in str(error) else "inside out" if " is wound inside out: " in str(error) else "crossing" if " crosses itself: " in str(error) else str(error) self.assertEqual(got, {(row["name"], frame): row["reads"] for row in rows for frame in ("own", "placed")}) reads = [row["reads"] for row in rows] - self.assertEqual((reads.count("inside out"), reads.count("open"), reads.count("pass"), sum(row["mirrored"] for row in rows)), (21, 3, 9, 7)) + self.assertEqual(tuple(reads.count(kind) for kind in ("inside out", "crossing", "open", "pass")) + (sum(row["mirrored"] for row in rows),), MECH_SAMPLE) + self.assertEqual(sorted(row["name"] for row in rows if row["reads"] == "crossing"), ["seraph:Torso.LowerInL", "seraph:Torso.LowerInR", "walker:GunL.gunmetal", "walker:GunR.gunmetal"]) if __name__ == "__main__": From ba5672b47f8861204d449a96269c63e53a35a103 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 08:04:54 +0100 Subject: [PATCH 183/223] live ram_knee: a turned bar beside a cube is inside out by its volume; welded to it, the part crosses itself and is told where 24 checks ok under Blender 5.3.0. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/ram_knee.py | 22 ++++++++++--------- .../blender/tests/live/ram_knee.result.json | 20 ++++++++--------- 2 files changed, 22 insertions(+), 20 deletions(-) diff --git a/surfaces/blender/tests/live/ram_knee.py b/surfaces/blender/tests/live/ram_knee.py index a8d31b9..bacddf2 100644 --- a/surfaces/blender/tests/live/ram_knee.py +++ b/surfaces/blender/tests/live/ram_knee.py @@ -12,8 +12,8 @@ without them). is an absolute path; writes .result.json and .r3_ The oracle is ram.Signed: a point is inside a part where the winding number of the part's faces about it is 0.5 or more. tests/fixtures/ram_plates.json holds the rocker plates as Imagination's jointlib builds them, four closed bars joined into one mesh, a side's two overlapping, and 29 points inside them: none reads outside. Nor does a point where -two welded boxes overlap. A part that is open or wound inside out is refused when the oracle is made, a hollow mass -and a part mirrored by its matrix are read, and the depth is to the part's surface: a face buried in another of the +two welded boxes overlap. A part that is open, wound inside out or crossing itself is refused when the oracle is made, a +hollow mass and a part mirrored by its matrix are read, and the depth is to the part's surface: a face buried in another of the part's solids is not read, and outside the distance is to the nearest face of all. A clearance verdict is a sign, the gate's own. FLAT follows lodur:ruling:deterministic-bound-margin. The checks run @@ -345,9 +345,9 @@ try: [int((plates >= 0).sum()), int(both.sum()), int((got != truth).sum())]) # a part with no inside to sign is refused when the oracle is made, by its reason: a cube with its top off, or - # two adjacent faces off, is open; a cube turned over, mirrored with its winding kept, or a turned-over bar beside - # a whole cube or welded to one along an edge (a positive volume in all) is wound inside out. What has an inside - # is read: a mirrored cube handed as its own mesh and its matrix, and a hollow mass, its cavity an inward shell + # two adjacent faces off, is open; a cube turned over or mirrored with its winding kept, or a turned-over bar beside + # a whole cube, is a solid of negative volume and wound inside out; the bar welded to the cube along an edge (one + # solid, a positive volume in all) crosses itself, and is told where. What has an inside is read: a mirrored cube handed as its own mesh and its matrix, and a hollow mass, its cavity an inward shell def one(*meshes): at, faces = {}, [] for v, f in meshes: @@ -367,11 +367,13 @@ try: except R.RamError as error: said[name] = str(error) RES["refusals"] = said - want = {"top off": "is open: solid 0 of 1 has 4 edges", "two faces off": "is open: solid 0 of 1 has 6 edges", "turned over": "is wound inside out: 6 faces, from face 0 of solid 0 of 1, stand before a region that winds -1", - "mirrored": "is wound inside out: 6 faces, from face 0 of solid 0 of 1, stand before a region that winds -1", "a turned-over bar beside a cube": "is wound inside out: 6 faces, from face 6 of solid 1 of 2, stand before a region that winds -1", - "a turned-over bar welded to a cube": "is wound inside out: 6 faces, from face 6 of solid 0 of 1, stand before a region that winds -1"} - check("no-inside-is-refused: an open part is refused by its solid and edge count, an inside-out one by its turned faces and their region, a turned-over bar beside a whole cube or welded to it included", - len(one((v1, f1), rail)[0]) == 14 and all(said[name] is not None and "part 'cube' " + text in said[name] for name, text in want.items()), said) + want = {"top off": "is open: solid 0 of 1 has 4 edges", "two faces off": "is open: solid 0 of 1 has 6 edges", "turned over": "is wound inside out: solid 0 of 1 has a volume of -0.192 of the part's extent cubed, and 6 of its faces, from face 0, stand before a region that winds -1", + "mirrored": "is wound inside out: solid 0 of 1 has a volume of -0.192 of the part's extent cubed, and 6 of its faces, from face 0, stand before a region that winds -1", + "a turned-over bar beside a cube": "is wound inside out: solid 1 of 2 has a volume of -0.0133 of the part's extent cubed, and 6 of its faces, from face 6, stand before a region that winds -1", + "a turned-over bar welded to a cube": "crosses itself: 6 faces, from face 6 of solid 0 of 1, stand before a region that winds -1"} + check("no-inside-is-refused: an open part is refused by its solid and edge count, an inside-out one by its solid's negative volume, and a turned-over bar welded to a whole cube as crossing itself about (1.1, 0.5, -0.1), never as inside out", + len(one((v1, f1), rail)[0]) == 14 and all(said[name] is not None and "part 'cube' " + text in said[name] for name, text in want.items()) + and "about (1.1, 0.5, -0.1) and within 0.5 of it" in said["a turned-over bar welded to a cube"] and "inside out" not in said["a turned-over bar welded to a cube"], said) hollow = [wound((-1, -1, -1), (1, 1, 1)), (lambda v, f: (v, [face[::-1] for face in f]))(*wound((0.4, 0.4, 0.4), (0.6, 0.6, 0.6)))] at = np.array([(0.5, 0.5, 0.5), (0.0, 0.0, 0.0), (0.5, 0.5, 0.95), (1.2, 0.0, 0.0)]) left = np.array([(-0.5, 0.5, 0.5), (0.5, 0.5, 0.5), (-0.5, 0.5, 0.9)]) diff --git a/surfaces/blender/tests/live/ram_knee.result.json b/surfaces/blender/tests/live/ram_knee.result.json index 5c63306..2038c22 100644 --- a/surfaces/blender/tests/live/ram_knee.result.json +++ b/surfaces/blender/tests/live/ram_knee.result.json @@ -22,7 +22,7 @@ "detail": null }, { - "name": "no-inside-is-refused: an open part is refused by its solid and edge count, an inside-out one by its turned faces and their region, a turned-over bar beside a whole cube or welded to it included", + "name": "no-inside-is-refused: an open part is refused by its solid and edge count, an inside-out one by its solid's negative volume, and a turned-over bar welded to a whole cube as crossing itself about (1.1, 0.5, -0.1), never as inside out", "ok": true, "detail": null }, @@ -136,7 +136,7 @@ "bell crank: least margin of a zoned pair, 251 steps uncapped": 0.000118, "bell crank: pairs": 60, "bell crank: pairs refused with nothing let": 19, - "bell crank: seconds, 49 steps capped": 1.52, + "bell crank: seconds, 49 steps capped": 1.87, "bell crank: zoned pairs": 20, "boss through a wall (faces that cross a solid are kept or left whole): in both (the surface is 0.502 off), in the wall (0.583), in the boss (0.2), off it (0.1)": [ -0.5, @@ -175,7 +175,7 @@ "search: candidates": 13824, "search: pass the gates before clearance": 78, "search: refused on their own parts": 21, - "search: seconds": 73.9, + "search: seconds": 45.2, "search: worlds built": 22, "slab with a boss through it: off its faces (0.05, 0.02), off the boss's end (0.2), under it (0.2)": [ 0.05000000447034836, @@ -189,10 +189,10 @@ "refusals": { "top off": "mesh ram: signed: part 'cube' is open: solid 0 of 1 has 4 edges no face runs the other way", "two faces off": "mesh ram: signed: part 'cube' is open: solid 0 of 1 has 6 edges no face runs the other way", - "turned over": "mesh ram: signed: part 'cube' is wound inside out: 6 faces, from face 0 of solid 0 of 1, stand before a region that winds -1.01 and holds 1.12 of the part's extent cubed", - "mirrored": "mesh ram: signed: part 'cube' is wound inside out: 6 faces, from face 0 of solid 0 of 1, stand before a region that winds -1.01 and holds 1.12 of the part's extent cubed", - "a turned-over bar beside a cube": "mesh ram: signed: part 'cube' is wound inside out: 6 faces, from face 6 of solid 1 of 2, stand before a region that winds -1 and holds 0.0605 of the part's extent cubed", - "a turned-over bar welded to a cube": "mesh ram: signed: part 'cube' is wound inside out: 6 faces, from face 6 of solid 0 of 1, stand before a region that winds -1 and holds 0.0271 of the part's extent cubed" + "turned over": "mesh ram: signed: part 'cube' is wound inside out: solid 0 of 1 has a volume of -0.192 of the part's extent cubed, and 6 of its faces, from face 0, stand before a region that winds -1.01", + "mirrored": "mesh ram: signed: part 'cube' is wound inside out: solid 0 of 1 has a volume of -0.192 of the part's extent cubed, and 6 of its faces, from face 0, stand before a region that winds -1.01", + "a turned-over bar beside a cube": "mesh ram: signed: part 'cube' is wound inside out: solid 1 of 2 has a volume of -0.0133 of the part's extent cubed, and 6 of its faces, from face 6, stand before a region that winds -1", + "a turned-over bar welded to a cube": "mesh ram: signed: part 'cube' crosses itself: 6 faces, from face 6 of solid 0 of 1, stand before a region that winds -1 and holds 0.0271 of the part's extent cubed, about (1.1, 0.5, -0.1) and within 0.5 of it, and no solid there has a negative volume: its surfaces cut through one another (cutters never joined, a fold), or a turned piece is welded into a whole one" }, "zones": { "barrel[0] | parent.seat": { @@ -566,9 +566,9 @@ } }, "renders": [ - "F:/aeth-wt/fable-ramlows/scratch/h5/out/live_shipped2/knee.r3_0.png", - "F:/aeth-wt/fable-ramlows/scratch/h5/out/live_shipped2/knee.r3_62p5.png", - "F:/aeth-wt/fable-ramlows/scratch/h5/out/live_shipped2/knee.r3_125.png" + "F:/aeth-wt/hands-ramlows6-scratch/out/live/knee.r3_0.png", + "F:/aeth-wt/hands-ramlows6-scratch/out/live/knee.r3_62p5.png", + "F:/aeth-wt/hands-ramlows6-scratch/out/live/knee.r3_125.png" ], "ok": true } \ No newline at end of file From e41d51282c0bbd7d9c9038554514c975821783f9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 08:54:52 +0100 Subject: [PATCH 184/223] brokkr_reference.block_plate: a plate's first free cage from traces naming two consecutive corners, solved by fit_runs with a plane and fairness for its prior (cut trace-block) fit_runs takes its prior as rows (A, b); fit_sheet passes none, which is the identity it had. triangulate, plate_sheet and block_plate after fit_sheet; the operator, its action row, docs/reference.md "block_plate", BlockTests and tests/fixtures/spectre_plates.json. Where the spec was silent or could not be built as written: - a mirrored plate's centre stands in the half, not on x = 0: a face of three seam points is its own reflection and brokkr_kitbash's parser refuses it. The seam's sides keep their centre faces and lose only the skirt. - views under 9.7 degrees apart (the geometric mean of 19 and 5) do not start a corner; that is what refuses a 5 degree plate with no plane. - block_plate takes the cage's parser as an argument: core imports nothing. - SPECTRE's traces close no outline; the fixture closes them with edges of the fitted cage, marked. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/__init__.py | 60 ++- .../brokkr_reference/brokkr_actions.json | 57 +++ surfaces/blender/brokkr_reference/core.py | 350 +++++++++++++++++- surfaces/blender/docs/reference.md | 69 ++++ .../tests/fixtures/spectre_plates.json | 1 + surfaces/blender/tests/test_reference.py | 246 +++++++++++- 6 files changed, 776 insertions(+), 7 deletions(-) create mode 100644 surfaces/blender/tests/fixtures/spectre_plates.json diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index d106882..7a3b619 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -14,6 +14,8 @@ cameras, scores and a fitted sheet. The edges flow_score reads are computed on e fit_shell reads a shell's request through brokkr_kitbash (the sheet's one parser) and returns a sheet; it writes nothing. brokkr_kitbash.shell is the cage's one writer: the caller applies the fitted sheet with it. +block_plate returns a plate's first sheet from traces of its outline, checked by the same parser, and the traces as +fit_shell takes them; it writes nothing either. """ bl_info = {"name": "Brokkr Reference", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), "category": "Camera", "description": "Solve a reference view's camera from marked points; agent-callable through Brokkr."} @@ -263,7 +265,63 @@ class BROKKR_REFERENCE_OT_fit_shell(PolishOperator): return {"object": obj.name, **out, "seconds": round(time.perf_counter() - started, 3)} -classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_flow_score, BROKKR_REFERENCE_OT_fit_shell) +class BROKKR_REFERENCE_OT_block_plate(PolishOperator): + """Block a plate's first free cage from traces of its outline through solved cameras, each trace naming the two + corners it runs between, and say what decided each corner's depth; nothing is written""" + bl_idname = "brokkr_reference.block_plate" + bl_label = "Block Plate From Traces" + frame_object: bpy.props.StringProperty(name="Frame", maxlen=63, description="An empty or object, unscaled, whose place in the world is the plate's frame") + plate: bpy.props.StringProperty(name="Plate", maxlen=2000, description="JSON {corners: [names in the outline's order], mirror, seam: [corners on x = 0]}") + traces: bpy.props.StringProperty(name="Traces", maxlen=12000, description="A JSON array of {camera, box, frame, from, to, side, line: [[u, v], ...]}") + plane: bpy.props.StringProperty(name="Plane", maxlen=200, description="'' for the plane through the corners the views decide, or 'x,y,z; nx,ny,nz' in the frame") + share: bpy.props.FloatProperty(name="Share", default=0.1, min=0.0009, max=10.0, description="A crown point this share of the plate's extent off the plane costs what one pixel of miss does") + tol: bpy.props.FloatProperty(name="Tolerance", default=core.TOL, min=0.09, max=100.0, description="Pixels: nine tenths of every trace must lie this near its built side, or the side gains a point") + + def work(self, context): + try: + import brokkr_kitbash + except ImportError as error: + raise Refused(f"block_plate needs the brokkr_kitbash add-on beside this one ({error}).") from None + obj = bpy.data.objects.get(self.frame_object) + if obj is None or obj.name not in context.scene.objects: + raise Refused(f"frame_object {self.frame_object!r} is not an object of this scene.") + if max(abs(v - 1.0) for v in obj.matrix_world.to_scale()) > 1e-6: + raise Refused(f"frame_object {obj.name!r} is scaled {tuple(round(v, 6) for v in obj.matrix_world.to_scale())}: a plate is in metres of its frame. Apply or clear the scale.") + try: + plate, traces = json.loads(self.plate), json.loads(self.traces) + except ValueError as error: + raise Refused(f"plate and traces must be JSON ({error}).") from None + if not isinstance(traces, list) or not all(isinstance(trace, dict) for trace in traces): + raise Refused("traces must be a JSON array of objects {camera, box, frame, from, to, side, line}.") + plane = None + if self.plane.strip(): + halves = self.plane.split(";") + try: + if len(halves) != 2: + raise core.ReferenceFitError(f"plane {self.plane.strip()!r} is not 'x,y,z; nx,ny,nz'") + plane = {"point": core.numbers(halves[0], 3, "plane's point"), "normal": core.numbers(halves[1], 3, "plane's normal")} + except core.ReferenceFitError as refusal: + raise Refused(f"{refusal}.") from None + own, views = [list(row) for row in obj.matrix_world], [] + for k, trace in enumerate(traces): + box = trace.get("box") + if box is not None and not (isinstance(box, list) and len(box) == 4 and all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in box)): + raise Refused(f"traces[{k}].box must be [u0, v0, u1, v1], or absent for the render's own frame.") + if not isinstance(trace.get("camera"), str): + raise Refused(f"traces[{k}].camera must name a camera object.") + try: + views.append((record(context, trace["camera"], "" if box is None else ",".join(repr(float(v)) for v in box)), trace.get("frame") or own)) + except (Refused, core.ReferenceFitError) as refusal: + raise Refused(f"traces[{k}]: {refusal}") from None + started = time.perf_counter() + try: + out = core.block_plate(views, plate, traces, brokkr_kitbash.core.sheet, plane=plane, share=self.share, tol=self.tol) + except core.ReferenceFitError as refusal: + raise Refused(f"{refusal}. Nothing changed.") from None + return {"frame_object": obj.name, **out, "seconds": round(time.perf_counter() - started, 3)} + + +classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_flow_score, BROKKR_REFERENCE_OT_fit_shell, BROKKR_REFERENCE_OT_block_plate) def register(): diff --git a/surfaces/blender/brokkr_reference/brokkr_actions.json b/surfaces/blender/brokkr_reference/brokkr_actions.json index a1d4856..38499c6 100644 --- a/surfaces/blender/brokkr_reference/brokkr_actions.json +++ b/surfaces/blender/brokkr_reference/brokkr_actions.json @@ -174,6 +174,63 @@ "doc": "pixels: nine tenths of every trace must lie this near its built run, or the fit is refused" } ] + }, + { + "name": "brokkr_reference.block_plate", + "doc": "Block a plate's first free cage from traces of its outline, each seen through a scene camera and naming the two consecutive corners it runs between: the only correspondence is a trace's ends to its corners. The crown (the corners and each side's points between) is solved until the sides as built draw on the traces; a side whose trace is not explained gains a point, up to 6. Depth comes from the views where two see a corner 9.7 degrees or more apart, from x = 0 for a mirrored plate's seam corners, and otherwise from a plane: the one given, or the one through the corners the views and the seam decide. Each corner says which (decided_by views, mirror or plane; views means the prior's share is under 0.2). A corner one view sees is refused when the plane stands over 66 degrees off that view. Returns the sheet for brokkr_kitbash.shell, checked by its parser, and fit_traces for brokkr_reference.fit_shell (left_out lists the traces fit_shell cannot state: another frame, or a partner's side -1). Writes nothing (docs/reference.md).", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "frame_object", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "an empty or object, unscaled, whose place in the world is the plate's frame" + }, + { + "name": "plate", + "type": "string", + "required": true, + "minLength": 2, + "maxLength": 2000, + "doc": "JSON {corners: [names, in the outline's order], mirror: true or false, seam: [the corners on x = 0 of a mirrored plate, two or more next to each other]}; side i runs from corner i to corner i + 1 and is one hard crease" + }, + { + "name": "traces", + "type": "string", + "required": true, + "minLength": 2, + "maxLength": 12000, + "doc": "a JSON array of {camera, box, frame, from, to, side, line}: camera a camera object's name; box [u0,v0,u1,v1], its frame on the image, absent for the render's own; frame a 4 x 4 (rows), the part's pose in that view, absent for frame_object's; from and to two consecutive corners; side 1, or -1 for the mirrored half or the partner across the frame's x = 0; line [[u,v],...] drawn from `from` to `to`" + }, + { + "name": "plane", + "type": "string", + "required": false, + "maxLength": 200, + "default": "", + "doc": "'' for the plane through the corners the views and the seam decide, or 'x,y,z; nx,ny,nz' in the frame: a point of the plane and its normal" + }, + { + "name": "share", + "type": "number", + "minimum": 0.001, + "maximum": 10, + "default": 0.1, + "doc": "the prior: a crown point this share of the corners' extent off the plane costs what one pixel of miss does" + }, + { + "name": "tol", + "type": "number", + "minimum": 0.1, + "maximum": 100, + "default": 5.2, + "doc": "pixels: nine tenths of every trace must lie this near its built side, or the side gains a point" + } + ] } ] } diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index 69549b4..970adee 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -37,6 +37,13 @@ only where the built runs explain every trace; docs/reference.md, "fit_shell", s fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol) the moved cage and the report fit_sheet(document, cage, frame, traces, cams, share, tol) the same for a sheet's named runs: the fitted sheet + +A plate's first cage is blocked from traces of its outline, each naming the two corners it runs between: the crown +is solved by fit_runs with a plane and fairness for its prior; docs/reference.md, "block_plate". + + triangulate(obs, seam) where sight lines meet, and how far apart they stand + plate_sheet(crown, corners, flare, drop, dome, mirror, seam, facing) the crown, skirt and centre free-cage document + block_plate(views, plate, traces, parse, plane, share, tol) the blocked sheet and what decided each corner """ from __future__ import annotations @@ -527,7 +534,7 @@ def _hard_runs(cage, runs): "more hard edges meet, or on the rim") -def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL): +def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL, prior_rows=None): """Move a cage's points until its hard runs, as built and as cameras draw them, lie on their traces. views [(camera record, frame)]: the frame is the 4 x 4 that carries the cage to the world @@ -538,7 +545,10 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL): movable (vertices, 3) of bool: the coordinates that may move. Only authored vertices move mirror_of per vertex, the authored vertex it mirrors across x = 0, or itself: a mirrored half is the same parameters seen again, x negated - share the prior: a move of share x diag from the cage as given costs what one pixel of miss does + share the prior's weight: a prior row that reads share x diag metres costs what one pixel of miss does + prior_rows (A, b) in metres over the movable coordinates, in the order of movable's True entries: the prior is + the rows A p - b. None is the identity, A = I and b the cage as given: a move from where each + point was blocked. block_plate gives distances to a plane and a side's second differences instead tol pixels: PART in a hundred of each trace must lie this near its built run as drawn The residual per run is the pixel distance from each built point (crease_run LEVELS times, drawn through the @@ -581,6 +591,9 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL): prepared.append((run["name"], views[run["view"]], line, W, source, np.stack([flip[chain], np.ones(len(chain)), np.ones(len(chain))], 1), column.reshape(-1, 3)[source])) # the parameter column of each chain point's coordinate, -1 where held p0 = V0.ravel()[index] + A0, b0 = (np.eye(len(p0)), p0) if prior_rows is None else (np.asarray(prior_rows[0], float), np.asarray(prior_rows[1], float)) + if A0.ndim != 2 or A0.shape != (len(b0), len(p0)): + raise ReferenceFitError(f"prior_rows must be (A, b) with a column of A per movable coordinate ({len(p0)}) and a row per entry of b") def terms(p): """(residual, Jacobian, each run's built points as drawn) at parameters p.""" @@ -603,7 +616,7 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL): res += [dist, u[0] - line[0], u[-1] - line[-1]] rows.append(block) drawn.append((u, dist)) - return np.concatenate(res + [prior * (p - p0)]), np.vstack(rows + [prior * np.eye(len(p))]), drawn + return np.concatenate(res + [prior * (A0 @ p - b0)]), np.vstack(rows + [prior * A0]), drawn p, lam, rounds = p0.copy(), 1e-3, 0 r, J, drawn = terms(p) @@ -730,6 +743,337 @@ def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=TOL): return {"sheet": out, "traces": report["traces"], "points": points} +# --- a plate's first cage from its traces ------------------------------------------------------------------------------ + +FAIR = 0.2 # a side's second differences of this share of its chord cost what one pixel of miss does (0.02 held a bowed side straight; docs/reference.md) +K_MAX = 6 # points a side grows to before its trace is refused as fit_runs refuses it +SQUARE = 0.4 # the cosine between a plane's normal and a sight line under which a trace is not lifted onto it: past 66 degrees the lift stretches over 2.5 times +PARALLAX = 9.7 # degrees between a corner's widest pair of sight lines under which the views do not start it: the geometric mean of 19, where a plate blocks from its views, and 5, where its corners land 0.25 to 1.5 m off (tests/test_reference.py BlockTests) +VIEWS = 0.2 # a prior_share under this: the views decide the point (fit_shell's line) +FLARE, DROP, DOME = 0.06, 0.07, 0.02 # metres: a plate's skirt out from and back of its crown, and its centre's rise +TRACE_KEYS = ("camera", "box", "frame", "from", "to", "side", "line") + + +def _unit(v): + v = np.asarray(v, float) + return v / max(float(np.linalg.norm(v)), 1e-12) + + +def _partner(frame, side): + """The frame a trace's side is seen through: the part's own, or for side -1 its reflection across the frame's + x = 0 (the mirrored half of a plate, or the plate's partner on the other limb).""" + F = np.array(frame, float) + if side == -1: + F[:3, 0] = -F[:3, 0] + return F + + +def _sight(cam, frame, pixel): + """A pixel's line of sight (origin, unit direction) in a frame's own coordinates.""" + o, d = ray(cam, pixel) + inv = np.linalg.inv(np.asarray(frame, float)) + return inv[:3, :3] @ o + inv[:3, 3], _unit(inv[:3, :3] @ d) + + +def triangulate(obs, seam=False): + """Where sight lines meet. `obs` is [(camera record, frame, side, pixel)]: the pixel each view draws one point + of the frame at, side -1 a view of the point's reflection across x = 0. The midpoint of the sight lines, then + Gauss-Newton on the reprojection; `seam` holds the point on x = 0, which one view then decides. Returns (the + point in the frame, parallax_deg: the angle between the widest pair of sight lines, the worst reprojection miss + in pixels, m_per_px: the most one pixel of error moves the point). One sight line and no seam is no point.""" + frames = [_partner(frame, side) for _, frame, side, _ in obs] + rays = [_sight(cam, F, pixel) for (cam, _, _, pixel), F in zip(obs, frames)] + free = [1, 2] if seam else [0, 1, 2] + if len(rays) < 2 and not seam: + raise ReferenceFitError("one sight line meets nothing: a point is triangulated from two or more views, or held on the mirror plane") + A, b = np.zeros((3, 3)), np.zeros(3) + for o, d in rays: + P = np.eye(3) - np.outer(d, d) + A, b = A + P, b + P @ o + X = np.zeros(3) + X[free] = np.linalg.lstsq(A[:, free], b, rcond=None)[0] + + def terms(X): + drawn = [_drawn(cam, F, X[None]) for (cam, _, _, _), F in zip(obs, frames)] + if any(seen_ is None for seen_ in drawn): + raise ReferenceFitError("the sight lines meet behind a camera") + return np.concatenate([seen_[0][0] - np.asarray(pixel, float) for seen_, (_, _, _, pixel) in zip(drawn, obs)]), np.vstack([seen_[1][0] for seen_ in drawn])[:, free] + + for _ in range(10): + r, J = terms(X) + X[free] -= np.linalg.lstsq(J, r, rcond=None)[0] + r, J = terms(X) + parallax = max((math.degrees(math.acos(min(1.0, abs(float(a[1] @ c[1]))))) for a in rays for c in rays), default=0.0) + return X, parallax, float(np.abs(r).max()), float(math.sqrt(max(np.linalg.eigvalsh(np.linalg.pinv(J.T @ J)).max(), 0.0))) + + +def plate_sheet(crown, corners, flare=FLARE, drop=DROP, dome=DOME, mirror=False, seam=(), facing=None): + """The free-cage document of a plate whose raised outline is `crown`, a closed ring of points in the plate's + frame: the crown ring (vertices 0 to n - 1, in the ring's order), a skirt ring `flare` out from it and `drop` + back of it (the chamfered wall), and one centre vertex `dome` proud of the ring's middle. Every crown side is + creased 1; `corners` (ring indices) are pinned 1 on crown and skirt, so the crown between two corners is one + hard run, and the points between them are free to round it. The centre is the cage's pole unless the ring has + four points. `facing` is a direction the outer face looks along; the ring is taken as wound that way, or the + sheet is flipped. + + mirror: `seam` names the ring's points on x = 0 (one unbroken stretch of it). The crown between them is the + crease the two halves meet at: it has no skirt, the skirt of its two ends stands on x = 0, and those ends are + poles (six edges meet there once the half is reflected). The centre stands in the half, not on the plane: a + face of three points of x = 0 is its own reflection and the cage's parser refuses it.""" + P = np.asarray(crown, float) + n, seam = len(P), set(seam) if mirror else set() + Q = np.roll(P, -1, axis=0) + normal = _unit(np.cross(P, Q).sum(0)) # Newell's: the ring's own facing, counter-clockwise seen from where it points + flip = facing is not None and float(normal @ np.asarray(facing, float)) < 0 + out_ = -normal if flip else normal + middle = P.mean(0) + walled = [i for i in range(n) if not (i in seam and (i - 1) % n in seam and (i + 1) % n in seam)] # a point inside the seam has no skirt + skirt = {} + for i in walled: + away = (P[i] - middle) - out_ * ((P[i] - middle) @ out_) + back = out_.copy() + if i in seam: + away[0], back[0] = 0.0, 0.0 + point = P[i] + _unit(away) * flare - back * drop + if i in seam: + point[0] = 0.0 + skirt[i] = point + under = {i: n + m for m, i in enumerate(walled)} + centre = n + len(walled) + verts = [[round(float(x), 6) + 0.0 for x in p] for p in list(P) + [skirt[i] for i in walled] + [middle + out_ * dome]] + faces, creases = [], [] + for i in range(n): + j = (i + 1) % n + faces.append([i, j, centre]) + creases.append([i, j, 1.0]) + if not (i in seam and j in seam): + faces.append([under[i], under[j], j, i]) + pinned = [[i, 1.0] for i in corners] + [[under[i], 1.0] for i in corners if i in under] + poles = ([] if n == 4 else [centre]) + sorted(i for i in seam if i in under) + document = {"verts": verts, "faces": faces, "creases": creases, "corners": pinned, "poles": sorted(poles), "rim": 0.0} + if mirror: + document["mirror"] = True + if flip: + document["flip"] = True + return document + + +def block_plate(views, plate, traces, parse, plane=None, share=0.1, tol=TOL): + """A plate's first cage from traces of its outline across solved views; docs/reference.md, "block_plate". + + plate {"corners": [names, in loop order], "mirror": bool, "seam": [corner names on x = 0]}: side i runs from + corner i to corner i + 1 and is one hard crease of the crown + traces [{"from", "to": two consecutive corners, "side": 1, or -1 for the mirrored half or partner, "line": + [[u, v], ...] drawn from `from` to `to`}]; "camera", "box" and "frame" are the caller's and are echoed + views per trace, (camera record, the 4 x 4 that carries the plate's coordinates to the world as that view + poses the part): the plate's own frame, or the trace's "frame" where it states one + parse brokkr_kitbash.core.sheet, the cage's one parser: every sheet built here goes through it + plane {"point", "normal"} in the plate's coordinates, or None for the plane through the corners the views + or the seam decide + + The one correspondence is a trace's two ends to its named corners. The crown's points (the corners and each + side's points between them) are solved by fit_runs: its residual on every trace, and for a prior each crown + point's distance to the plane (one pixel per share x diag, diag the corners' extent) and each side's second + differences (one pixel per FAIR x the side's chord). A distance to a plane does not resist a move in the + plane, so the views decide wherever they see. A side starts as its two corners; a side with a trace not + explained gains a point and the plate is solved again, to K_MAX points. Skirt and centre are rebuilt from the + solved crown (plate_sheet). Returns {"sheet", "fit_traces", "left_out", "corners", "sides", "plane", "rounds"}; + raises ReferenceFitError naming the field for everything it refuses.""" + if not isinstance(plate, dict) or set(plate) - {"corners", "mirror", "seam"}: + raise ReferenceFitError("plate must be {corners, mirror, seam}") + names, mirror, seam_names = plate.get("corners"), plate.get("mirror", False), plate.get("seam", []) + if not isinstance(names, list) or len(names) < 3 or not all(isinstance(name, str) and name for name in names) or len(set(names)) != len(names): + raise ReferenceFitError("plate.corners must be three or more different names, in the outline's order") + if not isinstance(mirror, bool): + raise ReferenceFitError(f"plate.mirror must be true or false, not {mirror!r}") + N, at = len(names), {name: i for i, name in enumerate(names)} + if not isinstance(seam_names, list) or any(name not in at for name in seam_names) or len(set(seam_names)) != len(seam_names): + raise ReferenceFitError("plate.seam must name corners of plate.corners, none twice") + held = {at[name] for name in seam_names} + if mirror != bool(held) or (mirror and (not 2 <= len(held) < N or sum(1 for i in held if (i + 1) % N not in held) != 1)): + raise ReferenceFitError("plate.seam must name two or more corners next to each other in the outline, and not all of them, on a mirrored plate, and none otherwise: " + "the halves meet along the sides between them. A plate that only has a partner across x = 0 is not mirrored: trace the partner with side -1") + if not isinstance(traces, list) or not traces: + raise ReferenceFitError("traces must be an array of one or more {camera, box, frame, from, to, side, line}") + if len(views) != len(traces): + raise ReferenceFitError(f"views must be one (camera, frame) a trace: {len(views)} for {len(traces)} traces") + seen_by, per_side, runs_of, frames = [dict() for _ in names], [[] for _ in names], [], [] + for k, trace in enumerate(traces): + where = f"traces[{k}]" + if not isinstance(trace, dict) or set(trace) - set(TRACE_KEYS): + raise ReferenceFitError(f"{where} must be {{camera, box, frame, from, to, side, line}}") + a, b, side = trace.get("from"), trace.get("to"), trace.get("side", 1) + if a not in at or b not in at: + raise ReferenceFitError(f"{where}.from and .to must name corners of plate.corners, not {a!r} and {b!r}") + step = (at[b] - at[a]) % N + if step not in (1, N - 1): + raise ReferenceFitError(f"{where}.from {a!r} and .to {b!r} are not consecutive corners: a trace is one side of the outline, drawn from one corner to the next") + if side not in (1, -1) or isinstance(side, bool): + raise ReferenceFitError(f"{where}.side must be 1, or -1 for the mirrored half or partner, not {side!r}") + cam, frame = views[k] + if cam is None: + raise ReferenceFitError(f"{where}.camera {trace.get('camera')!r} is no camera of this plate") + try: + F = np.array(frame, float) + except (TypeError, ValueError): + F = np.zeros(0) + if F.shape != (4, 4) or not np.isfinite(F).all() or np.abs(F[:3, :3].T @ F[:3, :3] - np.eye(3)).max() > 1e-6 or np.abs(F[3] - [0, 0, 0, 1]).max() > 1e-9: + raise ReferenceFitError(f"{where}.frame must be a 4 x 4 that only turns and moves the part: a scaled or sheared frame is not metres of the plate") + try: + line = np.array(trace.get("line"), float) + except (TypeError, ValueError): + line = np.zeros(0) + if line.ndim != 2 or line.shape[1] != 2 or len(line) < 2 or not np.isfinite(line).all() or np.linalg.norm(np.diff(line, axis=0), axis=1).sum() < 1e-9: + raise ReferenceFitError(f"{where}.line must be two or more [u, v] points, not all in one place") + F = _partner(F, side) + frames.append(F) + i = at[a] if step == 1 else at[b] + per_side[i].append(k) + runs_of.append((i, step == 1)) + view = (json.dumps([cam["C"], cam["R"], cam["f"], cam["c"]], default=float), F.tobytes()) + for corner, pixel in ((at[a], line[0]), (at[b], line[-1])): + seen_by[corner].setdefault(view, (cam, F, [], k))[2].append(pixel) + for i, name in enumerate(names): + if not seen_by[i]: + raise ReferenceFitError(f"plate.corners[{i}] {name!r}: no trace ends at it. Every corner is the end of a traced side") + for i, name in enumerate(names): + if not per_side[i]: + raise ReferenceFitError(f"the side from {name!r} to {names[(i + 1) % N]!r} is traced in no view: every side of the outline is traced, or the plate is given fewer corners") + lines = sum(len(json.dumps(trace.get("line"), separators=(",", ":"))) for trace in traces) + size = 44 * (2 * N * (K_MAX - 1) + 1) + 34 * N * (K_MAX - 1) + lines + 90 * len(traces) + 150 * N + 400 + if size > RESULT_LIMIT: + raise ReferenceFitError(f"traces: the sheet and its report could be about {size} characters, over the {RESULT_LIMIT} a receipt carries: nothing was solved. " + "Trace with fewer points, or block the plate as two") + + start, parallax, decided = np.zeros((N, 3)), np.zeros(N), np.zeros(N, bool) + obs = [[(cam, F, 1, np.mean(pixels, axis=0)) for cam, F, pixels, _ in seen_by[i].values()] for i in range(N)] + for i in range(N): + if i in held or len(obs[i]) >= 2: + start[i], parallax[i], _, _ = triangulate(obs[i], seam=i in held) + decided[i] = i in held or parallax[i] >= PARALLAX + if plane is None: + if decided.sum() < 3: + raise ReferenceFitError(f"plane: none was given, and {', '.join(repr(names[i]) for i in np.flatnonzero(~decided))} are seen by one view only (or by views under " + f"{PARALLAX:g} degrees apart): three corners the views or the seam decide make the plane. Give plane, or trace those corners in another view") + point = start[decided].mean(0) + _, spread, axes = np.linalg.svd(start[decided] - point) + if spread[1] < 1e-6 * max(spread[0], 1e-12): + raise ReferenceFitError("plane: none was given, and the corners the views decide stand in one line. Give plane") + normal, source = axes[2], "corners" + else: + try: + point, normal = np.array(plane["point"], float), np.array(plane["normal"], float) + fine = point.shape == (3,) and normal.shape == (3,) and np.isfinite(point).all() and np.isfinite(normal).all() and np.linalg.norm(normal) > 1e-9 + except (TypeError, ValueError, KeyError): + fine = False + if not fine: + raise ReferenceFitError("plane must be {point: [x, y, z], normal: [x, y, z]} in the plate's frame, the normal not zero") + normal, source = _unit(normal), "given" + for i in np.flatnonzero(~decided): + lifted = [] + for cam, F, pixels, k in seen_by[i].values(): + o, d = _sight(cam, F, np.mean(pixels, axis=0)) + square = abs(float(normal @ d)) + if square < SQUARE: + raise ReferenceFitError(f"plate.corners[{i}] {names[i]!r}: the plane stands {math.degrees(math.acos(square)):.0f} degrees off square-on to the view of traces[{k}], the " + f"only depth this corner has. A trace lifted onto it stretches past {1 / SQUARE:g} times: turn plane to the face the view shows, or trace the corner in another view") + lifted.append(o + d * (((point - o) @ normal) / (d @ normal))) + start[i] = np.mean(lifted, axis=0) + free_ = [i for i in range(N) if i not in held] + + def crossed(corners_, what): + side_ = 1.0 if sum(1 for i in free_ if corners_[i, 0] > 0) * 2 >= len(free_) else -1.0 + for i in free_: + if mirror and corners_[i, 0] * side_ <= 0: + raise ReferenceFitError(f"plate.corners[{i}] {names[i]!r} {what} at x = {corners_[i, 0]:.3f}, across the mirror plane from the plate's other corners. A corner on the " + "plane is named in plate.seam; one off it is traced where the views agree which side it is on") + + crossed(start, "starts") + diag = float(np.linalg.norm(np.ptp(start, axis=0))) + toward = _sight(views[0][0], frames[0], np.asarray(traces[0]["line"], float)[0])[0] - start.mean(0) + count, solves = [2] * N, 0 + while True: + solves += 1 + first = np.concatenate([[0], np.cumsum([k - 1 for k in count])]) # ring index of each corner; first[N] is the ring's size + n = int(first[N]) + ring = np.concatenate([np.linspace(start[i], start[(i + 1) % N], count[i])[:-1] for i in range(N)]) + chains = [[int(first[i]) + m for m in range(count[i] - 1)] + [int(first[i + 1]) % n] for i in range(N)] + on_seam = {v for i in range(N) if i in held and (i + 1) % N in held for v in chains[i]} | {int(first[i]) for i in held} + build = lambda crown: plate_sheet(crown, [int(first[i]) for i in range(N)], mirror=mirror, seam=sorted(on_seam), facing=toward) # noqa: E731 + + def parsed(document): + try: + return parse(document) + except Exception as refusal: # the parser's own error type is its package's + raise ReferenceFitError(f"sheet: the cage's parser does not take the plate as blocked ({refusal})") from None + + cage = parsed(build(ring)) + movable = np.zeros((len(cage.V), 3), bool) + movable[:n] = True + movable[sorted(on_seam), 0] = False + index = np.flatnonzero(movable.ravel()) + column = np.full(movable.size, -1) + column[index] = np.arange(len(index)) + column = column.reshape(-1, 3) + V0, A, b = np.asarray(cage.V, float), [], [] + + def row(parts, weight): + """One prior row: weight x the sum of factor x coordinate over `parts`, the held coordinates on its right side.""" + line_, right = np.zeros(len(index)), 0.0 + for v, c, factor in parts: + if column[v, c] >= 0: + line_[column[v, c]] += weight * factor + else: + right -= weight * factor * V0[v, c] + A.append(line_) + b.append(right) + + for v in range(n): + row([(v, c, normal[c]) for c in range(3)], 1.0) + b[-1] += float(normal @ point) + for i, chain in enumerate(chains): + fair = share * diag / (FAIR * max(float(np.linalg.norm(start[(i + 1) % N] - start[i])), 1e-9)) + for m in range(1, len(chain) - 1): + for c in range(3): + row([(chain[m - 1], c, 1.0), (chain[m], c, -2.0), (chain[m + 1], c, 1.0)], fair) + runs = [{"name": f"traces[{k}]", "chain": chains[i] if forward else chains[i][::-1], "view": k, "line": trace["line"]} for k, (trace, (i, forward)) in enumerate(zip(traces, runs_of))] + try: + V, report = fit_runs([(cam, F) for (cam, _), F in zip(views, frames)], cage, runs, movable, cage.mirror_of, share, diag, tol, prior_rows=(np.array(A), np.array(b))) + except ReferenceFitError as refusal: + rows = getattr(refusal, "traces", None) + if rows is None: + raise + grow = sorted({runs_of[k][0] for k, row_ in enumerate(rows) if row_["unexplained_px"] > tol}) + full = [i for i in grow if count[i] >= K_MAX] + if full: + error = ReferenceFitError(f"the side from {names[full[0]]!r} to {names[(full[0] + 1) % N]!r} is not explained at {K_MAX} points, the most a side is given: {refusal}") + error.traces = rows + raise error from None + for i in grow: + count[i] += 1 + continue + break + crown = V[:n] + crossed(crown[first[:N]], "ends") + document = build(crown) + parsed(document) + by_vertex = {row_["vertex"]: row_ for row_ in report["points"]} + corners = [] + for i, name in enumerate(names): + row_ = by_vertex[int(first[i])] + corners.append({"name": name, "decided_by": "mirror" if i in held else "views" if row_["prior_share"] < VIEWS else "plane", "parallax_deg": round(float(parallax[i]), 1), + "m_per_px": round(row_["m_per_px"], 4), "prior_share": round(row_["prior_share"], 3)}) + sides = [{"from": names[i], "to": names[(i + 1) % N], "points": count[i], "traces": [report["traces"][k] for k in per_side[i]]} for i in range(N)] + fit_traces, left_out = [], [] + for k, (trace, (i, forward)) in enumerate(zip(traces, runs_of)): + if (trace.get("side", 1) == -1 and not mirror) or trace.get("frame") is not None: + left_out.append(k) # fit_shell takes one frame, the shell's own, and side -1 only as a mirrored sheet's other half + continue + fit_traces.append({**{key: trace[key] for key in ("camera", "box") if key in trace}, "run": {"verts": chains[i] if forward else chains[i][::-1]}, "side": trace.get("side", 1), "line": trace["line"]}) + return {"sheet": document, "fit_traces": fit_traces, "left_out": left_out, "corners": corners, "sides": sides, + "plane": {"point": [round(float(x), 6) for x in point], "normal": [round(float(x), 6) for x in normal], "from": source}, "rounds": solves} + + # --- fields ---------------------------------------------------------------------------------------------------------- diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index bbde414..f55cf6e 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -274,6 +274,72 @@ fitted; a run's depth with no mirror partner, no second view and no mirror plane The acceptance reads nine tenths of a trace: it passes a short doubled stretch and a tip that stands off, and reports both as `worst_px`. `m_per_px` is a sensitivity to one pixel, not an error bound. +## block_plate: a plate's first cage from its traces + +`fit_shell` refines a cage somebody blocked. `brokkr_reference.block_plate` makes the first one. A plate is a +closed outline of named corners in order; side i runs from corner i to corner i + 1 and is one hard crease of the +plate's crown. A trace is one side drawn in one view, `{camera, box, frame, from, to, side, line}`: `from` and `to` +are two consecutive corners and the line is drawn from the one to the other. That is the only correspondence +there is: a trace's two ends are its two corners. Every other point of the crown is placed by `fit_shell`'s +residual, the pixel distance from the side as built to the trace. Nothing matches a point of one trace to a +point of another. + +`frame_object` is the plate's frame. A trace's `frame` is the part's pose in that view where it differs (a limb +swung, a hull pitched); `side` -1 is a view of the plate's reflection across the frame's x = 0, which is the +other half of a mirrored plate or the same plate on the partner limb. `plate` is `{corners, mirror, seam}`. On a +mirrored plate `seam` names the corners on x = 0, two or more next to each other: they are held there, the sides +between them lie on it, and one view decides them. + +Where a corner's depth comes from, in this order: + +- **the views**, where two or more see it and its sight lines stand 9.7 degrees or more apart. Under that the + triangulation is not used as a start: at 5 degrees corners of a 1.2 m plate landed 0.25 to 1.5 m off. +- **the mirror plane**, for a seam corner. +- **a plane**, for the rest: `plane` (`x,y,z; nx,ny,nz`, a point and the normal, in the frame), or with none given + the plane through the corners the views and the seam decide, three or more. A corner one view sees is lifted + onto it, and refused when the plane stands more than 66 degrees off square-on to that view: the lift stretches + past 2.5 times there. + +The crown is then solved by the same solver as `fit_shell`, with a different prior: each crown point's distance +to the plane costs a pixel per `share` x the corners' extent, and each side's second differences a pixel per 0.2 +x its chord. A distance to a plane does not resist a move in the plane, so the views decide wherever they see, +and a view that sees nothing along its own sight line leaves that to the plane. A side starts as its two +corners. After each solve a side with a trace not explained (the same nine tenths within `tol`) gains one point +and the plate is solved again, to six points a side; past that it is refused as `fit_shell` refuses a trace. + +The cage is the crown ring, a skirt 0.06 m out and 0.07 m back of it, and one centre vertex: every crown side +creased 1, the named corners pinned, the centre the declared pole unless the crown has four points. On a +mirrored plate the seam's sides have no skirt and the seam's two ends are poles too. The skirt and centre are +rebuilt from the solved crown and never solved. The sheet goes through `brokkr_kitbash`'s parser before it is +returned, and `brokkr_kitbash.shell` builds it; `block_plate` writes nothing. + +The report: `sheet`; `fit_traces`, the traces as `fit_shell` takes them (each side a run of authored vertices), +and `left_out`, the traces `fit_shell` cannot state (one with its own `frame`, or a partner's side -1 on a plate +that is not mirrored); per corner `decided_by` (`views` when the prior's share is under 0.2, `mirror` on the seam, +else `plane`), `parallax_deg`, `m_per_px` and `prior_share`; per side its points and each trace's readings; +`plane` with `from` `given` or `corners`; `rounds`, the solves it took. + +Refused, naming the field: a corner no trace ends at, a side traced in no view, a trace whose corners are not +consecutive, an unknown camera, a scaled frame, a seam that is not one stretch of the outline, no plane where +fewer than three corners are decided, the 66 degrees, a mirrored plate's corner that starts or ends across x = 0 +from the others (name it in `seam`, or trace it where the views agree), a side not explained at six points, a +sheet the cage's parser does not take, and a result that could pass the 16000 characters a receipt carries. + +Measured (`tests/test_reference.py` BlockTests, Python 3.13 on Starfire). SPECTRE's roof from no blocking: the +ridge, traced in the side view alone, 7.3 mm at most from the cage `fit_shell` had fitted from a hand blocking; +the brow, traced in the hero's mirrored half and the side 62.8 degrees apart, a median of 8.4 mm and 78.6 mm at +most from it, in four points; 0.05 s. A twisted pentagon 1.2 m across with sides bowed 8% toward the camera, +17.6 m off at 663 px: 39 and 52 mm from the truth at 60 degrees with traces 0.5 and 1.5 px off, every corner +decided by the views; 65 and 135 mm at 19 degrees, where the plane already has 0.30 to 0.38 of each corner. At +that range and lens two views 19 degrees apart do not decide a corner by this report's own line. + +What it gives up. One outline loop a plate: a plate that wraps a corner is two plates, and creases inside the +outline are not blocked. A bend smaller than `tol` is built straight: the bowed pentagon's 56 mm bow reads under +2 px and stays in the error above. Fairness holds a grown side flatter than its trace while the trace still +reads as explained: a plate whose sides bow 35% of their length ended 42 mm off its truth from exact traces, and +`fit_shell` on the returned `fit_traces` moved it 74 mm back. The plane through the decided corners is a guess +at a twisted plate, and where one view sees a corner the plane is all the depth it has: `decided_by` says so. + ## What it cannot do It solves one pinhole camera for one view: no lens distortion, no two views solved together, one turned group and @@ -281,6 +347,8 @@ no other pose. It does not find the points; marking them is the caller's. Points points on rigid features of one body, because the build's pose is not the drawing's. It does not say whether the subject is the right size: a build twice too large is the same picture from twice as far. +`block_plate` blocks one outline loop a plate and no crease inside it. + ## From a script ```python @@ -291,6 +359,7 @@ origin, direction = core.ray(cam, (u, v)) # a pixel's line of point = core.lift(cam, (u, v), plane_point, plane_normal) # a traced pixel on a plane run = core.crease_run(column) # the hard crease Blender builds from a cage column fit = core.fit_sheet(sheet, cage, frame, traces, cams) # the fitted sheet and its report; cage is brokkr_kitbash.core.sheet(sheet) +out = core.block_plate(views, plate, traces, parse) # a plate's first sheet and what decided each corner; parse is brokkr_kitbash.core.sheet score = core.along(line, segments, height) # on, off, run against [u0, v0, u1, v1] segments params = core.blender(cam, 1000) # matrix_world, lens, shifts, resolution cam2 = core.camera_of(params, box) # and back diff --git a/surfaces/blender/tests/fixtures/spectre_plates.json b/surfaces/blender/tests/fixtures/spectre_plates.json new file mode 100644 index 0000000..75bbce6 --- /dev/null +++ b/surfaces/blender/tests/fixtures/spectre_plates.json @@ -0,0 +1 @@ +{"note":"SPECTRE's roof and cheek as plates. Cameras: spectre_skel.cameras() at nibu/fable-spectre-2 74fc241, solved by this repo's brokkr_reference.core; frames: the hull pitched about the waist by spectre_skel.PITCH (hero 3 degrees, side 0). Traces marked hand are spectre_skel.TRACES (roof brow and ridge, cheek chine); a trace marked fitted-edge is the straight edge between two vertices of spectre_fits.json's fitted cage drawn through the camera, standing in for a side nobody traced, so the outline closes. reference is spectre_fits.json's fitted cage along the traced runs: a fit from a hand blocking, not ground truth.","cameras":{"hero":{"C":[-9.721115556958573,18.859090658741355,5.242272804029844],"R":[[-0.862189601405842,-0.5065857195259607,0.0],[0.034125232508362004,-0.05807984607580026,0.9977285201827507],[-0.5054350202883507,0.8602311551276064,0.06736319480204615]],"f":1785.0,"c":[378.0,353.0]},"side":{"C":[60.84416742645475,1.422308134553987,3.13474760877321],"R":[[3.061616997868383e-16,1.0,0.0],[0.011634411213376642,-3.5620111131064444e-18,0.9999323179474289],[0.9999323179474289,-3.0614097813457806e-16,-0.011634411213376642]],"f":2200.0,"c":[892.0,532.0]}},"frames":{"hero":[[1.0,0.0,0.0,0.0],[0.0,0.9986295347545738,0.052335956242943835,-0.2773805680876023],[0.0,-0.052335956242943835,0.9986295347545738,0.007263465800758873],[0.0,0.0,0.0,1.0]],"side":[[1.0,0.0,0.0,0.0],[0.0,1.0,0.0,0.0],[0.0,-0.0,1.0,0.0],[0.0,0.0,0.0,1.0]]},"plates":{"roof":{"plate":{"corners":["ridge_rear","nose","brow_rear"],"mirror":true,"seam":["ridge_rear","nose"]},"traces":[{"view":"side","from":"ridge_rear","to":"nose","side":1,"line":[[883,400],[898,408],[930,426],[958,441]],"source":"hand"},{"view":"hero","from":"brow_rear","to":"nose","side":-1,"line":[[487,47],[443,92],[427,126],[400,128],[360,135],[325,142]],"source":"hand"},{"view":"side","from":"brow_rear","to":"nose","side":1,"line":[[883,404],[900.7,413.6],[919,423.6],[938.6,436.4],[958.6,443]],"source":"hand"},{"view":"hero","from":"brow_rear","to":"ridge_rear","side":-1,"line":[[487.1,47.1],[424.7,35.3]],"source":"fitted-edge"},{"view":"side","from":"brow_rear","to":"ridge_rear","side":1,"line":[[883.0,404.1],[883.0,399.9]],"source":"fitted-edge"}],"reference":{"ridge":[[0.0,1.173941,7.498167],[0.0,2.063931,7.015758],[0.0,2.624251,6.687296],[0.0,3.079302,6.461668],[0.0,3.280227,6.334663]],"brow":[[0.776479,1.177565,7.327593],[0.653669,2.30313,6.743599],[0.929821,2.609515,6.428508],[0.197231,2.908778,6.436474],[0.0,3.280227,6.334663]]}},"cheek":{"plate":{"corners":["chine_rear","jaw","chin"],"mirror":true,"seam":["jaw","chin"]},"traces":[{"view":"hero","from":"chine_rear","to":"jaw","side":-1,"line":[[472,169],[438,180],[390,170],[312,182]],"source":"hand"},{"view":"side","from":"chine_rear","to":"jaw","side":1,"line":[[919,447],[945,456.5],[961,459]],"source":"hand"},{"view":"side","from":"jaw","to":"chin","side":1,"line":[[965.6,456.7],[957.7,463.1]],"source":"fitted-edge"},{"view":"hero","from":"chin","to":"chine_rear","side":-1,"line":[[331.3,199.5],[472.1,167.8]],"source":"fitted-edge"},{"view":"side","from":"chin","to":"chine_rear","side":1,"line":[[957.7,463.1],[921.1,451.0]],"source":"fitted-edge"}],"reference":{"chine":[[1.097992,2.211844,6.0315],[0.924701,2.658187,5.897007],[0.340462,2.978516,6.057156],[0.0,3.458134,5.926945]]}}}} \ No newline at end of file diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index db8af73..1f06e16 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -717,6 +717,241 @@ class FitTests(unittest.TestCase): core.fit_sheet(sheet_, kit.sheet(sheet_), FIT_FRAME, traces, cams) +EYE = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] +PLATE = [f"c{i}" for i in range(5)] +ON_Y = {"point": [0, 0, 0], "normal": [0, 1, 0]} + + +def plate_camera(azimuth, distance=17.6, f=663.0): + """A camera `distance` off the origin, level, turned `azimuth` degrees from looking along +y: Paladin's hero's + lens and range (663 px, 17.6 m).""" + a = math.radians(azimuth) + C = distance * np.array([math.sin(a), -math.cos(a), 0.0]) + right = np.cross(-C / distance, [0, 0, 1.0]) + right /= np.linalg.norm(right) + return {"C": C.tolist(), "R": np.stack([right, np.cross(right, -C / distance), C / distance]).tolist(), "f": f, "c": [500.0, 500.0]} + + +def pentagon(bow, lateral=0.0, twist=0.15): + """The sides of a pentagon plate 1.2 m across facing -y, as five-point cage chains: its corners `twist` metres + off the plane y = 0 (a twisted plate), each side bowed `bow` of its length toward -y, which a view from there + sees end on, and `lateral` of it outward in the plate.""" + angles = [2 * math.pi * i / 5 + 0.3 for i in range(5)] + P = np.array([[0.6 * math.cos(t), twist * math.cos(2 * t), 0.6 * math.sin(t)] for t in angles]) + s, sides = np.linspace(0, 1, 5)[:, None], [] + for a, b in zip(P, np.roll(P, -1, axis=0)): + sides.append(a + s * (b - a) + np.sin(math.pi * s) * np.linalg.norm(b - a) * (bow * np.array([0, -1.0, 0]) + lateral * (a + b) / np.linalg.norm(a + b))) + return sides + + +def plate_traces(cams, sides, sigma=0.0, seed=7): + """(views, traces) of a plate's sides as built, drawn through each camera in 12 points, `sigma` px of noise.""" + rng, views, traces = np.random.default_rng(seed), [], [] + for i, side in enumerate(sides): + for k, cam in enumerate(cams): + u = core.resampled(core.project(cam, core.crease_run(core.crease_run(side))), 12) + traces.append({"camera": f"View{k}", "from": PLATE[i], "to": PLATE[(i + 1) % 5], "side": 1, "line": (u + rng.normal(0, sigma, u.shape)).tolist()}) + views.append((cam, EYE)) + return views, traces + + +def crown_chains(out): + """Per side of a block_plate report, its crown vertices in the sheet.""" + n, first, chains = sum(side["points"] - 1 for side in out["sides"]), 0, [] + for side in out["sides"]: + chains.append([(first + m) % n for m in range(side["points"])]) + first += side["points"] - 1 + return chains + + +def off_run(out, chain, truth): + """The furthest a blocked side as built stands from a true cage chain as built, metres.""" + built = core.crease_run(core.crease_run(np.array(out["sheet"]["verts"])[chain])) + return core._off(built, core.resampled(core.crease_run(core.crease_run(np.asarray(truth, float))), 400)) + + +def off_plate(out, sides): + return max(float(off_run(out, chain, side).max()) for chain, side in zip(crown_chains(out), sides)) + + +def blocked_plate(views, traces, **more): + return core.block_plate(views, {"corners": PLATE}, traces, kit.sheet, **more) + + +@unittest.skipIf(np is None, "numpy") +class BlockTests(unittest.TestCase): + """block_plate: a plate's first cage from traces of its outline. Bounds follow + lodur:ruling:deterministic-bound-margin; the other numbers are tolerances round a known truth. Mutants, each + run once on a copy: + M1 no end terms test_spectre_roof_and_cheek + M2 a point prior (fit_shell's) for the plane distance test_one_view_and_a_plane_block_a_bowed_plate + M3 a seam corner's x free test_spectre_roof_and_cheek + M5 the 66 degree guard off test_a_plane_far_off_square_on_to_its_one_view_is_refused + M6 no growth (K_MAX 2) test_a_side_grows_until_its_trace_is_explained, test_spectre_roof_and_cheek + M4 no fairness test_spectre_roof_and_cheek + + M4 is claimed by one reading, SPECTRE's brow (a median of 8.4 mm with fairness, 19.8 without), against a + reference that is itself a fit. Against a known truth it reads the other way: the bowed plate of + test_a_side_grows_until_its_trace_is_explained ends 41.6 mm off with fairness and 12.1 without, the one-view + bowed plate 85.1 mm with it and 2.7 without, the twisted plate at 19 degrees and 1.5 px 135.1 either way. FAIR + 0.2 came from five-point chains under noise (research probe-synthetic-sensitivity); a side grown only as far + as its trace asks has less for fairness to hold. + + The twisted, bowed plate does not block within 1.35 x noise x m_per_px, the probe's figure for five-point + chains: its bow toward the first camera is 56 mm, under 2 px at 60 degrees, the default tol explains it with a + straight side, and what is left is the bow (test_a_twisted_bowed_plate_blocks_from_two_views).""" + + def test_a_twisted_bowed_plate_blocks_from_two_views(self): + """block-synthetic. Views 60 and 19 degrees apart, traces 0.5 and 1.5 px off: every trace is explained with + two points a side, and the crown as built ends 39.3, 52.1 (60 degrees) and 65.0, 135.1 mm (19) from the + truth, 1.46 to 4.23 times noise x the worst corner's m_per_px. At 60 degrees every corner is decided by the + views (prior_share 0.138 at most, under core.VIEWS by 1.45); at 19 the plane has 0.30 to 0.38 of each.""" + sides = pentagon(0.08) + for apart, sigma, most, by in ((60, 0.5, 0.06, "views"), (60, 1.5, 0.08, "views"), (19, 0.5, 0.1, "plane"), (19, 1.5, 0.2, "plane")): + out = blocked_plate(*plate_traces([plate_camera(0), plate_camera(apart)], sides, sigma)) + self.assertLess(off_plate(out, sides), most, (apart, sigma)) + self.assertEqual({corner["decided_by"] for corner in out["corners"]}, {by}, (apart, sigma)) + self.assertLess(max(abs(corner["parallax_deg"] - apart) for corner in out["corners"]), 1.5) + self.assertEqual(out["plane"]["from"], "corners") + kit.sheet(out["sheet"]) + + def test_views_5_degrees_apart_take_their_depth_from_a_plane_or_are_refused(self): + """block-low-parallax. At 5 degrees the corners triangulate 0.25 to 1.5 m off (the probe): under + core.PARALLAX the views start no corner. With a plane every corner is decided by it (prior_share 0.795 to + 0.838); with none the plate is refused naming the corners.""" + views, traces = plate_traces([plate_camera(0), plate_camera(5)], pentagon(0.08), 0.5) + out = blocked_plate(views, traces, plane=ON_Y) + self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["plane"] * 5) + self.assertGreater(min(corner["prior_share"] for corner in out["corners"]), 0.7) + self.assertEqual(out["plane"]["from"], "given") + with self.assertRaisesRegex(core.ReferenceFitError, r"^plane: none was given, and 'c0', 'c1', 'c2', 'c3', 'c4' are seen by one view only"): + blocked_plate(views, traces) + + def test_a_side_grows_until_its_trace_is_explained(self): + """block-growth, M6. A straight-sided plate blocks with its corners alone, 1.9 mm from the truth (the plane + draws its twisted corners in). Sides bowed 35% of their length in the plate grow to three points and every + trace reads under 1 px; M6 refuses the plate, its first side not explained at two points. The grown crown + ends 41.6 mm off: fairness holds the bow in while the traces stay explained (M4, in the class's notes).""" + cams = [plate_camera(0), plate_camera(60)] + out = blocked_plate(*plate_traces(cams, pentagon(0.0))) + self.assertEqual(([side["points"] for side in out["sides"]], out["rounds"], len(out["sheet"]["verts"])), ([2] * 5, 1, 11)) + self.assertLess(off_plate(out, pentagon(0.0)), 0.004) + sides = pentagon(0.08, 0.35) + out = blocked_plate(*plate_traces(cams, sides)) + self.assertEqual(([side["points"] for side in out["sides"]], out["rounds"], len(out["sheet"]["verts"])), ([3] * 5, 2, 21)) + self.assertLess(max(trace["unexplained_px"] for side in out["sides"] for trace in side["traces"]), core.TOL / 1.2) + self.assertLess(off_plate(out, sides), 0.06) + + def test_one_view_and_a_plane_block_a_bowed_plate(self): + """M2. A flat plate in the plane it is given, its sides bowed 35% in the plate, traced exactly in one view + 30 degrees off square-on: every corner is decided by the plane, the sides grow to three points and the + crown ends 85.1 mm off the truth. M2, which holds each point where it was started instead of to the plane, + ends 109.7 mm off: the bound is their geometric mean, separation 1.14 each side (1.29 across), the least + the ruling takes.""" + sides = pentagon(0.0, 0.35, twist=0.0) + out = blocked_plate(*plate_traces([plate_camera(30)], sides), plane=ON_Y) + self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["plane"] * 5) + self.assertEqual([corner["parallax_deg"] for corner in out["corners"]], [0.0] * 5) + self.assertEqual([side["points"] for side in out["sides"]], [3] * 5) + self.assertLess(off_plate(out, sides), 0.0966) + + def test_a_plane_far_off_square_on_to_its_one_view_is_refused(self): + """M5: the guard promoted from the Paladin harness (paladin_limbs.plate, the 8 m pauldron). One view 64 + degrees off the plane's normal blocks the plate on it; at 68 degrees (cosine 0.375, under core.SQUARE) the + plate is refused naming the corner, the trace and the angle. M5 blocks it.""" + sides = pentagon(0.0, twist=0.0) + out = blocked_plate(*plate_traces([plate_camera(64)], sides), plane=ON_Y) + self.assertLess(off_plate(out, sides), 1e-4) + with self.assertRaisesRegex(core.ReferenceFitError, r"^plate\.corners\[0\] 'c0': the plane stands 67 degrees off square-on to the view of traces\[0\]"): + blocked_plate(*plate_traces([plate_camera(68)], sides), plane=ON_Y) + + def spectre(self, name): + fixture = json.loads((Path(__file__).resolve().parent / "fixtures" / "spectre_plates.json").read_text(encoding="utf-8")) + plate = fixture["plates"][name] + traces = [{"camera": trace["view"], **{key: trace[key] for key in ("from", "to", "side", "line")}, **({"frame": fixture["frames"]["hero"]} if trace["view"] == "hero" else {})} for trace in plate["traces"]] + return fixture, plate, core.block_plate([(fixture["cameras"][trace["view"]], fixture["frames"][trace["view"]]) for trace in plate["traces"]], plate["plate"], traces, kit.sheet) + + def test_spectre_roof_and_cheek(self): + """block-spectre, M1, M3, M6. SPECTRE's roof and cheek from no blocking (tests/fixtures/spectre_plates.json: + the brow, ridge and chine are hand traces, the sides nobody traced are edges of the fitted cage). Roof: the + brow's free corner is decided by the views (62.8 degrees, prior_share 0.054), the ridge's two by the mirror + plane; the ridge, traced in the side view alone, is built 7.3 mm at most from the fitted ridge and the brow + a median of 8.4 mm from the fitted brow (78.6 at most), in four points. M1 reads 27.7 and 18.9 (M4 19.8 on the brow): the bounds + are the geometric means, separations 1.95 and 1.50 each side. Cheek: the jaw, where the two hand traces + disagree by 0.27 m, stays on x = 0. M3 lands the roof's nose at x = -0.049 and the jaw at -0.140 and the + cage's parser refuses both; M1 puts the cheek's skirt across the plane and it is refused; M6 refuses both + at two points a side.""" + fixture, plate, out = self.spectre("roof") + self.assertEqual([(corner["name"], corner["decided_by"]) for corner in out["corners"]], [("ridge_rear", "mirror"), ("nose", "mirror"), ("brow_rear", "views")]) + self.assertLess(out["corners"][2]["prior_share"], core.VIEWS / 1.2) + self.assertGreater(out["corners"][2]["parallax_deg"], 60) + ridge, brow, rear = crown_chains(out) + self.assertEqual([side["points"] for side in out["sides"]], [2, 4, 2]) + self.assertLess(float(off_run(out, ridge, plate["reference"]["ridge"]).max()), 0.0142) + self.assertLess(float(np.median(off_run(out, brow, plate["reference"]["brow"]))), 0.0126) + verts = np.array(out["sheet"]["verts"]) + self.assertEqual(float(np.abs(verts[ridge, 0]).max()), 0.0) + self.assertEqual(out["left_out"], [1, 3]) # the hero poses the hull 3 degrees down: fit_shell has one frame + self.assertEqual([trace["run"] for trace in out["fit_traces"]], [{"verts": ridge}, {"verts": brow[::-1]}, {"verts": rear}]) + fixture, plate, out = self.spectre("cheek") + self.assertEqual([(corner["name"], corner["decided_by"]) for corner in out["corners"]], [("chine_rear", "views"), ("jaw", "mirror"), ("chin", "mirror")]) + chine, seam, _ = crown_chains(out) + self.assertEqual([float(x) for x in np.array(out["sheet"]["verts"])[seam, 0]], [0.0, 0.0]) + self.assertEqual(out["sheet"]["mirror"], True) + self.assertEqual(out["sheet"]["poles"], [seam[0], seam[1], len(out["sheet"]["verts"]) - 1]) + + def test_the_blocking_goes_to_the_parser_and_to_fit_shell(self): + """block-then-fit without Blender (tests/live/reference_block.py builds it): the sheet is one the cage's + parser takes, fit_traces name each side as a run of authored vertices, and fit_sheet takes both. On the + straight plate fit_shell's own prior moves no point 5 mm (2.2 at most: the plane had drawn the twisted + corners in); on the bowed plate it moves the grown points up to 74 mm, back toward the bow fairness held in.""" + cams = [plate_camera(0), plate_camera(60)] + for sides, most in ((pentagon(0.0), 0.005), (pentagon(0.08, 0.35), 0.09)): + views, traces = plate_traces(cams, sides) + out = blocked_plate(views, traces) + self.assertEqual((len(out["fit_traces"]), out["left_out"]), (10, [])) + self.assertEqual(set(out["fit_traces"][0]), {"camera", "run", "side", "line"}) + fit = core.fit_sheet(out["sheet"], kit.sheet(out["sheet"]), EYE, out["fit_traces"], [cam for cam, _ in views]) + self.assertLess(max(point["moved_m"] for point in fit["points"]), most) + self.assertLess(len(json.dumps(out, separators=(",", ":"))), core.RESULT_LIMIT) + + def test_block_refusals_name_their_field(self): + """block-refusals.""" + cams = [plate_camera(0), plate_camera(60)] + views, traces = plate_traces(cams, pentagon(0.0)) + + def refused(pattern, views_=views, traces_=traces, plate=None, parse=None, **more): + with self.assertRaisesRegex(core.ReferenceFitError, pattern): + core.block_plate(views_, plate or {"corners": PLATE}, traces_, parse or kit.sheet, **more) + + keep = [k for k, trace in enumerate(traces) if trace["from"] != "c2"] + refused(r"^the side from 'c2' to 'c3' is traced in no view", [views[k] for k in keep], [traces[k] for k in keep]) + keep = [k for k, trace in enumerate(traces) if trace["from"] not in ("c1", "c2")] + refused(r"^plate\.corners\[2\] 'c2': no trace ends at it", [views[k] for k in keep], [traces[k] for k in keep]) + refused(r"^traces\[0\]\.from 'c0' and \.to 'c2' are not consecutive corners", traces_=[{**traces[0], "to": "c2"}] + traces[1:]) + refused(r"^traces\[0\]\.from and \.to must name corners", traces_=[{**traces[0], "to": "c9"}] + traces[1:]) + refused(r"^traces\[3\]\.camera 'View1' is no camera of this plate", views[:3] + [(None, EYE)] + views[4:]) + refused(r"^traces\[1\]\.frame must be a 4 x 4 that only turns and moves", views[:1] + [(cams[1], (2 * np.eye(4)).tolist())] + views[2:]) + refused(r"^traces\[2\]\.side must be 1, or -1", traces_=traces[:2] + [{**traces[2], "side": 2}] + traces[3:]) + refused(r"^traces\[2\]\.line must be two or more", traces_=traces[:2] + [{**traces[2], "line": [[1, 2]]}] + traces[3:]) + refused(r"^traces\[2\] must be \{camera, box, frame, from, to, side, line\}", traces_=traces[:2] + [{**traces[2], "run": {}}] + traces[3:]) + refused(r"^plate\.corners must be three or more different names", plate={"corners": ["a", "b"]}) + refused(r"^plate\.seam must name two or more corners next to each other", plate={"corners": PLATE, "mirror": True, "seam": ["c0"]}) + refused(r"^plate\.seam must name two or more corners next to each other", plate={"corners": PLATE, "seam": ["c0", "c1"]}) + refused(r"^plane must be \{point: \[x, y, z\], normal: \[x, y, z\]\}", plane={"point": [0, 0, 0], "normal": [0, 0, 0]}) + + def no(document): + raise kit.KitError("sheet.verts[0] is not to its taste") + + refused(r"^sheet: the cage's parser does not take the plate as blocked \(sheet\.verts\[0\] is not to its taste\)", parse=no) + long = [{**trace, "line": core.resampled(np.array(trace["line"]), 160).round(1).tolist()} for trace in traces] + refused(r"^traces: the sheet and its report could be about \d+ characters, over the 16000", traces_=long) + # a mirrored plate's corner drawn across the mirror plane from the others + P, names = np.array([[0, 0, 0.5], [0, 0, -0.5], [0.5, 0.1, -0.4], [-0.05, 0.1, 0.4]]), ["a", "b", "c", "d"] + mirrored = [{"from": names[i], "to": names[(i + 1) % 4], "side": 1, "line": core.project(cam, P[[i, (i + 1) % 4]]).tolist()} for i in range(4) for cam in cams] + refused(r"^plate\.corners\[3\] 'd' starts at x = -0\.050, across the mirror plane", [(cam, EYE) for _ in range(4) for cam in cams], mirrored, {"corners": names, "mirror": True, "seam": ["a", "b"]}) + + @unittest.skipIf(np is None, "numpy") class CameraTests(unittest.TestCase): CAM = {"C": [3.0, -7.0, 2.5], "f": 1400.0, "c": [640.0, 395.0], "box": BOX} @@ -780,8 +1015,8 @@ class HostFileTests(unittest.TestCase): def test_the_row_names_the_operator_and_properties_the_add_on_defines(self): source = (SURFACE / "brokkr_reference" / "__init__.py").read_text(encoding="utf-8") - self.assertEqual([row["name"] for row in self.document["actions"]], ["brokkr_reference.solve_camera", "brokkr_reference.flow_score", "brokkr_reference.fit_shell"]) - self.assertEqual(source.count("bl_idname = "), 3) + self.assertEqual([row["name"] for row in self.document["actions"]], ["brokkr_reference.solve_camera", "brokkr_reference.flow_score", "brokkr_reference.fit_shell", "brokkr_reference.block_plate"]) + self.assertEqual(source.count("bl_idname = "), 4) for row in self.document["actions"]: self.assertIn(f'bl_idname = "{row["name"]}"', source) self.assertEqual(row.get("result"), "brokkr_mesh_polish_result") @@ -807,6 +1042,11 @@ class HostFileTests(unittest.TestCase): for bad in ({"tol": 0}, {"share": 11}, {"traces": ""}, {"object_name": "x" * 64}): with self.assertRaises(at.IntentInvalid): at.validate({**fit, **bad}, self.host) + block = {**self.envelope, "action": "brokkr_reference.block_plate", "frame_object": "Frame", "plate": "{}", "traces": "[{}]"} + self.assertEqual((at.validate(block, self.host)["share"], at.validate(block, self.host)["tol"], at.validate(block, self.host)["plane"]), (0.1, core.TOL, "")) + for bad in ({"tol": 0}, {"share": 11}, {"traces": ""}, {"plate": ""}, {"frame_object": "x" * 64}, {"plane": "x" * 201}): + with self.assertRaises(at.IntentInvalid): + at.validate({**block, **bad}, self.host) class OwnershipTests(unittest.TestCase): @@ -827,7 +1067,7 @@ class OwnershipTests(unittest.TestCase): decided by matching trace points to each other.""" for path in (SURFACE / "brokkr_reference").glob("*.py"): text = path.read_text(encoding="utf-8") - self.assertIsNone(re.search(r"def pair|_smoothest|cage_through|on_plane", text), path.name) + self.assertIsNone(re.search(r"def pair|_smoothest|cage_through|on_plane|epipolar", text), path.name) self.assertIsNone(re.search(r"SHELL\] *=|kit_shell\"\] *=|\.data\.vertices|foreach_set|from_pydata", text), path.name) def test_no_other_package_names_this_one(self): From 5de5c3b5b19f93e03de990d62c9c7d154144bd35 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 08:57:27 +0100 Subject: [PATCH 185/223] tests/live/reference_block.py: block_plate through run_intent in Blender 5.3, the sheet built by brokkr_kitbash.shell, fit_shell on its fit_traces, a mirrored plate's seam built where crease_run says Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/reference.md | 4 +- .../blender/tests/live/reference_block.py | 244 ++++++++++++++++++ .../tests/live/reference_block.result.json | 175 +++++++++++++ 3 files changed, 422 insertions(+), 1 deletion(-) create mode 100644 surfaces/blender/tests/live/reference_block.py create mode 100644 surfaces/blender/tests/live/reference_block.result.json diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index f55cf6e..c53f107 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -370,4 +370,6 @@ through the action and rendered again; `reference.result.json` is its last run) (`crease_run` against Blender's own subdivision, a box and a folded sheet scored by `flow_score`; `reference_flow.result.json` is its last run) and `tests/live/reference_fit.py` (a mirrored loft and a mirrored free cage, each blocked off its design, fitted through the action and rebuilt by `brokkr_kitbash.shell`; -`reference_fit.result.json` is its last run). +`reference_fit.result.json` is its last run) and `tests/live/reference_block.py` (a bowed plate and a mirrored plate +blocked through the action from traces alone, built by `brokkr_kitbash.shell` and handed to `fit_shell`; +`reference_block.result.json` is its last run). diff --git a/surfaces/blender/tests/live/reference_block.py b/surfaces/blender/tests/live/reference_block.py new file mode 100644 index 0000000..7af9c42 --- /dev/null +++ b/surfaces/blender/tests/live/reference_block.py @@ -0,0 +1,244 @@ +"""Live proof, in a background Blender, of brokkr_reference.block_plate through run_intent. + +A plate stands in a frame turned and moved in the world: an empty, "Frame". Its truth is a five-sided crown with +bowed sides, built by brokkr_kitbash.shell from core.plate_sheet, and two cameras 60 degrees apart look at it. Each +side is traced in both views where Blender's own projection draws the side as core.crease_run builds it. Then: + + block_plate from the frame, the corner names and the ten traces, no blocking: a sheet with every trace + explained, each corner decided by the views, nothing written to the scene + built brokkr_kitbash.shell takes the sheet without refusal, and at one level Blender builds each crown + side where core.crease_run says + fit_shell with the returned fit_traces on the built plate: accepted, every trace explained, and no point + moved further than the unit test's reading allows (tests/test_reference.py + test_the_blocking_goes_to_the_parser_and_to_fit_shell: fairness holds a bowed side in, and + fit_shell's own prior lets it out) + mirrored a mirrored plate with two seam corners, traced the same way: the seam stays on x = 0, + brokkr_kitbash.shell builds both halves, and Blender builds the seam's side and a free side where + core.crease_run says + refusals a scaled frame, an unknown camera and a side nobody traced, each a failed receipt naming its cause + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_block.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). is an absolute path: it writes .result.json and exits 1 when a check failed. Not part +of the unittest run: it needs Blender. +""" +import json +import math +import os +import sys +import tempfile +import time +import traceback +import types +from pathlib import Path + +import bpy +import numpy as np +from bpy_extras.object_utils import world_to_camera_view +from mathutils import Euler, Matrix, Vector + +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 os.path.isabs(OUT): + raise SystemExit(f" must be an absolute path, not {OUT!r}: a relative one lands in Blender's start directory") +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 + +sys.path.append(str(SURFACE)) +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_kitbash", "brokkr_reference"): + addon_utils.enable(module, default_set=True) +from brokkr_reference import core # noqa: E402 + +target = bt.BrokkrBlenderTarget(bpy) +target.configure_action_dirs("", tempfile.mkdtemp(prefix="brokkr-reference-block-live-")) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], + "hostRows": [row["name"] for row in target.host_actions()[0]]} +COUNT = [0] +T0 = time.time() +WIDTH, HEIGHT = 1000, 800 +MOVED = 0.09 # metres fit_shell may move a point of the blocked bowed plate: the unit test's tolerance round its reading of 0.074 + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +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 = json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None + print("SEND", f"{time.time() - T0:.1f}s", action, receipt["status"], str(receipt["message"])[:400], flush=True) + return receipt, result + + +def built(chain): + return core.crease_run(core.crease_run(np.asarray(chain, float))) + + +def pentagon(): + """Five sides as five-point cage chains: a plate 1.2 m across facing -y, its corners up to 0.15 m off the plane + y = 0, each side bowed 8% of its length toward -y and 35% outward in the plate.""" + angles = [2 * math.pi * i / 5 + 0.3 for i in range(5)] + P = np.array([[0.6 * math.cos(t), 0.15 * math.cos(2 * t), 0.6 * math.sin(t)] for t in angles]) + s, sides = np.linspace(0, 1, 5)[:, None], [] + for a, b in zip(P, np.roll(P, -1, axis=0)): + sides.append(a + s * (b - a) + np.sin(math.pi * s) * np.linalg.norm(b - a) * (0.08 * np.array([0, -1.0, 0]) + 0.35 * (a + b) / np.linalg.norm(a + b))) + return sides + + +def half(): + """A mirrored plate's authored half as chains: the seam's side on x = 0, bowed in the plane, and three free sides.""" + P = np.array([[0.0, 0.0, 0.5], [0.0, 0.0, -0.5], [0.5, 0.1, -0.4], [0.3, 0.1, 0.4]]) + s, sides = np.linspace(0, 1, 5)[:, None], [] + for i, (a, b) in enumerate(zip(P, np.roll(P, -1, axis=0))): + bow = np.array([0.0, -0.3, 0.0]) if i == 0 else np.array([0.25, -0.1, 0.0]) if i == 1 else np.zeros(3) + sides.append(a + s * (b - a) + np.sin(math.pi * s) * np.linalg.norm(b - a) * bow) + return sides + + +def pixels(camera, frame, points, side=1): + out = [] + for p in np.asarray(points, float) * [side, 1, 1]: + x, y, _ = world_to_camera_view(bpy.context.scene, camera, frame.matrix_world @ Vector(p)) + out.append([round(x * WIDTH, 3), round((1.0 - y) * HEIGHT, 3)]) + return out + + +def chains_of(out): + n, first, chains = sum(side["points"] - 1 for side in out["sides"]), 0, [] + for side in out["sides"]: + chains.append([(first + m) % n for m in range(side["points"])]) + first += side["points"] - 1 + return chains + + +def at_one_level(name, sheet, chains, mirror=False): + """The furthest a crown side as core.crease_run builds it at one level stands from a vertex Blender built.""" + send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(sheet), thickness=0.03, levels=1) + shell = bpy.data.objects[name] + wall = shell.modifiers["Kit Solidify"] + wall.show_viewport = False + mesh = np.array([v.co for v in shell.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh().vertices]) + wall.show_viewport = True + verts = np.array(sheet["verts"]) + return max(float(np.linalg.norm(mesh - p * [side, 1, 1], axis=1).min()) for chain in chains for side in ((1, -1) if mirror else (1,)) for p in core.crease_run(verts[chain])) + + +def snapshot(): + return sorted((o.name, o.type, tuple(round(c, 6) for row in o.matrix_world for c in row), o.get("kit_shell")) for o in bpy.data.objects) + + +try: + check("host files admitted with the block_plate row", not R["hostErrors"] and "brokkr_reference.block_plate" in R["hostRows"], R["hostErrors"] or R["hostRows"][-4:]) + scene = bpy.context.scene + scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage = WIDTH, HEIGHT, 100 + frame = bpy.data.objects.new("Frame", None) + scene.collection.objects.link(frame) + frame.matrix_world = Matrix.Translation((0.3, -0.2, 1.0)) @ Euler((0.0, 0.0, math.radians(15.0))).to_matrix().to_4x4() + cameras = [] + for name, azimuth in (("A", 15.0), ("B", 75.0)): + camera = bpy.data.objects.new(name, bpy.data.cameras.new(name)) + scene.collection.objects.link(camera) + camera.data.lens, camera.data.sensor_fit = 50.0, "HORIZONTAL" + a = math.radians(azimuth) + camera.location = Vector((0.3, -0.2, 1.0)) + 7.0 * Vector((math.sin(a), -math.cos(a), 0.15)) + camera.rotation_euler = (Vector((0.3, -0.2, 1.0)) - camera.location).to_track_quat("-Z", "Y").to_euler() + cameras.append(camera) + bpy.context.view_layer.update() + + # --- the truth, built by brokkr_kitbash.shell, and its sides traced in both views ------------------------------- + names = [f"c{i}" for i in range(5)] + sides = pentagon() + crown = np.concatenate([side[:-1] for side in sides]) + truth = core.plate_sheet(crown, [0, 4, 8, 12, 16], facing=[0.0, -1.0, 0.0]) + made, _ = send("brokkr_kitbash.shell", object_name="Truth", sheet=json.dumps(truth), thickness=0.03, levels=2) + bpy.data.objects["Truth"].matrix_world = frame.matrix_world + bpy.context.view_layer.update() + traces = [{"camera": camera.name, "from": names[i], "to": names[(i + 1) % 5], "side": 1, "line": pixels(camera, frame, core.resampled(built(side), 24))} for i, side in enumerate(sides) for camera in cameras] + inside = all(0 <= u <= WIDTH and 0 <= v <= HEIGHT for trace in traces for u, v in trace["line"]) + check("brokkr_kitbash.shell builds the truth from core.plate_sheet, and both cameras frame every side", made["status"] == "accepted" and inside, made["message"]) + + # --- block_plate ------------------------------------------------------------------------------------------------------ + before = snapshot() + receipt, out = send("brokkr_reference.block_plate", frame_object="Frame", plate=json.dumps({"corners": names}), traces=json.dumps(traces, separators=(",", ":"))) + ok = receipt["status"] == "accepted" and out is not None + check(f"block_plate returns a sheet with every trace explained within {core.TOL:g} px and each corner decided by the views", + ok and max(row["unexplained_px"] for side in out["sides"] for row in side["traces"]) <= core.TOL and {corner["decided_by"] for corner in out["corners"]} == {"views"} + and len(receipt["hostResult"]) < 16000, + out and {"sides": [side["points"] for side in out["sides"]], "corners": [[corner["parallax_deg"], corner["m_per_px"], corner["prior_share"]] for corner in out["corners"]], + "rounds": out["rounds"], "seconds": out["seconds"], "chars": len(receipt["hostResult"])} or receipt["message"]) + check("block_plate wrote nothing: every object is as it was", snapshot() == before) + if ok: + chains = chains_of(out) + verts = np.array(out["sheet"]["verts"]) + gap = max(float(core._off(built(verts[chain]), core.resampled(built(side), 400)).max()) for chain, side in zip(chains, sides)) + check("the blocked crown as built stands within 0.06 m of the truth's (the unit test's tolerance; fairness holds the bow in)", gap < 0.06, gap) + worst = at_one_level("Blocked", out["sheet"], chains) + check("brokkr_kitbash.shell takes the blocked sheet, and at one level Blender builds every crown side where core.crease_run says, within 1e-4 m", + "Blocked" in bpy.data.objects and worst < 1e-4, worst) + applied, _ = send("brokkr_kitbash.shell", object_name="Blocked", sheet=json.dumps(out["sheet"]), thickness=0.03, levels=2) + bpy.data.objects["Blocked"].matrix_world = frame.matrix_world + bpy.context.view_layer.update() + receipt, fit = send("brokkr_reference.fit_shell", object_name="Blocked", traces=json.dumps(out["fit_traces"], separators=(",", ":"))) + moved = fit and max(point["moved_m"] for point in fit["points"]) + check(f"fit_shell takes the returned fit_traces on the built plate: accepted, every trace explained, no point moved over {MOVED:g} m", + applied["status"] == "accepted" and receipt["status"] == "accepted" and len(out["fit_traces"]) == 10 and out["left_out"] == [] and moved < MOVED + and max(row["unexplained_px"] for row in fit["traces"]) <= core.TOL, {"moved_m": moved} if fit else receipt["message"]) + + # --- a mirrored plate --------------------------------------------------------------------------------------------------- + names = ["top", "bottom", "low", "high"] + sides = half() + traces = [{"camera": camera.name, "from": names[i], "to": names[(i + 1) % 4], "side": side_, "line": pixels(camera, frame, core.resampled(built(side), 24), side_)} + for i, side in enumerate(sides) for camera, side_ in ((cameras[0], 1), (cameras[1], 1), (cameras[0], -1))] + traces = [trace for trace in traces if not (trace["from"] == "top" and trace["side"] == -1)] # the seam's side is its own reflection + receipt, out = send("brokkr_reference.block_plate", frame_object="Frame", plate=json.dumps({"corners": names, "mirror": True, "seam": ["top", "bottom"]}), + traces=json.dumps(traces, separators=(",", ":"))) + ok = receipt["status"] == "accepted" and out is not None + if ok: + chains = chains_of(out) + verts = np.array(out["sheet"]["verts"]) + gap = max(float(core._off(built(verts[chain]), core.resampled(built(side), 400)).max()) for chain, side in zip(chains, sides)) + check("a mirrored plate: the seam's corners are decided by the mirror plane, its side stays on x = 0, and the crown as built stands within 0.06 m of the truth's", + [corner["decided_by"] for corner in out["corners"]][:2] == ["mirror", "mirror"] and float(np.abs(verts[chains[0], 0]).max()) == 0.0 and gap < 0.06, + {"gap": gap, "sides": [side["points"] for side in out["sides"]], "corners": [corner["decided_by"] for corner in out["corners"]], "poles": out["sheet"]["poles"]}) + worst = at_one_level("Mirrored", out["sheet"], chains, mirror=True) + check("brokkr_kitbash.shell builds both halves of the mirrored sheet, and at one level Blender builds the seam's side and the free sides, on both halves, where core.crease_run says, within 1e-4 m", + "Mirrored" in bpy.data.objects and worst < 1e-4, worst) + else: + check("block_plate blocks a mirrored plate", False, receipt["message"]) + + # --- refusals --------------------------------------------------------------------------------------------------------- + before = snapshot() + plate, text = json.dumps({"corners": names, "mirror": True, "seam": ["top", "bottom"]}), json.dumps(traces, separators=(",", ":")) + receipt, _ = send("brokkr_reference.block_plate", frame_object="Frame", plate=plate, traces=json.dumps([dict(traces[0], camera="Nobody")] + traces[1:], separators=(",", ":"))) + check("an unknown camera is refused naming the trace", receipt["status"] == "failed" and "traces[0]" in receipt["message"] and "Nobody" in receipt["message"], receipt["message"]) + receipt, _ = send("brokkr_reference.block_plate", frame_object="Frame", plate=plate, traces=json.dumps([trace for trace in traces if trace["from"] != "low"], separators=(",", ":"))) + check("a side nobody traced is refused by its corners' names", receipt["status"] == "failed" and "the side from 'low' to 'high' is traced in no view" in receipt["message"], receipt["message"]) + receipt, _ = send("brokkr_reference.block_plate", frame_object="Frame", plate=plate, traces=text, plane="0,0,0; 0,0") + check("a plane that is not a point and a normal is refused", receipt["status"] == "failed" and "plane" in receipt["message"], receipt["message"]) + check("no refusal changed the scene", snapshot() == before) + frame.scale = (2.0, 2.0, 2.0) + bpy.context.view_layer.update() + receipt, _ = send("brokkr_reference.block_plate", frame_object="Frame", plate=plate, traces=text) + check("a scaled frame is refused", receipt["status"] == "failed" and "scaled" in receipt["message"], receipt["message"]) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:]) + +R["ok"] = all(c["ok"] for c in R["checks"]) +for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/reference_block.result.json b/surfaces/blender/tests/live/reference_block.result.json new file mode 100644 index 0000000..2d913ea --- /dev/null +++ b/surfaces/blender/tests/live/reference_block.result.json @@ -0,0 +1,175 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "host files admitted with the block_plate row", + "ok": true, + "detail": [ + "brokkr_reference.solve_camera", + "brokkr_reference.flow_score", + "brokkr_reference.fit_shell", + "brokkr_reference.block_plate" + ] + }, + { + "name": "brokkr_kitbash.shell builds the truth from core.plate_sheet, and both cameras frame every side", + "ok": true, + "detail": "Operator brokkr_kitbash.shell finished." + }, + { + "name": "block_plate returns a sheet with every trace explained within 5.2 px and each corner decided by the views", + "ok": true, + "detail": { + "sides": [ + 3, + 3, + 3, + 3, + 3 + ], + "corners": [ + [ + 60.6, + 0.0031, + 0.019 + ], + [ + 61.0, + 0.0042, + 0.026 + ], + [ + 56.4, + 0.0035, + 0.022 + ], + [ + 57.3, + 0.0036, + 0.022 + ], + [ + 60.1, + 0.0037, + 0.023 + ] + ], + "rounds": 2, + "seconds": 0.236, + "chars": 7242 + } + }, + { + "name": "block_plate wrote nothing: every object is as it was", + "ok": true, + "detail": null + }, + { + "name": "the blocked crown as built stands within 0.06 m of the truth's (the unit test's tolerance; fairness holds the bow in)", + "ok": true, + "detail": 0.002711610846938251 + }, + { + "name": "brokkr_kitbash.shell takes the blocked sheet, and at one level Blender builds every crown side where core.crease_run says, within 1e-4 m", + "ok": true, + "detail": 1.1421151381392388e-07 + }, + { + "name": "fit_shell takes the returned fit_traces on the built plate: accepted, every trace explained, no point moved over 0.09 m", + "ok": true, + "detail": { + "moved_m": 0.0048 + } + }, + { + "name": "a mirrored plate: the seam's corners are decided by the mirror plane, its side stays on x = 0, and the crown as built stands within 0.06 m of the truth's", + "ok": true, + "detail": { + "gap": 0.013972102623404082, + "sides": [ + 3, + 3, + 2, + 2 + ], + "corners": [ + "mirror", + "mirror", + "views", + "views" + ], + "poles": [ + 0, + 2, + 11 + ] + } + }, + { + "name": "brokkr_kitbash.shell builds both halves of the mirrored sheet, and at one level Blender builds the seam's side and the free sides, on both halves, where core.crease_run says, within 1e-4 m", + "ok": true, + "detail": 8.42242114374928e-08 + }, + { + "name": "an unknown camera is refused naming the trace", + "ok": true, + "detail": "Error: traces[0]: 'Nobody' is not a camera object." + }, + { + "name": "a side nobody traced is refused by its corners' names", + "ok": true, + "detail": "Error: the side from 'low' to 'high' is traced in no view: every side of the outline is traced, or the plate is given fewer corners. Nothing changed." + }, + { + "name": "a plane that is not a point and a normal is refused", + "ok": true, + "detail": "Error: plane's normal '0,0' is not 3 finite numbers with commas between." + }, + { + "name": "no refusal changed the scene", + "ok": true, + "detail": null + }, + { + "name": "a scaled frame is refused", + "ok": true, + "detail": "Error: frame_object 'Frame' is scaled (2.0, 2.0, 2.0): a plate is in metres of its frame. Apply or clear the scale." + } + ], + "hostErrors": [], + "hostRows": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick", + "brokkr_kitbash.place_part", + "brokkr_kitbash.set_params", + "brokkr_kitbash.describe", + "brokkr_kitbash.report", + "brokkr_kitbash.attach", + "brokkr_kitbash.detach", + "brokkr_kitbash.roll", + "brokkr_kitbash.aim", + "brokkr_kitbash.reach", + "brokkr_kitbash.joint", + "brokkr_kitbash.slide", + "brokkr_kitbash.joints", + "brokkr_kitbash.close", + "brokkr_kitbash.boolean", + "brokkr_kitbash.cut", + "brokkr_kitbash.cut_many", + "brokkr_kitbash.freeze", + "brokkr_kitbash.thaw", + "brokkr_kitbash.ribs", + "brokkr_kitbash.shell", + "brokkr_kitbash.hose", + "brokkr_reference.solve_camera", + "brokkr_reference.flow_score", + "brokkr_reference.fit_shell", + "brokkr_reference.block_plate" + ], + "ok": true +} \ No newline at end of file From 29aaf87365e737839fb7a5cc32a83c6bf61e26d0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 08:59:11 +0100 Subject: [PATCH 186/223] brokkr_kitbash.shell: Kit Solidify with plain offset; the faceted suite's fold onset, wall and volume bounds re-read for it Even offset divides a crease vertex's move by the cosine of the crease's half-angle: at a pinned corner of a narrow plate the factor runs away and the wall throws a needle. With it off every inner vertex stands the thickness from its outer one along the vertex normal. kitbash_faceted pinned the even wall, so it follows: the wedge folds at (W / 2^levels) / sin(phi), 0.106 (was tan, 0.075); the wall's distance off the thickness reads 0.0061 behind the creased shoulder (was 0.0001), bound 0.0122 against S6 at 0.024; the volume reads 0.028, S6 0.071, bound 0.0447. fold_lofts.json: seeds 5185 and 5196 fold at 0.0425 and 0.0232 with a plain offset (0.0019 and under 0.0009 with even), so their thickness and holds stand 1.2 over and under those. Cut aetheria-release:cut_spec:cut-shell-plain-wall.r1. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 4 ++- .../blender/tests/fixtures/fold_lofts.json | 10 +++--- .../blender/tests/live/kitbash_faceted.py | 34 ++++++++++--------- .../tests/live/kitbash_faceted.result.json | 26 ++++++++------ 4 files changed, 41 insertions(+), 33 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 19c7090..83f47c5 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1650,7 +1650,9 @@ class BROKKR_KITBASH_OT_shell(PolishOperator): smooth.levels = smooth.render_levels = self.levels smooth.subdivision_type, smooth.boundary_smooth, smooth.use_creases = "CATMULL_CLARK", built.boundary, True wall = obj.modifiers.get(SOLIDIFY) or obj.modifiers.new(SOLIDIFY, "SOLIDIFY") - wall.thickness, wall.offset, wall.use_even_offset, wall.use_rim = self.thickness, self.offset, True, True + # plain offset: each inner vertex stands the thickness off its outer one along the vertex normal. Even offset divides by the cosine + # of the crease's half-angle, and at a pinned corner of a narrow plate that factor throws a needle (docs/kitbash.md, Thickness at a crease) + wall.thickness, wall.offset, wall.use_even_offset, wall.use_rim = self.thickness, self.offset, False, True sync_bevel(obj, self.bevel) obj[SHELL] = json.dumps({"sheet": document, "thickness": self.thickness, "offset": self.offset, "levels": self.levels, "bevel": self.bevel}) starts = np.cumsum(built.counts) - built.counts diff --git a/surfaces/blender/tests/fixtures/fold_lofts.json b/surfaces/blender/tests/fixtures/fold_lofts.json index 566c2b0..adf39d2 100644 --- a/surfaces/blender/tests/fixtures/fold_lofts.json +++ b/surfaces/blender/tests/fixtures/fold_lofts.json @@ -1,12 +1,12 @@ { - "about": "Lofts of planar trapezoid facets on which a shell's wall folds well under any figure read from the cage: the seeded lofts of Soul's probe of 2026-12-02 (aetheria-release:verdict:cut-kit-faceted-shell.s3), seed, levels and offset as drawn there. thickness is one at which the evaluated wall folds; holds, where the action's range reaches it, one at which it does not.", + "about": "Lofts of planar trapezoid facets: the seeded lofts of Soul's probe of 2026-12-02 (aetheria-release:verdict:cut-kit-faceted-shell.s3), seed, levels and offset as drawn there, on which a wall of even offset folded well under any figure read from the cage (at 0.006342, 0.010394 and 0.00617). thickness is one at which the evaluated wall, Kit Solidify's plain offset, folds; holds, where the action's range reaches it, one at which it does not. Read 2026-12-03: seed 5185 first folds at 0.0425 and seed 5196 at 0.0232, thickness and holds standing 1.2 over and under; seed 5101 folds at the range's floor.", "lofts": [ { "seed": 5185, "levels": 1, "offset": -1.0, - "thickness": 0.006342, - "holds": 0.001, + "thickness": 0.051, + "holds": 0.0354, "sheet": { "rings": [ [ @@ -357,8 +357,8 @@ "seed": 5196, "levels": 1, "offset": 1.0, - "thickness": 0.00617, - "holds": null, + "thickness": 0.0279, + "holds": 0.0194, "sheet": { "rings": [ [ diff --git a/surfaces/blender/tests/live/kitbash_faceted.py b/surfaces/blender/tests/live/kitbash_faceted.py index a7c09ab..122f46e 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.py +++ b/surfaces/blender/tests/live/kitbash_faceted.py @@ -1,5 +1,5 @@ """Live proof, in a background Blender, of brokkr_kitbash.shell through run_intent: a loft of rings becomes a cage whose -crease runs stay crisp under subdivision while the rest stays smooth, a wall of even thickness with a filled rim, a +crease runs stay crisp under subdivision while the rest stays smooth, a wall of plain offset with a filled rim, a mirror, a rebuild in place under cutters and ribs, cut_many and ribs on the shell, and the refusals. Not part of the unittest run: it needs Blender. @@ -78,18 +78,20 @@ SOFT = 12.0 # the surface keeps the cage's corner. Shipped 0 (read as 1e-7, what a float32 mesh is good to); least claimed mutant # 0.15 (S5, boundary_smooth ALL: the corner rounds off); the geometric mean, separation 900 each side. CORNER = 1.6e-4 -# The wall's volume over the designed surface's area times the thickness, less 1, as a magnitude. Shipped 0.027 (a wall -# grown inward loses volume inside the crown's curve); least claimed mutant 0.036 (S6, the Solidify above the -# Subdivision: the wall's own edges are rounded off); the geometric mean, a total separation of 1.34. -SOLID = 0.0313 +# The wall's volume over the designed surface's area times the thickness, less 1, as a magnitude. Shipped 0.028 (a wall +# grown inward loses volume inside the crown's curve, and a plain offset is thinner behind the creased shoulder); least +# claimed mutant 0.071 (S6, the Solidify above the Subdivision: the wall's own edges are rounded off); the geometric +# mean, separation 1.58 each side. +SOLID = 0.0447 # Metres between the thickness and the distance from a vertex of the wall's inner face to the designed surface. Shipped -# 0.0001 (a float32 mesh under three levels of subdivision); least claimed mutant 0.024 (S6: the inner face is subdivided again and pulls in); the geometric mean, separation 15 each side. -EVEN = 1.5e-3 -# Metres: the thickness at which the wedge of shell-fold folds, (W / 2^levels) / tan(phi) of its narrower facet, as +# 0.0061 (a plain offset behind the creased shoulder: the wall is 0.0539 there, the thickness x cos(phi)); least claimed +# mutant 0.024 (S6: the inner face is subdivided again and pulls in); the geometric mean, separation 1.99 each side. +WALL_OFF = 0.0122 +# Metres: the thickness at which the wedge of shell-fold folds, (W / 2^levels) / sin(phi) of its narrower facet, as # measured on flat facets (docs/kitbash.md, Thickness at a crease). The wall is built at FOLD / FOLD_STEP (no inner # face folded) and at FOLD x FOLD_STEP (some folded); FOLD_STEP is the 1.2 separation the margin rule asks on each # side of the onset. The counts themselves are exact: count_folds is held to this script's own count, face for face. -FOLD, FOLD_STEP = 0.075, 1.2 +FOLD, FOLD_STEP = 0.106, 1.2 def check(name, ok, detail=None): @@ -220,9 +222,9 @@ try: report["thickness"], report["offset"], report["children"]) == ("Pauldron", False, 6, 6, 25, 25, 0, 1600, 3, 0.06, -1.0, []) and report["facing"][2] > 0.5 and abs(np.linalg.norm(report["facing"]) - 1.0) < 1e-5, report) smooth, wall = pauldron.modifiers.get("Kit Subsurf"), pauldron.modifiers.get("Kit Solidify") - check("the stack is Kit Subsurf, Kit Solidify, Kit Bevel: creases used, corners preserved, an even wall inward with its rim filled", + check("the stack is Kit Subsurf, Kit Solidify, Kit Bevel: creases used, corners preserved, a wall of plain offset inward with its rim filled", stack(pauldron) == ["Kit Subsurf", "Kit Solidify", "Kit Bevel"] and (smooth.levels, smooth.render_levels, smooth.use_creases, smooth.boundary_smooth) == (3, 3, True, "PRESERVE_CORNERS") - and (wall.use_even_offset, wall.use_rim, wall.offset) == (True, True, -1.0) and abs(wall.thickness - WALL) < 1e-7 and abs(pauldron.modifiers["Kit Bevel"].width - 0.004) < 1e-7, + and (wall.use_even_offset, wall.use_rim, wall.offset) == (False, True, -1.0) and abs(wall.thickness - WALL) < 1e-7 and abs(pauldron.modifiers["Kit Bevel"].width - 0.004) < 1e-7, stack(pauldron)) # W1 dies here: the mesh's edges are not in the order core.sheet lists its creases, so the weights must be looked up by pair expected = {tuple(pair): round(weight, 6) for pair, weight in zip(built.creases.tolist(), built.weights.tolist())} @@ -256,7 +258,7 @@ try: # --- shell-fold: count_folds, against this script's own count on the evaluated wall ------------------------------------------- section("shell-fold") - # a ridge of two flat facets 0.3 and 1.0 wide, each tilted 45 degrees, full crease, levels 2: the narrower facet binds, (0.3 / 4) / tan 45 = 0.075 + # a ridge of two flat facets 0.3 and 1.0 wide, each tilted 45 degrees, full crease, levels 2: the narrower facet binds, (0.3 / 4) / sin 45 = 0.106 wedge = {"rings": [[[-1.0 * math.sqrt(0.5), y, -1.0 * math.sqrt(0.5)], [0.0, y, 0.0], [0.3 * math.sqrt(0.5), y, -0.3 * math.sqrt(0.5)]] for y in (0.0, 0.5, 1.0)], "creases": [{"column": 1, "from": 0, "to": 2, "weight": 1.0}]} @@ -290,7 +292,7 @@ try: seeded = {f"{loft['seed']} offset {loft['offset']:g}": folded(f"Loft{loft['seed']}", loft["sheet"], loft["thickness"], offset=loft["offset"], levels=loft["levels"], count_folds=True) for loft in lofts} held = {f"{loft['seed']} offset {loft['offset']:g}": folded(f"Held{loft['seed']}", loft["sheet"], loft["holds"], offset=loft["offset"], levels=loft["levels"], count_folds=True) for loft in lofts if loft["holds"]} R["folds"] = {"seeded": seeded, "held": held} - check("shell-fold: on seeded lofts whose walls fold under any figure of the cage, at offsets -1, 0 and 1, count_folds counts the faces this script counts, and none at a thickness the wall holds", + check("shell-fold: on seeded lofts, at offsets -1, 0 and 1, count_folds counts the faces this script counts at a thickness the wall folds at, and none at one it holds", len(seeded) == 3 and all(told == own > 0 for told, own in seeded.values()) and held and all(pair == [0, 0] for pair in held.values()), [seeded, held]) for name in ["FoldUnder", "FoldOver", "FoldUnasked", "FoldOut"] + [f"{kind}{loft['seed']}" for loft in lofts for kind in ("Loft", "Held")]: if name in bpy.data.objects: @@ -306,10 +308,10 @@ try: inner = [v.co for v in whole.verts if all(outer.find_nearest(f.calc_center_median())[3] > WALL / 2 for f in v.link_faces)] reading("solid", abs(whole.calc_volume(signed=True) / (area * WALL) - 1.0)) for co in inner: - reading("even", abs(outer.find_nearest(co)[3] - WALL)) - check("shell-solid: the plate is a closed wall of even thickness behind the designed surface, its rim filled", + reading("wallOff", abs(outer.find_nearest(co)[3] - WALL)) + check("shell-solid: the plate is a closed wall behind the designed surface, its thickness off it but for the creased shoulder's cosine, its rim filled", sum(1 for e in whole.edges if not e.is_manifold) == 0 and whole.calc_volume(signed=True) > 0 and len(whole.faces) == 2 * 1600 + 4 * 40 and len(inner) > 0.9 * len(designed.verts) - and R["readings"]["solid"] < SOLID and R["readings"]["even"] < EVEN, [R["readings"], len(whole.faces), len(inner), len(designed.verts)]) + and R["readings"]["solid"] < SOLID and R["readings"]["wallOff"] < WALL_OFF, [R["readings"], len(whole.faces), len(inner), len(designed.verts)]) whole.free() # a mirrored breast sheet: symmetric as evaluated diff --git a/surfaces/blender/tests/live/kitbash_faceted.result.json b/surfaces/blender/tests/live/kitbash_faceted.result.json index 14af0bd..8ae3dc9 100644 --- a/surfaces/blender/tests/live/kitbash_faceted.result.json +++ b/surfaces/blender/tests/live/kitbash_faceted.result.json @@ -12,7 +12,7 @@ "detail": null }, { - "name": "the stack is Kit Subsurf, Kit Solidify, Kit Bevel: creases used, corners preserved, an even wall inward with its rim filled", + "name": "the stack is Kit Subsurf, Kit Solidify, Kit Bevel: creases used, corners preserved, a wall of plain offset inward with its rim filled", "ok": true, "detail": null }, @@ -47,12 +47,12 @@ "detail": null }, { - "name": "shell-fold: on seeded lofts whose walls fold under any figure of the cage, at offsets -1, 0 and 1, count_folds counts the faces this script counts, and none at a thickness the wall holds", + "name": "shell-fold: on seeded lofts, at offsets -1, 0 and 1, count_folds counts the faces this script counts at a thickness the wall folds at, and none at one it holds", "ok": true, "detail": null }, { - "name": "shell-solid: the plate is a closed wall of even thickness behind the designed surface, its rim filled", + "name": "shell-solid: the plate is a closed wall behind the designed surface, its thickness off it but for the creased shoulder's cosine, its rim filled", "ok": true, "detail": null }, @@ -176,32 +176,36 @@ "readings": { "corner": 1.8e-07, "crisp": 52.0, - "even": 0.0001, "foldOver": 8.0, "foldUnder": 0.0, "ribsAcrossTheCrease": 1.0, "soft": 5.8, - "solid": 0.027 + "solid": 0.028, + "wallOff": 0.0061 }, "folds": { "seeded": { "5185 offset -1": [ - 2, - 2 + 1, + 1 ], "5101 offset 0": [ - 13, - 13 + 9, + 9 ], "5196 offset 1": [ - 4, - 4 + 1, + 1 ] }, "held": { "5185 offset -1": [ 0, 0 + ], + "5196 offset 1": [ + 0, + 0 ] } }, From aeac2e26ad23de37ee82c2d615a3d818dc041c47 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 09:02:11 +0100 Subject: [PATCH 187/223] tests/live/kitbash_cage.py: a narrow plate's wall throws no needle and a hexagon's thin wall folds no face plain-wall-no-needle: a crown-skirt-centre plate 0.13 x 1.2 m, wall 0.04, bevel 0.01, levels 2, stands 0.95 thicknesses beyond its cage's bounds; at even offset (W1) 3.28; bound 1.77. plain-wall-folds: the 1.2 m hexagon at 0.015 folds 0 of 168 inner faces; W1 20; the count + 1 bounded at 4.6. W1 in the operator fails both. Cut aetheria-release:cut_spec:cut-shell-plain-wall.r1. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/kitbash_cage.py | 60 ++++++++++++++++++- .../tests/live/kitbash_cage.result.json | 14 +++++ 2 files changed, 73 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/tests/live/kitbash_cage.py b/surfaces/blender/tests/live/kitbash_cage.py index e3a2724..8976977 100644 --- a/surfaces/blender/tests/live/kitbash_cage.py +++ b/surfaces/blender/tests/live/kitbash_cage.py @@ -1,6 +1,7 @@ """Live proof, in a background Blender, of brokkr_kitbash.shell's free cage through run_intent: a cage of triangles and quads with declared poles becomes a shell whose subdivided face count is the reported one at each level, takes a -wall, counts folds and is cut; a mirrored cage closes over its seam; a loft shell is rebuilt in place as a free cage +wall, counts folds and is cut; a narrow plate's wall throws no needle and a hexagon's thin wall does not fold; a +mirrored cage closes over its seam; a loft shell is rebuilt in place as a free cage under its cutters; the pole gate refuses without writing; tools/cage_export.py reads a cage back, an open one included, as its maker's Subdivision draws it; and tools/cage_score.py ranks a near copy, a moved vertex, an over-creased and a creaseless cage in that order. Not part of the unittest run: it needs Blender. @@ -72,6 +73,13 @@ SAME = 1.3e-2 # Keep Corners, read here by setting it) 7.7; the geometric mean, separation 670 each side. A closed cage does not tell # the two apart, and a hand-modelled hull's own round trip is 0.28 (its seam snap): the open plate stands inside that. OPEN = 1.1e-2 +# Wall thicknesses: how far the furthest vertex of a narrow plate, as evaluated, stands beyond its cage's bounds. +# Shipped 0.95; mutant W1 (Kit Solidify at even offset, read here by setting it: a pinned corner's vertex moves the +# thickness over the cosine of its crease's half-angle) 3.28; the geometric mean, separation 1.86 each side. +NEEDLE = 1.77 +# Inner faces of a hexagon plate's wall that fold, read as the count + 1. Shipped 0, read 1; W1 20, read 21; the +# geometric mean, separation 4.6 each side. +FOLDS = 4.6 # A tent: four triangles round an apex of valence 4 with two ridges creased, and a quad hung under one edge: 7 @@ -82,6 +90,9 @@ TENT = {"verts": [[0.0, 0.0, 0.5], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, HULL = {"verts": [[0.0, -1.0, 0.0], [0.004, 0.0, 0.3], [0.0, 1.0, 0.0], [0.0, 0.0, -0.3], [0.6, 0.0, 0.0]], "faces": [[0, 4, 1], [1, 4, 2], [2, 4, 3], [3, 4, 0]], "creases": [[0, 4, 1.0], [4, 2, 1.0]], "mirror": True} LOFT = {"rings": [[[0.3 * j - 0.45, 0.02 * j * j, 0.3 * i] for j in range(4)] for i in range(3)], "flip": True} +# Two crowns, each the outline of a plate's raised face in the plane y = 0: a strip 0.13 m wide and 1.2 m long, and a hexagon 1.2 m across. +STRIP = [[-0.06, 0.0, 0.6], [-0.07, 0.0, -0.6], [0.07, 0.0, -0.6], [0.06, 0.0, 0.6]] +HEXAGON = [[-0.5, 0.0, 0.6], [-0.62, 0.0, 0.1], [-0.4, 0.0, -0.7], [0.4, 0.0, -0.7], [0.62, 0.0, 0.1], [0.5, 0.0, 0.6]] CUTS = [{"name": "TentLine", "part": "slab", "params": "gap=0.02; length=0.4; depth=0.03", "origin": [0.3, -0.35, 3.0], "direction": [0, 0, -1]}] @@ -132,6 +143,31 @@ def sharpest(obj): return worst +def crown_plate(crown, flare=0.06, drop=0.07, dome=0.03): + """The cage of a plate as the mech experiments block one, facing -y: the crown ring with its sides creased, a skirt + ring flared out of it and dropped back, one centre vertex domed, every ring corner pinned: 2N + 1 vertices.""" + P = np.array(crown, dtype=float) + N = len(P) + normal = np.cross(P, np.roll(P, -1, axis=0)).sum(axis=0) + if normal[1] > 0: + P, normal = P[::-1].copy(), -normal + normal, centre = normal / np.linalg.norm(normal), P.mean(axis=0) + out = (P - centre) - np.outer((P - centre) @ normal, normal) + skirt = P + flare * out / np.linalg.norm(out, axis=1)[:, None] - drop * normal + return {"verts": np.vstack([P, skirt, centre + dome * normal]).round(5).tolist(), + "faces": [[i, (i + 1) % N, 2 * N] for i in range(N)] + [[N + i, N + (i + 1) % N, (i + 1) % N, i] for i in range(N)], + "creases": [[i, (i + 1) % N, 1.0] for i in range(N)], "corners": [[i, 1.0] for i in range(2 * N)], "poles": [] if N == 4 else [2 * N], "rim": 0.0} + + +def beyond(obj, sheet): + """Metres: how far the furthest vertex of an object, as evaluated, stands outside its cage's bounds along an axis.""" + bm = evaluated(obj) + at = np.array([v.co[:] for v in bm.verts]) + bm.free() + cage = np.array(sheet["verts"]) + return float(max((cage.min(axis=0) - at).max(), (at - cage.max(axis=0)).max(), 0.0)) + + def state(): return {o.name: (sorted(k for k in o.keys() if k.startswith("kit_")), len(o.data.vertices) if o.type == "MESH" else None, [m.name for m in o.modifiers]) for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes) @@ -161,6 +197,28 @@ try: [tuple(p.vertices) for p in tent.data.polygons] == [tuple(f) for f in TENT["faces"]] and np.abs(np.array([v.co[:] for v in tent.data.vertices]) - built.V).max() < 1e-6 and json.loads(tent["kit_shell"])["sheet"] == TENT, tent["kit_shell"]) + # --- plain-wall: the Solidify's plain offset --------------------------------------------------------------------------- + section("plain-wall") + strip, hexagon = crown_plate(STRIP), crown_plate(HEXAGON) + receipt, report = send("brokkr_kitbash.shell", object_name="Strip", sheet=json.dumps(strip), thickness=0.04, levels=2, bevel=0.01) + plate = bpy.data.objects.get("Strip") + needle = beyond(plate, strip) / 0.04 + plate.modifiers["Kit Solidify"].use_even_offset = True # W1 + R["readings"].update({"needleThicknesses": needle, "needleThicknessesW1": beyond(plate, strip) / 0.04}) + check(f"plain-wall-no-needle: a plate 0.13 m wide with a wall of 0.04 stands under {NEEDLE} thicknesses beyond its cage's bounds, and over that at even offset", + receipt["status"] == "accepted" and report["cageVerts"] == 9 and needle < NEEDLE < R["readings"]["needleThicknessesW1"], [receipt["message"], R["readings"]]) + receipt, report = send("brokkr_kitbash.shell", object_name="Hexagon", sheet=json.dumps(hexagon), thickness=0.015, levels=2, count_folds=True) + plate = bpy.data.objects.get("Hexagon") + plate.modifiers["Kit Solidify"].use_even_offset = True # W1 + even = sys.modules["brokkr_kitbash"].BROKKR_KITBASH_OT_shell.folded_faces(bpy.context, plate, report["subdividedFaces"]) + R["readings"].update({"foldedPlusOne": report["folded"] + 1, "foldedPlusOneW1": even + 1}) + check(f"plain-wall-folds: a hexagon plate 1.2 m across with a wall of 0.015 folds no inner face of its 168 (the count + 1 under {FOLDS}), and over that at even offset", + receipt["status"] == "accepted" and (report["cageVerts"], report["subdividedFaces"], report["poles"]) == (13, 168, {"6": 1}) and report["folded"] + 1 < FOLDS < even + 1, [receipt["message"], report, even]) + for name in ("Strip", "Hexagon"): + mesh = bpy.data.objects[name].data + bpy.data.objects.remove(bpy.data.objects[name]) + bpy.data.meshes.remove(mesh) + # --- the creases reach the surface ----------------------------------------------------------------------------------- section("free-cage-crisp") crisp = sharpest(tent) diff --git a/surfaces/blender/tests/live/kitbash_cage.result.json b/surfaces/blender/tests/live/kitbash_cage.result.json index 4f40224..236e084 100644 --- a/surfaces/blender/tests/live/kitbash_cage.result.json +++ b/surfaces/blender/tests/live/kitbash_cage.result.json @@ -41,6 +41,16 @@ "ok": true, "detail": null }, + { + "name": "plain-wall-no-needle: a plate 0.13 m wide with a wall of 0.04 stands under 1.77 thicknesses beyond its cage's bounds, and over that at even offset", + "ok": true, + "detail": null + }, + { + "name": "plain-wall-folds: a hexagon plate 1.2 m across with a wall of 0.015 folds no inner face of its 168 (the count + 1 under 4.6), and over that at even offset", + "ok": true, + "detail": null + }, { "name": "the creased ridge stays an edge under subdivision: over 34.0 degrees, and under it with crease_edge cleared", "ok": true, @@ -144,6 +154,10 @@ "costSelf": 0.28, "crispDegrees": 71.0, "crispDegreesK1": 16.0, + "foldedPlusOne": 1.0, + "foldedPlusOneW1": 21.0, + "needleThicknesses": 0.95, + "needleThicknessesW1": 3.3, "openRoundTripPct": 1.7e-05, "openRoundTripPctB1": 7.7, "scoreLiftedHausdorffPct": 3.3, From d4d0872d76029970cfcf7531b586bc866113ca75 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 09:03:15 +0100 Subject: [PATCH 188/223] docs/kitbash.md: Thickness at a crease for the plain offset: t x cos(phi) at a crease, folds from (W / 2^levels) / sin(phi), no needle The flat-facet onset re-measured with the plain offset (31 of 31 readings at 1.00 of the sin figure; Even Thickness at 1.00 of the tan figure in the same 31), the three seeded lofts' first folds, the narrow plate and the hexagon with both modes, and the Seraph readings marked as Even Thickness readings. Cut aetheria-release:cut_spec:cut-shell-plain-wall.r1. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 59 ++++++++++++++++++++------------ 1 file changed, 38 insertions(+), 21 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 211bf4e..3ac8bad 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -491,7 +491,7 @@ column 3, the shoulder line, is creased, so the crown and the steep outer face a dips: the plate is concave there, which no convex hull can be. The object carries the cage, `crease_edge` and `crease_vert`, and the modifiers `Kit Subsurf` (`levels`, creases -used) then `Kit Solidify` (`thickness`, `offset`, even, rim filled), then any Booleans `cut` adds, then the `Kit +used) then `Kit Solidify` (`thickness`, `offset`, plain offset, rim filled), then any Booleans `cut` adds, then the `Kit Bevel` when `bevel` is over 0. `kit_shell` on it is the request, and it owns the cage as `kit_params` owns a part's mesh: an edit of the cage by hand is lost at the next `shell` call. `shell` reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases` (edges with a weight over 0), `folded` (see Thickness at a crease), @@ -513,29 +513,46 @@ the outline, and the plate left between two bites is a tab. it; a rib deeper than the room a tight crease leaves is refused with the size to lower. **Thickness at a crease.** `shell` takes any `thickness` in its range and does not refuse one the cage cannot -hold: the limit is a fact of the subdivided mesh, not of the cage. Even thickness moves a vertex on a -full crease along the crease's bisector, which slides it `thickness` x tan(phi) across each facet, phi being half -the angle between the two facets' normals; the vertices beside it move straight in. Where that slide is longer than -the first row of subdivided faces, the wall's far face folds over itself beside the crease: at a wall depth over -(W / 2^`levels`) / tan(phi), W the width across the crease of the narrower of its two facets. The fold is on the -crease's concave side: behind a ridge, so under a wall grown inward, and in front of a valley, under a wall grown -outward; the two read the same. Measured on two flat facets, a crease of 1.0: the fold starts at 1.00 of that -figure in 23 of 23 readings (W 1 and 0.4; phi 15 to 60; levels 1 to 3; a ridge and a valley), which is 0.217 for W -1, phi 30, levels 3, and 0.029 for W 0.4, phi 60, levels 3. Facets 1.0 and 0.3 wide at phi 45, levels 2, fold at -0.075, the narrow facet's figure, not the wide one's 0.25. A crease of 0.5 folds at 1.02 to 1.32 of it, and an -uncreased edge folds too, at 1.17 to 4.2 of it. The fold is inside the wall and one subdivided row wide: the -designed surface is unchanged and the mesh has no open or non-manifold edge, but the solid passes through itself -there, and a cut through that place is untested. +hold: the limit is a fact of the subdivided mesh, not of the cage. `Kit Solidify` is a plain offset (Even Thickness +off): each vertex of the wall's far face stands `thickness` from its vertex of the designed surface, along that +vertex's normal. On a full crease that normal is the crease's bisector, so the wall there is `thickness` x cos(phi) +thick square to a facet, phi being half the angle between the two facets' normals: 0.71 of it at a right-angled +crease, and the rim strip at a creased corner is narrower by the same factor. A wall of 0.06 reads 0.0539 behind +the pauldron's shoulder crease above. The crease vertex slides `thickness` x sin(phi) across each facet; the +vertices beside it move straight in. Where that slide is longer than the first row of subdivided faces, the wall's +far face folds over itself beside the crease: at a wall depth over (W / 2^`levels`) / sin(phi), W the width across +the crease of the narrower of its two facets. The fold is on the crease's concave side: behind a ridge, so under a +wall grown inward, and in front of a valley, under a wall grown outward; the two read the same. Measured on two +flat facets, a crease of 1.0: the fold starts at 1.00 of that figure in 31 of 31 readings (W 1 and 0.4; phi 15 to +60; levels 1 to 3; a ridge, and a valley at levels 2), which is 0.25 for W 1, phi 30, levels 3, and 0.058 for W +0.4, phi 60, levels 3. Facets 1.0 and 0.3 wide at phi 45, levels 2, fold at 0.106, the narrow facet's figure, not +the wide one's 0.354. A crease of 0.5 folds at 0.72 to 1.14 of it, and an uncreased edge folds too, at 1.21 to 3.3 +of it (three readings each). The fold is inside the wall and one subdivided row wide: the designed surface is +unchanged and the mesh has no open or non-manifold edge, but the solid passes through itself there, and a cut +through that place is untested. -No figure read from the cage bounds this. The flat-facet figure above, taken over every cage edge, is neither a -floor nor a ceiling on a real plate: on seeded lofts of planar trapezoid facets with partial crease runs the -evaluated wall first folded at 0.44 of it with the wall grown inward, at 0.03 of it at `offset` 0 and at 0.08 of it -grown outward, and on the Seraph's plates a first face normal turned at 0.74 to 2.6 of it (`tests/fixtures/fold_lofts.json` holds three of -those lofts; 2026-12-02). So `shell` counts instead of estimating: with `count_folds` it evaluates the wall alone, +Even Thickness would hold the wall at `thickness` square to both facets by moving the crease vertex `thickness` / +cos(phi) along the bisector. That slides it `thickness` x tan(phi) across each facet, so the wall folds sooner, at +(W / 2^`levels`) / tan(phi) (1.00 of it in the same 31 readings), and where creases meet at a pinned corner of a +narrow plate the factor runs away and the wall throws a needle. A plate of a crown ring, a flared skirt and a +domed centre, 0.13 m wide and 1.2 m long, with a wall of 0.04, stood 3.28 thicknesses beyond its cage's bounds +with Even Thickness and stands 0.95 with the plain offset (0.372 m against 0.076 m at a wall of 0.08). A hexagon of +the same make 1.2 m across folded 20 of its 168 inner faces at 0.015, 28 at 0.03 and 44 at 0.07; with the plain +offset it folds 0, 2 and 20. `tests/live/kitbash_cage.py` holds the two plates. Solidify's thickness clamp with +its angle clamp changed no fold count and no bound in either mode, and its complex mode threw a vertex 2.07 m +beyond a 1.0 m plate's cage at a wall of 0.08 (2026-12-03). + +No figure read from the cage bounds this. Of three seeded lofts of planar trapezoid facets with partial crease +runs (`tests/fixtures/fold_lofts.json`), the evaluated wall first folds at 0.042 with the wall grown inward and +at 0.023 grown outward, and at `offset` 0 it folds at the least thickness `shell` takes (2026-12-03). The lofts +were drawn against Even Thickness, where the flat-facet figure of that mode, taken over every cage edge, was +neither a floor nor a ceiling: the wall first folded at 0.44 of it grown inward, at 0.03 of it at `offset` 0 and at +0.08 of it grown outward, and on the Seraph's plates a first face normal turned at 0.74 to 2.6 of it (2026-12-02). +So `shell` counts instead of estimating: with `count_folds` it evaluates the wall alone, `Kit Subsurf` and `Kit Solidify` with every other modifier hidden for the reading and shown again, and reports `folded`, the number of the wall's inner faces that fold. An inner face folds when the turn at any of its corners runs with its outer twin's normal: the corner has passed over its neighbour. That is sooner than the face's own -normal turning: on the Seraph's cap a corner turned at 0.033 and no face normal had at 0.0416. Without `count_folds`, `folded` is null +normal turning: on the Seraph's cap, with Even Thickness, a corner turned at 0.033 and no face normal had at 0.0416. Without `count_folds`, `folded` is null and nothing is evaluated. The count cost 3.9 ms on a new plate of 1600 subdivided faces (a call of 7.7 ms against 3.8 ms), and nothing measurable on a rebuild under six cutters (0.94 s against 0.92 s, the call's own Boolean), medians of three interleaved calls in the live suite (Blender 5.3 on Starfire). On a shell whose `Kit Subsurf` or @@ -543,7 +560,7 @@ medians of three interleaved calls in the live suite (Blender 5.3 on Starfire). `folded` 0 is not yet a wall an Exact Boolean takes cleanly. Short of the fold the inner quads at a tight rim corner are twisted, and the Boolean, which cuts quads into triangles, can read the wall as passing through itself and -leave edges with four faces. On the Seraph's cap that began at 0.91 of the thickness at which the first face +leave edges with four faces. On the Seraph's cap, read with Even Thickness, that began at 0.91 of the thickness at which the first face folds (0.0301 against 0.033), on the left cap and not on its mirror, the right; on its breast plate at 0.91 as well (0.032 against 0.035). Read `nonManifoldEdges` after cutting (`boolean`, `freeze`, or a count on the evaluated mesh), and keep `thickness` clear of the first folding one with a thinner wall, fewer `levels` or wider facets at From 643dc599ab1ef2e90d01577f20a726dfbd53346c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 09:06:31 +0100 Subject: [PATCH 189/223] tests/fixtures/paladin_plates.json: Paladin's 16 single-view plates from one Blender run of e688951's build, each decided by its agent's plane; the thigh shields as partners are refused (two polygons, not one plate mirrored); a frame's turn is held to 1e-5, what a float32 matrix keeps Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/core.py | 2 +- surfaces/blender/docs/reference.md | 3 ++ .../tests/fixtures/paladin_plates.json | 1 + surfaces/blender/tests/test_reference.py | 29 +++++++++++++++++++ 4 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 surfaces/blender/tests/fixtures/paladin_plates.json diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index 970adee..bf6d11c 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -917,7 +917,7 @@ def block_plate(views, plate, traces, parse, plane=None, share=0.1, tol=TOL): F = np.array(frame, float) except (TypeError, ValueError): F = np.zeros(0) - if F.shape != (4, 4) or not np.isfinite(F).all() or np.abs(F[:3, :3].T @ F[:3, :3] - np.eye(3)).max() > 1e-6 or np.abs(F[3] - [0, 0, 0, 1]).max() > 1e-9: + if F.shape != (4, 4) or not np.isfinite(F).all() or np.abs(F[:3, :3].T @ F[:3, :3] - np.eye(3)).max() > 1e-5 or np.abs(F[3] - [0, 0, 0, 1]).max() > 1e-9: raise ReferenceFitError(f"{where}.frame must be a 4 x 4 that only turns and moves the part: a scaled or sheared frame is not metres of the plate") try: line = np.array(trace.get("line"), float) diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index c53f107..c9473b1 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -332,6 +332,9 @@ most from it, in four points; 0.05 s. A twisted pentagon 1.2 m across with sides 17.6 m off at 663 px: 39 and 52 mm from the truth at 60 degrees with traces 0.5 and 1.5 px off, every corner decided by the views; 65 and 135 mm at 19 degrees, where the plane already has 0.30 to 0.38 of each corner. At that range and lens two views 19 degrees apart do not decide a corner by this report's own line. +Paladin's 16 plates, each a polygon traced in one view with the plane its agent gave: every corner decided by the +plane, the crown within 1 mm of the one the harness had lifted. Its two thigh shields traced as partners are +refused, a side 19 px unexplained: the sheet draws two different polygons, not one plate and its reflection. What it gives up. One outline loop a plate: a plate that wraps a corner is two plates, and creases inside the outline are not blocked. A bend smaller than `tol` is built straight: the bowed pentagon's 56 mm bow reads under diff --git a/surfaces/blender/tests/fixtures/paladin_plates.json b/surfaces/blender/tests/fixtures/paladin_plates.json new file mode 100644 index 0000000..a89bd01 --- /dev/null +++ b/surfaces/blender/tests/fixtures/paladin_plates.json @@ -0,0 +1 @@ +{"note":"Paladin's 16 traced plates as e688951 (nibu/fable-paladin-2) blocked them, dumped from one Blender 5.3 run of its build (experiments/mechs/paladin.py as far as its last traced plate, against this repo's add-ons): per plate the view, the limb's frame as built, the plane the agent gave (point and normal in that frame), and the traced polygon of paladin_form.TRACES, a pixel a corner, moved by the camera's miss at the joints the build named, one two-point trace a side. reference.crown is the crown the build lifted onto the plane and reference.fit_prior_share the least and greatest prior_share its fit_shell read. ThighShield.partners is ThighR.Shield with ThighL.Shield's polygon as its partner (side -1, the left thigh's frame), corners paired by the nearest lifted crown: the two polygons are not one plate mirrored, their lifted corners stand 0.16 to 0.77 m apart. ShinR.Upper has five corners and ShinL.Upper four: no pairing.","cameras":{"hero":{"C":[3.166359458844853,18.291375677273702,5.974887522617769],"R":[[-0.9954714736026896,0.08115547119873885,0.049500855929980235],[0.07193169063267664,0.30264152317512244,0.9503862058831489],[0.06214802592210706,0.9496430371169752,-0.3071086532959184]],"f":662.9901734726185,"c":[130.21617396138112,-8.096494835726665]},"rear":{"C":[-22.074827146253003,-40.54367537122909,4.880872134117224],"R":[[0.8803045809036056,-0.470549824446539,0.06038797523893856],[-0.054618671581600865,0.02591956697507224,0.998170815423135],[-0.47125433213370943,-0.8819926523283265,-0.002883692781031549]],"f":2046.1791620298611,"c":[521.0,255.0]},"side":{"C":[74.22580229606024,1.0919442264947585,3.1052411455157483],"R":[[3.061616997868383e-16,1.0,0.0],[0.027200224236332445,-8.327666886778697e-18,0.9996300054527641],[0.9996300054527641,-3.060484216273447e-16,-0.027200224236332445]],"f":2919.7828838468417,"c":[787.5,255.0]}},"frames":{"f0":[[0.999706864,0.009348843,0.022330457,-2.854834557],[-8.7e-08,0.922424495,-0.386177242,0.434564203],[-0.024208475,0.386064053,0.922154129,6.620359421],[0.0,0.0,0.0,1.0]],"f1":[[1.0,0.0,0.0,-3.099999905],[0.0,1.0,0.0,0.350000024],[0.0,0.0,1.0,8.384795189],[0.0,0.0,0.0,1.0]],"f2":[[1.0,0.0,0.0,3.099999905],[0.0,1.0,0.0,0.350000024],[0.0,0.0,1.0,8.384795189],[0.0,0.0,0.0,1.0]],"f3":[[0.996464431,-0.024993408,0.080212094,-1.635337234],[3.2e-08,0.954726696,0.297484338,0.857389331],[-0.084015772,-0.296432555,0.951351285,3.586615086],[0.0,0.0,0.0,1.0]],"f4":[[0.991480708,0.034509547,-0.125598863,1.737102032],[-8.8e-08,0.964264691,0.264940679,0.861362159],[0.130253524,-0.26268363,0.956049919,3.599395275],[0.0,0.0,0.0,1.0]],"f5":[[0.996464431,0.034608867,0.076556362,-1.485286713],[3.2e-08,0.911213994,-0.411933333,0.050000001],[-0.084015772,0.410476923,0.907992363,5.366280079],[0.0,0.0,0.0,1.0]],"f6":[[0.991480708,-0.053919706,-0.118569165,1.504706502],[-8.8e-08,0.91029495,-0.413960278,0.050000001],[0.130253524,0.41043362,0.902539909,5.368373394],[0.0,0.0,0.0,1.0]]},"plates":{"ForearmL.Front":{"plate":{"corners":["c0","c1","c2","c3"]},"plane":{"point":[0,0.5,-1.0],"normal":[0.12,1,0.05]},"traces":[{"view":"hero","frame":"f0","from":"c0","to":"c1","side":1,"line":[[300.352,206.901],[318.352,203.901]]},{"view":"hero","frame":"f0","from":"c1","to":"c2","side":1,"line":[[318.352,203.901],[341.352,244.901]]},{"view":"hero","frame":"f0","from":"c2","to":"c3","side":1,"line":[[341.352,244.901],[326.352,253.901]]},{"view":"hero","frame":"f0","from":"c3","to":"c0","side":1,"line":[[326.352,253.901],[300.352,206.901]]}],"reference":{"crown":[[-0.06885,0.55132,-1.86109],[-0.4718,0.58919,-1.65145],[-0.13752,0.49637,-0.59739],[0.3254,0.44428,-0.66659]],"fit_prior_share":[0.957,0.966],"fit_refused":null}},"ForearmL.Outer":{"plate":{"corners":["c0","c1","c2","c3"]},"plane":{"point":[-0.36,0.38,-1.0],"normal":[-0.6,0.8,0]},"traces":[{"view":"hero","frame":"f0","from":"c0","to":"c1","side":1,"line":[[317.352,185.901],[327.352,186.901]]},{"view":"hero","frame":"f0","from":"c1","to":"c2","side":1,"line":[[327.352,186.901],[351.352,240.901]]},{"view":"hero","frame":"f0","from":"c2","to":"c3","side":1,"line":[[351.352,240.901],[343.352,247.901]]},{"view":"hero","frame":"f0","from":"c3","to":"c0","side":1,"line":[[343.352,247.901],[317.352,185.901]]}],"reference":{"crown":[[-0.69888,0.12584,-1.5561],[-1.06198,-0.14649,-1.2766],[-0.58265,0.21301,-0.00603],[-0.20602,0.49549,-0.11596]],"fit_prior_share":[0.998,1.0],"fit_refused":null}},"PauldronL.Front":{"plate":{"corners":["c0","c1","c2","c3","c4","c5"]},"plane":{"point":[0,1.34,0.1],"normal":[-0.22,1,0.3]},"traces":[{"view":"hero","frame":"f1","from":"c0","to":"c1","side":1,"line":[[287.046,82.555],[302.046,85.555]]},{"view":"hero","frame":"f1","from":"c1","to":"c2","side":1,"line":[[302.046,85.555],[327.046,125.555]]},{"view":"hero","frame":"f1","from":"c2","to":"c3","side":1,"line":[[327.046,125.555],[332.046,139.555]]},{"view":"hero","frame":"f1","from":"c3","to":"c4","side":1,"line":[[332.046,139.555],[319.046,155.555]]},{"view":"hero","frame":"f1","from":"c4","to":"c5","side":1,"line":[[319.046,155.555],[292.046,143.555]]},{"view":"hero","frame":"f1","from":"c5","to":"c0","side":1,"line":[[292.046,143.555],[287.046,82.555]]}],"reference":{"crown":[[1.08317,1.83903,-0.76912],[0.39257,1.75937,-1.01002],[-0.03547,1.53706,-0.58287],[0.04478,1.4498,-0.23316],[0.5966,1.26801,0.77746],[1.01705,1.34934,0.81469]],"fit_prior_share":[0.892,0.996],"fit_refused":null}},"PauldronL.Rear":{"plate":{"corners":["c0","c1","c2","c3","c4","c5"]},"plane":{"point":[0,-1.34,0.1],"normal":[-0.2,-1,0.3]},"traces":[{"view":"rear","frame":"f1","from":"c0","to":"c1","side":1,"line":[[439.3,45.444],[466.3,20.444]]},{"view":"rear","frame":"f1","from":"c1","to":"c2","side":1,"line":[[466.3,20.444],[479.3,28.444]]},{"view":"rear","frame":"f1","from":"c2","to":"c3","side":1,"line":[[479.3,28.444],[481.3,100.444]]},{"view":"rear","frame":"f1","from":"c3","to":"c4","side":1,"line":[[481.3,100.444],[466.3,115.444]]},{"view":"rear","frame":"f1","from":"c4","to":"c5","side":1,"line":[[466.3,115.444],[440.3,86.444]]},{"view":"rear","frame":"f1","from":"c5","to":"c0","side":1,"line":[[440.3,86.444],[439.3,45.444]]}],"reference":{"crown":[[-0.0372,-1.32587,0.12231],[0.48584,-1.60647,-0.46435],[0.84109,-1.57086,-0.10881],[0.91968,-1.10828,1.48552],[0.64337,-1.00748,1.63731],[0.00516,-1.0639,1.02376]],"fit_prior_share":[0.93,0.999],"fit_refused":null}},"PauldronR.Front":{"plate":{"corners":["c0","c1","c2","c3","c4","c5"]},"plane":{"point":[0,1.34,0.1],"normal":[0.22,1,0.3]},"traces":[{"view":"hero","frame":"f2","from":"c0","to":"c1","side":1,"line":[[96.805,67.754],[112.805,54.754]]},{"view":"hero","frame":"f2","from":"c1","to":"c2","side":1,"line":[[112.805,54.754],[131.805,55.754]]},{"view":"hero","frame":"f2","from":"c2","to":"c3","side":1,"line":[[131.805,55.754],[132.805,108.754]]},{"view":"hero","frame":"f2","from":"c3","to":"c4","side":1,"line":[[132.805,108.754],[119.805,122.754]]},{"view":"hero","frame":"f2","from":"c4","to":"c5","side":1,"line":[[119.805,122.754],[98.805,104.754]]},{"view":"hero","frame":"f2","from":"c5","to":"c0","side":1,"line":[[98.805,104.754],[96.805,67.754]]}],"reference":{"crown":[[-0.3798,1.47361,-0.06685],[-0.90805,1.72094,-0.50389],[-1.2103,1.67902,-0.14251],[-1.15307,1.24243,1.27081],[-0.66791,1.13033,1.28871],[-0.2769,1.15587,0.91682]],"fit_prior_share":[0.908,0.988],"fit_refused":null}},"PauldronR.Outer":{"plate":{"corners":["c0","c1","c2","c3","c4"]},"plane":{"point":[0.72,1.0,0.0],"normal":[0.75,0.6,0.3]},"traces":[{"view":"hero","frame":"f2","from":"c0","to":"c1","side":1,"line":[[95.805,69.754],[98.805,104.754]]},{"view":"hero","frame":"f2","from":"c1","to":"c2","side":1,"line":[[98.805,104.754],[83.805,119.754]]},{"view":"hero","frame":"f2","from":"c2","to":"c3","side":1,"line":[[83.805,119.754],[58.805,106.754]]},{"view":"hero","frame":"f2","from":"c3","to":"c4","side":1,"line":[[58.805,106.754],[56.805,99.754]]},{"view":"hero","frame":"f2","from":"c4","to":"c0","side":1,"line":[[56.805,99.754],[95.805,69.754]]}],"reference":{"crown":[[0.67692,1.02494,0.05783],[0.60612,1.21248,-0.14025],[-0.03193,2.2109,-0.54198],[-0.3535,2.44436,-0.20497],[-0.24172,1.83683,0.73064]],"fit_prior_share":[0.652,0.942],"fit_refused":null}},"ShinL.Inner":{"plate":{"corners":["c0","c1","c2","c3"]},"plane":{"point":[0.64,0.1,-1.2],"normal":[1,0.5,0]},"traces":[{"view":"hero","frame":"f3","from":"c0","to":"c1","side":1,"line":[[267.281,315.546],[285.281,302.546]]},{"view":"hero","frame":"f3","from":"c1","to":"c2","side":1,"line":[[285.281,302.546],[288.281,333.546]]},{"view":"hero","frame":"f3","from":"c2","to":"c3","side":1,"line":[[288.281,333.546],[275.281,345.546]]},{"view":"hero","frame":"f3","from":"c3","to":"c0","side":1,"line":[[275.281,345.546],[267.281,315.546]]}],"reference":{"crown":[[0.08941,1.20119,-0.07078],[-0.09318,1.56637,0.37388],[-0.0563,1.49259,1.02156],[0.2009,0.97821,0.50136]],"fit_prior_share":[0.933,0.992],"fit_refused":null}},"ShinL.Lower":{"plate":{"corners":["c0","c1","c2","c3"]},"plane":{"point":[0,0.7,-1.4],"normal":[-0.1,1,-0.08]},"traces":[{"view":"hero","frame":"f3","from":"c0","to":"c1","side":1,"line":[[291.746,334.445],[312.746,329.445]]},{"view":"hero","frame":"f3","from":"c1","to":"c2","side":1,"line":[[312.746,329.445],[303.746,352.445]]},{"view":"hero","frame":"f3","from":"c2","to":"c3","side":1,"line":[[303.746,352.445],[279.746,346.445]]},{"view":"hero","frame":"f3","from":"c3","to":"c0","side":1,"line":[[279.746,346.445],[291.746,334.445]]}],"reference":{"crown":[[-0.14864,0.7707,-0.33047],[-0.74551,0.69397,-0.54349],[-0.95935,0.71544,-0.00781],[-0.4394,0.76223,-0.07285]],"fit_prior_share":[0.937,0.998],"fit_refused":null}},"ShinL.Upper":{"plate":{"corners":["c0","c1","c2","c3"]},"plane":{"point":[0,0.86,-0.1],"normal":[-0.1,1,0.1]},"traces":[{"view":"hero","frame":"f3","from":"c0","to":"c1","side":1,"line":[[288.746,297.445],[305.746,296.445]]},{"view":"hero","frame":"f3","from":"c1","to":"c2","side":1,"line":[[305.746,296.445],[312.746,327.445]]},{"view":"hero","frame":"f3","from":"c2","to":"c3","side":1,"line":[[312.746,327.445],[291.746,332.445]]},{"view":"hero","frame":"f3","from":"c3","to":"c0","side":1,"line":[[291.746,332.445],[288.746,297.445]]}],"reference":{"crown":[[-0.42465,0.80781,-0.0027],[-0.94727,0.74963,0.05646],[-0.80695,0.69339,0.75912],[-0.38584,0.73396,0.77458]],"fit_prior_share":[0.909,0.942],"fit_refused":null}},"ShinR.Lower":{"plate":{"corners":["c0","c1","c2","c3","c4"]},"plane":{"point":[0,0.7,-1.4],"normal":[0.1,1,-0.08]},"traces":[{"view":"hero","frame":"f4","from":"c0","to":"c1","side":1,"line":[[113.561,326.916],[150.561,324.916]]},{"view":"hero","frame":"f4","from":"c1","to":"c2","side":1,"line":[[150.561,324.916],[147.561,358.916]]},{"view":"hero","frame":"f4","from":"c2","to":"c3","side":1,"line":[[147.561,358.916],[139.561,395.916]]},{"view":"hero","frame":"f4","from":"c3","to":"c4","side":1,"line":[[139.561,395.916],[111.561,398.916]]},{"view":"hero","frame":"f4","from":"c4","to":"c0","side":1,"line":[[111.561,398.916],[113.561,326.916]]}],"reference":{"crown":[[0.00201,0.6732,-1.73254],[-0.60378,0.75143,-1.51188],[-0.61382,0.82236,-0.63778],[-0.52739,0.87594,0.13998],[0.28087,0.77599,-0.09909]],"fit_prior_share":[0.869,0.99],"fit_refused":null}},"ShinR.Outer":{"plate":{"corners":["c0","c1","c2","c3","c4"]},"plane":{"point":[0.6,0.35,-1.5],"normal":[0.7,0.7,0]},"traces":[{"view":"hero","frame":"f4","from":"c0","to":"c1","side":1,"line":[[72.561,328.916],[88.561,316.916]]},{"view":"hero","frame":"f4","from":"c1","to":"c2","side":1,"line":[[88.561,316.916],[100.561,328.916]]},{"view":"hero","frame":"f4","from":"c2","to":"c3","side":1,"line":[[100.561,328.916],[100.561,383.916]]},{"view":"hero","frame":"f4","from":"c3","to":"c4","side":1,"line":[[100.561,383.916],[80.561,386.916]]},{"view":"hero","frame":"f4","from":"c4","to":"c0","side":1,"line":[[80.561,386.916],[72.561,328.916]]}],"reference":{"crown":[[0.72289,0.22711,-1.83415],[0.31158,0.63842,-1.46757],[0.53636,0.41364,-0.35818],[0.84834,0.10166,-0.27489],[1.15616,-0.20616,-0.75718]],"fit_prior_share":[0.849,0.999],"fit_refused":null}},"ShinR.Upper":{"plate":{"corners":["c0","c1","c2","c3","c4"]},"plane":{"point":[0,0.86,-0.1],"normal":[0.1,1,0.1]},"traces":[{"view":"hero","frame":"f4","from":"c0","to":"c1","side":1,"line":[[112.66,287.053],[143.66,291.053]]},{"view":"hero","frame":"f4","from":"c1","to":"c2","side":1,"line":[[143.66,291.053],[144.66,320.053]]},{"view":"hero","frame":"f4","from":"c2","to":"c3","side":1,"line":[[144.66,320.053],[121.66,325.053]]},{"view":"hero","frame":"f4","from":"c3","to":"c4","side":1,"line":[[121.66,325.053],[106.66,311.053]]},{"view":"hero","frame":"f4","from":"c4","to":"c0","side":1,"line":[[106.66,311.053],[112.66,287.053]]}],"reference":{"crown":[[0.50508,0.77741,0.22084],[0.11372,0.8384,0.00227],[-0.37595,0.86583,0.21762],[-0.23816,0.79185,0.8197],[0.4713,0.72747,0.754]],"fit_prior_share":[0.957,1.0],"fit_refused":null}},"ThighL.Inner":{"plate":{"corners":["c0","c1","c2","c3","c4"]},"plane":{"point":[0.74,0.25,-1.0],"normal":[1,0.55,0]},"traces":[{"view":"hero","frame":"f5","from":"c0","to":"c1","side":1,"line":[[243.338,250.068],[253.338,262.068]]},{"view":"hero","frame":"f5","from":"c1","to":"c2","side":1,"line":[[253.338,262.068],[263.338,292.068]]},{"view":"hero","frame":"f5","from":"c2","to":"c3","side":1,"line":[[263.338,292.068],[247.338,300.068]]},{"view":"hero","frame":"f5","from":"c3","to":"c4","side":1,"line":[[247.338,300.068],[233.338,268.068]]},{"view":"hero","frame":"f5","from":"c4","to":"c0","side":1,"line":[[233.338,268.068],[243.338,250.068]]}],"reference":{"crown":[[0.64942,0.41469,-0.92537],[0.50343,0.68012,-1.76754],[0.22347,1.18915,-1.76114],[0.29331,1.06216,-1.0278],[0.42366,0.82517,-0.6451]],"fit_prior_share":[0.869,0.913],"fit_refused":null}},"ThighL.Shield":{"plate":{"corners":["c0","c1","c2","c3","c4","c5","c6"]},"plane":{"point":[0,0.86,-0.9],"normal":[-0.12,1,0.08]},"traces":[{"view":"hero","frame":"f5","from":"c0","to":"c1","side":1,"line":[[252.338,243.068],[260.338,236.068]]},{"view":"hero","frame":"f5","from":"c1","to":"c2","side":1,"line":[[260.338,236.068],[273.338,238.068]]},{"view":"hero","frame":"f5","from":"c2","to":"c3","side":1,"line":[[273.338,238.068],[295.338,288.068]]},{"view":"hero","frame":"f5","from":"c3","to":"c4","side":1,"line":[[295.338,288.068],[291.338,296.068]]},{"view":"hero","frame":"f5","from":"c4","to":"c5","side":1,"line":[[291.338,296.068],[265.338,292.068]]},{"view":"hero","frame":"f5","from":"c5","to":"c6","side":1,"line":[[265.338,292.068],[253.338,262.068]]},{"view":"hero","frame":"f5","from":"c6","to":"c0","side":1,"line":[[253.338,262.068],[252.338,243.068]]}],"reference":{"crown":[[0.2485,0.89538,-0.96955],[0.10603,0.93559,-1.68579],[-0.51538,0.86882,-1.78331],[-0.6642,0.83615,-1.59821],[-0.40747,0.76773,-0.35786],[-0.07638,0.80346,-0.30779],[0.17235,0.84797,-0.4911]],"fit_prior_share":[0.887,0.964],"fit_refused":null}},"ThighR.Outer":{"plate":{"corners":["c0","c1","c2","c3","c4","c5"]},"plane":{"point":[0.62,0.5,-0.6],"normal":[0.7,0.7,0.1]},"traces":[{"view":"hero","frame":"f6","from":"c0","to":"c1","side":1,"line":[[111.702,188.513],[124.702,186.513]]},{"view":"hero","frame":"f6","from":"c1","to":"c2","side":1,"line":[[124.702,186.513],[120.702,217.513]]},{"view":"hero","frame":"f6","from":"c2","to":"c3","side":1,"line":[[120.702,217.513],[99.702,261.513]]},{"view":"hero","frame":"f6","from":"c3","to":"c4","side":1,"line":[[99.702,261.513],[87.702,261.513]]},{"view":"hero","frame":"f6","from":"c4","to":"c5","side":1,"line":[[87.702,261.513],[95.702,224.513]]},{"view":"hero","frame":"f6","from":"c5","to":"c0","side":1,"line":[[95.702,224.513],[111.702,188.513]]}],"reference":{"crown":[[1.05475,-0.01706,-0.02383],[1.09973,0.08158,-1.02911],[0.82099,0.36772,-1.08101],[0.48061,0.54859,0.03562],[0.48367,0.41439,0.95357],[0.79818,0.09537,0.98514]],"fit_prior_share":[0.823,0.98],"fit_refused":null}},"ThighR.Shield":{"plate":{"corners":["c0","c1","c2","c3","c4","c5","c6"]},"plane":{"point":[0,0.86,-0.9],"normal":[0.12,1,0.08]},"traces":[{"view":"hero","frame":"f6","from":"c0","to":"c1","side":1,"line":[[121.702,218.513],[150.702,221.513]]},{"view":"hero","frame":"f6","from":"c1","to":"c2","side":1,"line":[[150.702,221.513],[161.702,239.513]]},{"view":"hero","frame":"f6","from":"c2","to":"c3","side":1,"line":[[161.702,239.513],[161.702,273.513]]},{"view":"hero","frame":"f6","from":"c3","to":"c4","side":1,"line":[[161.702,273.513],[151.702,291.513]]},{"view":"hero","frame":"f6","from":"c4","to":"c5","side":1,"line":[[151.702,291.513],[113.702,280.513]]},{"view":"hero","frame":"f6","from":"c5","to":"c6","side":1,"line":[[113.702,280.513],[114.702,247.513]]},{"view":"hero","frame":"f6","from":"c6","to":"c0","side":1,"line":[[114.702,247.513],[121.702,218.513]]}],"reference":{"crown":[[0.53857,0.79075,-0.84226],[0.45475,0.86439,-1.63699],[-0.44412,0.98228,-1.76237],[-0.63795,0.96942,-1.31088],[-0.56905,0.8941,-0.47264],[-0.25844,0.82238,-0.04206],[0.46661,0.73756,-0.0694]],"fit_prior_share":[0.9,1.0],"fit_refused":null}},"ThighShield.partners":{"plate":{"corners":["c0","c1","c2","c3","c4","c5","c6"]},"traces":[{"view":"hero","frame":"f6","from":"c0","to":"c1","side":1,"line":[[121.702,218.513],[150.702,221.513]]},{"view":"hero","frame":"f6","from":"c1","to":"c2","side":1,"line":[[150.702,221.513],[161.702,239.513]]},{"view":"hero","frame":"f6","from":"c2","to":"c3","side":1,"line":[[161.702,239.513],[161.702,273.513]]},{"view":"hero","frame":"f6","from":"c3","to":"c4","side":1,"line":[[161.702,273.513],[151.702,291.513]]},{"view":"hero","frame":"f6","from":"c4","to":"c5","side":1,"line":[[151.702,291.513],[113.702,280.513]]},{"view":"hero","frame":"f6","from":"c5","to":"c6","side":1,"line":[[113.702,280.513],[114.702,247.513]]},{"view":"hero","frame":"f6","from":"c6","to":"c0","side":1,"line":[[114.702,247.513],[121.702,218.513]]},{"view":"hero","frame":"f5","from":"c0","to":"c1","side":-1,"line":[[295.338,288.068],[273.338,238.068]]},{"view":"hero","frame":"f5","from":"c1","to":"c2","side":-1,"line":[[273.338,238.068],[260.338,236.068]]},{"view":"hero","frame":"f5","from":"c2","to":"c3","side":-1,"line":[[260.338,236.068],[252.338,243.068]]},{"view":"hero","frame":"f5","from":"c3","to":"c4","side":-1,"line":[[252.338,243.068],[253.338,262.068]]},{"view":"hero","frame":"f5","from":"c4","to":"c5","side":-1,"line":[[253.338,262.068],[265.338,292.068]]},{"view":"hero","frame":"f5","from":"c5","to":"c6","side":-1,"line":[[265.338,292.068],[291.338,296.068]]},{"view":"hero","frame":"f5","from":"c6","to":"c0","side":-1,"line":[[291.338,296.068],[295.338,288.068]]}],"reference":{"crown":[[0.53857,0.79075,-0.84226],[0.45475,0.86439,-1.63699],[-0.44412,0.98228,-1.76237],[-0.63795,0.96942,-1.31088],[-0.56905,0.8941,-0.47264],[-0.25844,0.82238,-0.04206],[0.46661,0.73756,-0.0694]]}}}} \ No newline at end of file diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index 1f06e16..a18eb3a 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -900,6 +900,35 @@ class BlockTests(unittest.TestCase): self.assertEqual(out["sheet"]["mirror"], True) self.assertEqual(out["sheet"]["poles"], [seam[0], seam[1], len(out["sheet"]["verts"]) - 1]) + def test_paladin_plates_one_view_each(self): + """block-paladin (tests/fixtures/paladin_plates.json). Paladin's 16 traced plates, each a polygon traced in + one view with the plane the agent gave it: every corner is decided by the plane (prior_share 1.00 to 2.13: + over 1 where the sight line leans on the plane), every side stays two points, and the crown is the one the + harness lifted onto that plane, within 1 mm (its fit_shell read 0.65 to 1.0 on the same plates). None of + the 16 planes stands over 66 degrees off its view at e688951 (ForearmL.Outer, 61.6, is the furthest): the + guard is claimed by test_a_plane_far_off_square_on_to_its_one_view_is_refused. The thigh shields as + partners, the left's polygon seen as the right's reflection in the left thigh's frame, are refused, a side + 19.0 px unexplained at six points: the sheet's two polygons are not one plate mirrored (their lifted corners + stand 0.16 to 0.77 m apart), so no Paladin plate has a corner decided by a partner view here.""" + fixture = json.loads((Path(__file__).resolve().parent / "fixtures" / "paladin_plates.json").read_text(encoding="utf-8")) + + def block(name): + plate = fixture["plates"][name] + views = [(fixture["cameras"][trace["view"]], fixture["frames"][trace["frame"]]) for trace in plate["traces"]] + return plate, core.block_plate(views, plate["plate"], [{key: trace[key] for key in ("from", "to", "side", "line")} for trace in plate["traces"]], kit.sheet, plane=plate.get("plane")) + + single = sorted(name for name in fixture["plates"] if name != "ThighShield.partners") + self.assertEqual(len(single), 16) + for name in single: + plate, out = block(name) + n = len(plate["plate"]["corners"]) + self.assertEqual(({corner["decided_by"] for corner in out["corners"]}, [side["points"] for side in out["sides"]], out["plane"]["from"]), ({"plane"}, [2] * n, "given"), name) + self.assertGreater(min(corner["prior_share"] for corner in out["corners"]), 0.9, name) + crown, lifted = np.array(out["sheet"]["verts"])[:n], np.array(plate["reference"]["crown"]) # the harness turned some crowns to face out: the same ring from another corner, or the other way round + self.assertLess(min(float(np.abs(crown - np.roll(lifted[::way], turn, axis=0)).max()) for way in (1, -1) for turn in range(n)), 0.001, name) + with self.assertRaisesRegex(core.ReferenceFitError, r"^the side from 'c0' to 'c1' is not explained at 6 points, the most a side is given: traces\[0\] is not explained"): + block("ThighShield.partners") + def test_the_blocking_goes_to_the_parser_and_to_fit_shell(self): """block-then-fit without Blender (tests/live/reference_block.py builds it): the sheet is one the cage's parser takes, fit_traces name each side as a run of authored vertices, and fit_sheet takes both. On the From a570eb8478506f8fdd0346e68a6f38cceb140b0a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 09:21:34 +0100 Subject: [PATCH 190/223] tests/live/reference_block.py: tolerances round this scene's own readings (a pixel is 5 mm there); its last run Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/reference_block.py | 14 +++++++------- .../blender/tests/live/reference_block.result.json | 8 ++++---- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/surfaces/blender/tests/live/reference_block.py b/surfaces/blender/tests/live/reference_block.py index 7af9c42..ce4f864 100644 --- a/surfaces/blender/tests/live/reference_block.py +++ b/surfaces/blender/tests/live/reference_block.py @@ -9,9 +9,9 @@ side is traced in both views where Blender's own projection draws the side as co built brokkr_kitbash.shell takes the sheet without refusal, and at one level Blender builds each crown side where core.crease_run says fit_shell with the returned fit_traces on the built plate: accepted, every trace explained, and no point - moved further than the unit test's reading allows (tests/test_reference.py - test_the_blocking_goes_to_the_parser_and_to_fit_shell: fairness holds a bowed side in, and - fit_shell's own prior lets it out) + moved over MOVED (fairness holds a bowed side in and fit_shell's own prior lets it out: + tests/test_reference.py test_the_blocking_goes_to_the_parser_and_to_fit_shell reads 74 mm of + it where a pixel is 27 mm; here a pixel is 5 mm) mirrored a mirrored plate with two seam corners, traced the same way: the seam stays on x = 0, brokkr_kitbash.shell builds both halves, and Blender builds the seam's side and a free side where core.crease_run says @@ -69,7 +69,7 @@ R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_ COUNT = [0] T0 = time.time() WIDTH, HEIGHT = 1000, 800 -MOVED = 0.09 # metres fit_shell may move a point of the blocked bowed plate: the unit test's tolerance round its reading of 0.074 +MOVED, GAP, GAP_MIRRORED = 0.01, 0.01, 0.03 # metres, tolerances round this scene's readings (0.0048, 0.0027, 0.014; a pixel is 5 mm here): what fit_shell may move a point of the blocked plate, and how far the blocked crowns may stand from their truths def check(name, ok, detail=None): @@ -185,7 +185,7 @@ try: chains = chains_of(out) verts = np.array(out["sheet"]["verts"]) gap = max(float(core._off(built(verts[chain]), core.resampled(built(side), 400)).max()) for chain, side in zip(chains, sides)) - check("the blocked crown as built stands within 0.06 m of the truth's (the unit test's tolerance; fairness holds the bow in)", gap < 0.06, gap) + check(f"the blocked crown as built stands within {GAP:g} m of the truth's", gap < GAP, gap) worst = at_one_level("Blocked", out["sheet"], chains) check("brokkr_kitbash.shell takes the blocked sheet, and at one level Blender builds every crown side where core.crease_run says, within 1e-4 m", "Blocked" in bpy.data.objects and worst < 1e-4, worst) @@ -211,8 +211,8 @@ try: chains = chains_of(out) verts = np.array(out["sheet"]["verts"]) gap = max(float(core._off(built(verts[chain]), core.resampled(built(side), 400)).max()) for chain, side in zip(chains, sides)) - check("a mirrored plate: the seam's corners are decided by the mirror plane, its side stays on x = 0, and the crown as built stands within 0.06 m of the truth's", - [corner["decided_by"] for corner in out["corners"]][:2] == ["mirror", "mirror"] and float(np.abs(verts[chains[0], 0]).max()) == 0.0 and gap < 0.06, + check(f"a mirrored plate: the seam's corners are decided by the mirror plane, its side stays on x = 0, and the crown as built stands within {GAP_MIRRORED:g} m of the truth's", + [corner["decided_by"] for corner in out["corners"]][:2] == ["mirror", "mirror"] and float(np.abs(verts[chains[0], 0]).max()) == 0.0 and gap < GAP_MIRRORED, {"gap": gap, "sides": [side["points"] for side in out["sides"]], "corners": [corner["decided_by"] for corner in out["corners"]], "poles": out["sheet"]["poles"]}) worst = at_one_level("Mirrored", out["sheet"], chains, mirror=True) check("brokkr_kitbash.shell builds both halves of the mirrored sheet, and at one level Blender builds the seam's side and the free sides, on both halves, where core.crease_run says, within 1e-4 m", diff --git a/surfaces/blender/tests/live/reference_block.result.json b/surfaces/blender/tests/live/reference_block.result.json index 2d913ea..4c7503e 100644 --- a/surfaces/blender/tests/live/reference_block.result.json +++ b/surfaces/blender/tests/live/reference_block.result.json @@ -55,7 +55,7 @@ ] ], "rounds": 2, - "seconds": 0.236, + "seconds": 0.301, "chars": 7242 } }, @@ -65,7 +65,7 @@ "detail": null }, { - "name": "the blocked crown as built stands within 0.06 m of the truth's (the unit test's tolerance; fairness holds the bow in)", + "name": "the blocked crown as built stands within 0.01 m of the truth's", "ok": true, "detail": 0.002711610846938251 }, @@ -75,14 +75,14 @@ "detail": 1.1421151381392388e-07 }, { - "name": "fit_shell takes the returned fit_traces on the built plate: accepted, every trace explained, no point moved over 0.09 m", + "name": "fit_shell takes the returned fit_traces on the built plate: accepted, every trace explained, no point moved over 0.01 m", "ok": true, "detail": { "moved_m": 0.0048 } }, { - "name": "a mirrored plate: the seam's corners are decided by the mirror plane, its side stays on x = 0, and the crown as built stands within 0.06 m of the truth's", + "name": "a mirrored plate: the seam's corners are decided by the mirror plane, its side stays on x = 0, and the crown as built stands within 0.03 m of the truth's", "ok": true, "detail": { "gap": 0.013972102623404082, From 198b79590e34905fee0975a6636d3e2512d467cb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 10:31:07 +0100 Subject: [PATCH 191/223] brokkr_kitbash core: close_loop solves a two-unknown planar loop; LIMIT_SLACK at its measured midpoint core.close_loop is Newton on a closure's in-plane error over two joints in series, with the analytic Jacobian, refusing a loop that is not planar, a dead centre, no convergence and an axial miss. FollowTests reads it against ram.pose's four-bar and a barrel-and-rod loop. LIMIT_SLACK moves to 2.4e-7 with cases 1.2 either side (cut kit-follows-2, step 1). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/core.py | 81 ++++++++++++- surfaces/blender/tests/test_kitbash.py | 155 ++++++++++++++++++++++++ 2 files changed, 233 insertions(+), 3 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index e68c566..0473318 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1470,9 +1470,12 @@ def residual(parent_world, parent_socket: dict, child_world, child_socket: dict, DOFS = ("revolute", "prismatic") # what a socket type's dof may state: the child turns about the parent socket's z, or slides along it # How far past an end of its limits a joint's value may stand and still be inside them, as a fraction of the larger -# of 1 and the ends' sizes. A rule: an action's roll and slide are float32 fields and limits are JSON doubles, so a -# value typed as an end of its own limits stands up to 6e-08 of itself off that end; 1e-06 is 17 of those. -LIMIT_SLACK = 1e-6 +# of 1 and the ends' sizes. An action's roll and slide are float32 fields and limits are JSON doubles, so a value +# typed as an end of its own limits stands off that end: shipped worst 1.9e-08 of it (float32(-20.1), which must be +# inside); the least a test refuses stood 3e-06 off. The geometric mean, separation 12.6 each side. JointRecordTests +# reads both sides of it at 1.2: a slack of 2e-06 or 2.9e-06 takes the value 2.9e-07 off, one of 1.9e-08 loses the +# one 2e-07 off. +LIMIT_SLACK = 2.4e-7 def within(value: float, lo: float, hi: float, revolute: bool) -> float | None: @@ -1577,6 +1580,78 @@ def closure_residual(world_a, socket_a: dict, world_b, socket_b: dict) -> float: return float(max(np.abs(a[:3, 3] - b[:3, 3]).max(), np.abs(a[:3, 2] + b[:3, 2]).max())) +HELD = 1e-5 # a connection or a closure holds when its residual is at most this: the add-on's HELD is this one +# close_loop's three bounds, each read in FollowTests (lodur:ruling:deterministic-bound-margin). +# Metres of in-plane closure error Newton stops at. Shipped worst error of an accepted solve 4.1e-11; the least +# error it was still iterating on 2.5e-10; the geometric mean, +# separation 2.4 each side (read by an instrumented copy over FollowTests' solves). +FOLLOW_TOLERANCE = 1e-10 +# Newton steps one solve may take. Shipped worst 4 (a driver step of 5 degrees toward a dead centre, and one solve +# across a 40 degree jump); a rule, four times the worst. +FOLLOW_ITERATIONS = 16 +# The smaller singular value of the Jacobian with its two columns scaled to unit length (so a linkage's size and the +# metres-per-degree of a revolute column do not move it): about sin(angle between the columns) / sqrt(2), 0 at a dead +# centre, where the two unknowns move the closing pin along one line. Shipped least over the solves that are accepted +# 0.184; the greatest a refused solve reads 0.047 (the four-bar 6.7 degrees from straight); the geometric mean, separation 2.0 each side. +FOLLOW_SINGULAR = 0.093 + + +def close_loop(base_world, joints, closing: dict, target_world, seed) -> tuple[tuple[float, float], int]: + """((value 1, value 2), Newton iterations) that close a planar loop of two unknowns. `joints` is two + (parent socket, child socket, kind) in series: the first child mated on a socket of the part at base_world, the + second on a socket of the first; a value is a revolute joint's roll in degrees or a prismatic one's slide in + metres (its other coordinate is 0: a caller with a prismatic joint's stated roll turns the parent socket by it). + `closing` is the second child's socket that closes, target_world the 4x4 world frame of the socket it closes on. + Newton on the closing origin's error across the target's z, with the analytic Jacobian (a revolute column + z x (q - o) pi / 180 for the joint's pin z through o, a prismatic one z), from `seed`: the root found is the one + on the seed's assembly branch when the seed is near, so a caller steps its input. Refuses, naming which: pins + that are not parallel (each revolute z along the target's z, each prismatic z across it, the closing z opposed + to it: the loop is planar); a dead centre (FOLLOW_SINGULAR); no convergence in FOLLOW_ITERATIONS; and a loop + that closes in the plane and misses along the pin (closure_residual over HELD).""" + base, target = np.asarray(base_world, dtype=np.float64), np.asarray(target_world, dtype=np.float64) + (parent_1, child_1, kind_1), (parent_2, child_2, kind_2) = joints + n, values = target[:3, 2], np.array([float(seed[0]), float(seed[1])], dtype=np.float64) + + def placed(values): + at_1 = base @ parent_1["matrix"] + world_1 = base @ (mate(parent_1, child_1, values[0]) if kind_1 == "revolute" else mate(parent_1, child_1, 0.0, values[0])) + at_2 = world_1 @ parent_2["matrix"] + world_2 = world_1 @ (mate(parent_2, child_2, values[1]) if kind_2 == "revolute" else mate(parent_2, child_2, 0.0, values[1])) + return at_1, at_2, world_2 @ closing["matrix"] + + at_1, at_2, end = placed(values) + for name, kind, at in ((parent_1["name"], kind_1, at_1), (parent_2["name"], kind_2, at_2)): + off = float(np.abs(np.cross(at[:3, 2], n)).max() if kind == "revolute" else abs(at[:3, 2] @ n)) + if off > HELD: + raise KitError(f"the loop is not planar: the {kind} joint on socket {name!r} " + f"{'turns about a pin that is not parallel to' if kind == 'revolute' else 'slides along a line that is not across'} " + f"the pin it closes on (off by {off:.6g})") + if float(np.abs(end[:3, 2] + n).max()) > HELD: + raise KitError(f"the loop is not planar: closing socket {closing['name']!r} does not face the pin it closes on " + f"(normals off by {float(np.abs(end[:3, 2] + n).max()):.6g})") + for iteration in range(FOLLOW_ITERATIONS + 1): + at_1, at_2, end = placed(values) + error = target[:3, 3] - end[:3, 3] + error = error - n * (error @ n) + J = np.stack([np.cross(at[:3, 2], end[:3, 3] - at[:3, 3]) * (math.pi / 180.0) if kind == "revolute" else at[:3, 2] + for kind, at in ((kind_1, at_1), (kind_2, at_2))], axis=1) + lengths = np.linalg.norm(J, axis=0) + singular = 0.0 if lengths.min() < 1e-12 else float(np.linalg.svd(J / lengths, compute_uv=False)[-1]) + if singular < FOLLOW_SINGULAR: + raise KitError(f"the loop is at a dead centre (its two joints move closing socket {closing['name']!r} along one line: " + f"conditioning {singular:.3g}, under {FOLLOW_SINGULAR:g})") + if float(np.linalg.norm(error)) <= FOLLOW_TOLERANCE: + break + if iteration == FOLLOW_ITERATIONS: + raise KitError(f"the loop did not close in {FOLLOW_ITERATIONS} steps (closing socket {closing['name']!r} stands " + f"{float(np.linalg.norm(error)):.6g} m off in the plane)") + values = values + np.linalg.lstsq(J, error, rcond=None)[0] + apart = closure_residual(np.eye(4), {"matrix": end}, np.eye(4), {"matrix": target}) + if apart > HELD: + raise KitError(f"the loop closes in its plane and closing socket {closing['name']!r} misses along the pin by {apart:.6g} m") + return (float(values[0]), float(values[1])), iteration + + EQUAL, SLACK = 0.01, 1e-9 # 'equal' sizes may differ by 1 percent of the larger; SLACK keeps a size at the limit inside it diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 49d85e2..584dd63 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1594,6 +1594,161 @@ class JointRecordTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, "it reaches -1.000000 m to 1.000000 m"): core.reach_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (1.0, 0.0, 0.0), 1.5, 0.0, (0.0, 90.0)) + def test_limit_slack_sits_between_a_typed_end_and_the_least_refused(self): + """joint-records-lows. core.LIMIT_SLACK at the midpoint of its readings (2.4e-07), read 1.2 either side: a + slack of 1.9e-08 loses float32(-20.1) and the value 2e-07 off; one of 2e-06 or 2.9e-06 (or the 1e-06 there + was) takes the value 2.9e-07 off.""" + typed = float(np.float32(-20.1)) + self.assertAlmostEqual(abs(typed + 20.1) / 20.1, 1.9e-8, delta=1e-9) + for revolute in (False, True): + self.assertEqual(core.within(typed, -20.1, 5.0, revolute), -20.1) + self.assertEqual(core.within(-20.1 * (1 + 2.0e-7), -20.1, 5.0, revolute), -20.1) + self.assertIsNone(core.within(5.0 + 20.1 * 2.9e-7, -20.1, 5.0, revolute)) + self.assertIsNone(core.within(-20.1 * (1 + 2.9e-7), -20.1, 5.0, False)) + + +@unittest.skipIf(np is None, "numpy is not installed") +class FollowTests(unittest.TestCase): + """core.close_loop: a driven pair of joints solved from the kit's socket frames and one closure. The four-bar is + three mechanical struts, crank (the driver, on a ground pin), rocker and coupler, the coupler's end_b closing on the + crank's end_b, against ram.pose's analytic four-bar; the ram is a ram_barrel on a ground pin and a ram_rod in its + bore, rod_end closing on the crank's end_b_back. Bounds by lodur:ruling:deterministic-bound-margin; T1 is + core.FOLLOW_TOLERANCE at core.HELD.""" + D0, REST, RAM_REST = 30.0, (-40.0, 70.0), (200.0, 0.1) + PHI = 2.8e-7 # degrees between the rocker's roll change and ram.pose's phi. shipped 1.9e-10; least mutant 4.0e-4 (T1); separation 1.4e3 each side + SLID = 5.6e-10 # metres between the rod's slide and |pin - base| less the closed length. shipped 5.4e-13; least mutant 5.9e-7 (T1); separation 1.0e3 each side + BRANCH = 1e-6 # degrees between one solve across a jump and the stepped answer. shipped 4e-12 (both converge to FOLLOW_TOLERANCE); a rule: the other branch stands tens of degrees off + + @classmethod + def setUpClass(cls): + spec = importlib.util.spec_from_file_location("brokkr_kitbash_ram_reference", SURFACE / "brokkr_kitbash" / "ram.py") + cls.ram = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = cls.ram + spec.loader.exec_module(cls.ram) + kit = core.load_kit("mechanical") + sockets = lambda name, **params: {s["name"]: s for s in core.build(core.part(kit, name), params).sockets} # noqa: E731 + cls.crank, cls.rocker, cls.coupler = sockets("strut", length=0.5), sockets("strut", length=0.9), sockets("strut", length=0.7) + cls.barrel, cls.rod = sockets("ram_barrel"), sockets("ram_rod") + cls.ground = cls.pin((0.0, 0.0, 0.0)) + cls.rocker_pin = cls.pin(cls.crank_pin(cls.D0)[:3, 3] - cls.coupler_end(cls.ground, cls.REST)[:3, 3]) # where the loop closes at rest + cls.four_bar = [(cls.rocker_pin, cls.rocker["end_a"], "revolute"), (cls.rocker["end_b"], cls.coupler["end_a"], "revolute")] + cls.barrel_pin = cls.pin(cls.crank_pin(cls.D0, "end_b_back")[:3, 3] - cls.rod_end(cls.ground, cls.RAM_REST)[:3, 3]) + cls.ram_loop = [(cls.barrel_pin, cls.barrel["base"], "revolute"), (cls.barrel["bore"], cls.rod["piston"], "prismatic")] + + @staticmethod + def pin(origin, z=(0.0, 1.0, 0.0), y=(0.0, 0.0, 1.0)): + z, y, frame = np.array(z, dtype=np.float64), np.array(y, dtype=np.float64), np.eye(4) + frame[:3, 0], frame[:3, 1], frame[:3, 2], frame[:3, 3] = np.cross(y, z), y, z, origin + return {"name": "ground", "type": "pivot", "matrix": frame} + + @classmethod + def crank_pin(cls, driver, socket="end_b"): + return core.mate(cls.ground, cls.crank["end_a"], driver) @ cls.crank[socket]["matrix"] + + @classmethod + def coupler_end(cls, pin, values): + return core.mate(pin, cls.rocker["end_a"], values[0]) @ core.mate(cls.rocker["end_b"], cls.coupler["end_a"], values[1]) @ cls.coupler["end_b"]["matrix"] + + @classmethod + def rod_end(cls, pin, values): + return core.mate(pin, cls.barrel["base"], values[0]) @ core.mate(cls.barrel["bore"], cls.rod["piston"], 0.0, values[1]) @ cls.rod["rod_end"]["matrix"] + + def solve(self, driver, seed): + return core.close_loop(np.eye(4), self.four_bar, self.coupler["end_b"], self.crank_pin(driver), seed) + + def conditioning(self, values): + """The reading core.FOLLOW_SINGULAR bounds, by this file's own route: the two unit Jacobian columns' smaller singular value.""" + first = core.mate(self.rocker_pin, self.rocker["end_a"], values[0]) + q, columns = self.coupler_end(self.rocker_pin, values)[:3, 3], [] + for at in (self.rocker_pin["matrix"], first @ self.rocker["end_b"]["matrix"]): + column = np.cross(at[:3, 2], q - at[:3, 3]) + columns.append(column / np.linalg.norm(column)) + return float(np.linalg.svd(np.stack(columns, axis=1), compute_uv=False)[-1]) + + def stepped(self, deltas): + seed, worst = self.REST, {"phi": 0.0, "iterations": 0, "conditioning": math.inf} + rest = (core.mate(self.rocker_pin, self.rocker["end_a"], self.REST[0]) @ self.rocker["end_b"]["matrix"])[:3, 3] + four_bar = self.ram.Mechanism("four_bar", pivot=self.ground["matrix"][:3, 3], axis=self.ground["matrix"][:3, 2], lo=-90, hi=130, a=np.array([0.3, 0.0, -0.4]), + rocker=self.rocker_pin["matrix"][:3, 3], p=rest, c=self.crank_pin(self.D0)[:3, 3], d=rest) + for delta in deltas: + seed, iterations = self.solve(self.D0 + delta, seed) + worst["phi"] = max(worst["phi"], abs(seed[0] - self.REST[0] - math.degrees(self.ram.pose(four_bar, delta).phi[0]))) + worst["iterations"], worst["conditioning"] = max(worst["iterations"], iterations), min(worst["conditioning"], self.conditioning(seed)) + return seed, worst + + def test_a_four_bar_loop_matches_ram_pose(self): + """loop-matches-ram-pose. 56 driver steps of 5 degrees, +120 and back to -30. Mutant F1 (a revolute Jacobian + column's sign flipped: no solve converges). The readings here are the shipped side of core's three bounds: + conditioning least 0.184 (at -30), iterations at most 4 (the step to -30).""" + _, worst = self.stepped([*np.arange(0.0, 121.0, 5.0), *np.arange(120.0, -31.0, -5.0)]) + self.assertLess(worst["phi"], self.PHI) + self.assertEqual(worst["iterations"], 4) + self.assertAlmostEqual(worst["conditioning"], 0.184, delta=0.001) + self.assertGreater(worst["conditioning"], 1.2 * core.FOLLOW_SINGULAR) + + def test_a_ram_loop_slides_to_the_pin(self): + """loop-matches-ram-pose, a revolute and a prismatic unknown: the slide is the distance from the barrel's base + pin to the pin the rod closes on, less that distance closed.""" + seed, base, worst = self.RAM_REST, self.barrel_pin["matrix"][:3, 3], 0.0 + closed = float(np.linalg.norm(self.rod_end(self.barrel_pin, (self.RAM_REST[0], 0.0))[:3, 3] - base)) + for delta in np.arange(0.0, 121.0, 5.0): + target = self.crank_pin(self.D0 + delta, "end_b_back") + seed, iterations = core.close_loop(np.eye(4), self.ram_loop, self.rod["rod_end"], target, seed) + worst = max(worst, abs(seed[1] - (float(np.linalg.norm(target[:3, 3] - base)) - closed))) + self.assertLessEqual(iterations, 3) + self.assertLess(worst, self.SLID) + self.assertGreater(seed[1] - self.RAM_REST[1], 0.2) # the rod moved + + def test_a_dead_centre_is_refused(self): + """loop-refusals. Stepping the crank back, rocker and coupler straighten: the step to -35 stands 6.7 degrees + from straight, conditioning 0.047, the refused side of core.FOLLOW_SINGULAR; past it no pose closes the loop.""" + seed, _ = self.stepped(np.arange(0.0, -31.0, -5.0)) + self.assertLess(0.047, core.FOLLOW_SINGULAR / 1.2) + for delta in (-35.0, -40.0, -60.0): + with self.assertRaisesRegex(core.KitError, r"^the loop is at a dead centre \(its two joints move closing socket 'end_b' along one line"): + self.solve(self.D0 + delta, seed) + near, _ = self.stepped(np.arange(0.0, -34.0, -1.0)) # by single degrees it is accepted to -33, and -34 reads 0.092 + self.assertAlmostEqual(self.conditioning(near), 0.1212, delta=0.001) + with self.assertRaisesRegex(core.KitError, r"conditioning 0\.0919, under 0\.093\)$"): + self.solve(self.D0 - 34.0, near) + + def test_a_loop_that_is_not_planar_is_refused(self): + """loop-refusals. Mutant F8 (the parallel check dropped). A pin a degree off the closure's, a slide a degree out + of the plane, a closing socket facing the wrong way, and a loop that closes in the plane and misses along the pin.""" + tilted = self.pin(self.rocker_pin["matrix"][:3, 3], z=(math.sin(math.radians(1.0)), math.cos(math.radians(1.0)), 0.0)) + with self.assertRaisesRegex(core.KitError, r"^the loop is not planar: the revolute joint on socket 'ground' turns about a pin that is not parallel to the pin it closes on \(off by 0\.0174"): + core.close_loop(np.eye(4), [(tilted, self.rocker["end_a"], "revolute"), self.four_bar[1]], self.coupler["end_b"], self.crank_pin(self.D0), self.REST) + lean = np.eye(4) + lean[:3, :3] = core._rotation((1.0, 0.0, 0.0)) + bore = {**self.barrel["bore"], "matrix": self.barrel["bore"]["matrix"] @ lean} + with self.assertRaisesRegex(core.KitError, r"the prismatic joint on socket 'bore' slides along a line that is not across the pin it closes on"): + core.close_loop(np.eye(4), [self.ram_loop[0], (bore, self.rod["piston"], "prismatic")], self.rod["rod_end"], self.crank_pin(self.D0, "end_b_back"), self.RAM_REST) + with self.assertRaisesRegex(core.KitError, r"closing socket 'end_b_back' does not face the pin it closes on"): + core.close_loop(np.eye(4), self.four_bar, self.coupler["end_b_back"], self.crank_pin(self.D0), self.REST) + missed = self.crank_pin(self.D0) + missed[:3, 3] += 0.001 * missed[:3, 2] + with self.assertRaisesRegex(core.KitError, r"^the loop closes in its plane and closing socket 'end_b' misses along the pin by 0\.001 m$"): + core.close_loop(np.eye(4), self.four_bar, self.coupler["end_b"], missed, self.REST) + self.assertEqual(self.solve(self.D0, self.REST), (self.REST, 0)) # at rest it holds: no step is taken + + def test_stepping_keeps_the_assembly_branch(self): + """branch-kept. One solve across a 40 degree jump lands on the stepped answer; one solve from near the toggle + (-32) across 49 degrees does not: Newton's first step throws the pair through the dead centre, where it is + refused instead of landing on the other branch, and the same jump stepped by 5 arrives. Mutant F2 is the + add-on's (pose solving once from the stated value): tests/live/kitbash_follows.py kills it.""" + stepped, _ = self.stepped(np.arange(0.0, 41.0, 5.0)) + jumped, iterations = self.solve(self.D0 + 40.0, self.REST) + self.assertLess(max(abs(a - b) for a, b in zip(stepped, jumped)), self.BRANCH) + self.assertEqual(iterations, 4) + toggle, _ = self.stepped(np.arange(0.0, -33.0, -1.0)) + with self.assertRaisesRegex(core.KitError, "dead centre"): + self.solve(self.D0 + 17.0, toggle) + seed = toggle + for delta in (-27.0, -22.0, -17.0, -12.0, -7.0, -2.0, 3.0, 8.0, 13.0, 17.0): + seed, _ = self.solve(self.D0 + delta, seed) + direct, _ = self.stepped([17.0]) + self.assertLess(max(abs(a - b) for a, b in zip(seed, direct)), self.BRANCH) + @unittest.skipIf(np is None, "numpy is not installed") class StructureTests(unittest.TestCase): From 53eac397c7f5c5d9ac86e78facd16a98f500b78a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 10:42:56 +0100 Subject: [PATCH 192/223] brokkr_kitbash: followers derived from their driver; write_connections writes them with it; joints v2 The record gains follows (kit_follows, kit_follows_driver). write_connections checks every entry before writing any; set_params seats through it, so its direct seat loop goes and a hand-edited out-of-limit roll or stray slide is refused. joint_record reads None for what record_refusal would refuse. pose() refuses a follower and derives a driver's followers (driven: ratio, then loops by core.close_loop, stepped). brokkr_kitbash.follow states and clears; detach clears a loop partner. brokkr.joints version 2: driven, unlimited, after/next, the root's own row (cut kit-follows-2, steps 2 to 4). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 505 ++++++++++++++++---- surfaces/blender/tests/live/kitbash_pose.py | 8 +- surfaces/blender/tests/test_kitbash.py | 41 +- 3 files changed, 461 insertions(+), 93 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 83f47c5..5546959 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -62,8 +62,15 @@ follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes th 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 -solves a loop: a closure never places a part, and a report says how far its two sockets stand apart. +writes them, only when the two sockets already meet, and writes nothing else; detach clears them. A closure never +places a part, and a report says how far its two sockets stand apart. + +A connection may follow another: kit_follows on the follower (a ratio k and offset, or a loop) and kit_follows_driver, +a pointer to the driver. A follower's kit_roll or kit_slide is then derived: by k x the driver's value + offset, or, +for the closing part of a loop and its parent, by solving the two so the closure holds (core.close_loop, over the +kit's socket frames at stored params: no pin is stored). pose() derives every follower of a driver in the driver's +own action (driven) and write_connections writes them with it, all or none; roll, aim, reach and slide on a follower +are refused. A follower has one driver and a driver is never a follower. No Blender driver or constraint is made. """ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (5, 3, 0), "category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."} @@ -90,13 +97,14 @@ from . import core, route KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" SOCKET, PARENT_SOCKET, ROLL = "kit_socket", "kit_parent_socket", "kit_roll" SLIDE, LIMIT_MIN, LIMIT_MAX, MECHANISM, COMPLIANCE = "kit_slide", "kit_min", "kit_max", "kit_mechanism", "kit_compliance" # a connection's joint record; write_connection is its one writer -RECORD = (SLIDE, LIMIT_MIN, LIMIT_MAX, MECHANISM, COMPLIANCE) +FOLLOWS, FOLLOWS_DRIVER = "kit_follows", "kit_follows_driver" # on a follower's connection: what its value is derived from, as JSON, and an ID pointer to the driver; write_connections is their one writer +RECORD = (SLIDE, LIMIT_MIN, LIMIT_MAX, MECHANISM, COMPLIANCE, FOLLOWS, FOLLOWS_DRIVER) LABEL = r"[a-z0-9_]{1,32}" # a mechanism label TURN, TRAVEL, HERTZ, DAMPING = 360.0, 10.0, 30.0, 2.0 # what a joint record may state: degrees a revolute joint's limits span and stand from 0, metres a prismatic one's stand from 0, a compliance's hertz and damping ratio FROZEN = "kit_frozen" # on a frozen object: an ID pointer to its live mesh; its presence is the frozen state. hold writes it and nothing else does KEPT = "kit_kept" # on a live mesh a frozen object holds: an ID pointer to that object's frozen mesh, beside the fake user that keeps the live mesh through a purge. hold writes both 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) +HELD = core.HELD # 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 @@ -115,6 +123,7 @@ HOSE_OFFSETS = ((0.0, 0.0, 0.0), (0.5, 0.5, 0.5), (0.31, 0.67, 0.13)) # of a st HOSE_FINEST = 0.005 # metres: the least step, and the least a refused step is halved to for one more round of seeds HOSE_SEGMENTS = 12 # sides of a hose, a ferrule and a clamp's pad ROLL_STEP = 5.0 # degrees between the rolls of a joint's range that hose measures first: the step an assembly's clearance is read at +FOLLOW_SLIDE_STEP = 0.02 # metres a prismatic driver moves between the solves of the loops that follow it, as ROLL_STEP degrees for a revolute one: a rule, 0.044 m is what a 0.5 m crank's pin moves in 5 degrees ROLL_FINEST = 0.3 # degrees: the half width under which a bin of rolls that falls short is refused instead of halved (5 degrees halved 4 times) @@ -211,23 +220,52 @@ def dof(parent, parent_socket: dict): return core.load_kit(str(parent.get(KIT, "")))["socketTypes"][parent_socket["type"]].get("dof") +def connection_kind(obj) -> tuple: + """(DOF kind, parent socket type) of the connection a child states, from the parent's kit by the socket's name + alone (a socket's type is the same at every params), or (None, None) when it cannot be read: no parent, a + parent that is no kit part, a socket the part does not have.""" + try: + kit = core.load_kit(str(obj.parent.get(KIT, ""))) + socket_type = next(s["type"] for s in core.part(kit, str(obj.parent[PART]))["sockets"] if s["name"] == obj.get(PARENT_SOCKET)) + return kit["socketTypes"][socket_type].get("dof"), socket_type + except (AttributeError, KeyError, StopIteration, core.KitError): + return None, None + + def joint_record(obj) -> dict: - """The joint record a child's connection states, {limits: (lo, hi) or None, mechanism, compliance}: degrees of - its roll on a revolute joint, metres of its slide on a prismatic one. Every report, the joints report, the - poses and hose read it here. A value written by hand that write_connection would not have written reads None.""" - lo, hi, label, spring = obj.get(LIMIT_MIN), obj.get(LIMIT_MAX), obj.get(MECHANISM), None + """The joint record a child's connection states, {limits: (lo, hi) or None, mechanism, compliance, follows}: + degrees of its roll on a revolute joint, metres of its slide on a prismatic one; follows is None or {driver (the + object, None once it is gone, as closure's other part), kind 'ratio' | 'loop', k, offset}. Every report, the joints report, the + poses and hose read it here. A value written by hand that write_connections would not have written reads None: + one that is not of its shape, and one record_refusal refuses for this connection's DOF kind (a compliance on a + revolute joint), so no report emits it and the next write clears it.""" + lo, hi, label, spring, follows = obj.get(LIMIT_MIN), obj.get(LIMIT_MAX), obj.get(MECHANISM), None, None with contextlib.suppress(ValueError, TypeError): spring = json.loads(obj.get(COMPLIANCE, "null")) - return {"limits": (float(lo), float(hi)) if core.finite(lo) and core.finite(hi) and lo <= hi else None, - "mechanism": label if isinstance(label, str) and re.fullmatch(LABEL, label) else None, - "compliance": spring if isinstance(spring, dict) and set(spring) == {"hertz", "damping_ratio"} and all(core.finite(v) for v in spring.values()) else None} + with contextlib.suppress(ValueError, TypeError): + follows = json.loads(obj.get(FOLLOWS, "null")) + ratio = (isinstance(follows, dict) and set(follows) == {"kind", "k", "offset"} and follows["kind"] == "ratio" + and core.finite(follows["k"]) and follows["k"] != 0 and core.finite(follows["offset"])) + driver = obj.get(FOLLOWS_DRIVER) + record = {"limits": (float(lo), float(hi)) if core.finite(lo) and core.finite(hi) and lo <= hi else None, + "mechanism": label if isinstance(label, str) and re.fullmatch(LABEL, label) else None, + "compliance": spring if isinstance(spring, dict) and set(spring) == {"hertz", "damping_ratio"} and all(core.finite(v) for v in spring.values()) else None, + "follows": {"driver": driver if isinstance(driver, bpy.types.Object) and driver.users_collection else None, "kind": follows["kind"], + "k": float(follows["k"]) if ratio else None, "offset": float(follows["offset"]) if ratio else None} + if ratio or follows == {"kind": "loop"} else None} + kind, socket_type = connection_kind(obj) + for field in ("limits", "mechanism", "compliance", "follows"): # limits first: a compliance is read beside the limits that stand + alone = {**dict.fromkeys(record), "limits": record["limits"] if field == "compliance" else None, field: record[field]} + if record[field] is not None and record_refusal(kind, socket_type, alone) is not None: + record[field] = None + return record def record_refusal(kind, socket_type: str, record: dict) -> str | None: """None when a connection of this DOF kind may carry the record, else why not.""" limits, spring = record["limits"], record["compliance"] if kind is None: - return (f"socket type {socket_type!r} states no dof: the connection is rigid and carries no limits, mechanism or compliance" + return (f"socket type {socket_type!r} states no dof: the connection is rigid and carries no limits, mechanism, compliance or follows" if any(value is not None for value in record.values()) else None) if limits is not None and kind == "revolute" and (limits[1] - limits[0] > TURN or max(abs(limits[0]), abs(limits[1])) > TURN): return f"limits {limits[0]:.6g} to {limits[1]:.6g}: a revolute joint's span at most {TURN:g} degrees, each end within {TURN:g} of 0" @@ -319,38 +357,221 @@ def seat(child, basis) -> None: child.matrix_basis = Matrix(np.asarray(basis).tolist()) +def connection_checks(entries) -> list: + """What write_connections writes for `entries`, each checked: (child, parent, sockets, socket, parent socket, + roll, slide, DOF kind, record). An entry is (child, parent, mated()'s sockets for `stated`, stated, the joint + record to state or None to keep the one the child states). Refuses, naming the connection, a record its DOF + kind may not carry (record_refusal), a slide on a connection that is not prismatic, and a value with no + representative inside the limits (core.within), naming value and limits; the value answered is that + representative. Writes nothing.""" + checked = [] + for child, parent, sockets, stated, record in entries: + kind, (socket, parent_socket, roll, slide) = dof(parent, sockets[0]), stated + record, here = joint_record(child) if record is None else record, f"{child.name!r} on {parent.name!r}" + refusal = record_refusal(kind, sockets[0]["type"], record) + if refusal is None and kind != "prismatic" and slide != 0.0: + refusal = f"socket type {sockets[0]['type']!r} is {kind or 'rigid'}: only a prismatic connection slides" + if refusal is None and record["limits"] is not None: + value = roll if kind == "revolute" else slide + inside = core.within(value, *record["limits"], kind == "revolute") + if inside is None: + refusal = (f"its {'roll' if kind == 'revolute' else 'slide'} {value:.6g} is outside the joint's limits " + f"{record['limits'][0]:.6g} to {record['limits'][1]:.6g}") + roll, slide = (inside, slide) if kind == "revolute" else (roll, inside) + if refusal: + raise Refused(f"{here}: {refusal}; nothing changed.") + checked.append((child, parent, sockets, socket, parent_socket, roll, slide, kind, record)) + return checked + + +def write_connections(entries) -> None: + """State connections and seat them, all or none: each child's parent, its derived matrix_basis, its three + properties and its joint record, kit_follows and its driver pointer with it. Every entry is checked + (connection_checks) before any is written, so one refusal leaves every part as it stood. attach, set_params, + roll, aim, reach, slide, joint and follow write a connection here and nowhere else, so what a joint record may + be, and that a follower's value is written with its driver's, is decided here.""" + for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in connection_checks(entries): + child.parent = parent + seat(child, core.mate(*sockets, roll, slide)) + child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll + (lo, hi), follows = record["limits"] or (None, None), record["follows"] + for key, value in ((SLIDE, slide if kind == "prismatic" else None), (LIMIT_MIN, lo), (LIMIT_MAX, hi), (MECHANISM, record["mechanism"]), + (COMPLIANCE, record["compliance"] and json.dumps(record["compliance"], sort_keys=True))): + if value is not None: + child[key] = value + elif key in child: + del child[key] + for key in (FOLLOWS, FOLLOWS_DRIVER): + if key in child and (follows is None or follows["driver"] is None and key == FOLLOWS_DRIVER): + del child[key] + if follows is not None: + child[FOLLOWS] = json.dumps({key: follows[key] for key in ("kind", "k", "offset") if follows[key] is not None}, sort_keys=True) + if follows is not None and follows["driver"] is not None: + child[FOLLOWS_DRIVER] = follows["driver"] + + def write_connection(child, parent, sockets, stated, record=None) -> None: - """State a connection and seat it: the child's parent, its derived matrix_basis, its three properties and its - joint record. `sockets` is mated()'s answer for `stated`; `record` is the joint record to state (joint_record's - shape), None to keep the one the child states. attach, roll, aim, reach, slide and joint write a connection - here and nowhere else, so what a joint record may be is decided here: before anything is written it refuses a - record its DOF kind may not carry (record_refusal), a slide on a connection that is not prismatic, and a value - with no representative inside the limits (core.within), naming value and limits; the value written is that - representative.""" - kind, (socket, parent_socket, roll, slide) = dof(parent, sockets[0]), stated - record, here = joint_record(child) if record is None else record, f"{child.name!r} on {parent.name!r}" - refusal = record_refusal(kind, sockets[0]["type"], record) - if refusal is None and kind != "prismatic" and slide != 0.0: - refusal = f"socket type {sockets[0]['type']!r} is {kind or 'rigid'}: only a prismatic connection slides" - if refusal is None and record["limits"] is not None: - value = roll if kind == "revolute" else slide - inside = core.within(value, *record["limits"], kind == "revolute") - if inside is None: - refusal = (f"its {'roll' if kind == 'revolute' else 'slide'} {value:.6g} is outside the joint's limits " - f"{record['limits'][0]:.6g} to {record['limits'][1]:.6g}") - roll, slide = (inside, slide) if kind == "revolute" else (roll, inside) - if refusal: - raise Refused(f"{here}: {refusal}; nothing changed.") - child.parent = parent - seat(child, core.mate(*sockets, roll, slide)) - child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll - lo, hi = record["limits"] or (None, None) - for key, value in ((SLIDE, slide if kind == "prismatic" else None), (LIMIT_MIN, lo), (LIMIT_MAX, hi), (MECHANISM, record["mechanism"]), - (COMPLIANCE, record["compliance"] and json.dumps(record["compliance"], sort_keys=True))): - if value is not None: - child[key] = value - elif key in child: - del child[key] + """write_connections for one connection.""" + write_connections([(child, parent, sockets, stated, record)]) + + +def followers(driver) -> list: + """The parts whose connection states that it follows `driver`, by name.""" + return sorted((o for o in bpy.data.objects if o.get(FOLLOWS_DRIVER) == driver and o.users_collection and joint_record(o)["follows"] is not None), + key=lambda o: o.name) + + +def loop_pair(obj, stating=None): + """(the parent follower, the closing follower) of the loop a loop follower is one of, or None when it has no + partner. The closing follower states the closure and its parent is the other: both follow one driver as a + loop, and the parent follower states no closure (follow and close keep it so).""" + def loop_of(o): + follows = (stating or {}).get(o) or joint_record(o)["follows"] + return follows["driver"] if follows is not None and follows["kind"] == "loop" else None + driver = loop_of(obj) + if driver is None: + return None + if CLOSE in obj: + return (obj.parent, obj) if obj.parent is not None and CLOSE not in obj.parent and loop_of(obj.parent) == driver else None + closing = [child for child in sorted(attached(obj), key=lambda o: o.name) if CLOSE in child and loop_of(child) == driver] + return (obj, closing[0]) if closing else None + + +def driven(driver, sockets, stated, roll: float, slide: float, record, stating=None) -> tuple[list, list]: + """(the entries write_connections takes, [{part, value}]) for a connection given a new value and everything + that follows it: the one place a follower's value is derived. `stating` is {part: follows} for followers a + follow is about to state. With no follower the entry is the connection's own. With some, the driver steps from + its stated value to the new one in ceil(|change| / step) steps (ROLL_STEP degrees, FOLLOW_SLIDE_STEP metres; at + least one, so posing a driver where it stands derives its followers again), and each step places ratio followers + (k x the driver's value + offset) and then solves each loop (core.close_loop, seeded by the step before) in an + order where a loop's base and the part it closes on are placed before it. Worlds are composed from stated mates + and the scene's matrices; nothing is written. Only the last step is answered. Refuses a ratio whose driver + states no limits, a loop without its partner or its closure, loops that wait on each other, and what close_loop + refuses, naming the driver's value and the closing part.""" + stating, kits = stating or {}, {} + own = (driver, driver.parent, sockets, (stated[0], stated[1], roll, slide), record) + found = sorted({*followers(driver), *stating}, key=lambda o: o.name) + kind = dof(driver.parent, sockets[0]) + if not found or kind is None: + return [own], [] + *_, roll, slide, _, record = connection_checks([own])[0] # the driver's value as it will be written, or its refusal + revolute = kind == "revolute" + old, new = (stated[2], roll) if revolute else (stated[3], slide) + change = core._wrapped(new - old) if revolute and record["limits"] is None else new - old + count = max(1, math.ceil(abs(change) / (ROLL_STEP if revolute else FOLLOW_SLIDE_STEP))) + + def read(obj): + part, built = built_part(obj, kits) + said = link(obj) + if said is None or obj.parent is None: + raise Refused(f"{obj.name!r} follows {driver.name!r} and states no connection: brokkr_kitbash.follow with record null clears it; nothing changed.") + mates = mated(obj.parent, *built_part(obj.parent, kits), obj, part, built, said) + return mates, dof(obj.parent, mates[0]), said, {**joint_record(obj), **({"follows": stating[obj]} if obj in stating else {})} + + links = {obj: read(obj) for obj in found} + links[driver] = (sockets, kind, stated, record) + ratios, loops = [obj for obj in found if links[obj][3]["follows"]["kind"] == "ratio"], [] + if ratios and record["limits"] is None: + raise Refused(f"{driver.name!r} on {driver.parent.name!r}: {ratios[0].name!r} follows it by ratio, and a ratio's driver states limits (its value is then " + "one number, not one of many a turn apart): give it limits with brokkr_kitbash.joint; nothing changed.") + for obj in found: + if obj in ratios or CLOSE not in obj and loop_pair(obj, stating) is not None: + continue + pair, closing = loop_pair(obj, stating), closure(obj) + if pair is None or closing is None or closing[1] is None: + raise Refused(f"{obj.name!r} follows {driver.name!r} as a loop and has no {'partner (a closing part and its parent, both following the driver)' if pair is None else 'part to close on'}: " + "brokkr_kitbash.follow with record null clears it; nothing changed.") + other_part, other_built = built_part(closing[1], kits) + there, here = mated(closing[1], other_part, other_built, obj, *built_part(obj, kits), (closing[0], closing[2], 0.0, 0.0), "closing on") + joints = [({**links[o][0][0], "matrix": links[o][0][0]["matrix"] @ core._roll(links[o][2][2])} if links[o][1] == "prismatic" else links[o][0][0], + links[o][0][1], links[o][1]) for o in pair] + loops.append({"pair": pair, "base": pair[0].parent, "to": closing[1], "there": there, "here": here, "joints": joints, + "seed": tuple(links[o][2][2] if links[o][1] == "revolute" else links[o][2][3] for o in pair)}) + + def above(obj) -> set: + found = set() + while obj is not None: + found.add(obj) + obj = obj.parent + return found + + ordered, waiting = [], list(loops) # a loop waits on every loop one of whose pair is its base, the part it closes on, or above either + while waiting: + ready = [loop for loop in waiting if not any(set(other["pair"]) & (above(loop["base"]) | above(loop["to"])) for other in waiting if other is not loop)] + if not ready: + raise Refused(f"{driver.name!r}: the loops closing at {', '.join(repr(loop['pair'][1].name) for loop in waiting)} each wait on another: " + "a loop's base and the part it closes on are placed before it is solved; nothing changed.") + ordered.append(ready[0]) + waiting.remove(ready[0]) + values = {} + + def world(obj, memo): + if obj not in memo: + if obj.parent is None: + memo[obj] = np.array(obj.matrix_world, dtype=np.float64) + elif obj in values: + memo[obj] = world(obj.parent, memo) @ core.mate(*links[obj][0], *values[obj]) + else: # it moves with its parent as it stands on it + memo[obj] = world(obj.parent, memo) @ np.linalg.inv(np.array(obj.parent.matrix_world, dtype=np.float64)) @ np.array(obj.matrix_world, dtype=np.float64) + return memo[obj] + + def valued(obj, value): + return (value, links[obj][2][3]) if links[obj][1] == "revolute" else (links[obj][2][2], value) + + for step in range(1, count + 1): + at = new if step == count else old + change * step / count + values = {driver: valued(driver, at)} + for obj in ratios: + values[obj] = valued(obj, links[obj][3]["follows"]["k"] * at + links[obj][3]["follows"]["offset"]) + for loop in ordered: + memo = {} + try: + loop["seed"], _ = core.close_loop(world(loop["base"], memo), loop["joints"], loop["here"], world(loop["to"], memo) @ loop["there"]["matrix"], loop["seed"]) + except core.KitError as error: + raise Refused(f"{driver.name!r} at {at:.6g}: the loop {loop['pair'][1].name!r} closes on {loop['to'].name!r} ({loop['pair'][0].name!r} and " + f"{loop['pair'][1].name!r} follow): {error}; nothing changed.") from None + for obj, value in zip(loop["pair"], loop["seed"]): + values[obj] = valued(obj, value) + entries, moved = [own], [] + for obj in (*ratios, *(obj for loop in ordered for obj in loop["pair"])): + mates, its_kind, said, its_record = links[obj] + value = values[obj][0] if its_kind == "revolute" else values[obj][1] + if its_kind == "revolute" and its_record["limits"] is None: + value = core._wrapped(value) # a derived roll has no turn to keep + entries.append((obj, obj.parent, mates, (said[0], said[1], *valued(obj, value)), its_record)) + moved.append({"part": obj.name, "value": round(value, 6)}) + return entries, moved + + +def follows_report(obj, record: dict, kind, stated) -> dict | None: + """None for a connection that follows nothing, else {driver, kind, k, offset, holds, reason}. A ratio holds when + the value stands within HELD of k x the driver's + offset (a roll: of a turn of it); a loop when the closure its + closing part states holds. holds is false with a reason when the driver is gone or states no DOF connection. + Derived at each report; stored nowhere.""" + follows = record["follows"] + if follows is None: + return None + driver = follows["driver"] + row = {"driver": driver and driver.name, "kind": follows["kind"], "k": follows["k"], "offset": follows["offset"], "holds": False, "reason": None} + said, driver_kind = (link(driver), connection_kind(driver)[0]) if driver is not None else (None, None) + if driver is None: + row["reason"] = "the driver is gone: deleted, or in no collection" + elif said is None or driver_kind is None or said[2] is None or said[3] is None: + row["reason"] = "the driver states no DOF connection" + elif follows["kind"] == "ratio": + want = follows["k"] * (said[2] if driver_kind == "revolute" else said[3]) + follows["offset"] + off = abs(core._wrapped(stated[2] - want)) if kind == "revolute" else abs(stated[3] - want) + if off > HELD: + row["reason"] = f"its value stands {off:.6g} from k x the driver's + offset: pose the driver" + else: + pair = loop_pair(obj) + found = closure_report(pair[1], *built_part(pair[1])) if pair is not None else None + if found is None: + row["reason"] = "its loop has no partner: a closing part and its parent, both following the driver" + elif not found["holds"]: + row["reason"] = f"the closure {pair[1].name!r} states does not hold ({found['reason']}): pose the driver" + row["holds"] = row["reason"] is None + return row def connection_report(obj, part, built): @@ -359,7 +580,7 @@ def connection_report(obj, part, built): stands within HELD of core.mate. A child moved or re-parented by another action reads holds false until set_params seats it again. With it the joint record: dof (the parent socket's type's: revolute, prismatic or null for rigid), slide, limits, mechanism, compliance, and within, false only for a value written by hand - outside its limits.""" + outside its limits; and follows (follows_report), null for a connection that follows nothing.""" stated = link(obj) if stated is None: return None @@ -367,7 +588,7 @@ def connection_report(obj, part, built): row = {"parent": obj.parent.name if obj.parent else None, "socket": stated[0], "parentSocket": stated[1], "roll": None if stated[2] is None else round(stated[2], 6), "residual": None, "holds": False, "dof": None, "slide": None if stated[3] is None else round(stated[3], 6), "limits": record["limits"] and [round(v, 6) for v in record["limits"]], - "mechanism": record["mechanism"], "compliance": record["compliance"], "within": True} + "mechanism": record["mechanism"], "compliance": record["compliance"], "within": True, "follows": None} try: if obj.parent is None or stated[2] is None or stated[3] is None: return row @@ -378,6 +599,7 @@ def connection_report(obj, part, built): return row if record["limits"] is not None and row["dof"] is not None: row["within"] = core.within(stated[2] if row["dof"] == "revolute" else stated[3], *record["limits"], row["dof"] == "revolute") is not None + row["follows"] = follows_report(obj, record, row["dof"], stated) row["residual"] = round(core.residual(obj.parent.matrix_world, parent_socket, obj.matrix_world, socket, stated[2], stated[3]), 9) row["holds"] = bool(np.abs(np.array(obj.matrix_parent_inverse) - np.eye(4)).max() <= HELD and row["residual"] <= HELD) return row @@ -699,7 +921,9 @@ class BROKKR_KITBASH_OT_place_part(PolishOperator): class BROKKR_KITBASH_OT_set_params(PolishOperator): """Change params of a placed kit part and rebuild its mesh in place: its modifiers and material slots stay, each shape keeps its faces' material, the Bevel width follows, and its connection and those of the parts - attached to it are seated again on the moved sockets; a closure is never seated, only reported""" + attached to it are seated again on the moved sockets, through write_connections (a value outside its joint's + limits or a stray slide, written by hand, is refused before anything changes); a closure is never seated and a + follower never derived again, only reported""" bl_idname = "brokkr_kitbash.set_params" bl_label = "Set Kit Part Params" object_name: bpy.props.StringProperty(name="Object") @@ -717,15 +941,16 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): mated(closing[1], *built_part(closing[1]), obj, part, built, (closing[0], closing[2], 0.0, 0.0), "closing on") for other in closing_on(obj): mated(obj, part, built, other, *built_part(other), (closure(other)[0], closure(other)[2], 0.0, 0.0), "closing on") - seats, stated = [], link(obj) # every connection this part is an end of, checked against its new sockets before anything is written + entries, stated = [], link(obj) # every connection this part is an end of, checked against its new sockets and its joint record before anything is written if stated is not None: if obj.parent is None: raise Refused(f"{obj.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.") parent_part, parent_built = built_part(obj.parent) - seats.append((obj, core.mate(*mated(obj.parent, parent_part, parent_built, obj, part, built, stated), *stated[2:]))) + entries.append((obj, obj.parent, mated(obj.parent, parent_part, parent_built, obj, part, built, stated), stated, None)) for child in attached(obj): child_part, child_built = built_part(child) - seats.append((child, core.mate(*mated(obj, part, built, child, child_part, child_built, link(child)), *link(child)[2:]))) + entries.append((child, obj, mated(obj, part, built, child, child_part, child_built, link(child)), link(child), None)) + connection_checks(entries) try: old = core.build(part, stored) except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by @@ -738,9 +963,8 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): obj.data.update() sync_bevel(obj, built.bevel) obj[PARAMS] = json.dumps(built.params) - for seated, basis in seats: # deeper descendants follow through parenting: their sockets did not move - seat(seated, basis) - if seats: + write_connections(entries) # deeper descendants follow through parenting: their sockets did not move + if entries: context.view_layer.update() report = part_report(obj, part, built) report["closures"] = scene_closures(context, report, (obj,)) @@ -778,14 +1002,15 @@ class BROKKR_KITBASH_OT_attach(PolishOperator): sockets = mated(parent, parent_part, parent_built, child, part, built, stated) free(parent, self.parent_socket) free(child, self.socket) - write_connection(child, parent, sockets, stated, {"limits": None, "mechanism": None, "compliance": None}) # a new connection states no joint record: brokkr_kitbash.joint gives it one + write_connection(child, parent, sockets, stated, dict.fromkeys(("limits", "mechanism", "compliance", "follows"))) # a new connection states no joint record: brokkr_kitbash.joint and follow give it one context.view_layer.update() return part_report(child, part, built) class BROKKR_KITBASH_OT_detach(PolishOperator): """Clear a kit part's connection and the closure it states: it stays where it stands in the world, loses its - parent, and the parts attached to it stay attached to it""" + parent, and the parts attached to it stay attached to it. A loop follower's partner stops following with it; a + driver's followers keep their statements and report that the driver states no DOF connection""" bl_idname = "brokkr_kitbash.detach" bl_label = "Detach Kit Part" object_name: bpy.props.StringProperty(name="Object") @@ -796,6 +1021,7 @@ class BROKKR_KITBASH_OT_detach(PolishOperator): if SOCKET not in obj and CLOSE not in obj: raise Refused(f"{obj.name!r} is not attached (it has no {SOCKET} property) and states no closure; nothing changed.") part, built = built_part(obj) + pair = loop_pair(obj) # a loop follower's partner follows nothing once the loop is gone if SOCKET in obj: world = obj.matrix_world.copy() obj.parent = None @@ -803,17 +1029,24 @@ class BROKKR_KITBASH_OT_detach(PolishOperator): for key in (SOCKET, PARENT_SOCKET, ROLL, *RECORD, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET): if key in obj: del obj[key] + for other in pair or (): + for key in (FOLLOWS, FOLLOWS_DRIVER): + if key in other: + del other[key] return part_report(obj, part, built) -def pose(context, name: str, solve) -> dict: +def pose(context, name: str, solve, keeps: bool = False) -> dict: """Give an attached part a new roll, slide or joint record where it hangs: its parent and both sockets stay, and what is attached to it follows. `solve(child, built, sockets, stated, joint)` answers (the roll, the slide, what to add to the report, the joint record to state or None to keep it), or refuses; `joint` is the record the connection states with its `dof` and the parent socket's `type`. Refuses a part that states no connection or - has no parent, what mated() refuses and what write_connection does: a value outside the joint's limits. The - report is the part's and, as set_params', every closure in the scene with the part's own first: a pose can open - one, and never seats one.""" + has no parent, what mated() refuses and what write_connections does: a value outside the joint's limits. A + follower's value is derived: it is refused here, naming its driver, unless the solve `keeps` the value (joint's). + A driver's followers are derived with it (driven) and written with it in one write_connections: one of them + outside its own limits, or a loop that cannot close, refuses the pose with nothing changed. The report is the + part's with followers, [{part, value}] in the order written, and, as set_params', every closure in the scene + with the part's own first: a pose can open one, and seats none but those of the loops that follow it.""" child = mesh_object(name) part, built = built_part(child) stated = link(child) @@ -822,13 +1055,18 @@ def pose(context, name: str, solve) -> dict: if child.parent is None: raise Refused(f"{child.name!r} states a connection and has no parent: detach it to clear the connection; nothing changed.") sockets = mated(child.parent, *built_part(child.parent), child, part, built, stated) + follows = joint_record(child)["follows"] + if follows is not None and not keeps: + raise Refused(f"{child.name!r} follows {repr(follows['driver'].name) if follows['driver'] else 'a driver that is gone'} ({follows['kind']}): its value is derived. " + "Pose the driver, or clear the statement with brokkr_kitbash.follow and record null; nothing changed.") try: roll, slide, solved, record = solve(child, built, sockets, stated, {**joint_record(child), "dof": dof(child.parent, sockets[0]), "type": sockets[0]["type"]}) except core.KitError as error: raise Refused(f"{child.name!r} on {child.parent.name!r}: {error}; nothing changed.") from None - write_connection(child, child.parent, sockets, (stated[0], stated[1], float(roll), float(slide)), record) + entries, moved = driven(child, sockets, stated, float(roll), float(slide), record) + write_connections(entries) context.view_layer.update() - report = {**part_report(child, part, built), **solved} + report = {**part_report(child, part, built), **solved, "followers": moved} report["closures"] = scene_closures(context, report, (child,)) return report @@ -902,7 +1140,7 @@ class BROKKR_KITBASH_OT_reach(PolishOperator): class BROKKR_KITBASH_OT_joint(PolishOperator): """State the joint record of an attached kit part's connection: its limits, a mechanism label and, on a slide, - its compliance""" + its compliance. A follower keeps its derived value; a driver's followers are derived again""" bl_idname = "brokkr_kitbash.joint" bl_label = "State Kit Joint" object_name: bpy.props.StringProperty(name="Object", description="An attached part on a revolute or prismatic socket") @@ -926,7 +1164,7 @@ class BROKKR_KITBASH_OT_joint(PolishOperator): def solve(child, built, sockets, stated, joint): if joint["dof"] is None: raise Refused(f"{child.name!r} on {child.parent.name!r}: socket type {joint['type']!r} states no dof: the connection is rigid and carries no joint record; nothing changed.") - record = {key: joint[key] for key in ("limits", "mechanism", "compliance")} + record = {key: joint[key] for key in ("limits", "mechanism", "compliance", "follows")} if "limits" in given: record["limits"] = limits and (float(limits[0]), float(limits[1])) if "mechanism" in given: @@ -934,7 +1172,7 @@ class BROKKR_KITBASH_OT_joint(PolishOperator): if "compliance" in given: record["compliance"] = spring and {key: float(spring[key]) for key in ("hertz", "damping_ratio")} return stated[2], stated[3], {}, record - return pose(context, self.object_name, solve) + return pose(context, self.object_name, solve, keeps=True) class BROKKR_KITBASH_OT_slide(PolishOperator): @@ -958,38 +1196,137 @@ class BROKKR_KITBASH_OT_slide(PolishOperator): class BROKKR_KITBASH_OT_joints(PolishOperator): """Report the joints of the tree of kit parts under a root: each revolute or prismatic connection with its - parent joint, axis, value, limits, mechanism and compliance, in the root's frame""" + parent joint, axis, value, limits, mechanism, compliance and what drives it, in the root's frame""" bl_idname = "brokkr_kitbash.joints" bl_label = "Report Kit Joints" bl_options = {"REGISTER"} - object_name: bpy.props.StringProperty(name="Object", description="The root: a kit part; the report is of what is attached below it") + object_name: bpy.props.StringProperty(name="Object", description="The root: a kit part; the report is of its own joint, when it states one, and of what is attached below it") + after: bpy.props.StringProperty(name="After", description="Empty, or the id of a row: the report carries the rows after it (the `next` of the report before)") @kit_work def work(self, context): root, kits, rows, rigid_count = mesh_object(self.object_name), {}, [], 0 built_part(root, kits) frame = np.linalg.inv(np.array(root.matrix_world, dtype=np.float64)) - todo = [(child, None) for child in sorted(attached(root), key=lambda o: o.name, reverse=True)] + todo = [(root, None)] while todo: # depth first, children by name: a joint's parent joint is the nearest DOF connection above it, and rigid connections fold into it child, above = todo.pop() - part, built = built_part(child, kits) - stated = link(child) - parent_socket, _ = mated(child.parent, *built_part(child.parent, kits), child, part, built, stated) - kind = dof(child.parent, parent_socket) - if kind is None: - rigid_count += 1 - else: - record, value = joint_record(child), stated[2] if kind == "revolute" else stated[3] - at = frame @ np.array(child.parent.matrix_world, dtype=np.float64) @ parent_socket["matrix"] - limits = record["limits"] and [round(v, 6) for v in record["limits"]] - rows.append({"id": child.name, "parent": above, "part": part["name"], "socket": f"{child.parent.name}:{stated[1]}", "kind": kind, - "axis": [round(float(v), 6) for v in at[:3, 2]], "origin": [round(float(v), 6) for v in at[:3, 3]], "value": round(value, 6), - "limits": limits, "min": limits and round(record["limits"][0] - value, 6), "max": limits and round(record["limits"][1] - value, 6), - "mechanism": record["mechanism"], "compliance": record["compliance"]}) - above = child.name + if child != root or link(child) is not None and child.parent is not None and PART in child.parent: # the root's own joint comes first, parent null + part, built = built_part(child, kits) + stated = link(child) + parent_socket, _ = mated(child.parent, *built_part(child.parent, kits), child, part, built, stated) + kind = dof(child.parent, parent_socket) + if kind is None: + rigid_count += child != root + else: + record, value = joint_record(child), stated[2] if kind == "revolute" else stated[3] + at = frame @ np.array(child.parent.matrix_world, dtype=np.float64) @ parent_socket["matrix"] + limits, follows = record["limits"] and [round(v, 6) for v in record["limits"]], record["follows"] + rows.append({"id": child.name, "parent": above, "part": part["name"], "socket": f"{child.parent.name}:{stated[1]}", "kind": kind, + "axis": [round(float(v), 6) for v in at[:3, 2]], "origin": [round(float(v), 6) for v in at[:3, 3]], "value": round(value, 6), + "limits": limits, "min": limits and round(record["limits"][0] - value, 6), "max": limits and round(record["limits"][1] - value, 6), + "mechanism": record["mechanism"], "compliance": record["compliance"], + "driven": follows and {"by": follows["driver"] and follows["driver"].name, "kind": follows["kind"], "k": follows["k"], "offset": follows["offset"]}}) + above = child.name todo += [(below, above) for below in sorted(attached(child), key=lambda o: o.name, reverse=True)] - report = {"schema": "brokkr.joints", "version": 1, "root": root.name, "frame": "the root object's: Blender axes (+Z up), metres", "rigid": rigid_count} + report = {"schema": "brokkr.joints", "version": 2, "root": root.name, "frame": "the root object's: Blender axes (+Z up), metres", "rigid": rigid_count, + "unlimited": [row["id"] for row in rows if row["limits"] is None and row["driven"] is None], "next": "x" * 63} + if self.after: + ids = [row["id"] for row in rows] + if self.after not in ids: + raise Refused(f"after {self.after!r} is not the id of a joint under {root.name!r}: it is the `next` of the report before, or empty.") + rows = rows[ids.index(self.after) + 1:] report["joints"] = fitted(report, "joints", rows) + report["next"] = report["joints"][-1]["id"] if "jointsOmitted" in report and report["joints"] else None + return report + + +class BROKKR_KITBASH_OT_follow(PolishOperator): + """State that an attached kit part's joint follows another's: its value is derived from the driver's, by a ratio + or by closing the loop its closure states, whenever the driver is posed""" + bl_idname = "brokkr_kitbash.follow" + bl_label = "Follow Kit Joint" + object_name: bpy.props.StringProperty(name="Object", description="The follower: a part attached on a revolute or prismatic socket; for a loop, the part that states the closure") + record: bpy.props.StringProperty(name="Record", default="null", description='{"driver": name, "kind": "ratio", "k": number, "offset": number}, ' + '{"driver": name, "kind": "loop"}, or null to clear') + + @kit_work + def work(self, context): + try: + given = json.loads(self.record) + except ValueError as error: + raise Refused(f"record must be JSON ({error}); nothing changed.") from None + ratio = isinstance(given, dict) and set(given) == {"driver", "kind", "k", "offset"} and given["kind"] == "ratio" + if not (given is None or isinstance(given, dict) and isinstance(given.get("driver"), str) and ( + ratio and core.finite(given["k"]) and given["k"] != 0 and core.finite(given["offset"]) or set(given) == {"driver", "kind"} and given["kind"] == "loop")): + raise Refused('record must be {"driver": name, "kind": "ratio", "k": a number that is not 0, "offset": a number}, {"driver": name, "kind": "loop"}, ' + "or null to clear; nothing changed.") + obj = mesh_object(self.object_name) + part, built = built_part(obj) + + def connection(o, what): + """(sockets, stated, DOF kind) of the DOF connection a part states, or the refusal that names what it is here.""" + said = link(o) + if said is None or o.parent is None: + raise Refused(f"{o.name!r} ({what}) is not attached: attach gives it a connection; nothing changed.") + mates = mated(o.parent, *built_part(o.parent), o, *built_part(o), said) + if dof(o.parent, mates[0]) is None: + raise Refused(f"{o.name!r} ({what}) on {o.parent.name!r}: socket type {mates[0]['type']!r} states no dof: the connection is rigid, " + "and only a revolute or prismatic connection follows or drives; nothing changed.") + return mates, said, dof(o.parent, mates[0]) + + sockets, stated, _ = connection(obj, "the follower") + current = joint_record(obj)["follows"] + if given is None: + if current is None: + raise Refused(f"{obj.name!r} follows nothing; nothing changed.") + cleared = loop_pair(obj) or (obj,) + write_connections([(o, o.parent, connection(o, "a follower")[0], link(o), {**joint_record(o), "follows": None}) for o in cleared]) + context.view_layer.update() + return {**part_report(obj, part, built), "cleared": [o.name for o in cleared]} + driver = mesh_object(given["driver"]) + pair = (obj,) if ratio else (obj.parent, obj) + if not ratio: + connection(obj.parent, "the follower's parent: a loop's two unknowns are the closing part's joint and its parent's") + closing = closure(obj) + if not ratio and (closing is None or closing[1] is None or not closure_report(obj, part, built)["holds"]): + raise Refused(f"{obj.name!r} states no closure that holds: a loop follower is the part that states the closure (brokkr_kitbash.close, where the " + "two sockets meet), and its joint and its parent's are solved to keep it; nothing changed.") + if not ratio and CLOSE in obj.parent: + raise Refused(f"{obj.parent.name!r}, the parent of {obj.name!r}, states a closure itself: a loop's parent follower states none; nothing changed.") + driver_sockets, driver_stated, _ = connection(driver, "the driver") + if joint_record(driver)["follows"] is not None: + raise Refused(f"{driver.name!r} is itself a follower: a driver is never a follower (one joint, one driver); nothing changed.") + for o in pair: + below = driver + while below is not None and below != o: + below = below.parent + if below == o: + raise Refused(f"{driver.name!r} is {'the follower itself' if driver == o else 'below ' + repr(o.name)}: a follower's driver is neither it nor below it; nothing changed.") + if joint_record(o)["follows"] is not None: + raise Refused(f"{o.name!r} already follows: clear it first (brokkr_kitbash.follow with record null); nothing changed.") + if followers(o): + raise Refused(f"{o.name!r} drives {followers(o)[0].name!r}: a driver is never a follower (one joint, one driver); nothing changed.") + if ratio and joint_record(driver)["limits"] is None: + raise Refused(f"{driver.name!r} states no limits: a ratio's driver states them (its value is then one number, not one of many a turn apart); " + "brokkr_kitbash.joint gives it limits; nothing changed.") + if not ratio: + moving = {driver, *followers(driver)} # what moves when the driver is posed: it, what follows it, and what hangs from either + + def moves(o) -> bool: + while o is not None and o not in moving: + o = o.parent + return o is not None + ends = (obj.parent.parent, closing[1]) + if moves(ends[0]) == moves(ends[1]): + raise Refused(f"the loop's two ends, {ends[0].name!r} (the base) and {ends[1].name!r} (closed on), {'both move' if moves(ends[0]) else 'neither moves'} with " + f"{driver.name!r}: exactly one of them is the driver, follows it, or hangs from one that does; nothing changed.") + follows = {"driver": driver, "kind": given["kind"], "k": float(given["k"]) if ratio else None, "offset": float(given["offset"]) if ratio else None} + entries, moved = driven(driver, driver_sockets, driver_stated, driver_stated[2], driver_stated[3], None, {o: follows for o in pair}) + write_connections(entries) + context.view_layer.update() + report = {**part_report(obj, part, built), "followers": moved} + report["closures"] = scene_closures(context, report, (obj,)) return report @@ -1013,6 +1350,8 @@ class BROKKR_KITBASH_OT_close(PolishOperator): raise Refused(f"{obj.name!r} cannot close on itself; nothing changed.") if closure(obj) is not None: raise Refused(f"{obj.name!r} already states a closure (its socket {closure(obj)[0]!r}): a part states one, and detach clears it; nothing changed.") + if (joint_record(obj)["follows"] or {}).get("kind") == "loop": + raise Refused(f"{obj.name!r} follows as the parent of a loop: the closing part of a loop states its closure, and its parent states none; nothing changed.") there, here = mated(other, other_part, other_built, obj, part, built, (self.socket, self.other_socket, 0.0, 0.0), "closing on") free(other, self.other_socket) free(obj, self.socket) @@ -2134,7 +2473,7 @@ class BROKKR_KITBASH_OT_report(PolishOperator): classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report, BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach, - BROKKR_KITBASH_OT_joint, BROKKR_KITBASH_OT_slide, BROKKR_KITBASH_OT_joints, + BROKKR_KITBASH_OT_joint, BROKKR_KITBASH_OT_slide, BROKKR_KITBASH_OT_joints, BROKKR_KITBASH_OT_follow, BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_freeze, BROKKR_KITBASH_OT_thaw, BROKKR_KITBASH_OT_ribs, BROKKR_KITBASH_OT_shell, BROKKR_KITBASH_OT_hose) diff --git a/surfaces/blender/tests/live/kitbash_pose.py b/surfaces/blender/tests/live/kitbash_pose.py index 8ff9464..82130d8 100644 --- a/surfaces/blender/tests/live/kitbash_pose.py +++ b/surfaces/blender/tests/live/kitbash_pose.py @@ -445,7 +445,8 @@ try: R["joints"] = joints table = {row["id"]: row for row in (joints or {}).get("joints", [])} check("joints reports the tree under the tank: schema, the root's frame, a row per DOF connection depth first with children by name, parents first, rigid ones counted", - receipt["status"] == "accepted" and {k: v for k, v in joints.items() if k != "joints"} == {"schema": "brokkr.joints", "version": 1, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres", "rigid": 2} + receipt["status"] == "accepted" and {k: v for k, v in joints.items() if k != "joints"} == {"schema": "brokkr.joints", "version": 2, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres", "rigid": 2, + "unlimited": ["Barrel", "Toe", "Ram"], "next": None} and [row["id"] for row in joints["joints"]] == ["Strut", "Barrel", "Rod", "Hinge", "Toe", "Ram"], [receipt["message"], joints]) check("a joint's parent is the nearest DOF connection above it, not the object it hangs from: the toe's is the hinge, through the rigid foot; the rod's is the barrel", {name: row["parent"] for name, row in table.items()} == {"Strut": None, "Barrel": "Strut", "Rod": "Barrel", "Hinge": "Strut", "Toe": "Hinge", "Ram": "Strut"} and toe.parent == foot, @@ -466,8 +467,9 @@ try: and table["Strut"] == {**table["Strut"], "value": round(value, 6), "min": round(round(near + 2.0, 3) - value, 6), "max": round(round(far - 2.0, 3) - value, 6), "mechanism": "knee"} and table["Ram"] == {**table["Ram"], "value": -36.0, "limits": None, "min": None, "max": None, "mechanism": None, "compliance": None}, table) receipt, below = send("brokkr_kitbash.joints", object_name="Hinge") - check("under another root the rows are in its frame and begin below it", receipt["status"] == "accepted" and [(row["id"], row["parent"]) for row in below["joints"]] == [("Toe", None)] and below["rigid"] == 1 - and float(np.abs((np.linalg.inv(np.array(hinge.matrix_world, dtype=np.float64)) @ frame(foot, "pivot"))[:3, 3] - below["joints"][0]["origin"]).max()) < JOINT_FRAME, below) + check("under another root the rows are in its frame and begin with the root's own joint, parent null", receipt["status"] == "accepted" + and [(row["id"], row["parent"]) for row in below["joints"]] == [("Hinge", None), ("Toe", "Hinge")] and below["rigid"] == 1 and below["unlimited"] == ["Toe"] + and float(np.abs((np.linalg.inv(np.array(hinge.matrix_world, dtype=np.float64)) @ frame(foot, "pivot"))[:3, 3] - below["joints"][1]["origin"]).max()) < JOINT_FRAME, below) refused("joints of a mesh that is not a kit part", "brokkr_kitbash.joints", {"object_name": "Plain"}, "'Plain' is not a kit part") # --- detach clears the record ------------------------------------------------------------------------------------------- diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 584dd63..2e9b476 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -2439,6 +2439,30 @@ 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_a_follower_has_one_writer_and_one_place_it_is_derived(self): + """The negative patterns of cut kit-follows-2: kit_follows and its driver pointer are written only inside + write_connections; set_params seats through it, its checks before the mesh is rebuilt; no linkage record is + stored and no Blender driver or constraint is made; close_loop is called from driven alone.""" + source = self.sources()["__init__.py"] + writer = source.split("\ndef write_connections(")[1].split("\n\n\n")[0] + writes = r"\[FOLLOWS(?:_DRIVER)?\] =" + self.assertEqual(re.findall(writes, source), re.findall(writes, writer)) + self.assertEqual(len(re.findall(writes, writer)), 2) + for name, text in self.sources().items(): + self.assertIsNone(re.search("kit_" "drive" r"\b", text), name) + self.assertIsNone(re.search(r"seat\(seated|driver_add\(|constraints\.new\(", source)) + self.assertEqual(source.count("seat("), 5) # its def, write_connections, and a cutter's, a ribs' and a hose's own frames + body = source.split("class BROKKR_KITBASH_OT_set_params(")[1].split("class BROKKR_KITBASH_OT_")[0] + self.assertLess(body.index("connection_checks(entries)"), body.index("clear_geometry()")) + self.assertLess(body.index("clear_geometry()"), body.index("write_connections(entries)")) + self.assertEqual(source.count("core.close_loop("), 1) + self.assertIn("core.close_loop(", source.split("\ndef driven(")[1].split("\n\n\n")[0]) + self.assertEqual(source.count("write_connections(["), 2) # write_connection, and follow clearing a statement + pose = source.split("\ndef pose(")[1].split("\n\n\n")[0] + self.assertLess(pose.index("if follows is not None and not keeps:"), pose.index("= solve(child")) + self.assertEqual(source.count("keeps=True"), 1) + self.assertIn("keeps=True", source.split("class BROKKR_KITBASH_OT_joint(")[1].split("class BROKKR_KITBASH_OT_")[0]) + def test_only_cut_boolean_and_ribs_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.""" @@ -2574,23 +2598,26 @@ class OwnershipTests(unittest.TestCase): its own, and no DOF kind is read from a socket type's name.""" source = self.sources()["__init__.py"] writes = re.findall(r'[^\n]*(?:\[ROLL\]|\["kit_roll"\])\s*=(?!=)[^\n]*', source) - self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll"]) - writer = source.split("def write_connection(")[1].split("\n\n\n")[0] + self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll"]) + writer = source.split("def write_connections(")[1].split("\n\n\n")[0] self.assertIn(writes[0], writer) record = r"SLIDE|LIMIT_MIN|LIMIT_MAX|MECHANISM|COMPLIANCE|RECORD" written = rf'\[(?:{record})\](?:, \w+\[\w+\])*\s*=(?!=)|\["kit_(?:slide|min|max|mechanism|compliance)"\]' self.assertIsNone(re.search(written, source)) - self.assertEqual(re.findall(r"[^\n]*\[key\] = [^\n]*", source), [" child[key] = value"]) - self.assertIn(" child[key] = value", writer) + self.assertEqual(re.findall(r"[^\n]*\[key\] = [^\n]*", source), [" child[key] = value"]) + self.assertIn(" child[key] = value", writer) named = [body.split("(")[0] for body in re.split(r"\n(?:def|class) ", source)[1:] if re.search(rf"\b(?:{record})\b", body)] - self.assertEqual(named, ["link", "joint_record", "mated", "write_connection", "BROKKR_KITBASH_OT_detach"]) + self.assertEqual(named, ["link", "joint_record", "mated", "write_connections", "BROKKR_KITBASH_OT_detach"]) for text in ("child[SLIDE] = slide", "obj[LIMIT_MIN], obj[LIMIT_MAX] = limits", 'obj["kit_compliance"] = text'): self.assertIsNotNone(re.search(written, text)) self.assertNotIn('"range"', source) self.assertNotIn('"pivot"', source) bodies = {body.split("(")[0]: body.split("\n\n\n")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:]} callers = [name for name, body in bodies.items() if "write_connection(" in body] - self.assertEqual((callers, source.count("write_connection("), source.split("def pose(")[1].split("\n\n\n")[0].count("write_connection(")), (["attach"], 3, 1)) + self.assertEqual((callers, source.count("write_connection(")), (["attach"], 2)) # its def, which is write_connections for one, and attach + callers = [name for name, body in bodies.items() if "write_connections(" in body] + self.assertEqual((callers, source.count("write_connections("), source.split("def pose(")[1].split("\n\n\n")[0].count("write_connections(entries)")), + (["set_params", "follow"], 6, 1)) # its def, write_connection, set_params, pose, and follow stating and clearing for name in ("roll", "aim", "reach", "slide", "joint"): self.assertEqual((bodies[name].count("pose(context, self.object_name, "), bool(re.search(r"\.parent\s*=(?!=)|\bseat\(|matrix_basis", bodies[name]))), (1, False), name) self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|matrix_basis", bodies["attach"])) @@ -2617,7 +2644,7 @@ class OwnershipTests(unittest.TestCase): self.assertIsNone(re.search(placing, bodies["close"])) for text in ("child.matrix_basis = basis", "obj.matrix_world = world", "obj.parent = other", "seat(obj, basis)"): self.assertIsNotNone(re.search(placing, text)) - self.assertIsNotNone(re.search(placing, source.split("def write_connection(")[1].split("\n\n\n")[0])) + self.assertIsNotNone(re.search(placing, source.split("def write_connections(")[1].split("\n\n\n")[0])) def test_the_patterns_bite(self): planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name', From 3bf5d736584ea17e22e3f38c52232bcb1fbe9f43 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 10:51:07 +0100 Subject: [PATCH 193/223] brokkr_kitbash.follow in the action table; tests/live/kitbash_follows.py The follow row, the joints row as version 2 with its after field, and roll, aim, reach, slide and joint say what a follower and a driver do. The live test drives a four-bar, a ram closing on its rocker, ratio followers and a torque link through run_intent, pages a joints report and reads the joint-records Lows. follow checks the closure before the parent and leaves the ratio's limits rule to driven (cut kit-follows-2, steps 5 and 6). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 10 +- .../brokkr_kitbash/brokkr_actions.json | 44 +- .../blender/tests/live/kitbash_follows.py | 475 ++++++++++++++++++ surfaces/blender/tests/test_kitbash.py | 2 +- 4 files changed, 517 insertions(+), 14 deletions(-) create mode 100644 surfaces/blender/tests/live/kitbash_follows.py diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 5546959..bc64a05 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -1285,13 +1285,12 @@ class BROKKR_KITBASH_OT_follow(PolishOperator): context.view_layer.update() return {**part_report(obj, part, built), "cleared": [o.name for o in cleared]} driver = mesh_object(given["driver"]) - pair = (obj,) if ratio else (obj.parent, obj) - if not ratio: - connection(obj.parent, "the follower's parent: a loop's two unknowns are the closing part's joint and its parent's") - closing = closure(obj) + pair, closing = (obj,) if ratio else (obj.parent, obj), closure(obj) if not ratio and (closing is None or closing[1] is None or not closure_report(obj, part, built)["holds"]): raise Refused(f"{obj.name!r} states no closure that holds: a loop follower is the part that states the closure (brokkr_kitbash.close, where the " "two sockets meet), and its joint and its parent's are solved to keep it; nothing changed.") + if not ratio: + connection(obj.parent, "the follower's parent: a loop's two unknowns are the closing part's joint and its parent's") if not ratio and CLOSE in obj.parent: raise Refused(f"{obj.parent.name!r}, the parent of {obj.name!r}, states a closure itself: a loop's parent follower states none; nothing changed.") driver_sockets, driver_stated, _ = connection(driver, "the driver") @@ -1307,9 +1306,6 @@ class BROKKR_KITBASH_OT_follow(PolishOperator): raise Refused(f"{o.name!r} already follows: clear it first (brokkr_kitbash.follow with record null); nothing changed.") if followers(o): raise Refused(f"{o.name!r} drives {followers(o)[0].name!r}: a driver is never a follower (one joint, one driver); nothing changed.") - if ratio and joint_record(driver)["limits"] is None: - raise Refused(f"{driver.name!r} states no limits: a ratio's driver states them (its value is then one number, not one of many a turn apart); " - "brokkr_kitbash.joint gives it limits; nothing changed.") if not ratio: moving = {driver, *followers(driver)} # what moves when the driver is posed: it, what follows it, and what hangs from either diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 93be89c..f70394f 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -176,7 +176,7 @@ }, { "name": "brokkr_kitbash.roll", - "doc": "Turn an attached kit part to a roll about its parent socket's normal, in place: its parent and both sockets stay, and what is attached to it follows. Refuses a part that is not attached and, on a revolute joint with limits, a roll with no turn of itself inside them (the roll written is the one inside). Reports the part and closures, every closure in the scene as {part, to, holds}, its own first: a roll can open one and never seats one.", + "doc": "Turn an attached kit part to a roll about its parent socket's normal, in place: its parent and both sockets stay, and what is attached to it follows. Refuses a part that is not attached and, on a revolute joint with limits, a roll with no turn of itself inside them (the roll written is the one inside). Refused on a follower (a part whose connection states follows), naming its driver: its value is derived. On a driver, every follower moves with it in the same action, and a follower outside its own limits or a loop that cannot close refuses the pose with nothing changed; the report's followers lists each as {part, value}. Reports the part and closures, every closure in the scene as {part, to, holds}, its own first: a roll can open one and seats none but those of the loops that follow the part.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -201,7 +201,7 @@ }, { "name": "brokkr_kitbash.aim", - "doc": "Turn an attached kit part about its pin until one of its own axes points as near a world direction as the pin lets it. The roll is solved exactly, not searched. On a revolute joint with limits the roll stays inside them: where the free roll is outside, the end of the limits that points the axis nearer. Refuses an axis or a direction that lies along the pin (within about 0.06 degrees), and a zero direction. Reports the part, aimed: {roll, dot} (dot 1 when the axis reaches the direction) and closures as roll does.", + "doc": "Turn an attached kit part about its pin until one of its own axes points as near a world direction as the pin lets it. The roll is solved exactly, not searched. On a revolute joint with limits the roll stays inside them: where the free roll is outside, the end of the limits that points the axis nearer. Refuses an axis or a direction that lies along the pin (within about 0.06 degrees), and a zero direction. Refused on a follower, and moves a driver's followers, as roll does. Reports the part, aimed: {roll, dot} (dot 1 when the axis reaches the direction) and closures as roll does.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -254,7 +254,7 @@ }, { "name": "brokkr_kitbash.reach", - "doc": "Turn an attached kit part about its pin until one of its sockets' origins stands at a height along a world direction (by default world z): of the two rolls that do it, the one nearer the roll it has. Solved exactly. On a revolute joint with limits only a roll inside them is taken; with neither inside it refuses, naming both rolls and the limits. Refuses a height the socket cannot reach, naming the range it can (either end of the range is taken), and a socket that lies on the pin. Reports the part, reached: {roll, residual} and closures as roll does.", + "doc": "Turn an attached kit part about its pin until one of its sockets' origins stands at a height along a world direction (by default world z): of the two rolls that do it, the one nearer the roll it has. Solved exactly. On a revolute joint with limits only a roll inside them is taken; with neither inside it refuses, naming both rolls and the limits. Refuses a height the socket cannot reach, naming the range it can (either end of the range is taken), and a socket that lies on the pin. Reports the part, reached: {roll, residual} and closures as roll does. Refused on a follower, and moves a driver's followers, as roll does.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -310,7 +310,7 @@ }, { "name": "brokkr_kitbash.joint", - "doc": "State the joint record of an attached kit part's connection. The connection's DOF is its parent socket's type's: revolute (its value is the roll, degrees) or prismatic (the slide, metres). record is a JSON object of any of limits ([lo, hi] or null), mechanism (a label of 1 to 32 a-z, 0-9 and _, or null) and compliance ({\"hertz\": over 0 to 30, \"damping_ratio\": 0 to 2} or null: a slide in the load path that settles under load, a record for a runtime, solved by nothing here); a key left out keeps what is stated and null clears it. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits spanning over 360 degrees or with an end past 360, prismatic limits with an end past 10 m, and compliance on a revolute joint or without limits. Moves nothing but a roll to its turn inside the limits. Reports the part and closures as roll does.", + "doc": "State the joint record of an attached kit part's connection. The connection's DOF is its parent socket's type's: revolute (its value is the roll, degrees) or prismatic (the slide, metres). record is a JSON object of any of limits ([lo, hi] or null), mechanism (a label of 1 to 32 a-z, 0-9 and _, or null) and compliance ({\"hertz\": over 0 to 30, \"damping_ratio\": 0 to 2} or null: a slide in the load path that settles under load, a record for a runtime, solved by nothing here); a key left out keeps what is stated and null clears it. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits spanning over 360 degrees or with an end past 360, prismatic limits with an end past 10 m, and compliance on a revolute joint or without limits. Moves nothing but a roll to its turn inside the limits: a follower keeps its derived value (limits that do not hold it are refused), and a driver's followers are derived again where it stands. Limits cannot be cleared from a driver a ratio follows. Reports the part and closures as roll does.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -335,7 +335,7 @@ }, { "name": "brokkr_kitbash.slide", - "doc": "Slide an attached kit part along its parent socket's normal, in place, on a prismatic connection (a ram_rod in a ram_barrel's bore: slide 0 is closed, the slide is the extension): its parent and both sockets stay, and what is attached to it follows. Refuses a revolute or rigid connection naming its socket type, and a slide outside the joint's limits. Reports the part and closures as roll does.", + "doc": "Slide an attached kit part along its parent socket's normal, in place, on a prismatic connection (a ram_rod in a ram_barrel's bore: slide 0 is closed, the slide is the extension): its parent and both sockets stay, and what is attached to it follows. Refuses a revolute or rigid connection naming its socket type, and a slide outside the joint's limits. Reports the part and closures as roll does. Refused on a follower, and moves a driver's followers, as roll does.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -360,7 +360,7 @@ }, { "name": "brokkr_kitbash.joints", - "doc": "The joints of the tree of kit parts attached under a root part, as {schema: brokkr.joints, version: 1, root, frame, rigid, joints}. A row per revolute or prismatic connection, depth first with children by name, so a joint's parent row comes before it: id (the child object), parent (the id of the nearest joint above, or null: rigid connections fold into it and are counted in rigid), part, socket ('Object:socket', the parent socket), kind, axis and origin (that socket's z and origin in the root object's frame: Blender axes, +Z up, metres), value (the roll in degrees or the slide in metres now), limits ([lo, hi] or null), min and max (the limits less the value: the travel either way from this pose), mechanism and compliance. Axis, origin and order are derived at each report from the kits and the parent tree; nothing stores them. Rows a receipt cannot carry are counted in jointsOmitted. Refuses a connection that cannot be read. Evaluates no modifier.", + "doc": "The joints of the tree of kit parts attached under a root part, as {schema: brokkr.joints, version: 2, root, frame, rigid, unlimited, next, joints}. A row per revolute or prismatic connection, depth first with children by name, so a joint's parent row comes before it; a root that itself states a revolute or prismatic connection has its own row first, parent null: id (the child object), parent (the id of the nearest joint above, or null: rigid connections fold into it and are counted in rigid), part, socket ('Object:socket', the parent socket), kind, axis and origin (that socket's z and origin in the root object's frame: Blender axes, +Z up, metres), value (the roll in degrees or the slide in metres now), limits ([lo, hi] or null), min and max (the limits less the value: the travel either way from this pose), mechanism, compliance and driven (null, or {by: the driver's id, kind: ratio | loop, k, offset}: the value is derived from the driver's, so a rig makes a driven bone and not a DOF). kind is revolute or prismatic: Aetheria's ShipJoint calls them rotate and slide, one to one. unlimited lists the ids of the rows that are not driven and state no limits, in the whole tree: an exporter that needs limits refuses by this one field. Axis, origin and order are derived at each report from the kits and the parent tree; nothing stores them. Rows a receipt cannot carry are counted in jointsOmitted, and next is then the id of the last row carried (else null): call again with after set to it for the rows that follow. after refuses an id that is no row's. Refuses a connection that cannot be read. Evaluates no modifier.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", @@ -372,6 +372,38 @@ "minLength": 1, "maxLength": 63, "doc": "the root: a kit part" + }, + { + "name": "after", + "type": "string", + "maxLength": 63, + "default": "", + "doc": "empty, or the next of the report before: the rows after that id" + } + ] + }, + { + "name": "brokkr_kitbash.follow", + "doc": "State that an attached kit part's joint follows another's: its roll or slide is then derived from the driver's whenever the driver is posed, and roll, aim, reach and slide on it are refused. record is JSON. {\"driver\": name, \"kind\": \"ratio\", \"k\": number, \"offset\": number}: the value is k x the driver's value + offset (a kneecap at k 0.5, a pinion at minus ring over pinion, a crosshead's slide in metres per degree of a roll); the driver states limits, so its value is one number. {\"driver\": name, \"kind\": \"loop\"}: object_name is a part that states a closure that holds; its joint and its parent's are the two unknowns solved so the closure keeps holding (a rocker and coupler closing on a crank; a ram's barrel and rod closing on the part it pushes; a torque link's two arms), and both follow the driver. Exactly one end of the loop, the parent's parent or the part closed on, moves with the driver: it is the driver, follows it, or hangs from one that does. The loop is planar: its pins are parallel. null clears the statement, and a loop partner's with it. The follower moves at once and the report's followers lists every follower of the driver as {part, value}. Refuses, with nothing changed: a rigid connection; a driver that is the follower, below it, or itself a follower; a follower that already follows or that drives another; a ratio whose driver states no limits; a value outside the follower's own limits; a loop with no closure that holds, with both ends or neither moving with the driver, that is not planar, or at a dead centre (its two joints in line). Nothing stores a pin or a linkage: a loop is solved from the kits' socket frames each time, and no Blender driver or constraint is made.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the follower: a part attached on a revolute or prismatic socket; for a loop, the part that states the closure" + }, + { + "name": "record", + "type": "string", + "required": true, + "minLength": 4, + "maxLength": 400, + "doc": "{driver, kind: ratio, k, offset}, {driver, kind: loop}, or null" } ] }, diff --git a/surfaces/blender/tests/live/kitbash_follows.py b/surfaces/blender/tests/live/kitbash_follows.py new file mode 100644 index 0000000..335207b --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_follows.py @@ -0,0 +1,475 @@ +"""Live proof, in a background Blender, of brokkr_kitbash followers through run_intent: brokkr_kitbash.follow states a +ratio or a loop, posing a driver derives every follower in the same action (core.close_loop for a loop), a follower +refuses to be posed, brokkr.joints version 2 marks driven rows and pages, and each refusal changes nothing. Not part of +the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_follows.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. The checks run +inside one try: an uncaught error is a failed check that names the check before it. + +The scene, every strut 0.09 wide so its pins take a ram's: a four-bar (Crank on the root Ground, Rocker on the root +Base, Coupler closing on the crank); a ram (A_Barrel on the root Pad, A_Rod in its bore, closing on the rocker), named +to sort before the four-bar it waits on; ratio followers of the crank (Cap, Pinion, and X_Rod's slide in X_Barrel); a +torque link (T_Rod sliding in the root T_Barrel, T_Upper and T_Lower closing on T_Lug, a strut pinned on the rod's +rod_end_back: a strut's two pins face one way, so two arms from the barrel's pin cannot face the rod's own); Idle +and Tip for the refusals; a chain of 80 struts for a joints report over a receipt. Bounds follow +lodur:ruling:deterministic-bound-margin, both readings beside each; the result file carries the readings. +""" +import importlib.util +import json +import math +import os +import sys +import tempfile +import time +import traceback +import types +from pathlib import Path + +import bpy +import numpy as np +from mathutils import Matrix + +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-follows-")) +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] +kit = core.load_kit("mechanical") +# Each mutant's reading below is its least over the cases here that it changes; the shipped reading is the worst. +# Metres (or a difference of unit vectors) between a loop's closing socket and the socket it closes on, read from the two +# world matrices after a driver was posed. Shipped worst 1.9e-06 (float32 matrices); least claimed mutant 0.018 (F11, the +# ram solved before the four-bar its rocker follows, at the smallest turn here); separation 97 each side. +CLOSED = 1.8e-4 +# Degrees between a loop follower's roll and the one this file solves by its own steps of core.close_loop from the rest +# pose. Shipped worst 2.3e-05 (an action's roll is a float32 field); least claimed mutant 8.9 (F11 again: the barrel +# aimed at where the rocker was); separation 620 each side. +SOLVED = 1.4e-2 +# Metres between a ratio follower's slide, or degrees between its roll, and k x the driver's value + offset, read from +# the stored values. Shipped 0 (the same doubles), taken as one float32 step of the largest value here, 1.5e-05; least +# claimed mutant 15 (a ratio follower not moved by a 30 degree turn of its driver at k 0.5); separation 1e3 each side. +RATIO = 1.5e-2 +ROT = [0.3, -0.2, 0.5] # the roots' rotation: no axis of the scene lines up with the world's +D0, REST = 30.0, (-40.0, 70.0) # the four-bar at rest: the crank's roll, and the rocker's and coupler's +RAM_REST = (200.0, 0.1) # the ram at rest: the barrel's roll and the rod's slide + + +def check(name, ok, detail=None): + try: + json.dumps(detail, default=str) + except TypeError: + detail = repr(detail) + R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail}) + + +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 + if not action.endswith(("place_part", "attach")) or receipt["status"] != "accepted": + print("SEND", action, receipt["status"], str(receipt["message"])[:300], flush=True) + return receipt, result + + +def place(name, part, params="", world=None): + send("brokkr_kitbash.place_part", part=part, object_name=name, params=params) + if world is not None: + world = Matrix(np.asarray(world).tolist()) + send("setObjectTransform", targetObjectName=name, location=list(world.translation), rotationEuler=list(world.to_euler("XYZ"))) + return bpy.data.objects[name] + + +def attach(name, socket_name, parent, parent_socket, roll=0.0): + receipt, _ = send("brokkr_kitbash.attach", object_name=name, socket=socket_name, parent_name=parent, parent_socket=parent_socket, roll=roll) + return receipt["status"] == "accepted" + + +def socket(obj, name): + built = core.build(core.part(kit, obj["kit_part"]), json.loads(obj["kit_params"])) + return next(s for s in built.sockets if s["name"] == name) + + +def world(obj): + return np.array(obj.matrix_world, dtype=np.float64) + + +def frame(obj, name): + """A socket's world frame, from the object's matrix_world and core's build of its stored params.""" + return world(obj) @ socket(obj, name)["matrix"] + + +def apart(obj, name, other, other_name): + """How far two sockets stand from meeting as a pin, read from the scene: origins apart, or normals not opposed.""" + a, b = frame(obj, name), frame(other, other_name) + return max(float(np.abs(a[:3, 3] - b[:3, 3]).max()), float(np.abs(a[:3, 2] + b[:3, 2]).max())) + + +def connection(name): + receipt, report = send("brokkr_kitbash.report", object_name=name) + return report["parts"][0]["connection"] if report else {"error": receipt["message"]} + + +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(), len(o.data.vertices), + {k: repr(o[k]) for k in sorted(o.keys()) if k.startswith("kit_")}) for o in bpy.data.objects} + + +def refused(label, action, fields, *expected): + state = scene_state() + receipt, _ = send(action, **fields) + check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and all(text in str(receipt["message"]) for text in expected) and scene_state() == state, + [receipt["status"], receipt["message"], expected]) + + +def stepped(solve, seed, start, end, step): + """This file's own derivation: the loop's two values after the input goes from start to end in steps of at most `step`.""" + count = max(1, math.ceil(abs(end - start) / step)) + for index in range(1, count + 1): + seed, _ = solve(start + (end - start) * index / count, seed) + return seed + + +def turned(a, b): + return abs((a - b + 180.0) % 360.0 - 180.0) + + +try: + rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] + check("follow loads as a host action after joints, with no errors", not R["hostErrors"] and "brokkr_kitbash.joints" in rows + and rows[rows.index("brokkr_kitbash.joints") + 1] == "brokkr_kitbash.follow", [R["hostErrors"], rows]) + + # --- the four-bar ----------------------------------------------------------------------------------------------------- + turn = np.eye(4) + turn[:3, :3] = core._rotation([math.degrees(v) for v in ROT]) + turn[:3, 3] = [1.0, 2.0, 3.0] + W = "width=0.09; " + ground = place("Ground", "strut", W + "length=0.8", turn) + crank, rocker, coupler = place("Crank", "strut", W + "length=0.5"), place("Rocker", "strut", W + "length=0.9"), place("Coupler", "strut", W + "length=0.7") + attach("Crank", "end_a", "Ground", "end_a", D0) + + def crank_pin(roll, name="end_b"): + return world(ground) @ core.mate(socket(ground, "end_a"), socket(crank, "end_a"), roll) @ socket(crank, name)["matrix"] + + def rocker_world(base_world, roll): + return base_world @ core.mate(socket(ground, "end_a"), socket(rocker, "end_a"), roll) + + end = rocker_world(turn, REST[0]) @ core.mate(socket(rocker, "end_b"), socket(coupler, "end_a"), REST[1]) @ socket(coupler, "end_b")["matrix"] + shift = np.eye(4) + shift[:3, 3] = crank_pin(D0)[:3, 3] - end[:3, 3] + base = place("Base", "strut", W + "length=0.8", shift @ turn) # where the loop closes at rest + attach("Rocker", "end_a", "Base", "end_a", REST[0]) + attach("Coupler", "end_a", "Rocker", "end_b", REST[1]) + receipt, report = send("brokkr_kitbash.close", object_name="Coupler", socket="end_b", other_name="Crank", other_socket="end_b") + check("the four-bar stands closed at rest: crank on Ground, rocker on Base, the coupler's end closing on the crank's", receipt["status"] == "accepted" + and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) + four_bar = [(socket(base, "end_a"), socket(rocker, "end_a"), "revolute"), (socket(rocker, "end_b"), socket(coupler, "end_a"), "revolute")] + + def solve_four_bar(roll, seed): + return core.close_loop(world(base), four_bar, socket(coupler, "end_b"), crank_pin(roll), seed) + + # --- parts for the refusals --------------------------------------------------------------------------------------------- + place("Idle", "strut", W), place("Tip", "strut", W), place("Loose", "strut", W) + attach("Idle", "end_a", "Ground", "end_b", 15.0) + attach("Tip", "end_a", "Idle", "end_b", 0.0) + tank = place("Tank", "tank", "radius=0.3; length=1.2") + place("Brk", "bracket") + attach("Brk", "mount", "Tank", "lug_b") + loop = '{"driver": "Crank", "kind": "loop"}' + refused("a loop whose two ends both stand still when the driver moves (F7)", "brokkr_kitbash.follow", {"object_name": "Coupler", "record": '{"driver": "Idle", "kind": "loop"}'}, + "'Base' (the base) and 'Crank' (closed on), neither moves with 'Idle'") + refused("a loop follower that states no closure", "brokkr_kitbash.follow", {"object_name": "Rocker", "record": loop}, "'Rocker' states no closure that holds") + refused("a follower on a rigid connection", "brokkr_kitbash.follow", {"object_name": "Brk", "record": '{"driver": "Crank", "kind": "ratio", "k": 1, "offset": 0}'}, + "socket type 'mount' states no dof") + refused("a follower that is not attached", "brokkr_kitbash.follow", {"object_name": "Loose", "record": loop}, "'Loose' (the follower) is not attached") + refused("a part that follows itself", "brokkr_kitbash.follow", {"object_name": "Idle", "record": '{"driver": "Idle", "kind": "ratio", "k": 1, "offset": 0}'}, "'Idle' is the follower itself") + refused("a driver below its follower", "brokkr_kitbash.follow", {"object_name": "Idle", "record": '{"driver": "Tip", "kind": "ratio", "k": 1, "offset": 0}'}, "'Tip' is below 'Idle'") + for bad in ('{"driver": "Crank", "kind": "ratio", "k": 0, "offset": 0}', '{"driver": "Crank", "kind": "ratio", "k": 1}', '{"driver": "Crank", "kind": "gear"}', + '{"driver": "Crank", "kind": "loop", "k": 1}', "[1, 2]", '{"a"'): + refused(f"a record that is not one of the three shapes: {bad}", "brokkr_kitbash.follow", {"object_name": "Idle", "record": bad}, "record must be") + refused("clearing a part that follows nothing", "brokkr_kitbash.follow", {"object_name": "Idle", "record": "null"}, "'Idle' follows nothing") + + # --- a loop follows ----------------------------------------------------------------------------------------------------- + receipt, report = send("brokkr_kitbash.follow", object_name="Coupler", record=loop) + rocker_row, coupler_row = connection("Rocker"), report["connection"] if report else None + check("follow states the loop on the closing part and its parent, both following the crank, and the report lists them as written", + receipt["status"] == "accepted" and [f["part"] for f in report["followers"]] == ["Rocker", "Coupler"] + and coupler_row["follows"] == {"driver": "Crank", "kind": "loop", "k": None, "offset": None, "holds": True, "reason": None} == rocker_row["follows"] + and json.loads(rocker["kit_follows"]) == {"kind": "loop"} == json.loads(coupler["kit_follows"]) and rocker["kit_follows_driver"] == crank == coupler["kit_follows_driver"], + [receipt["message"], report and report.get("followers"), rocker_row, coupler_row]) + seed = REST + for roll, label in ((75.0, "a 45 degree turn"), (150.0, "to 120 past rest"), (D0, "and back to rest"), (0.0, "30 the other way")): + was = crank["kit_roll"] + receipt, report = send("brokkr_kitbash.roll", object_name="Crank", roll=roll) + seed = stepped(solve_four_bar, seed, was, roll, 5.0) + ok = receipt["status"] == "accepted" and reading("closed", apart(coupler, "end_b", crank, "end_b")) < CLOSED + ok = ok and max(reading("solved", turned(rocker["kit_roll"], seed[0])), reading("solved", turned(coupler["kit_roll"], seed[1]))) < SOLVED + check(f"rolling the crank {label} moves rocker and coupler with it: the closure holds in the scene and the rolls are this file's own stepped solve", + ok and [f["part"] for f in report["followers"]] == ["Rocker", "Coupler"] and report["closures"][0] == {"part": "Coupler", "to": "Crank", "holds": True} + and connection("Rocker")["holds"] and connection("Coupler")["holds"], [receipt["message"], R["readings"], report and report.get("followers"), seed]) + refused("the crank driven past the loop's dead centre, naming the driver's value and the closing part", "brokkr_kitbash.roll", {"object_name": "Crank", "roll": -5.0}, + "'Crank' at -5: the loop 'Coupler' closes on 'Crank' ('Rocker' and 'Coupler' follow): the loop is at a dead centre", "nothing changed") + send("brokkr_kitbash.roll", object_name="Crank", roll=-2.0) # beside the toggle: 32 back from rest + seed = stepped(solve_four_bar, seed, 0.0, -2.0, 5.0) + receipt, report = send("brokkr_kitbash.roll", object_name="Crank", roll=47.0) + seed = stepped(solve_four_bar, seed, -2.0, 47.0, 5.0) + direct = stepped(solve_four_bar, REST, D0, 47.0, 5.0) + check("a 49 degree jump from beside the toggle ends on the stepped answer, the branch the linkage is on (F2: one solve from the stated value is thrown through the dead centre)", + receipt["status"] == "accepted" and reading("solved", turned(rocker["kit_roll"], direct[0])) < SOLVED and reading("solved", turned(coupler["kit_roll"], direct[1])) < SOLVED + and reading("closed", apart(coupler, "end_b", crank, "end_b")) < CLOSED, [receipt["message"], rocker["kit_roll"], coupler["kit_roll"], direct, seed]) + send("brokkr_kitbash.roll", object_name="Crank", roll=D0) + seed = stepped(solve_four_bar, seed, 47.0, D0, 5.0) + + # --- followers are derived only --------------------------------------------------------------------------------------- + for name in ("Rocker", "Coupler"): + refused(f"roll on the follower {name}, naming its driver (F4)", "brokkr_kitbash.roll", {"object_name": name, "roll": 10.0}, f"{name!r} follows 'Crank' (loop): its value is derived") + refused("aim on a follower", "brokkr_kitbash.aim", {"object_name": "Rocker", "axis": "+z", "direction_x": 1.0, "direction_y": 0.0, "direction_z": 0.0}, "'Rocker' follows 'Crank'") + refused("reach on a follower", "brokkr_kitbash.reach", {"object_name": "Rocker", "socket": "end_b", "direction_x": 0.0, "direction_y": 0.0, "direction_z": 1.0, "height": 3.0}, "'Rocker' follows 'Crank'") + was = rocker["kit_roll"] + receipt, report = send("brokkr_kitbash.joint", object_name="Rocker", record='{"limits": [-100, 20], "mechanism": "rocker"}') + check("joint on a follower states limits and a mechanism and keeps its derived value and its statement", receipt["status"] == "accepted" and rocker["kit_roll"] == was + and report["connection"]["limits"] == [-100.0, 20.0] and report["connection"]["mechanism"] == "rocker" and report["connection"]["follows"]["holds"] is True, + [receipt["message"], report and report["connection"]]) + refused("joint limits on a follower that do not hold its derived value", "brokkr_kitbash.joint", {"object_name": "Rocker", "record": '{"limits": [0, 20]}'}, "is outside the joint's limits") + refused("a driver that is itself a follower", "brokkr_kitbash.follow", {"object_name": "Idle", "record": '{"driver": "Rocker", "kind": "ratio", "k": 1, "offset": 0}'}, + "'Rocker' is itself a follower") + refused("a follower that drives another", "brokkr_kitbash.follow", {"object_name": "Crank", "record": '{"driver": "Idle", "kind": "ratio", "k": 1, "offset": 0}'}, + "'Crank' drives 'Coupler': a driver is never a follower") + refused("a follower that already follows", "brokkr_kitbash.follow", {"object_name": "Coupler", "record": loop}, "'Rocker' already follows") + refused("a closure stated by a loop's parent follower", "brokkr_kitbash.close", {"object_name": "Rocker", "socket": "end_a_back", "other_name": "Loose", "other_socket": "end_a"}, + "'Rocker' follows as the parent of a loop") + + # --- ratios ----------------------------------------------------------------------------------------------------------------- + place("Cap", "strut", W), place("Pinion", "strut", W), place("X_Barrel", "ram_barrel"), place("X_Rod", "ram_rod") + attach("Cap", "end_a", "Crank", "end_a_back", 0.0) + attach("Pinion", "end_a", "Ground", "end_b_back", 0.0) + attach("X_Barrel", "base", "Ground", "end_a_back", 90.0) + attach("X_Rod", "piston", "X_Barrel", "bore", 0.0) + cap, pinion, x_rod = (bpy.data.objects[name] for name in ("Cap", "Pinion", "X_Rod")) + half = '{"driver": "Crank", "kind": "ratio", "k": 0.5, "offset": 0}' + refused("a ratio whose driver states no limits (F3)", "brokkr_kitbash.follow", {"object_name": "Cap", "record": half}, "'Cap' follows it by ratio, and a ratio's driver states limits") + send("brokkr_kitbash.joint", object_name="Crank", record='{"limits": [-2, 160], "mechanism": "crank"}') + receipts = [send("brokkr_kitbash.follow", object_name="Cap", record=half), send("brokkr_kitbash.follow", object_name="Pinion", record='{"driver": "Crank", "kind": "ratio", "k": -3, "offset": 10}'), + send("brokkr_kitbash.follow", object_name="X_Rod", record='{"driver": "Crank", "kind": "ratio", "k": 0.001, "offset": 0.02}')] + + def ratios(): + at = crank["kit_roll"] + return max(reading("ratio", turned(cap["kit_roll"], 0.5 * at)), reading("ratio", turned(pinion["kit_roll"], -3.0 * at + 10.0)), reading("ratio", abs(x_rod["kit_slide"] - (0.001 * at + 0.02)))) + + check("a kneecap at k 0.5, a pinion at k -3 and a crosshead's slide at 0.001 m a degree follow the crank at once: each is k x its roll + offset", + all(receipt["status"] == "accepted" for receipt, _ in receipts) and ratios() < RATIO and abs(cap["kit_roll"] - 15.0) < RATIO and abs(x_rod["kit_slide"] - 0.05) < RATIO + and [f["part"] for f in receipts[2][1]["followers"]] == ["Cap", "Pinion", "X_Rod", "Rocker", "Coupler"] + and receipts[2][1]["connection"]["follows"] == {"driver": "Crank", "kind": "ratio", "k": 0.001, "offset": 0.02, "holds": True, "reason": None} + and connection("X_Rod")["holds"] and connection("Cap")["holds"], [[r["message"] for r, _ in receipts], R["readings"], receipts[2][1] and receipts[2][1].get("followers")]) + receipt, report = send("brokkr_kitbash.roll", object_name="Crank", roll=120.0) + seed = stepped(solve_four_bar, seed, D0, 120.0, 5.0) + check("rolling the crank moves ratio followers and the loop in one action: ratios first in the report, the pinion's roll brought inside a turn", + receipt["status"] == "accepted" and ratios() < RATIO and abs(pinion["kit_roll"] - 10.0) < RATIO and abs(x_rod["kit_slide"] - 0.14) < RATIO + and reading("closed", apart(coupler, "end_b", crank, "end_b")) < CLOSED and reading("solved", turned(rocker["kit_roll"], seed[0])) < SOLVED + and reading("slid", float(np.linalg.norm(frame(x_rod, "piston")[:3, 3] - frame(x_rod.parent, "bore")[:3, 3] - 0.14 * frame(x_rod.parent, "bore")[:3, 2]))) < CLOSED + and [f["part"] for f in report["followers"]] == ["Cap", "Pinion", "X_Rod", "Rocker", "Coupler"], [receipt["message"], R["readings"], pinion["kit_roll"], x_rod["kit_slide"]]) + refused("slide on a follower", "brokkr_kitbash.slide", {"object_name": "X_Rod", "slide": 0.1}, "'X_Rod' follows 'Crank' (ratio): its value is derived") + send("brokkr_kitbash.joint", object_name="Cap", record='{"limits": [0, 70]}') + refused("a pose of the driver that takes a follower outside its own limits: the driver is not written either (F5)", "brokkr_kitbash.roll", {"object_name": "Crank", "roll": 150.0}, + "'Cap' on 'Crank': its roll 75 is outside the joint's limits 0 to 70") + refused("clearing the limits of a driver a ratio follows", "brokkr_kitbash.joint", {"object_name": "Crank", "record": '{"limits": null}'}, "'Cap' follows it by ratio, and a ratio's driver states limits") + receipt, report = send("brokkr_kitbash.follow", object_name="Pinion", record="null") + cleared = receipt["status"] == "accepted" and report["cleared"] == ["Pinion"] and report["connection"]["follows"] is None and "kit_follows" not in pinion and "kit_follows_driver" not in pinion + receipt, report = send("brokkr_kitbash.roll", object_name="Pinion", roll=33.0) + check("follow with null clears the statement, and the part is posed by hand again", cleared and receipt["status"] == "accepted" and abs(pinion["kit_roll"] - 33.0) < RATIO, [receipt["message"]]) + + # --- two loops: a ram closing on the rocker, solved after the four-bar --------------------------------------------------- + send("brokkr_kitbash.roll", object_name="Crank", roll=D0) + seed = stepped(solve_four_bar, seed, 120.0, D0, 5.0) + a_barrel, a_rod = place("A_Barrel", "ram_barrel"), place("A_Rod", "ram_rod") + + def rod_end(pad_world, values): + return pad_world @ core.mate(socket(ground, "end_a"), socket(a_barrel, "base"), values[0]) @ core.mate(socket(a_barrel, "bore"), socket(a_rod, "piston"), 0.0, values[1]) @ socket(a_rod, "rod_end")["matrix"] + + shift = np.eye(4) + shift[:3, 3] = frame(rocker, "end_b_back")[:3, 3] - rod_end(turn, RAM_REST)[:3, 3] + pad = place("Pad", "strut", W + "length=0.8", shift @ turn) + attach("A_Barrel", "base", "Pad", "end_a", RAM_REST[0]) + attach("A_Rod", "piston", "A_Barrel", "bore", 0.0) + send("brokkr_kitbash.slide", object_name="A_Rod", slide=RAM_REST[1]) + send("brokkr_kitbash.close", object_name="A_Rod", socket="rod_end", other_name="Rocker", other_socket="end_b_back") + receipt, report = send("brokkr_kitbash.follow", object_name="A_Rod", record=loop) + check("a ram on its own ground pin closes on the rocker and follows the crank: the end it closes on follows the driver", + receipt["status"] == "accepted" and [f["part"] for f in report["followers"]] == ["Cap", "X_Rod", "Rocker", "Coupler", "A_Barrel", "A_Rod"] + and report["connection"]["follows"]["holds"] is True, [receipt["message"], report and report.get("followers")]) + ram_loop = [(socket(pad, "end_a"), socket(a_barrel, "base"), "revolute"), (socket(a_barrel, "bore"), socket(a_rod, "piston"), "prismatic")] + ram_seed = RAM_REST + for roll in (60.0, 110.0, 45.0): + was = crank["kit_roll"] + receipt, report = send("brokkr_kitbash.roll", object_name="Crank", roll=roll) + count = max(1, math.ceil(abs(roll - was) / 5.0)) + for index in range(1, count + 1): # this file's own derivation: at each step the four-bar, then the ram against the rocker where that step put it + seed, _ = solve_four_bar(was + (roll - was) * index / count, seed) + pin = rocker_world(world(base), seed[0]) @ socket(rocker, "end_b_back")["matrix"] + ram_seed, _ = core.close_loop(world(pad), ram_loop, socket(a_rod, "rod_end"), pin, ram_seed) + check(f"rolling the crank to {roll:g} solves the four-bar and then the ram that closes on its rocker (F11): both closures hold and the barrel's roll and rod's slide are this file's own", + receipt["status"] == "accepted" and reading("closed", apart(a_rod, "rod_end", rocker, "end_b_back")) < CLOSED and reading("closed", apart(coupler, "end_b", crank, "end_b")) < CLOSED + and reading("solved", turned(a_barrel["kit_roll"], ram_seed[0])) < SOLVED and reading("closed", abs(a_rod["kit_slide"] - ram_seed[1])) < CLOSED + and [f["part"] for f in report["followers"]][-4:] == ["Rocker", "Coupler", "A_Barrel", "A_Rod"] + and [row for row in report["closures"] if not row["holds"]] == [], [receipt["message"], R["readings"], a_barrel["kit_roll"], a_rod["kit_slide"], ram_seed]) + + # --- a torque link: a slide drives two arms --------------------------------------------------------------------------------- + far = np.eye(4) + far[:3, 3] = [0.0, -8.0, 0.0] + t_barrel, t_rod = place("T_Barrel", "ram_barrel", "", far @ turn), place("T_Rod", "ram_rod") + t_upper, t_lower, t_lug = place("T_Upper", "strut", W + "length=0.5"), place("T_Lower", "strut", W + "length=0.5"), place("T_Lug", "strut", W + "length=0.3") + attach("T_Rod", "piston", "T_Barrel", "bore", 0.0) + send("brokkr_kitbash.joint", object_name="T_Rod", record='{"limits": [0, 0.3], "mechanism": "oleo", "compliance": {"hertz": 3, "damping_ratio": 0.6}}') + send("brokkr_kitbash.slide", object_name="T_Rod", slide=0.05) + attach("T_Lug", "end_a", "T_Rod", "rod_end_back", 90.0) + link = [(socket(t_barrel, "base_back"), socket(t_upper, "end_a"), "revolute"), (socket(t_upper, "end_b"), socket(t_lower, "end_a"), "revolute")] + + def lug_pin(slide): + return (world(t_barrel) @ core.mate(socket(t_barrel, "bore"), socket(t_rod, "piston"), 0.0, slide) @ core.mate(socket(t_rod, "rod_end_back"), socket(t_lug, "end_a"), 90.0) + @ socket(t_lug, "end_b")["matrix"]) + + def solve_link(slide, values): + return core.close_loop(world(t_barrel), link, socket(t_lower, "end_b"), lug_pin(slide), values) + + arms = None + for guess in ((40.0, 100.0), (-40.0, -100.0), (140.0, 100.0), (-140.0, -100.0), (90.0, 90.0), (-90.0, -90.0), (10.0, 150.0), (-10.0, -150.0)): + try: + arms, _ = solve_link(0.05, guess) + break + except core.KitError: + continue + check("the torque link's rest pose is found: two arms from the barrel's pin to the lug on the rod", arms is not None, "no guess closed the loop") + arms = tuple(core._wrapped(v) for v in arms) + attach("T_Upper", "end_a", "T_Barrel", "base_back", arms[0]) + attach("T_Lower", "end_a", "T_Upper", "end_b", arms[1]) + send("brokkr_kitbash.close", object_name="T_Lower", socket="end_b", other_name="T_Lug", other_socket="end_b") + receipt, report = send("brokkr_kitbash.follow", object_name="T_Lower", record='{"driver": "T_Rod", "kind": "loop"}') + check("the arms follow the rod's slide as a loop: its base is the barrel, above the driver, and it closes on a part that hangs from the driver", + receipt["status"] == "accepted" and [f["part"] for f in report["followers"]] == ["T_Upper", "T_Lower"], [receipt["message"], report and report.get("followers")]) + for slide in (0.15, 0.0, 0.11): + was = t_rod["kit_slide"] + receipt, report = send("brokkr_kitbash.slide", object_name="T_Rod", slide=slide) + arms = stepped(solve_link, arms, was, slide, 0.02) + check(f"sliding the rod to {slide:g} folds the arms: the closure holds in the scene and the rolls are this file's own stepped solve", + receipt["status"] == "accepted" and reading("closed", apart(t_lower, "end_b", t_lug, "end_b")) < CLOSED + and max(reading("solved", turned(t_upper["kit_roll"], arms[0])), reading("solved", turned(t_lower["kit_roll"], arms[1]))) < SOLVED + and report["closures"][0]["holds"] is True, [receipt["message"], R["readings"], t_upper["kit_roll"], t_lower["kit_roll"], arms]) + refused("a slide outside the driver's limits", "brokkr_kitbash.slide", {"object_name": "T_Rod", "slide": 0.4}, "its slide 0.4 is outside the joint's limits 0 to 0.3") + + # --- joints, version 2 ---------------------------------------------------------------------------------------------------------- + receipt, joints = send("brokkr_kitbash.joints", object_name="Ground") + table = {row["id"]: row for row in (joints or {}).get("joints", [])} + check("joints is version 2: a driven row names what drives it (F6), and unlimited lists the rows that are not driven and state no limits", + receipt["status"] == "accepted" and joints["version"] == 2 and [row["id"] for row in joints["joints"]] == ["Crank", "Cap", "Idle", "Tip", "Pinion", "X_Barrel", "X_Rod"] + and table["Crank"]["driven"] is None and table["Cap"]["driven"] == {"by": "Crank", "kind": "ratio", "k": 0.5, "offset": 0.0} + and table["X_Rod"]["driven"] == {"by": "Crank", "kind": "ratio", "k": 0.001, "offset": 0.02} and table["X_Rod"]["kind"] == "prismatic" + and joints["unlimited"] == ["Idle", "Tip", "Pinion", "X_Barrel"] and joints["next"] is None and "jointsOmitted" not in joints, [receipt["message"], joints]) + receipt, joints = send("brokkr_kitbash.joints", object_name="Base") + check("a loop's two followers are driven rows, kind loop", receipt["status"] == "accepted" and [(row["id"], row["driven"]) for row in joints["joints"]] == [ + ("Rocker", {"by": "Crank", "kind": "loop", "k": None, "offset": None}), ("Coupler", {"by": "Crank", "kind": "loop", "k": None, "offset": None})] and joints["unlimited"] == [], joints) + receipt, joints = send("brokkr_kitbash.joints", object_name="T_Rod") + check("a root that states a DOF connection has its own row first, parent null", receipt["status"] == "accepted" + and [(row["id"], row["parent"], row["kind"]) for row in joints["joints"]] == [("T_Rod", None, "prismatic"), ("T_Lug", "T_Rod", "revolute")] + and joints["joints"][0]["compliance"] == {"damping_ratio": 0.6, "hertz": 3.0} and joints["rigid"] == 0, joints) + receipt, joints = send("brokkr_kitbash.joints", object_name="Ground", after="Idle") + check("after carries the rows after an id (F12)", receipt["status"] == "accepted" and [row["id"] for row in joints["joints"]] == ["Tip", "Pinion", "X_Barrel", "X_Rod"] + and joints["joints"][0]["parent"] == "Idle" and joints["unlimited"] == ["Idle", "Tip", "Pinion", "X_Barrel"], joints) + refused("after an id that is no row's", "brokkr_kitbash.joints", {"object_name": "Ground", "after": "Base"}, "after 'Base' is not the id of a joint under 'Ground'") + place("L00", "strut", W + "length=0.3", far @ far @ turn) + for index in range(1, 81): + place(f"L{index:02d}", "strut", W + "length=0.3") + attach(f"L{index:02d}", "end_a", f"L{index - 1:02d}", "end_b", 7.0) + receipt, first = send("brokkr_kitbash.joints", object_name="L00") + carried = [row["id"] for row in (first or {}).get("joints", [])] + receipt, second = send("brokkr_kitbash.joints", object_name="L00", after=(first or {}).get("next") or "") + R["readings"]["rows in one receipt"] = len(carried) + check("a tree of 80 joints is two reports: the first counts what it omits and names the last id it carries as next, and after it the second carries the rest", + receipt["status"] == "accepted" and 0 < len(carried) < 80 and first["jointsOmitted"] == 80 - len(carried) and first["next"] == carried[-1] + and carried + [row["id"] for row in second["joints"]] == [f"L{index:02d}" for index in range(1, 81)] and second["next"] is None and "jointsOmitted" not in second + and len(first["unlimited"]) == 80, [receipt["message"], len(carried), first and first.get("next"), second and [row["id"] for row in second["joints"]][:3]]) + + # --- the joint-records Lows ------------------------------------------------------------------------------------------------- + send("brokkr_kitbash.joint", object_name="Idle", record='{"limits": [0, 30]}') + idle = bpy.data.objects["Idle"] + idle["kit_roll"] = 50.0 # by hand: no action writes a roll outside its limits + refused("set_params of a part whose roll was written by hand outside its limits (F9): the mesh is not rebuilt", "brokkr_kitbash.set_params", {"object_name": "Idle", "params": "length=0.6"}, + "'Idle' on 'Ground': its roll 50 is outside the joint's limits 0 to 30") + refused("and of its parent", "brokkr_kitbash.set_params", {"object_name": "Ground", "params": "length=0.9"}, "'Idle' on 'Ground': its roll 50 is outside the joint's limits 0 to 30") + idle["kit_roll"], idle["kit_slide"] = 15.0, 0.1 + refused("set_params of a part with a slide written by hand on a revolute connection", "brokkr_kitbash.set_params", {"object_name": "Idle", "params": "length=0.6"}, + "socket type 'pivot' is revolute: only a prismatic connection slides") + del idle["kit_slide"] + idle["kit_compliance"] = '{"damping_ratio": 0.7, "hertz": 4.0}' # by hand: a compliance is a prismatic joint's + receipt, joints = send("brokkr_kitbash.joints", object_name="Idle") + row = connection("Idle") + check("a compliance written by hand on a revolute joint reads null in the report and the joints report (F10), and the limits beside it still read", + receipt["status"] == "accepted" and row["compliance"] is None and row["limits"] == [0.0, 30.0] and joints["joints"][0]["id"] == "Idle" and joints["joints"][0]["compliance"] is None, [row, joints]) + receipt, report = send("brokkr_kitbash.set_params", object_name="Idle", params="length=0.6") + check("set_params seats through the one writer: the part is rebuilt, its child seated on the moved socket, and the hand-written compliance is gone", + receipt["status"] == "accepted" and "kit_compliance" not in idle and connection("Tip")["holds"] and reading("closed", apart(bpy.data.objects["Tip"], "end_a", idle, "end_b")) < CLOSED, + [receipt["message"], sorted(idle.keys())]) + + # --- detach --------------------------------------------------------------------------------------------------------------------- + receipt, report = send("brokkr_kitbash.detach", object_name="T_Lower") + upper_row = connection("T_Upper") + check("detaching a loop's closing follower clears its partner's statement too", receipt["status"] == "accepted" and upper_row["follows"] is None + and not [k for o in (t_upper, t_lower) for k in o.keys() if k.startswith("kit_follows")], [receipt["message"], upper_row, sorted(t_upper.keys())]) + receipt, report = send("brokkr_kitbash.roll", object_name="T_Upper", roll=12.0) + check("and the partner is posed by hand again", receipt["status"] == "accepted", receipt["message"]) + receipt, report = send("brokkr_kitbash.detach", object_name="Crank") + cap_row, coupler_row = connection("Cap"), connection("Coupler") + check("detaching a driver leaves its followers' statements, which report that the driver states no DOF connection", + receipt["status"] == "accepted" and cap_row["follows"] == {"driver": "Crank", "kind": "ratio", "k": 0.5, "offset": 0.0, "holds": False, "reason": "the driver states no DOF connection"} + and coupler_row["follows"]["holds"] is False and coupler_row["follows"]["reason"] == "the driver states no DOF connection", [receipt["message"], cap_row, coupler_row]) + bpy.data.objects.remove(crank) + coupler_row = connection("Coupler") + check("and once the driver is deleted, that it is gone", coupler_row["follows"]["driver"] is None and coupler_row["follows"]["reason"] == "the driver is gone: deleted, or in no collection", coupler_row) + constrained = [o.name for o in bpy.data.objects if o.constraints or (o.animation_data and o.animation_data.drivers)] + check("no Blender driver or constraint was made", constrained == [], constrained) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file + check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-8:]) + +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())} +for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") +print("READINGS", R["readings"], flush=True) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 2e9b476..029da85 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -2153,7 +2153,7 @@ class SheetTests(unittest.TestCase): ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", - "brokkr_kitbash.joint", "brokkr_kitbash.slide", "brokkr_kitbash.joints", "brokkr_kitbash.close", + "brokkr_kitbash.joint", "brokkr_kitbash.slide", "brokkr_kitbash.joints", "brokkr_kitbash.follow", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.freeze", "brokkr_kitbash.thaw", "brokkr_kitbash.ribs", "brokkr_kitbash.shell", "brokkr_kitbash.hose"] From fcf09bfae22d613e7fbbfa3da802f44e5d484c62 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 10:59:44 +0100 Subject: [PATCH 194/223] brokkr_reference.block_plate: every crown point says what decided it by its prior share, seam corners and sides' inner points included; a seam corner whose view runs along x = 0 goes to the plane and its guard; the views start a corner by metres a pixel against the prior's scale (START), not by degrees; the skirt in shares of the crown's extent; tests/fixtures/spectre_truth.json, SPECTRE's pass-3 roof built, rendered and traced off the renders: 39.1 mm from the truth as traced, 3.5 x noise x the coarser view's pixel at 1 and 2 px; FAIR 0.2 read against known truth (cut trace-block, Soul s1) Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/core.py | 55 +++-- .../blender/tests/fixtures/spectre_truth.json | 1 + surfaces/blender/tests/test_reference.py | 212 ++++++++++++++++-- 3 files changed, 234 insertions(+), 34 deletions(-) create mode 100644 surfaces/blender/tests/fixtures/spectre_truth.json diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index bf6d11c..6e808d1 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -748,9 +748,9 @@ def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=TOL): FAIR = 0.2 # a side's second differences of this share of its chord cost what one pixel of miss does (0.02 held a bowed side straight; docs/reference.md) K_MAX = 6 # points a side grows to before its trace is refused as fit_runs refuses it SQUARE = 0.4 # the cosine between a plane's normal and a sight line under which a trace is not lifted onto it: past 66 degrees the lift stretches over 2.5 times -PARALLAX = 9.7 # degrees between a corner's widest pair of sight lines under which the views do not start it: the geometric mean of 19, where a plate blocks from its views, and 5, where its corners land 0.25 to 1.5 m off (tests/test_reference.py BlockTests) +START = 1.0 # a corner's views start it where one pixel moves their meeting point less than this x share x the plate's extent, the prior's own scale: past it the views alone hold the corner looser than the plane would (tests/test_reference.py BlockTests reads 0.50 at 19 degrees and 1.90 at 5, Paladin's lens and range) VIEWS = 0.2 # a prior_share under this: the views decide the point (fit_shell's line) -FLARE, DROP, DOME = 0.06, 0.07, 0.02 # metres: a plate's skirt out from and back of its crown, and its centre's rise +FLARE, DROP, DOME = 0.05, 0.06, 0.017 # of the crown's extent (its two furthest points): a plate's skirt out from and back of its crown, and its centre's rise. A template's proportions, not readings: the crown is what is solved TRACE_KEYS = ("camera", "box", "frame", "from", "to", "side", "line") @@ -810,7 +810,9 @@ def triangulate(obs, seam=False): def plate_sheet(crown, corners, flare=FLARE, drop=DROP, dome=DOME, mirror=False, seam=(), facing=None): """The free-cage document of a plate whose raised outline is `crown`, a closed ring of points in the plate's frame: the crown ring (vertices 0 to n - 1, in the ring's order), a skirt ring `flare` out from it and `drop` - back of it (the chamfered wall), and one centre vertex `dome` proud of the ring's middle. Every crown side is + back of it (the chamfered wall), and one centre vertex `dome` proud of the ring's middle; the three are shares + of the crown's extent, the distance between its two furthest points, so a plate of any size has the same + proportions. Every crown side is creased 1; `corners` (ring indices) are pinned 1 on crown and skirt, so the crown between two corners is one hard run, and the points between them are free to round it. The centre is the cage's pole unless the ring has four points. `facing` is a direction the outer face looks along; the ring is taken as wound that way, or the @@ -822,6 +824,8 @@ def plate_sheet(crown, corners, flare=FLARE, drop=DROP, dome=DOME, mirror=False, face of three points of x = 0 is its own reflection and the cage's parser refuses it.""" P = np.asarray(crown, float) n, seam = len(P), set(seam) if mirror else set() + extent = float(np.linalg.norm(P[:, None] - P[None], axis=2).max()) + flare, drop, dome = flare * extent, drop * extent, dome * extent Q = np.roll(P, -1, axis=0) normal = _unit(np.cross(P, Q).sum(0)) # Newell's: the ring's own facing, counter-clockwise seen from where it points flip = facing is not None and float(normal @ np.asarray(facing, float)) < 0 @@ -940,21 +944,32 @@ def block_plate(views, plate, traces, parse, plane=None, share=0.1, tol=TOL): if not per_side[i]: raise ReferenceFitError(f"the side from {name!r} to {names[(i + 1) % N]!r} is traced in no view: every side of the outline is traced, or the plate is given fewer corners") lines = sum(len(json.dumps(trace.get("line"), separators=(",", ":"))) for trace in traces) - size = 44 * (2 * N * (K_MAX - 1) + 1) + 34 * N * (K_MAX - 1) + lines + 90 * len(traces) + 150 * N + 400 + size = 44 * (2 * N * (K_MAX - 1) + 1) + 34 * N * (K_MAX - 1) + 62 * N * (K_MAX - 2) + lines + 90 * len(traces) + 190 * N + 400 if size > RESULT_LIMIT: raise ReferenceFitError(f"traces: the sheet and its report could be about {size} characters, over the {RESULT_LIMIT} a receipt carries: nothing was solved. " "Trace with fewer points, or block the plate as two") - start, parallax, decided = np.zeros((N, 3)), np.zeros(N), np.zeros(N, bool) + start, parallax, decided, loose = np.zeros((N, 3)), np.zeros(N), np.zeros(N, bool), np.full(N, np.inf) obs = [[(cam, F, 1, np.mean(pixels, axis=0)) for cam, F, pixels, _ in seen_by[i].values()] for i in range(N)] for i in range(N): - if i in held or len(obs[i]) >= 2: - start[i], parallax[i], _, _ = triangulate(obs[i], seam=i in held) - decided[i] = i in held or parallax[i] >= PARALLAX + if len(obs[i]) >= 2: + start[i], parallax[i], _, loose[i] = triangulate(obs[i], seam=i in held) + met = np.isfinite(loose) + if met.any(): # the plate's extent as its views draw it: the corners' pixels at the range of where the sight lines meet, which a depth error hardly moves + middle, drawn = start[met].mean(0), {} + for i in range(N): + for view, (cam, F, pixels, _) in seen_by[i].items(): + drawn.setdefault(view, (cam, F, []))[2].append(np.mean(pixels, axis=0)) + extent = max(float(np.linalg.norm(np.ptp(pixels, axis=0))) * float(np.linalg.norm(_sight(cam, F, cam["c"])[0] - middle)) / cam["f"] for cam, F, pixels in drawn.values()) + decided = loose < START * share * extent + for i in held: # x = 0 meets a sight line that crosses it; one that runs along it within what SQUARE allows a plane is no meeting + if not decided[i] and max(abs(float(_sight(cam, F, np.mean(pixels, axis=0))[1][0])) for cam, F, pixels, _ in seen_by[i].values()) >= SQUARE: + start[i], decided[i] = triangulate(obs[i], seam=True)[0], True if plane is None: if decided.sum() < 3: - raise ReferenceFitError(f"plane: none was given, and {', '.join(repr(names[i]) for i in np.flatnonzero(~decided))} are seen by one view only (or by views under " - f"{PARALLAX:g} degrees apart): three corners the views or the seam decide make the plane. Give plane, or trace those corners in another view") + raise ReferenceFitError(f"plane: none was given, and {', '.join(repr(names[i]) for i in np.flatnonzero(~decided))} are decided by no view (seen by one only, by views so close that a pixel " + f"moves where they meet over {START * share:g} of the plate's extent, or on the seam by a view that runs along x = 0): three corners the views or the seam " + "decide make the plane. Give plane, or trace those corners in another view") point = start[decided].mean(0) _, spread, axes = np.linalg.svd(start[decided] - point) if spread[1] < 1e-6 * max(spread[0], 1e-12): @@ -979,6 +994,8 @@ def block_plate(views, plate, traces, parse, plane=None, share=0.1, tol=TOL): f"only depth this corner has. A trace lifted onto it stretches past {1 / SQUARE:g} times: turn plane to the face the view shows, or trace the corner in another view") lifted.append(o + d * (((point - o) @ normal) / (d @ normal))) start[i] = np.mean(lifted, axis=0) + if i in held: + start[i, 0] = 0.0 free_ = [i for i in range(N) if i not in held] def crossed(corners_, what): @@ -1058,12 +1075,22 @@ def block_plate(views, plate, traces, parse, plane=None, share=0.1, tol=TOL): document = build(crown) parsed(document) by_vertex = {row_["vertex"]: row_ for row_ in report["points"]} + + def decided_at(v): + """What decided a crown point's depth, by its prior share: the prior (the plane, and a side's fairness) from VIEWS up, whatever the point is.""" + row_ = by_vertex[v] + return {"decided_by": "plane" if row_["prior_share"] >= VIEWS else "mirror" if v in on_seam else "views", "m_per_px": round(row_["m_per_px"], 4), "prior_share": round(row_["prior_share"], 3)} + corners = [] for i, name in enumerate(names): - row_ = by_vertex[int(first[i])] - corners.append({"name": name, "decided_by": "mirror" if i in held else "views" if row_["prior_share"] < VIEWS else "plane", "parallax_deg": round(float(parallax[i]), 1), - "m_per_px": round(row_["m_per_px"], 4), "prior_share": round(row_["prior_share"], 3)}) - sides = [{"from": names[i], "to": names[(i + 1) % N], "points": count[i], "traces": [report["traces"][k] for k in per_side[i]]} for i in range(N)] + said = decided_at(int(first[i])) + corners.append({"name": name, "decided_by": said["decided_by"], "parallax_deg": round(float(parallax[i]), 1), "m_per_px": said["m_per_px"], "prior_share": said["prior_share"]}) + sides = [] + for i in range(N): + inner = [decided_at(v) for v in chains[i][1:-1]] + sides.append({"from": names[i], "to": names[(i + 1) % N], "points": count[i], "inner": inner, + "decided_by": "corners" if not inner else "plane" if any(point["decided_by"] == "plane" for point in inner) else inner[0]["decided_by"], + "traces": [report["traces"][k] for k in per_side[i]]}) fit_traces, left_out = [], [] for k, (trace, (i, forward)) in enumerate(zip(traces, runs_of)): if (trace.get("side", 1) == -1 and not mirror) or trace.get("frame") is not None: diff --git a/surfaces/blender/tests/fixtures/spectre_truth.json b/surfaces/blender/tests/fixtures/spectre_truth.json new file mode 100644 index 0000000..1597893 --- /dev/null +++ b/surfaces/blender/tests/fixtures/spectre_truth.json @@ -0,0 +1 @@ +{"note":"SPECTRE's roof (spectre_cages.roof at nibu/fable-spectre-3 14d834c: a hard mirrored cage of 11 vertices) built by brokkr_kitbash.shell at one level with the hull's jaw, flank and cheeks (thickness 0.1, bevel 0.016), rendered by Blender 5.3's Workbench through spectre_skel.cameras() at the sheet's own pixel size (hero 756 x 706, side 264 x 348), the hull posed per view by frames. truth is the cage: Blender built each of its vertices within built_off_m of it (the bevel). strokes are the roof's edges traced from the two renders, not projected: along each edge the drawn edge is the strongest brightness step within 2.5 px across it, a straight stroke is laid through the steps found on each segment, and strokes meet where they cross. drawn is the least share of a segment's length where a step was found, off_projection_px how far the stroke's points stand from the truth's projection. The ridge is traced in the side view only: the hero draws no step along it (its two facets shade alike). closing marks the strokes an agent closes the outline with (the rear edge, and the lip in the side view, half drawn).","cameras":{"hero":{"C":[-9.721115556958573,18.859090658741355,5.242272804029844],"R":[[-0.862189601405842,-0.5065857195259607,0.0],[0.034125232508362004,-0.05807984607580026,0.9977285201827507],[-0.5054350202883507,0.8602311551276064,0.06736319480204615]],"f":1785.0,"c":[378.0,353.0]},"side":{"C":[60.84416742645475,1.422308134553987,3.13474760877321],"R":[[3.061616997868383e-16,1.0,0.0],[0.011634411213376642,-3.5620111131064444e-18,0.9999323179474289],[0.9999323179474289,-3.0614097813457806e-16,-0.011634411213376642]],"f":2200.0,"c":[892.0,532.0]}},"frames":{"hero":[[1.0,0.0,0.0,0.0],[0.0,0.9986295347545738,0.052335956242943835,-0.2773805680876023],[0.0,-0.052335956242943835,0.9986295347545738,0.007263465800758873],[0.0,0.0,0.0,1.0]],"side":[[1.0,0.0,0.0,0.0],[0.0,1.0,0.0,0.0],[0.0,-0.0,1.0,0.0],[0.0,0.0,0.0,1.0]]},"plates":{"roof":{"loop":["ridge_rear","r4","r3","r2","r1","nose","a","b","c","d","e"],"seam":["ridge_rear","r4","r3","r2","r1","nose"],"truth":{"nose":[0.0,3.33,6.34],"r1":[0.0,2.82,6.735],"r2":[0.0,1.76,7.05],"r3":[0.0,1.0,7.5],"r4":[0.0,-0.8,7.8],"ridge_rear":[0.0,-1.9,7.95],"a":[0.77,2.57,6.475],"b":[0.6,1.9,6.83],"c":[0.69,1.0,7.34],"d":[0.64,-0.8,7.65],"e":[0.62,-1.9,7.8]},"built_off_m":0.0151,"strokes":[{"view":"side","side":1,"through":["ridge_rear","r4","r3","r2","r1","nose"],"line":[[772.01,383.39],[811.74,388.89],[876.96,399.88],[904.51,416.13],[941.84,427.31],[961.08,441.58]],"closing":false,"drawn":1.0,"off_projection_px":0.69},{"view":"hero","side":-1,"through":["nose","a"],"line":[[325.08,142.53],[427.02,126.4]],"closing":false,"drawn":1.0,"off_projection_px":0.86},{"view":"side","side":1,"through":["nose","a"],"line":[[961.51,439.35],[933.43,437.76]],"closing":true,"drawn":0.53,"off_projection_px":2.49},{"view":"hero","side":-1,"through":["a","b","c","d","e"],"line":[[426.46,125.71],[442.01,93.62],[487.59,47.65],[551.9,26.85],[587.64,18.75]],"closing":false,"drawn":0.71,"off_projection_px":0.98},{"view":"side","side":1,"through":["a","b","c","d","e"],"line":[[933.68,435.98],[908.72,424.05],[876.26,405.25],[810.61,394.34],[770.7,387.55]],"closing":false,"drawn":0.76,"off_projection_px":1.64},{"view":"hero","side":-1,"through":["e","ridge_rear"],"line":[[587.54,18.26],[541.95,9.26]],"closing":true,"drawn":1.0,"off_projection_px":0.09},{"view":"side","side":1,"through":["e","ridge_rear"],"line":[[769.96,387.04],[772.42,383.77]],"closing":true,"drawn":1.0,"off_projection_px":0.82}]}}} \ No newline at end of file diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index a18eb3a..a084f30 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -778,34 +778,71 @@ def blocked_plate(views, traces, **more): return core.block_plate(views, {"corners": PLATE}, traces, kit.sheet, **more) +def rendered(name, corners, sigma=0.0, close=0.0, seed=0): + """(views, plate, traces, the true sides, the fixture's plate) of a plate of tests/fixtures/spectre_truth.json + with `corners` of its loop named: each stroke traced from the renders is cut at the named corners it passes + through, every point `sigma` px off, a closing stroke moved `close` px as one.""" + fixture = json.loads((Path(__file__).resolve().parent / "fixtures" / "spectre_truth.json").read_text(encoding="utf-8")) + plate, rng, views, traces = fixture["plates"][name], np.random.default_rng(seed), [], [] + for stroke in plate["strokes"]: + line = np.array(stroke["line"]) + (rng.normal(0, sigma, (len(stroke["line"]), 2)) if sigma else 0.0) + if stroke["closing"] and close: + turn = rng.uniform(0, 2 * math.pi) + line = line + close * np.array([math.cos(turn), math.sin(turn)]) + cuts = [k for k, corner in enumerate(stroke["through"]) if corner in corners] + for a, b in zip(cuts, cuts[1:]): + traces.append({"camera": stroke["view"], "from": stroke["through"][a], "to": stroke["through"][b], "side": stroke["side"], "line": line[a:b + 1].tolist(), + **({"frame": fixture["frames"]["hero"]} if stroke["view"] == "hero" else {})}) + views.append((fixture["cameras"][stroke["view"]], fixture["frames"][stroke["view"]])) + loop, named = plate["loop"], [corner for corner in plate["loop"] if corner in corners] + sides = [] + for i, corner in enumerate(named): + a, b = loop.index(corner), loop.index(named[(i + 1) % len(named)]) + sides.append(np.array([plate["truth"][loop[k % len(loop)]] for k in range(a, (b if b > a else b + len(loop)) + 1)])) + return views, {"corners": named, "mirror": True, "seam": [corner for corner in plate["seam"] if corner in corners]}, traces, sides, (fixture, plate) + + +def off_rendered(out, sides): + """(the furthest a blocked corner stands from its own, the furthest a side as built and its true edge, a polyline + through the truth's corners, stand apart either way), metres.""" + verts, chains = np.array(out["sheet"]["verts"]), crown_chains(out) + edge = 0.0 + for chain, side in zip(chains, sides): + built = core.crease_run(core.crease_run(verts[chain])) + edge = max(edge, float(core._off(built, side).max()), float(core._off(core.resampled(side, 300), built).max())) + return max(float(np.linalg.norm(verts[chain[0]] - side[0])) for chain, side in zip(chains, sides)), edge + + @unittest.skipIf(np is None, "numpy") class BlockTests(unittest.TestCase): """block_plate: a plate's first cage from traces of its outline. Bounds follow lodur:ruling:deterministic-bound-margin; the other numbers are tolerances round a known truth. Mutants, each run once on a copy: M1 no end terms test_spectre_roof_and_cheek - M2 a point prior (fit_shell's) for the plane distance test_one_view_and_a_plane_block_a_bowed_plate - M3 a seam corner's x free test_spectre_roof_and_cheek - M5 the 66 degree guard off test_a_plane_far_off_square_on_to_its_one_view_is_refused + M2 a point prior (fit_shell's) for the plane distance test_one_view_and_a_plane_block_a_bowed_plate, test_fairness_is_set_by_the_rendered_roof + M3 a seam corner's x free test_spectre_roof_and_cheek, test_the_rendered_roof_blocks_from_traces_of_its_renders + M4 no fairness test_fairness_is_set_by_the_rendered_roof + M5 the 66 degree guard off test_a_plane_far_off_square_on_to_its_one_view_is_refused, test_a_seam_corner_says_what_decided_it M6 no growth (K_MAX 2) test_a_side_grows_until_its_trace_is_explained, test_spectre_roof_and_cheek - M4 no fairness test_spectre_roof_and_cheek + F5 FAIR 0.5, F05 FAIR 0.05 test_fairness_is_set_by_the_rendered_roof; test_a_side_grows_until_its_trace_is_explained + S1 a seam point labelled mirror whatever its share test_a_seam_corner_says_what_decided_it + S2 a seam corner never sent to the plane's guard test_a_seam_corner_says_what_decided_it + I1 a side's label from its first point only, never plane test_a_side_says_what_decided_its_inner_points + T06 START 0.6, T3 START 3.3 test_views_5_degrees_apart_take_their_depth_from_a_plane_or_are_refused + K1 a skirt of fixed metres test_a_plate_keeps_its_proportions_at_any_size - M4 is claimed by one reading, SPECTRE's brow (a median of 8.4 mm with fairness, 19.8 without), against a - reference that is itself a fit. Against a known truth it reads the other way: the bowed plate of - test_a_side_grows_until_its_trace_is_explained ends 41.6 mm off with fairness and 12.1 without, the one-view - bowed plate 85.1 mm with it and 2.7 without, the twisted plate at 19 degrees and 1.5 px 135.1 either way. FAIR - 0.2 came from five-point chains under noise (research probe-synthetic-sensitivity); a side grown only as far - as its trace asks has less for fairness to hold. - - The twisted, bowed plate does not block within 1.35 x noise x m_per_px, the probe's figure for five-point - chains: its bow toward the first camera is 56 mm, under 2 px at 60 degrees, the default tol explains it with a - straight side, and what is left is the bow (test_a_twisted_bowed_plate_blocks_from_two_views).""" + What the blocking is worth against a known truth is test_the_rendered_roof_blocks_from_traces_of_its_renders: + a built plate, rendered, its edges traced off the renders. test_spectre_roof_and_cheek and + test_paladin_plates_one_view_each read agreement with another fit and with a harness's lift on the same + pixels, not accuracy.""" def test_a_twisted_bowed_plate_blocks_from_two_views(self): """block-synthetic. Views 60 and 19 degrees apart, traces 0.5 and 1.5 px off: every trace is explained with two points a side, and the crown as built ends 39.3, 52.1 (60 degrees) and 65.0, 135.1 mm (19) from the - truth, 1.46 to 4.23 times noise x the worst corner's m_per_px. At 60 degrees every corner is decided by the - views (prior_share 0.138 at most, under core.VIEWS by 1.45); at 19 the plane has 0.30 to 0.38 of each.""" + truth: the 56 mm bow toward the first camera reads under 2 px, the default tol explains it with a straight + side, and the bow is the error. At 60 degrees every corner is decided by the views (prior_share 0.138 at + most, under core.VIEWS by 1.45); at 19 the plane has 0.30 to 0.38 of each. A side of two points has no + point of its own: it says corners.""" sides = pentagon(0.08) for apart, sigma, most, by in ((60, 0.5, 0.06, "views"), (60, 1.5, 0.08, "views"), (19, 0.5, 0.1, "plane"), (19, 1.5, 0.2, "plane")): out = blocked_plate(*plate_traces([plate_camera(0), plate_camera(apart)], sides, sigma)) @@ -813,19 +850,29 @@ class BlockTests(unittest.TestCase): self.assertEqual({corner["decided_by"] for corner in out["corners"]}, {by}, (apart, sigma)) self.assertLess(max(abs(corner["parallax_deg"] - apart) for corner in out["corners"]), 1.5) self.assertEqual(out["plane"]["from"], "corners") + self.assertEqual([(side["decided_by"], side["inner"]) for side in out["sides"]], [("corners", [])] * 5) kit.sheet(out["sheet"]) def test_views_5_degrees_apart_take_their_depth_from_a_plane_or_are_refused(self): - """block-low-parallax. At 5 degrees the corners triangulate 0.25 to 1.5 m off (the probe): under - core.PARALLAX the views start no corner. With a plane every corner is decided by it (prior_share 0.795 to - 0.838); with none the plate is refused naming the corners.""" + """block-low-parallax, T06, T3. The views start a corner where one pixel moves their meeting point less than + core.START x share x the plate's extent, the prior's own scale. At Paladin's lens and range that reads 0.74 + of the scale at 19 degrees (test_a_twisted_bowed_plate_blocks_from_two_views blocks there; T06 refuses it) + and 2.77 at 5, where the corners triangulate 0.25 to 1.5 m off: no corner is started. With a plane every + corner is decided by it (prior_share 0.795 to 0.838); with none the plate is refused naming the corners (T3 + blocks it). The line is metres a pixel, not degrees: through a lens three times as long the same plate 7 + degrees apart reads 0.66 and blocks from its views, 60.5 mm from the truth (65.0 at 19 degrees through the + short lens).""" views, traces = plate_traces([plate_camera(0), plate_camera(5)], pentagon(0.08), 0.5) out = blocked_plate(views, traces, plane=ON_Y) self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["plane"] * 5) self.assertGreater(min(corner["prior_share"] for corner in out["corners"]), 0.7) self.assertEqual(out["plane"]["from"], "given") - with self.assertRaisesRegex(core.ReferenceFitError, r"^plane: none was given, and 'c0', 'c1', 'c2', 'c3', 'c4' are seen by one view only"): + with self.assertRaisesRegex(core.ReferenceFitError, r"^plane: none was given, and 'c0', 'c1', 'c2', 'c3', 'c4' are decided by no view"): blocked_plate(views, traces) + sides = pentagon(0.08) + out = blocked_plate(*plate_traces([plate_camera(0, f=1989.0), plate_camera(7, f=1989.0)], sides, 0.5)) + self.assertEqual(out["plane"]["from"], "corners") + self.assertLess(off_plate(out, sides), 0.1) def test_a_side_grows_until_its_trace_is_explained(self): """block-growth, M6. A straight-sided plate blocks with its corners alone, 1.9 mm from the truth (the plane @@ -842,6 +889,66 @@ class BlockTests(unittest.TestCase): self.assertLess(max(trace["unexplained_px"] for side in out["sides"] for trace in side["traces"]), core.TOL / 1.2) self.assertLess(off_plate(out, sides), 0.06) + def test_a_side_says_what_decided_its_inner_points(self): + """interior-points (Soul s1), I1. The bowed pentagon from exact traces 60 degrees apart, asked at tol 0.1: + the sides grow to 4, 4, 4, 3, 4 points and every trace reads under 0.12 px, every corner is decided by the + views, and the side from c3 still ends 52.8 mm off the truth (the others 2.4 to 7.4). Its one inner point + has prior_share 0.405, twice core.VIEWS: the side says plane, and its inner point says why. A side whose + trace is explained is not thereby a side the views decided.""" + sides = pentagon(0.08) + out = blocked_plate(*plate_traces([plate_camera(0), plate_camera(60)], sides), tol=0.1) + self.assertEqual([side["points"] for side in out["sides"]], [4, 4, 4, 3, 4]) + self.assertEqual([len(side["inner"]) for side in out["sides"]], [2, 2, 2, 1, 2]) + self.assertEqual({corner["decided_by"] for corner in out["corners"]}, {"views"}) + self.assertLess(max(trace["unexplained_px"] for side in out["sides"] for trace in side["traces"]), 0.12) + off = [float(off_run(out, chain, side).max()) for chain, side in zip(crown_chains(out), sides)] + self.assertEqual(int(np.argmax(off)), 3) + self.assertEqual((out["sides"][3]["decided_by"], out["sides"][3]["inner"][0]["decided_by"]), ("plane", "plane")) + self.assertGreater(out["sides"][3]["inner"][0]["prior_share"], 1.2 * core.VIEWS) + self.assertEqual(set(out["sides"][3]["inner"][0]), {"decided_by", "m_per_px", "prior_share"}) + + def test_a_seam_corner_says_what_decided_it(self): + """seam-corner-grazing (Soul s1), S1, S2, M5. A mirrored plate, its seam a to b on x = 0, traced in one view + 0.5 px off with the plane y = 0.05 given. From 60 degrees off the mirror plane the seam's corners are + decided by it (prior_share 0.135 and 0.117, under core.VIEWS by 1.48; 7 mm off). From 10 degrees the sight + lines run along x = 0: the seam's corners are lifted onto the plane as any corner one view sees, and read + plane (0.571 and 0.513; 33 mm off): S1 reads them mirror. With a plane the view also runs along (its + normal 73 degrees off x) there is no depth at all, and the plate is refused naming the seam's corner: S2 + and M5 block it.""" + P, names = np.array([[0, 0, 0.6], [0, 0, -0.6], [0.5, 0.1, -0.5], [0.45, 0.1, 0.5]]), ["a", "b", "c", "d"] + + def block(azimuth, normal): + rng, cam, traces = np.random.default_rng(1), plate_camera(azimuth), [] + for i in range(4): + u = core.project(cam, P[[i, (i + 1) % 4]]) + traces.append({"from": names[i], "to": names[(i + 1) % 4], "side": 1, "line": (np.linspace(u[0], u[1], 6) + rng.normal(0, 0.5, (6, 2))).tolist()}) + return core.block_plate([(cam, EYE)] * 4, {"corners": names, "mirror": True, "seam": ["a", "b"]}, traces, kit.sheet, plane={"point": [0, 0.05, 0], "normal": normal}) + + out = block(60, [0, 1, 0]) + self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["mirror", "mirror", "plane", "plane"]) + self.assertLess(max(corner["prior_share"] for corner in out["corners"][:2]), core.VIEWS / 1.2) + self.assertLess(max(float(np.linalg.norm(np.array(out["sheet"]["verts"])[k] - P[k])) for k in (0, 1)), 0.012) + out = block(10, [0, 1, 0]) + self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["plane"] * 4) + self.assertGreater(min(corner["prior_share"] for corner in out["corners"][:2]), 1.2 * core.VIEWS) + self.assertEqual([float(x) for x in np.array(out["sheet"]["verts"])[:2, 0]], [0.0, 0.0]) + with self.assertRaisesRegex(core.ReferenceFitError, r"^plate\.corners\[0\] 'a': the plane stands 83 degrees off square-on to the view of traces\[0\]"): + block(10, [1, 0.3, 0]) + + def test_a_plate_keeps_its_proportions_at_any_size(self): + """plate-template (Soul s1), K1. The pentagon at 0.1, 1 and 10 times its size through cameras as many times + as far: the skirt stands 0.078 of the crown's extent from the crown and the centre 0.017 of it proud at + every size, where a skirt of fixed metres stood 0.81 of a 0.11 m plate's extent out and 0.008 of an 11 m + one's. The crown blocks within a ten-thousandth of the extent at each.""" + for scale in (0.1, 1.0, 10.0): + sides = [side * scale for side in pentagon(0.0, twist=0.0)] + out = blocked_plate(*plate_traces([plate_camera(0, distance=17.6 * scale), plate_camera(60, distance=17.6 * scale)], sides)) + verts = np.array(out["sheet"]["verts"]) + extent = float(np.linalg.norm(verts[:5, None] - verts[None, :5], axis=2).max()) + self.assertAlmostEqual(float(np.linalg.norm(verts[5:10] - verts[:5], axis=1).mean()) / extent, math.hypot(core.FLARE, core.DROP), places=4) + self.assertAlmostEqual(float(np.linalg.norm(verts[10] - verts[:5].mean(0))) / extent, core.DOME, places=4) + self.assertLess(off_plate(out, sides), 1e-4 * extent) + def test_one_view_and_a_plane_block_a_bowed_plate(self): """M2. A flat plate in the plane it is given, its sides bowed 35% in the plate, traced exactly in one view 30 degrees off square-on: every corner is decided by the plane, the sides grow to three points and the @@ -900,6 +1007,71 @@ class BlockTests(unittest.TestCase): self.assertEqual(out["sheet"]["mirror"], True) self.assertEqual(out["sheet"]["poles"], [seam[0], seam[1], len(out["sheet"]["verts"]) - 1]) + def test_the_rendered_roof_blocks_from_traces_of_its_renders(self): + """block-truth (Soul s1, real-readings-not-accuracy), M3. SPECTRE's pass-3 roof, a hard mirrored cage of 11 + known vertices, built by brokkr_kitbash.shell, rendered through SPECTRE's two solved cameras at the + sheet's pixel size and its edges traced off the renders (tests/fixtures/spectre_truth.json says how). The + ridge is traced in the side view alone, the lip, the outer edge and the rear edge in the hero's mirrored + half and in the side view, 62 degrees apart; the side view's pixel is 27.6 mm across at the plate, the + hero's 11.6. + + Every corner named: the ridge's six are decided by the mirror plane, the outer edge's five by the views + (prior_share 0.038 at most). From the traces as taken the worst corner stands 39.1 mm from the truth, 1.42 + of the side view's pixels (Blender builds the cage's vertices up to 15.1 mm inside it, the bevel; a + stroke stands up to 2.5 px from the truth's projection). With every traced point 1 px off, twelve draws: + 68.6 mm at the median, 96.1 at most; 2 px: 125.1 and 190.1. That is 3.5 x the noise x the coarser view's + pixel, and the bounds are tolerances 1.2 over it: no mutant is claimed by a margin here (M1 reads 49.3, + 116.6 and 206.5, under 1.3 away). M3 lands the ridge off x = 0 and is refused. The same readings are 4.6 + to 7.5 x noise x a view-decided corner's m_per_px, and a seam corner's m_per_px (0.0008) says nothing of + its 98 mm: m_per_px is a depth sensitivity, and most of this error lies across the sight line.""" + corners = ["ridge_rear", "r4", "r3", "r2", "r1", "nose", "a", "b", "c", "d", "e"] + views, plate, traces, sides, (fixture, record) = rendered("roof", corners) + middle = np.mean(list(record["truth"].values()), axis=0) + pixel = max(float(np.linalg.norm(np.array(cam["C"]) - middle)) / cam["f"] for cam in fixture["cameras"].values()) + self.assertAlmostEqual(pixel, 0.0276, places=4) + out = core.block_plate(views, plate, traces, kit.sheet) + self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["mirror"] * 6 + ["views"] * 5) + self.assertLess(max(corner["prior_share"] for corner in out["corners"]), core.VIEWS / 1.2) + self.assertGreater(min(corner["parallax_deg"] for corner in out["corners"][6:]), 59) + self.assertEqual([side["points"] for side in out["sides"]], [2] * 11) + self.assertEqual(float(np.abs(np.array(out["sheet"]["verts"])[:6, 0]).max()), 0.0) + self.assertLess(off_rendered(out, sides)[0], 1.7 * pixel) + for sigma in (1.0, 2.0): + worst = [] + for seed in range(12): + views, plate, traces, sides, _ = rendered("roof", corners, sigma, seed=seed) + worst.append(off_rendered(core.block_plate(views, plate, traces, kit.sheet), sides)[0]) + self.assertLess(max(worst), 4.2 * sigma * pixel, sigma) + self.assertLess(float(np.median(worst)), 2.8 * sigma * pixel, sigma) + + def test_fairness_is_set_by_the_rendered_roof(self): + """fair (Soul s1, fair-default-tuned-to-a-fit), F5, M4, M2. The rendered roof with four corners named + (ridge_rear, nose, a, e), so the ridge and the outer edge are one side each and grow through their knees: + from the traces as taken they grow to three points and stand 196.0 mm from the true edges at most, the + hard knees cut by a run that reads as explained within tol (5.2 px is 144 mm in the side view). With every + point 2 px off and the closing strokes moved 3 px, 24 draws: 15 block, and nine tenths of those stand + within 196.9 mm. FAIR 0.5 reads 369.5 there, no fairness 394.0, M2 388.8: the bound is the geometric mean + of 196.9 and 369.5, separation 1.37 each side. Over ten cells of known truth at 1 and 2 px (this roof four + ways, and the bowed pentagon at 60 and 30 degrees and in one view) the mean of the cells' 90th percentiles + reads 194, 184, 178, 178, 179, 186, 193, 196 mm at FAIR 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 1 and the + worst draw 301, 275, 273, 272, 312, 382, 494, 577: 0.2 stands at the low of both. From exact traces weaker + fairness is nearer the truth (the bowed pentagon: 41.6 mm at 0.2, 16.2 at 0.5, 12.1 with none); nobody + traces exactly, and at 1 px the difference is 16 mm at 60 degrees and the other way at 30.""" + corners = ["ridge_rear", "nose", "a", "e"] + views, plate, traces, sides, _ = rendered("roof", corners) + out = core.block_plate(views, plate, traces, kit.sheet) + self.assertEqual([side["points"] for side in out["sides"]], [3, 2, 3, 2]) + self.assertLess(off_rendered(out, sides)[1], 0.235) + edges = [] + for seed in range(24): + views, plate, traces, sides, _ = rendered("roof", corners, 2.0, 3.0, seed) + try: + edges.append(off_rendered(core.block_plate(views, plate, traces, kit.sheet), sides)[1]) + except core.ReferenceFitError: + pass + self.assertGreaterEqual(len(edges), 12) + self.assertLess(sorted(edges)[math.ceil(0.9 * len(edges)) - 1], 0.270) + def test_paladin_plates_one_view_each(self): """block-paladin (tests/fixtures/paladin_plates.json). Paladin's 16 traced plates, each a polygon traced in one view with the plane the agent gave it: every corner is decided by the plane (prior_share 1.00 to 2.13: From 29566492b50c992eec687240b586f8ce9c5cb954 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 11:03:26 +0100 Subject: [PATCH 195/223] tests/fixtures/raptor_plates.json: RAPTOR's 27 plate marked by eye in the hero and the SIDE view, the hero solved from hull marks (no camera under 25.1 px rms at 50 mm: the sheet's two views do not draw one hull); the plate blocks from its two views 34 to 40 degrees apart, the prior holding 0.17 to 0.20 of each corner; pinned as two views agreeing, not an accuracy (cut trace-block, Soul s1) Co-Authored-By: Claude Fable 5.2 --- .../blender/tests/fixtures/raptor_plates.json | 1 + surfaces/blender/tests/test_reference.py | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 surfaces/blender/tests/fixtures/raptor_plates.json diff --git a/surfaces/blender/tests/fixtures/raptor_plates.json b/surfaces/blender/tests/fixtures/raptor_plates.json new file mode 100644 index 0000000..ebf9c13 --- /dev/null +++ b/surfaces/blender/tests/fixtures/raptor_plates.json @@ -0,0 +1 @@ +{"note":"RAPTOR (sheet 38): the hull plate that bears the 27, its four corners marked by eye in the hero (the right flank) and in the SIDE view (the left flank, so side -1), with the nose's front face and the two laser emitters. Coordinates are the hull's (raptor_form.SHEET at 3ced828: x right, y forward of the sheet's hip column, z up). side is raptor_form.SHEET.camera(), square-on at the sheet's 28.6 px a metre. world gives each mark's (y, z) off the SIDE view and its x from the hull's mass (the nose 0, the emitters +-0.56, a plate corner the flank's half-width at its station and height): hero is brokkr_reference.core.solve(world, pixels, box, model rolled, lens 50). The seven marks admit no camera under 21.8 px rms (left-out 44 px, lens not determined; 25.1 px at 50 mm): the sheet's two views do not draw one rigid hull, and four of the seven marks are the plate's own corners. What block_plate gives through these cameras is two views agreeing on a plate, not a measured accuracy: there is no truth for this plate.","cameras":{"hero":{"C":[11.303769012415719,10.50084330876064,1.6426541643628032],"R":[[-0.5899084170655855,0.7870428136060581,0.1804762284242304],[0.1745987487019839,-0.09389198835577137,0.9801528306719831],[0.7883675135537211,0.6097113284773865,-0.08202901620441301]],"f":944.4444444444445,"c":[400.0,320.0]},"side":{"C":[-400.0,0.0,0.0],"R":[[0.0,-1.0,0.0],[0.0,0.0,1.0],[-1.0,0.0,0.0]],"f":11441.176470588236,"c":[348.5,849.5]}},"box":[60,0,740,640],"world":{"nose":[0.0,5.681233933161954,4.038046272493573],"emitter_r":[0.56,4.96452442159383,3.7583547557840613],"emitter_l":[-0.56,4.96452442159383,3.7583547557840613],"p_ft":[0.6753672831185238,4.14293059125964,5.4365038560411305],"p_fb":[1.0477429305912596,4.317737789203084,4.632390745501285],"p_rb":[1.2748071979434448,3.0940874035989716,4.80719794344473],"p_rt":[1.282382176520994,3.0241645244215936,5.576349614395887]},"pixels":{"nose":[683,250],"emitter_r":[557,273],"emitter_l":[617,283],"p_ft":[500,120],"p_fb":[539,183],"p_rb":[461,184],"p_rt":[459,108]},"plate":{"corners":["p_ft","p_fb","p_rb","p_rt"]},"traces":[{"view":"hero","from":"p_ft","to":"p_fb","side":1,"line":[[500,120],[539,183]]},{"view":"side","from":"p_ft","to":"p_fb","side":-1,"line":[[230,694],[225,717]]},{"view":"hero","from":"p_fb","to":"p_rb","side":1,"line":[[539,183],[461,184]]},{"view":"side","from":"p_fb","to":"p_rb","side":-1,"line":[[225,717],[260,712]]},{"view":"hero","from":"p_rb","to":"p_rt","side":1,"line":[[461,184],[459,108]]},{"view":"side","from":"p_rb","to":"p_rt","side":-1,"line":[[260,712],[262,690]]},{"view":"hero","from":"p_rt","to":"p_ft","side":1,"line":[[459,108],[500,120]]},{"view":"side","from":"p_rt","to":"p_ft","side":-1,"line":[[262,690],[230,694]]}]} \ No newline at end of file diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index a084f30..c79085c 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -1072,6 +1072,30 @@ class BlockTests(unittest.TestCase): self.assertGreaterEqual(len(edges), 12) self.assertLess(sorted(edges)[math.ceil(0.9 * len(edges)) - 1], 0.270) + def test_raptor_plate_from_two_views(self): + """block-raptor (tests/fixtures/raptor_plates.json): the hull plate bearing RAPTOR's 27, its corners marked + by eye in the hero (right flank) and in the SIDE view (left flank, side -1). The hero camera is solved + from hull marks alone (the nose, both emitters, the plate's corners): the seven admit none under 25.1 px + rms at 50 mm (the sheet's hero and SIDE view do not draw one rigid hull), where the first hero, solved + from leg joints, stood 18.5 degrees from the SIDE view and drew the hull tens of pixels off. Through it + the plate blocks from its two views: sight lines 33.9 to 40.1 degrees apart, every trace explained + within 3.2 px, the corners on the right flank at x 0.87 to 1.72 m. The prior has 0.173 to 0.197 of each + corner, under core.VIEWS by less than the margin, so the label is not asserted: on this sheet two views + decide a flank corner only just. No truth exists for the plate and four of the camera's seven marks are + its corners: this is two views agreeing, pinned as it read, not an accuracy.""" + fixture = json.loads((Path(__file__).resolve().parent / "fixtures" / "raptor_plates.json").read_text(encoding="utf-8")) + solved = core.solve(fixture["world"], fixture["pixels"], fixture["box"], model="rolled", lens=50) + self.assertGreater(solved["rms"], 20) + self.assertLess(float(np.abs(np.array(solved["C"]) - fixture["cameras"]["hero"]["C"]).max()), 1e-6) + traces = [{key: trace[key] for key in ("from", "to", "side", "line")} for trace in fixture["traces"]] + out = core.block_plate([(fixture["cameras"][trace["view"]], EYE) for trace in fixture["traces"]], fixture["plate"], traces, kit.sheet) + self.assertGreater(min(corner["parallax_deg"] for corner in out["corners"]), 30) + self.assertLess(max(corner["prior_share"] for corner in out["corners"]), 1.2 * core.VIEWS) + self.assertLess(max(trace["unexplained_px"] for side in out["sides"] for trace in side["traces"]), core.TOL / 1.2) + self.assertEqual((out["plane"]["from"], [side["points"] for side in out["sides"]]), ("corners", [2] * 4)) + crown = np.array(out["sheet"]["verts"])[:4] + self.assertTrue((crown[:, 0] > 0.8).all() and (crown[:, 0] < 1.8).all(), crown[:, 0]) + def test_paladin_plates_one_view_each(self): """block-paladin (tests/fixtures/paladin_plates.json). Paladin's 16 traced plates, each a polygon traced in one view with the plane the agent gave it: every corner is decided by the plane (prior_share 1.00 to 2.13: From 8b702c537e3865d0007d60b8d2bce7fbfbc2db99 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 11:11:38 +0100 Subject: [PATCH 196/223] docs/reference.md, brokkr_actions.json: block_plate's depth sources as shipped (the views by metres a pixel, a seam corner by a crossing sight line, the plane and its guard), decided_by read from prior_share for every crown point and each side's inner points, the skirt in shares of the crown; measured against the rendered roof's truth, FAIR's table, and agreement with other fits named as agreement Co-Authored-By: Claude Fable 5.2 --- .../brokkr_reference/brokkr_actions.json | 2 +- surfaces/blender/brokkr_reference/core.py | 12 ++- surfaces/blender/docs/reference.md | 93 ++++++++++++++----- 3 files changed, 81 insertions(+), 26 deletions(-) diff --git a/surfaces/blender/brokkr_reference/brokkr_actions.json b/surfaces/blender/brokkr_reference/brokkr_actions.json index 38499c6..d86e468 100644 --- a/surfaces/blender/brokkr_reference/brokkr_actions.json +++ b/surfaces/blender/brokkr_reference/brokkr_actions.json @@ -177,7 +177,7 @@ }, { "name": "brokkr_reference.block_plate", - "doc": "Block a plate's first free cage from traces of its outline, each seen through a scene camera and naming the two consecutive corners it runs between: the only correspondence is a trace's ends to its corners. The crown (the corners and each side's points between) is solved until the sides as built draw on the traces; a side whose trace is not explained gains a point, up to 6. Depth comes from the views where two see a corner 9.7 degrees or more apart, from x = 0 for a mirrored plate's seam corners, and otherwise from a plane: the one given, or the one through the corners the views and the seam decide. Each corner says which (decided_by views, mirror or plane; views means the prior's share is under 0.2). A corner one view sees is refused when the plane stands over 66 degrees off that view. Returns the sheet for brokkr_kitbash.shell, checked by its parser, and fit_traces for brokkr_reference.fit_shell (left_out lists the traces fit_shell cannot state: another frame, or a partner's side -1). Writes nothing (docs/reference.md).", + "doc": "Block a plate's first free cage from traces of its outline, each seen through a scene camera and naming the two consecutive corners it runs between: the only correspondence is a trace's ends to its corners. The crown (the corners and each side's points between) is solved until the sides as built draw on the traces; a side whose trace is not explained gains a point, up to 6. Depth comes from the views where two see a corner and a pixel moves their meeting point less than share x the plate's extent, from x = 0 for a mirrored plate's seam corners whose view crosses it, and otherwise from a plane: the one given, or the one through the corners the views and the seam decide. Every corner, and every point between corners (sides[].inner), says what decided it by its prior_share: plane from 0.2 up, else mirror on the seam, else views; a side says corners, views, mirror or plane. A corner one view sees, a seam corner seen along x = 0 included, is refused when the plane stands over 66 degrees off that view. Returns the sheet for brokkr_kitbash.shell, checked by its parser, and fit_traces for brokkr_reference.fit_shell (left_out lists the traces fit_shell cannot state: another frame, or a partner's side -1). Writes nothing (docs/reference.md).", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index 6e808d1..f34c73d 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -43,7 +43,7 @@ is solved by fit_runs with a plane and fairness for its prior; docs/reference.md triangulate(obs, seam) where sight lines meet, and how far apart they stand plate_sheet(crown, corners, flare, drop, dome, mirror, seam, facing) the crown, skirt and centre free-cage document - block_plate(views, plate, traces, parse, plane, share, tol) the blocked sheet and what decided each corner + block_plate(views, plate, traces, parse, plane, share, tol) the blocked sheet and what decided each crown point """ from __future__ import annotations @@ -882,7 +882,15 @@ def block_plate(views, plate, traces, parse, plane=None, share=0.1, tol=TOL): plane, so the views decide wherever they see. A side starts as its two corners; a side with a trace not explained gains a point and the plate is solved again, to K_MAX points. Skirt and centre are rebuilt from the solved crown (plate_sheet). Returns {"sheet", "fit_traces", "left_out", "corners", "sides", "plane", "rounds"}; - raises ReferenceFitError naming the field for everything it refuses.""" + raises ReferenceFitError naming the field for everything it refuses. + + A corner starts where its views meet when a pixel moves that point less than START x share x the plate's + extent; a seam corner where its sight line crosses x = 0, unless the line runs along the plane (SQUARE); any + other on the plane, lifted and guarded by SQUARE. What decided a point is read after the solve from its + prior_share, the same for every crown point: "plane" from VIEWS up (the prior holds its depth: the plane, and + for a side's inner points its fairness), else "mirror" on the seam, else "views". corners[] and each side's + "inner" (its points between corners) carry {"decided_by", "m_per_px", "prior_share"}; a side's own + "decided_by" is "corners" with no inner point, "plane" when any inner point is, else its inner points'.""" if not isinstance(plate, dict) or set(plate) - {"corners", "mirror", "seam"}: raise ReferenceFitError("plate must be {corners, mirror, seam}") names, mirror, seam_names = plate.get("corners"), plate.get("mirror", False), plate.get("seam", []) diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index c9473b1..eed579d 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -292,13 +292,20 @@ between them lie on it, and one view decides them. Where a corner's depth comes from, in this order: -- **the views**, where two or more see it and its sight lines stand 9.7 degrees or more apart. Under that the - triangulation is not used as a start: at 5 degrees corners of a 1.2 m plate landed 0.25 to 1.5 m off. -- **the mirror plane**, for a seam corner. +- **the views**, where two or more see it and one pixel moves the point their sight lines meet at less than + `share` x the plate's extent, the prior's own scale. Past that the views alone hold the corner looser than the + plane would and are not used as its start. The line is metres a pixel, so it moves with lens and range: a + 1.2 m plate 17.6 m off at 663 px reads 0.74 of the scale at 19 degrees and 2.77 at 5, where its corners landed + 0.25 to 1.5 m off; through a lens three times as long it reads 0.66 at 7 degrees and blocks. +- **the mirror plane**, for a seam corner whose sight line crosses x = 0 at 24 degrees or more. - **a plane**, for the rest: `plane` (`x,y,z; nx,ny,nz`, a point and the normal, in the frame), or with none given the plane through the corners the views and the seam decide, three or more. A corner one view sees is lifted onto it, and refused when the plane stands more than 66 degrees off square-on to that view: the lift stretches - past 2.5 times there. + past 2.5 times there. A seam corner whose one view runs along x = 0 is such a corner: it is lifted onto the + plane, held on x = 0, and refused by the same 66 degrees. + +That is where a corner starts. What the report says decided it is read after the solve, from the point's own +prior share, whatever kind of point it is. The crown is then solved by the same solver as `fit_shell`, with a different prior: each crown point's distance to the plane costs a pixel per `share` x the corners' extent, and each side's second differences a pixel per 0.2 @@ -307,7 +314,9 @@ and a view that sees nothing along its own sight line leaves that to the plane. corners. After each solve a side with a trace not explained (the same nine tenths within `tol`) gains one point and the plate is solved again, to six points a side; past that it is refused as `fit_shell` refuses a trace. -The cage is the crown ring, a skirt 0.06 m out and 0.07 m back of it, and one centre vertex: every crown side +The cage is the crown ring, a skirt 0.05 of the crown's extent out and 0.06 back of it, and one centre vertex +0.017 proud (the extent is the distance between the crown's two furthest points, so a plate of any size has the +same proportions): every crown side creased 1, the named corners pinned, the centre the declared pole unless the crown has four points. On a mirrored plate the seam's sides have no skirt and the seam's two ends are poles too. The skirt and centre are rebuilt from the solved crown and never solved. The sheet goes through `brokkr_kitbash`'s parser before it is @@ -315,9 +324,16 @@ returned, and `brokkr_kitbash.shell` builds it; `block_plate` writes nothing. The report: `sheet`; `fit_traces`, the traces as `fit_shell` takes them (each side a run of authored vertices), and `left_out`, the traces `fit_shell` cannot state (one with its own `frame`, or a partner's side -1 on a plate -that is not mirrored); per corner `decided_by` (`views` when the prior's share is under 0.2, `mirror` on the seam, -else `plane`), `parallax_deg`, `m_per_px` and `prior_share`; per side its points and each trace's readings; -`plane` with `from` `given` or `corners`; `rounds`, the solves it took. +that is not mirrored); per corner `decided_by`, `parallax_deg`, `m_per_px` and `prior_share`; per side its +points, each trace's readings, `inner` (the same `decided_by`, `m_per_px` and `prior_share` for each point between +its corners) and its own `decided_by`; `plane` with `from` `given` or `corners`; `rounds`, the solves it took. + +`decided_by` is read from `prior_share` for every crown point: `plane` from 0.2 up, the prior (the plane, and +for a side's inner points its fairness) holding the depth; under 0.2 `mirror` for a point on the seam and +`views` for any other. A seam corner seen from 10 degrees off the mirror plane reads `plane` (0.57), not +`mirror`. A side says `corners` when it has no point of its own, `plane` when any inner point does, else what +its inner points say: a side can read as explained to 0.1 px and stand 53 mm off with its one inner point at +0.41, and then it says `plane`. Refused, naming the field: a corner no trace ends at, a side traced in no view, a trace whose corners are not consecutive, an unknown camera, a scaled frame, a seam that is not one stretch of the outline, no plane where @@ -325,23 +341,54 @@ fewer than three corners are decided, the 66 degrees, a mirrored plate's corner from the others (name it in `seam`, or trace it where the views agree), a side not explained at six points, a sheet the cage's parser does not take, and a result that could pass the 16000 characters a receipt carries. -Measured (`tests/test_reference.py` BlockTests, Python 3.13 on Starfire). SPECTRE's roof from no blocking: the -ridge, traced in the side view alone, 7.3 mm at most from the cage `fit_shell` had fitted from a hand blocking; -the brow, traced in the hero's mirrored half and the side 62.8 degrees apart, a median of 8.4 mm and 78.6 mm at -most from it, in four points; 0.05 s. A twisted pentagon 1.2 m across with sides bowed 8% toward the camera, -17.6 m off at 663 px: 39 and 52 mm from the truth at 60 degrees with traces 0.5 and 1.5 px off, every corner -decided by the views; 65 and 135 mm at 19 degrees, where the plane already has 0.30 to 0.38 of each corner. At -that range and lens two views 19 degrees apart do not decide a corner by this report's own line. -Paladin's 16 plates, each a polygon traced in one view with the plane its agent gave: every corner decided by the -plane, the crown within 1 mm of the one the harness had lifted. Its two thigh shields traced as partners are -refused, a side 19 px unexplained: the sheet draws two different polygons, not one plate and its reflection. +Measured against a known truth (`tests/test_reference.py` BlockTests, Python 3.13 on Starfire; +`tests/fixtures/spectre_truth.json`). SPECTRE's pass-3 roof, a hard mirrored cage of 11 vertices, was built by +`brokkr_kitbash.shell`, rendered in Blender 5.3 through SPECTRE's two solved cameras at the sheet's pixel size, +and its edges traced off the renders: the ridge in the side view, the lip, outer edge and rear edge in the +hero's mirrored half and the side view, 62 degrees apart. The side view's pixel is 27.6 mm across at the plate. + +| traces | worst corner from the truth | +| --- | --- | +| as taken off the renders (up to 2.5 px from the truth's projection) | 39 mm | +| every point 1 px off, 12 draws | 69 mm median, 96 mm at most | +| every point 2 px off, 12 draws | 125 mm median, 190 mm at most | + +With every corner named, the worst corner of a blocked plate stood within 3.5 x the noise x the coarser view's +pixel, on a floor of 1.4 of that pixel from the render itself. That is one plate through one pair of views, not +a law. It is not a multiple of `m_per_px`: the same readings are 4.6 to 7.5 x noise x a view-decided corner's +`m_per_px`, and a seam corner 98 mm off reports 0.0008 m a pixel, because `m_per_px` is depth along the sight +line and most of this error lies across it. With only four corners named, the roof's ridge and outer edge are +one side each and are built as smooth runs through their hard knees: explained within `tol`, 196 mm from the +true edges (5.2 px is 144 mm there). Name a hard corner as a corner. + +Fairness, 0.2 x a side's chord, is set by known truth at traced noise. Over ten cells at 1 and 2 px (the rendered +roof with four corners named, with and without closing strokes moved 3 px, and a bowed pentagon at 60 and 30 +degrees and in one view), the mean of the cells' 90th percentiles and the worst draw, in mm: + +| FAIR | 0.1 | 0.15 | 0.2 | 0.25 | 0.3 | 0.4 | 0.5 | 1 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| mean 90th percentile | 194 | 184 | 178 | 178 | 179 | 186 | 193 | 196 | +| worst draw | 301 | 275 | 273 | 272 | 312 | 382 | 494 | 577 | + +From exact traces weaker fairness is nearer the truth (a pentagon bowed 35% of its sides: 42 mm at 0.2, 16 at +0.5, 12 with none). + +Agreement with other fits, which is not accuracy. SPECTRE's second-pass roof from its hand traces: the ridge +7.3 mm at most and the brow a median of 8.4 mm from the cage `fit_shell` had fitted to the same pixels; with +1 px of noise on those traces the brow's median read 11 to 75 mm over six draws (Soul's probe, verdict cut-trace-block.s1). Paladin's 16 plates, each a polygon traced in +one view with the plane its agent gave: every corner decided by the plane, the crown within 1 mm of the one +the harness had lifted onto the same plane. Its two thigh shields traced as partners are refused, a side 19 px +unexplained: the sheet draws two different polygons, not one plate and its reflection. RAPTOR's hull plate +bearing the 27 (`tests/fixtures/raptor_plates.json`), marked by eye in the hero and the SIDE view: seven hull +marks admit no hero camera under 25 px rms, so the sheet's two views do not draw one hull; through that camera +the plate blocks with its sight lines 34 to 40 degrees apart and the prior holding 0.17 to 0.20 of each corner. What it gives up. One outline loop a plate: a plate that wraps a corner is two plates, and creases inside the -outline are not blocked. A bend smaller than `tol` is built straight: the bowed pentagon's 56 mm bow reads under -2 px and stays in the error above. Fairness holds a grown side flatter than its trace while the trace still -reads as explained: a plate whose sides bow 35% of their length ended 42 mm off its truth from exact traces, and -`fit_shell` on the returned `fit_traces` moved it 74 mm back. The plane through the decided corners is a guess -at a twisted plate, and where one view sees a corner the plane is all the depth it has: `decided_by` says so. +outline are not blocked. A bend smaller than `tol` is built straight, and a hard knee inside a side is rounded. +Fairness holds a grown side flatter than its trace while the trace still reads as explained (the side's +`decided_by` says when the prior holds it). The plane through the decided corners is a guess at a twisted +plate, and where one view sees a corner the plane is all the depth it has. Every crown point carries a skirt +vertex, so a point a side grows costs two. ## What it cannot do From e98b6a4da117340732c656c3f0e39d7a581e98b2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 11:11:38 +0100 Subject: [PATCH 197/223] tests/live/reference_block.py: MOVED, GAP and GAP_MIRRORED each the geometric mean of the scene's reading and its least mutant's (FAIR 0.05 run through the script in Blender 5.3: 0.0565, 0.0288, 0.0534 against 0.0048, 0.0027, 0.0140); its last run Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/reference_block.py | 5 +++-- .../blender/tests/live/reference_block.result.json | 10 +++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/surfaces/blender/tests/live/reference_block.py b/surfaces/blender/tests/live/reference_block.py index ce4f864..2cd1627 100644 --- a/surfaces/blender/tests/live/reference_block.py +++ b/surfaces/blender/tests/live/reference_block.py @@ -11,7 +11,8 @@ side is traced in both views where Blender's own projection draws the side as co fit_shell with the returned fit_traces on the built plate: accepted, every trace explained, and no point moved over MOVED (fairness holds a bowed side in and fit_shell's own prior lets it out: tests/test_reference.py test_the_blocking_goes_to_the_parser_and_to_fit_shell reads 74 mm of - it where a pixel is 27 mm; here a pixel is 5 mm) + it where a pixel is 27 mm; here a pixel is 5 mm). MOVED, GAP and GAP_MIRRORED each stand between + this scene's reading and a mutant's mirrored a mirrored plate with two seam corners, traced the same way: the seam stays on x = 0, brokkr_kitbash.shell builds both halves, and Blender builds the seam's side and a free side where core.crease_run says @@ -69,7 +70,7 @@ R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_ COUNT = [0] T0 = time.time() WIDTH, HEIGHT = 1000, 800 -MOVED, GAP, GAP_MIRRORED = 0.01, 0.01, 0.03 # metres, tolerances round this scene's readings (0.0048, 0.0027, 0.014; a pixel is 5 mm here): what fit_shell may move a point of the blocked plate, and how far the blocked crowns may stand from their truths +MOVED, GAP, GAP_MIRRORED = 0.0165, 0.0088, 0.0273 # metres, each the geometric mean of this scene's reading and its least mutant's (lodur:ruling:deterministic-bound-margin), the mutants run through this script on a copy of the surface: fit_shell moves a point of the blocked plate 0.0048 (FAIR 0.05: 0.0565), the blocked crown stands 0.0027 from its truth (FAIR 0.05: 0.0288), the mirrored crown 0.0140 (FAIR 0.05: 0.0534; no end terms: 0.0646). Separations 3.4, 3.3 and 1.95 each side. A pixel is 5 mm here and the traces are exact, where weaker fairness reads nearer (FAIR 0.5: 0.0011, 0.0018, 0.0054): tests/test_reference.py test_fairness_is_set_by_the_rendered_roof says why 0.2 stands def check(name, ok, detail=None): diff --git a/surfaces/blender/tests/live/reference_block.result.json b/surfaces/blender/tests/live/reference_block.result.json index 4c7503e..5af413c 100644 --- a/surfaces/blender/tests/live/reference_block.result.json +++ b/surfaces/blender/tests/live/reference_block.result.json @@ -55,8 +55,8 @@ ] ], "rounds": 2, - "seconds": 0.301, - "chars": 7242 + "seconds": 0.137, + "chars": 7703 } }, { @@ -65,7 +65,7 @@ "detail": null }, { - "name": "the blocked crown as built stands within 0.01 m of the truth's", + "name": "the blocked crown as built stands within 0.0088 m of the truth's", "ok": true, "detail": 0.002711610846938251 }, @@ -75,14 +75,14 @@ "detail": 1.1421151381392388e-07 }, { - "name": "fit_shell takes the returned fit_traces on the built plate: accepted, every trace explained, no point moved over 0.01 m", + "name": "fit_shell takes the returned fit_traces on the built plate: accepted, every trace explained, no point moved over 0.0165 m", "ok": true, "detail": { "moved_m": 0.0048 } }, { - "name": "a mirrored plate: the seam's corners are decided by the mirror plane, its side stays on x = 0, and the crown as built stands within 0.03 m of the truth's", + "name": "a mirrored plate: the seam's corners are decided by the mirror plane, its side stays on x = 0, and the crown as built stands within 0.0273 m of the truth's", "ok": true, "detail": { "gap": 0.013972102623404082, From 1b6de6225311992e3f26881a42fcdd31ebb248ab Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 11:14:00 +0100 Subject: [PATCH 198/223] docs/kitbash.md: followers, joints version 2, the joint-records drift; live bounds at their readings Joint records gain the follows row and a Followers section (ratio and loop, what a loop is solved from, the dead-centre bound, what it gives up). The joints example is version 2 with driven, unlimited and paging; ShipJoint's kind and spring are recorded as ruled with the one-to-one map; the false 'next pose is refused' claim goes and a frozen part's actions are complete. kitbash_follows.py takes its bounds from the F11 and R1 readings and finds the jump one solve does not survive (cut kit-follows-2, steps 5 and 6). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 110 ++++-- .../blender/tests/live/kitbash_follows.py | 46 ++- .../tests/live/kitbash_follows.result.json | 346 ++++++++++++++++++ .../tests/live/kitbash_pose.result.json | 28 +- 4 files changed, 479 insertions(+), 51 deletions(-) create mode 100644 surfaces/blender/tests/live/kitbash_follows.result.json diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 7a8470d..d10f017 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -176,8 +176,8 @@ matrix_basis = S_parent @ T(0, 0, slide) @ Rz(roll) @ FLIP @ inverse(S_child) ``` with `S` each socket's frame in its own part at that part's stored params (`core.mate`); a turn about z and a move -along it commute, so one connection carries both. `attach`, `set_params`, `roll`, `aim`, `reach`, `slide` and -`joint` write it; nothing else should. +along it commute, so one connection carries both. `attach`, `set_params`, `roll`, `aim`, `reach`, `slide`, +`joint` and `follow` write it; nothing else should. **Joint records.** A connection's degree of freedom is its parent socket's type's: a socket type states `"dof": "revolute"` (the child turns about the socket's z: `pivot`), `"dof": "prismatic"` (it slides along it: @@ -191,14 +191,56 @@ roll is a build angle. Beside the value the child's connection carries a record: | `kit_min`, `kit_max` | the limits of the value, both or neither: degrees on a revolute joint (a span of at most 360, each end within 360 of 0), metres on a prismatic one (each end within 10 m of 0) | `joint` | | `kit_mechanism` | a label of 1 to 32 `a-z`, `0-9` and `_`: which mechanism the joint is (`knee`, `shock`) | `joint` | | `kit_compliance` | `{"hertz", "damping_ratio"}` (hertz over 0 to 30, damping ratio 0 to 2): a slide in the load path that settles and rebounds under load. Prismatic only, and it needs limits, the travel it settles within | `joint` | +| `kit_follows`, `kit_follows_driver` | that the value is derived from another joint's: `{"kind": "ratio", "k", "offset"}` or `{"kind": "loop"}`, and an ID pointer to the driver, which follows a rename | `follow` | -Every one of them is written by one function, `write_connection`, which `attach`, `roll`, `aim`, `reach`, `slide` -and `joint` all seat through; `detach` clears them with the connection. So the limits have one check: a value with -no representative inside them is refused before anything is written, naming value and limits, and a roll a turn -away from its limits is written as the roll inside them (limits 150 to 210 and a roll of -170: 190). `aim` inside -limits takes the free roll when the limits hold it and otherwise the end that points the axis nearer; `reach` -takes only a root inside them. A new connection states no record. A value written by hand outside its limits -reads `within: false` in every report and the next pose of that part is refused. +Every one of them is written by one function, `write_connections`, which `attach`, `set_params`, `roll`, `aim`, +`reach`, `slide`, `joint` and `follow` all seat through; `detach` clears them with the connection. It takes +several connections and checks every one before it writes any, so a driver and its followers are written together +or not at all. So the limits have one check: a value with no representative inside them is refused before anything +is written, naming value and limits, and a roll a turn away from its limits is written as the roll inside them +(limits 150 to 210 and a roll of -170: 190). `aim` inside limits takes the free roll when the limits hold it and +otherwise the end that points the axis nearer; `reach` takes only a root inside them. A new connection states no +record. A value written by hand outside its limits reads `within: false` in every report; a pose that puts it +inside them is accepted and clears that, and `set_params` of the part or of its parent is refused until then, as +it is for a slide written by hand on a connection that is not prismatic. A record written by hand that its +connection may not carry (a compliance on a revolute joint) reads null in every report and goes at the next write. + +**Followers.** A joint whose value is a function of another's is a follower, and `follow` states it. A follower has +exactly one driver and a driver is never a follower (aetheria-release:ruling:one-joint-one-driver); `roll`, `aim`, +`reach` and `slide` on a follower are refused naming its driver, and `joint` on one states limits and a mechanism +and keeps the derived value. Posing a driver derives every follower in the same action and writes them with it: a +follower outside its own limits, or a loop that cannot close, refuses the pose with nothing changed. + +| Kind | The follower's value | For | +| --- | --- | --- | +| `ratio` | `k` x the driver's value + `offset`, either joint revolute or prismatic (a slide following a roll has `k` in metres per degree). The driver states limits, so its value is one number and not one of many a turn apart | a kneecap on the bisector (`k` 0.5), lames at `k/n` of the knee, a pinion at minus ring over pinion, a crosshead | +| `loop` | solved: the part that states a closure and its parent both follow, and their two values are the ones at which the closure holds | a rocker and coupler closing on a crank; a ram's barrel and rod closing on the part it pushes; a torque link's two arms | + +A loop has exactly two unknowns, the closing part's joint and its parent's, and it is planar: each revolute pin is +parallel to the pin it closes on and each slide runs across it. Exactly one of its two ends (the parent's parent, +and the part closed on) moves with the driver: it is the driver, follows it, or hangs from one that does. Nothing +stores a pin position or a linkage record: `core.close_loop` solves the pair from the kits' socket frames at the +parts' stored params each time, by Newton's method on the closing pin's error in the loop's plane with the analytic +Jacobian. That is the position analysis of the kinematics texts (Nikravesh, *Computer-Aided Analysis of Mechanical +Systems*, 1988, ch. 4; Uicker, Pennock and Shigley, *Theory of Machines and Mechanisms*); the ratio is Box2D's +`b2GearJoint` and Jolt's `GearConstraint` and `RackAndPinionConstraint`. A loop has two assembly branches and +Newton finds the one nearest its seed, so a driver steps to its new value 5 degrees or 0.02 m at a time, each solve +seeded by the one before, and only the last step is written: the linkage stays on the branch it was built on. +Loops are solved in an order where a loop's base and the part it closes on are already placed (a ram closing on a +four-bar's rocker waits for the four-bar); loops that wait on each other are refused. At a dead centre, where the +pair's two joints move the closing pin along one line, the pose is refused naming the driver's value and the +closing part: the bound is 0.093 on the smaller singular value of the Jacobian with unit columns, which is the two +joints within about 7.6 degrees of in line (the four-bar of `tests/test_kitbash.py` reads 0.184 at its last +accepted step and 0.047 at the first refused one). + +What followers give up: a loop of three or more unknowns, or one out of a plane, is not solved (follow-up +`kit-follows-wider-loops`); a follower does not drive another; `set_params` never derives a follower again, so a +loop it opens reads `holds: false` until its driver is posed; and a part above a loop that is posed by hand opens +it the same way. A connection's row in a report carries `follows: {driver, kind, k, offset, holds, reason}`: +`holds` is false, with a reason, when the value stands off the ratio, the loop's closure does not hold, or the +driver is gone or states no revolute or prismatic connection. Detaching a driver leaves its followers' +statements; detaching a loop follower clears its partner's. No Blender driver or constraint is made: a follower's +pose is its stored value, as every connection's is. Limits and springs follow Box2D v3's `b2PrismaticJointDef` and Jolt's `SliderConstraintSettings`: the slide's limits and a spring as a frequency in hertz and a damping ratio sit on the joint itself. Frequency and damping @@ -211,24 +253,38 @@ is the parent tree. `brokkr_kitbash.joints` derives both at each call and emits nothing: ```json -{"schema": "brokkr.joints", "version": 1, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres", - "rigid": 2, "joints": [ +{"schema": "brokkr.joints", "version": 2, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres", + "rigid": 2, "unlimited": ["Barrel"], "next": null, "joints": [ {"id": "Strut", "parent": null, "part": "strut", "socket": "Mount:pivot", "kind": "revolute", "axis": [0.0, 1.0, 0.0], "origin": [0.436, 0.0, 0.85368], "value": -113.019997, "limits": [-116.02, -40.02], - "min": -3.000003, "max": 72.999997, "mechanism": "knee", "compliance": null}, + "min": -3.000003, "max": 72.999997, "mechanism": "knee", "compliance": null, "driven": null}, + {"id": "Cap", "parent": "Strut", "part": "strut", "socket": "Strut:end_a_back", "kind": "revolute", + "axis": [0.0, -1.0, 0.0], "origin": [0.436, -0.09, 0.85368], "value": -56.509999, "limits": null, + "min": null, "max": null, "mechanism": null, "compliance": null, + "driven": {"by": "Strut", "kind": "ratio", "k": 0.5, "offset": 0.0}}, {"id": "Rod", "parent": "Barrel", "part": "ram_rod", "socket": "Barrel:bore", "kind": "prismatic", "axis": [0.97429, 0.0, 0.225296], "origin": [1.072572, 0.124, 1.312762], "value": 0.12, "limits": [0.0, 0.3], - "min": -0.12, "max": 0.18, "mechanism": "shock", "compliance": {"damping_ratio": 0.7, "hertz": 4.0}}]} + "min": -0.12, "max": 0.18, "mechanism": "shock", "compliance": {"damping_ratio": 0.7, "hertz": 4.0}, "driven": null}]} ``` A row per revolute or prismatic connection under the root, depth first with children by name, so a row's parent -comes before it. `parent` is the nearest joint above, not the object the part hangs from: rigid connections fold -into it and are counted in `rigid`. `axis` and `origin` are the parent socket's z and origin in the root object's +comes before it; a root that itself states a revolute or prismatic connection has its own row first, with `parent` +null, so a report of a sub-tree carries the joint the sub-tree hangs by. `parent` is the nearest joint above, not +the object the part hangs from: rigid connections fold into it and are counted in `rigid`. `axis` and `origin` are the parent socket's z and origin in the root object's frame. `min` and `max` are the limits less the value, the travel either way from the pose the report was taken at, -which is the shape of Aetheria's `ShipJoint` (`Min` and `Max` about rest). What the report gives up: it is the -pose at the call, so rest is whatever the assembly stood at; it carries no meshes or bone names, so a consumer -joins rows to the exported objects by `id`; and `ShipJoint` has no slide and no spring yet -(aetheria-release:question:shipjoint-prismatic-dof), so a prismatic row has no Aetheria reader today. +which is the shape of Aetheria's `ShipJoint` (`Min` and `Max` about rest). `driven` is null, or what the row follows +(`by` the driver's id, `kind`, `k`, `offset`): a driven row's value is derived, so a rig makes a driven bone for it +and not a degree of freedom. `unlimited` lists the ids of the rows in the whole tree that are not driven and state +no limits, so an exporter that needs limits on every degree of freedom refuses by reading one field. A tree whose +rows a receipt cannot carry (about 60 rows) is read in pages: `jointsOmitted` counts the rows left off, `next` is +then the id of the last row carried, and a call with `after` set to it carries the rows that follow. + +`ShipJoint` is ruled to gain a kind per degree of freedom and an optional spring +(aetheria-release:ruling:shipjoint-gains-kind-and-spring), and the rows map to it one to one: `revolute` is its +`rotate` and `prismatic` its `slide`, with slide limits in metres, and `compliance` is its spring's hertz and +damping ratio. Brokkr keeps the kinematics names, which its kits' socket types state. What the report gives up: it +is the pose at the call, so rest is whatever the assembly stood at, and it carries no meshes or bone names, so a +consumer joins rows to the exported objects by `id`. **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 @@ -413,8 +469,8 @@ off in viewports and renders. Nothing is removed: the cutter objects stay, a cut is attached to it, and `booleans` still lists what cuts the object. The frozen mesh's material slots are the object'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 first slot. A frozen kit part keeps `kit_kit`, `kit_part`, `kit_params` and its -connections: its sockets are still derived from the params, so `attach`, `detach`, `roll`, `aim`, `reach` and -`close` work on it and on what hangs from it. `freeze` reports the part (or `object`), `frozen`, `faces` (the live +connections: its sockets are still derived from the params, so `attach`, `detach`, `roll`, `aim`, `reach`, `joint`, +`slide`, `joints`, `follow` and `close` work on it and on what hangs from it. `freeze` reports the part (or `object`), `frozen`, `faces` (the live mesh's count, as in every report), `evaluated: {faces, volume, nonManifoldEdges}` (the frozen mesh), `modifiers` and `booleans`. `report` on a frozen part gives `faces`, still the live mesh's, and `evaluated: {faces}`, the frozen mesh's. @@ -1262,12 +1318,13 @@ under such load (five runs), and reading a 336-face part takes 27 to 37 ms. | `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 `frozen`; a frozen part adds `evaluated: {faces}`, and `dirty` (with `frozen` false) when a modifier of it is shown again. `faces` is the live mesh's count. 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; 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.roll` | `object_name`, `roll` (degrees, -360 to 360) | Turns an attached part to that roll where it hangs. Refuses a part that is not attached. Reports the part and `closures` as `set_params` does. | +| `brokkr_kitbash.roll` | `object_name`, `roll` (degrees, -360 to 360) | Turns an attached part to that roll where it hangs, and every follower of it with it ("Followers"; the report's `followers` lists each as `{part, value}`). Refuses a part that is not attached, and a follower, naming its driver. Reports the part and `closures` as `set_params` does. | | `brokkr_kitbash.aim` | `object_name`, `axis` (`+x`, `-x`, `+y`, `-y`, `+z` or `-z`, the part's own), `direction_x`, `direction_y`, `direction_z` (world, any length) | Solves the roll that turns the axis as far toward the direction as the pin lets it, and turns the part to it. Refuses an axis or direction along the pin. Reports the part, `aimed: {roll, dot}` and `closures`. | | `brokkr_kitbash.reach` | `object_name`, `socket` (one of the part's), `height` (metres, -1000 to 1000), `direction_x`, `direction_y`, `direction_z` (world; default 0, 0, 1) | Solves the roll that brings the socket's origin to `height` along the direction, the nearer of the two, and turns the part to it. Refuses a height out of reach, naming the range. Reports the part, `reached: {roll, residual}` and `closures`. | -| `brokkr_kitbash.joint` | `object_name`, `record` (a JSON object of any of `limits`: `[lo, hi]` or null; `mechanism`: a label or null; `compliance`: `{hertz, damping_ratio}` or null) | States the joint record of an attached part's connection; a key left out keeps what is stated and null clears it. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits over a turn or past 360, prismatic limits past 10 m, and compliance on a revolute joint or without limits. Reports the part and `closures` as `roll` does | -| `brokkr_kitbash.slide` | `object_name`, `slide` (metres, -10 to 10) | Slides an attached part along its parent socket's normal on a prismatic connection, where it hangs. Refuses a revolute or rigid connection naming its socket type, and a slide outside the joint's limits. Reports the part and `closures` as `roll` does | -| `brokkr_kitbash.joints` | `object_name` (the root, a kit part) | Reports the joints of the tree attached under the root as `brokkr.joints` version 1: a row per revolute or prismatic connection, parents first, with `id`, `parent`, `part`, `socket`, `kind`, `axis`, `origin`, `value`, `limits`, `min`, `max`, `mechanism` and `compliance`, in the root's frame ("Joint records"). Changes nothing | +| `brokkr_kitbash.joint` | `object_name`, `record` (a JSON object of any of `limits`: `[lo, hi]` or null; `mechanism`: a label or null; `compliance`: `{hertz, damping_ratio}` or null) | States the joint record of an attached part's connection; a key left out keeps what is stated and null clears it. A follower keeps its derived value, and a driver's followers are derived again. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits over a turn or past 360, prismatic limits past 10 m, and compliance on a revolute joint or without limits. Reports the part and `closures` as `roll` does | +| `brokkr_kitbash.slide` | `object_name`, `slide` (metres, -10 to 10) | Slides an attached part along its parent socket's normal on a prismatic connection, where it hangs, and every follower of it with it. Refuses a revolute or rigid connection naming its socket type, a slide outside the joint's limits, and a follower. Reports the part and `closures` as `roll` does | +| `brokkr_kitbash.joints` | `object_name` (the root, a kit part), `after` (default empty: an id, the `next` of the report before) | Reports the joints of the tree attached under the root as `brokkr.joints` version 2: a row per revolute or prismatic connection, parents first and the root's own first when it states one, with `id`, `parent`, `part`, `socket`, `kind`, `axis`, `origin`, `value`, `limits`, `min`, `max`, `mechanism`, `compliance` and `driven`, in the root's frame, and `unlimited` and `next` beside them ("Joint records"). With `after`, the rows after that id. Changes nothing and evaluates no modifier. | +| `brokkr_kitbash.follow` | `object_name` (the follower; for a loop, the part that states the closure), `record` (JSON: `{driver, kind: "ratio", k, offset}`, `{driver, kind: "loop"}` or null) | States that the part's joint follows the driver's, by a ratio or by keeping its closure closed with its parent's joint, and moves it there at once; null clears the statement, and a loop partner's with it ("Followers"). Refuses a rigid connection, a driver that is the follower, below it or itself a follower, a follower that already follows or drives another, a ratio whose driver states no limits, and a loop without a closure that holds, with both ends or neither moving with the driver, that is not planar or that stands at a dead centre. Reports the part, `followers` and `closures`. | | `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. | | `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added; `booleansOmitted` counts rows a receipt had no room for) 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), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans` (with `booleansOmitted`, as `boolean`). | @@ -1406,4 +1463,5 @@ frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may re-parameterised, a beam seated on a bracket), `tests/live/kitbash_assembly.py` (attach, detach, `set_params` on assemblies, a braced leg closed by `close`, boolean, and freeze and thaw with what a frozen part costs), `tests/live/kitbash_shell.py` (`cut` and `cut_many` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no -collection) and `tests/live/kitbash_pose.py` (roll, aim and reach). +collection), `tests/live/kitbash_pose.py` (roll, aim, reach and joint records) and `tests/live/kitbash_follows.py` +(followers: a four-bar, a ram closing on its rocker, ratios, a torque link, and a joints report in pages). diff --git a/surfaces/blender/tests/live/kitbash_follows.py b/surfaces/blender/tests/live/kitbash_follows.py index 335207b..2189d2e 100644 --- a/surfaces/blender/tests/live/kitbash_follows.py +++ b/surfaces/blender/tests/live/kitbash_follows.py @@ -66,17 +66,18 @@ COUNT = [0] kit = core.load_kit("mechanical") # Each mutant's reading below is its least over the cases here that it changes; the shipped reading is the worst. # Metres (or a difference of unit vectors) between a loop's closing socket and the socket it closes on, read from the two -# world matrices after a driver was posed. Shipped worst 1.9e-06 (float32 matrices); least claimed mutant 0.018 (F11, the -# ram solved before the four-bar its rocker follows, at the smallest turn here); separation 97 each side. -CLOSED = 1.8e-4 +# world matrices after a driver was posed; a rod's slide against this file's own solve reads against it too. Shipped +# worst 6.4e-07 (float32 matrices); least claimed mutant 0.041 (F11, the ram solved before the four-bar whose rocker it +# closes on, at the smallest turn here); separation 250 each side. +CLOSED = 1.6e-4 # Degrees between a loop follower's roll and the one this file solves by its own steps of core.close_loop from the rest -# pose. Shipped worst 2.3e-05 (an action's roll is a float32 field); least claimed mutant 8.9 (F11 again: the barrel -# aimed at where the rocker was); separation 620 each side. -SOLVED = 1.4e-2 -# Metres between a ratio follower's slide, or degrees between its roll, and k x the driver's value + offset, read from -# the stored values. Shipped 0 (the same doubles), taken as one float32 step of the largest value here, 1.5e-05; least -# claimed mutant 15 (a ratio follower not moved by a 30 degree turn of its driver at k 0.5); separation 1e3 each side. -RATIO = 1.5e-2 +# pose. Shipped worst 3.3e-05 (an action's roll is a float32 field); least claimed mutant 2.7 (F11 again: the barrel +# aimed at where the rocker was); separation 290 each side. +SOLVED = 9.4e-3 +# A ratio follower's roll in degrees or slide in metres against k x the driver's value + offset, read from the stored +# values. Shipped 0: the same doubles. A rule, a double's rounding at these sizes (6e-14 at 360) with room; mutant R1 +# (the ratio taken from the driver's value before the pose) reads 0.09 on the crosshead's slide and 45 on the kneecap. +RATIO = 1e-9 ROT = [0.3, -0.2, 0.5] # the roots' rotation: no axis of the scene lines up with the world's D0, REST = 30.0, (-40.0, 70.0) # the four-bar at rest: the crank's roll, and the rocker's and coupler's RAM_REST = (200.0, 0.1) # the ram at rest: the barrel's roll and the rod's slide @@ -248,14 +249,24 @@ try: "'Crank' at -5: the loop 'Coupler' closes on 'Crank' ('Rocker' and 'Coupler' follow): the loop is at a dead centre", "nothing changed") send("brokkr_kitbash.roll", object_name="Crank", roll=-2.0) # beside the toggle: 32 back from rest seed = stepped(solve_four_bar, seed, 0.0, -2.0, 5.0) - receipt, report = send("brokkr_kitbash.roll", object_name="Crank", roll=47.0) - seed = stepped(solve_four_bar, seed, -2.0, 47.0, 5.0) - direct = stepped(solve_four_bar, REST, D0, 47.0, 5.0) - check("a 49 degree jump from beside the toggle ends on the stepped answer, the branch the linkage is on (F2: one solve from the stated value is thrown through the dead centre)", - receipt["status"] == "accepted" and reading("solved", turned(rocker["kit_roll"], direct[0])) < SOLVED and reading("solved", turned(coupler["kit_roll"], direct[1])) < SOLVED - and reading("closed", apart(coupler, "end_b", crank, "end_b")) < CLOSED, [receipt["message"], rocker["kit_roll"], coupler["kit_roll"], direct, seed]) + jump = None + for roll in range(10, 151): # the nearest jump from here that one solve from the stated rolls does not survive: refused in the dead centre, or on the other branch + direct = stepped(solve_four_bar, seed, -2.0, float(roll), 5.0) + try: + once, _ = solve_four_bar(float(roll), seed) + except core.KitError: + once = None + if once is None or turned(once[0], direct[0]) > 1.0: + jump = float(roll) + break + R["readings"]["jump"] = jump or 0.0 + receipt, report = send("brokkr_kitbash.roll", object_name="Crank", roll=jump or 47.0) + seed = stepped(solve_four_bar, seed, -2.0, jump or 47.0, 5.0) + check("a jump from beside the toggle that one solve from the stated rolls does not survive ends on the stepped answer, the branch the linkage is on (F2)", + jump is not None and receipt["status"] == "accepted" and reading("solved", turned(rocker["kit_roll"], seed[0])) < SOLVED and reading("solved", turned(coupler["kit_roll"], seed[1])) < SOLVED + and reading("closed", apart(coupler, "end_b", crank, "end_b")) < CLOSED, [jump, receipt["message"], rocker["kit_roll"], coupler["kit_roll"], seed]) send("brokkr_kitbash.roll", object_name="Crank", roll=D0) - seed = stepped(solve_four_bar, seed, 47.0, D0, 5.0) + seed = stepped(solve_four_bar, seed, jump or 47.0, D0, 5.0) # --- followers are derived only --------------------------------------------------------------------------------------- for name in ("Rocker", "Coupler"): @@ -344,6 +355,7 @@ try: seed, _ = solve_four_bar(was + (roll - was) * index / count, seed) pin = rocker_world(world(base), seed[0]) @ socket(rocker, "end_b_back")["matrix"] ram_seed, _ = core.close_loop(world(pad), ram_loop, socket(a_rod, "rod_end"), pin, ram_seed) + R["readings"][f"ram closed at {roll:g}"], R["readings"][f"ram solved at {roll:g}"] = apart(a_rod, "rod_end", rocker, "end_b_back"), turned(a_barrel["kit_roll"], ram_seed[0]) check(f"rolling the crank to {roll:g} solves the four-bar and then the ram that closes on its rocker (F11): both closures hold and the barrel's roll and rod's slide are this file's own", receipt["status"] == "accepted" and reading("closed", apart(a_rod, "rod_end", rocker, "end_b_back")) < CLOSED and reading("closed", apart(coupler, "end_b", crank, "end_b")) < CLOSED and reading("solved", turned(a_barrel["kit_roll"], ram_seed[0])) < SOLVED and reading("closed", abs(a_rod["kit_slide"] - ram_seed[1])) < CLOSED diff --git a/surfaces/blender/tests/live/kitbash_follows.result.json b/surfaces/blender/tests/live/kitbash_follows.result.json new file mode 100644 index 0000000..9c9bd7a --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_follows.result.json @@ -0,0 +1,346 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "follow loads as a host action after joints, with no errors", + "ok": true, + "detail": null + }, + { + "name": "the four-bar stands closed at rest: crank on Ground, rocker on Base, the coupler's end closing on the crank's", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a loop whose two ends both stand still when the driver moves (F7)", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a loop follower that states no closure", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a follower on a rigid connection", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a follower that is not attached", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a part that follows itself", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a driver below its follower", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a record that is not one of the three shapes: {\"driver\": \"Crank\", \"kind\": \"ratio\", \"k\": 0, \"offset\": 0}", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a record that is not one of the three shapes: {\"driver\": \"Crank\", \"kind\": \"ratio\", \"k\": 1}", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a record that is not one of the three shapes: {\"driver\": \"Crank\", \"kind\": \"gear\"}", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a record that is not one of the three shapes: {\"driver\": \"Crank\", \"kind\": \"loop\", \"k\": 1}", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a record that is not one of the three shapes: [1, 2]", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a record that is not one of the three shapes: {\"a\"", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: clearing a part that follows nothing", + "ok": true, + "detail": null + }, + { + "name": "follow states the loop on the closing part and its parent, both following the crank, and the report lists them as written", + "ok": true, + "detail": null + }, + { + "name": "rolling the crank a 45 degree turn moves rocker and coupler with it: the closure holds in the scene and the rolls are this file's own stepped solve", + "ok": true, + "detail": null + }, + { + "name": "rolling the crank to 120 past rest moves rocker and coupler with it: the closure holds in the scene and the rolls are this file's own stepped solve", + "ok": true, + "detail": null + }, + { + "name": "rolling the crank and back to rest moves rocker and coupler with it: the closure holds in the scene and the rolls are this file's own stepped solve", + "ok": true, + "detail": null + }, + { + "name": "rolling the crank 30 the other way moves rocker and coupler with it: the closure holds in the scene and the rolls are this file's own stepped solve", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: the crank driven past the loop's dead centre, naming the driver's value and the closing part", + "ok": true, + "detail": null + }, + { + "name": "a jump from beside the toggle that one solve from the stated rolls does not survive ends on the stepped answer, the branch the linkage is on (F2)", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: roll on the follower Rocker, naming its driver (F4)", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: roll on the follower Coupler, naming its driver (F4)", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: aim on a follower", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: reach on a follower", + "ok": true, + "detail": null + }, + { + "name": "joint on a follower states limits and a mechanism and keeps its derived value and its statement", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: joint limits on a follower that do not hold its derived value", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a driver that is itself a follower", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a follower that drives another", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a follower that already follows", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a closure stated by a loop's parent follower", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a ratio whose driver states no limits (F3)", + "ok": true, + "detail": null + }, + { + "name": "a kneecap at k 0.5, a pinion at k -3 and a crosshead's slide at 0.001 m a degree follow the crank at once: each is k x its roll + offset", + "ok": true, + "detail": null + }, + { + "name": "rolling the crank moves ratio followers and the loop in one action: ratios first in the report, the pinion's roll brought inside a turn", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: slide on a follower", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a pose of the driver that takes a follower outside its own limits: the driver is not written either (F5)", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: clearing the limits of a driver a ratio follows", + "ok": true, + "detail": null + }, + { + "name": "follow with null clears the statement, and the part is posed by hand again", + "ok": true, + "detail": null + }, + { + "name": "a ram on its own ground pin closes on the rocker and follows the crank: the end it closes on follows the driver", + "ok": true, + "detail": null + }, + { + "name": "rolling the crank to 60 solves the four-bar and then the ram that closes on its rocker (F11): both closures hold and the barrel's roll and rod's slide are this file's own", + "ok": true, + "detail": null + }, + { + "name": "rolling the crank to 110 solves the four-bar and then the ram that closes on its rocker (F11): both closures hold and the barrel's roll and rod's slide are this file's own", + "ok": true, + "detail": null + }, + { + "name": "rolling the crank to 45 solves the four-bar and then the ram that closes on its rocker (F11): both closures hold and the barrel's roll and rod's slide are this file's own", + "ok": true, + "detail": null + }, + { + "name": "the torque link's rest pose is found: two arms from the barrel's pin to the lug on the rod", + "ok": true, + "detail": null + }, + { + "name": "the arms follow the rod's slide as a loop: its base is the barrel, above the driver, and it closes on a part that hangs from the driver", + "ok": true, + "detail": null + }, + { + "name": "sliding the rod to 0.15 folds the arms: the closure holds in the scene and the rolls are this file's own stepped solve", + "ok": true, + "detail": null + }, + { + "name": "sliding the rod to 0 folds the arms: the closure holds in the scene and the rolls are this file's own stepped solve", + "ok": true, + "detail": null + }, + { + "name": "sliding the rod to 0.11 folds the arms: the closure holds in the scene and the rolls are this file's own stepped solve", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a slide outside the driver's limits", + "ok": true, + "detail": null + }, + { + "name": "joints is version 2: a driven row names what drives it (F6), and unlimited lists the rows that are not driven and state no limits", + "ok": true, + "detail": null + }, + { + "name": "a loop's two followers are driven rows, kind loop", + "ok": true, + "detail": null + }, + { + "name": "a root that states a DOF connection has its own row first, parent null", + "ok": true, + "detail": null + }, + { + "name": "after carries the rows after an id (F12)", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: after an id that is no row's", + "ok": true, + "detail": null + }, + { + "name": "a tree of 80 joints is two reports: the first counts what it omits and names the last id it carries as next, and after it the second carries the rest", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params of a part whose roll was written by hand outside its limits (F9): the mesh is not rebuilt", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: and of its parent", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params of a part with a slide written by hand on a revolute connection", + "ok": true, + "detail": null + }, + { + "name": "a compliance written by hand on a revolute joint reads null in the report and the joints report (F10), and the limits beside it still read", + "ok": true, + "detail": null + }, + { + "name": "set_params seats through the one writer: the part is rebuilt, its child seated on the moved socket, and the hand-written compliance is gone", + "ok": true, + "detail": null + }, + { + "name": "detaching a loop's closing follower clears its partner's statement too", + "ok": true, + "detail": null + }, + { + "name": "and the partner is posed by hand again", + "ok": true, + "detail": null + }, + { + "name": "detaching a driver leaves its followers' statements, which report that the driver states no DOF connection", + "ok": true, + "detail": null + }, + { + "name": "and once the driver is deleted, that it is gone", + "ok": true, + "detail": null + }, + { + "name": "no Blender driver or constraint was made", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "readings": { + "closed": 6.4e-07, + "jump": 49.0, + "ram closed at 110": 2.9e-07, + "ram closed at 45": 5.3e-07, + "ram closed at 60": 2.8e-07, + "ram solved at 110": 5.7e-14, + "ram solved at 45": 0.0, + "ram solved at 60": 0.0, + "ratio": 0.0, + "rows in one receipt": 62.0, + "slid": 1e-07, + "solved": 3.3e-05 + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/kitbash_pose.result.json b/surfaces/blender/tests/live/kitbash_pose.result.json index 9773931..3091443 100644 --- a/surfaces/blender/tests/live/kitbash_pose.result.json +++ b/surfaces/blender/tests/live/kitbash_pose.result.json @@ -457,7 +457,7 @@ "detail": null }, { - "name": "under another root the rows are in its frame and begin below it", + "name": "under another root the rows are in its frame and begin with the root's own joint, parent null", "ok": true, "detail": null }, @@ -494,10 +494,16 @@ }, "joints": { "schema": "brokkr.joints", - "version": 1, + "version": 2, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres", "rigid": 2, + "unlimited": [ + "Barrel", + "Toe", + "Ram" + ], + "next": null, "joints": [ { "id": "Strut", @@ -523,7 +529,8 @@ "min": -3.000003, "max": 72.999997, "mechanism": "knee", - "compliance": null + "compliance": null, + "driven": null }, { "id": "Barrel", @@ -546,7 +553,8 @@ "min": null, "max": null, "mechanism": null, - "compliance": null + "compliance": null, + "driven": null }, { "id": "Rod", @@ -575,7 +583,8 @@ "compliance": { "damping_ratio": 0.7, "hertz": 4.0 - } + }, + "driven": null }, { "id": "Hinge", @@ -601,7 +610,8 @@ "min": -75.0, "max": 35.0, "mechanism": "ankle", - "compliance": null + "compliance": null, + "driven": null }, { "id": "Toe", @@ -624,7 +634,8 @@ "min": null, "max": null, "mechanism": null, - "compliance": null + "compliance": null, + "driven": null }, { "id": "Ram", @@ -647,7 +658,8 @@ "min": null, "max": null, "mechanism": null, - "compliance": null + "compliance": null, + "driven": null } ] }, From 5dee3c685aba3e8306357b14f6737652af7c79cd Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 12:05:51 +0100 Subject: [PATCH 199/223] tests/fixtures/spectre_truth.json, test_reference.py, docs/reference.md: the rendered roof's accuracy read from takes searched off the answer (72, six families of seed), stated as what holds: worst corner within 1.18 x the worst traced point x the coarser view's pixel, the test at 1.42; the rms-noise bound dropped; START pinned between a plate that blocks (0.831, 16.5 degrees) and one refused (1.241, 11 degrees) and its comment corrected; FAIR's table with its refused draws (cut trace-block, Soul s2) bound-premise-seeded-by-truth: the fixture keeps the truth-seeded strokes for the fairness readings and says what they are; takes are the same search from a seed moved 0.5 to 1.5 px as one or 1 to 3 px a vertex. 62 of 72 block, no family stands out of the bound: the draws Soul's probe read at 3.5 to 6.5 had grown a side, and the probe read the vertex after a grown side's inner point as the next corner; by the crown's chains they stand at 0.40 to 0.75 (135 blocked draws of his 168: 1.19 at most). start-unpinned-and-comment-stale: START 0.6 and 0.8 refuse the 16.5 degree plate, 2.0, 2.6 and 3.3 block the 11. fair-table-drops-refusals: 19 to 27 of 168 refused, rising with FAIR; Soul's seeds named. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/core.py | 2 +- surfaces/blender/docs/reference.md | 76 +++++++---- .../blender/tests/fixtures/spectre_truth.json | 2 +- surfaces/blender/tests/test_reference.py | 118 +++++++++++------- 4 files changed, 130 insertions(+), 68 deletions(-) diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index f34c73d..18af047 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -748,7 +748,7 @@ def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=TOL): FAIR = 0.2 # a side's second differences of this share of its chord cost what one pixel of miss does (0.02 held a bowed side straight; docs/reference.md) K_MAX = 6 # points a side grows to before its trace is refused as fit_runs refuses it SQUARE = 0.4 # the cosine between a plane's normal and a sight line under which a trace is not lifted onto it: past 66 degrees the lift stretches over 2.5 times -START = 1.0 # a corner's views start it where one pixel moves their meeting point less than this x share x the plate's extent, the prior's own scale: past it the views alone hold the corner looser than the plane would (tests/test_reference.py BlockTests reads 0.50 at 19 degrees and 1.90 at 5, Paladin's lens and range) +START = 1.0 # a corner's views start it where one pixel moves their meeting point less than this x share x the plate's extent, the prior's own scale: past it the views alone hold the corner looser than the plane would. 1 is the prior's own unit, not a derived value: tests/test_reference.py BlockTests pins it between a plate that must block (its third corner starts at 0.831, views 16.5 degrees apart at Paladin's lens and range) and one that must be refused (1.241, 11 degrees) VIEWS = 0.2 # a prior_share under this: the views decide the point (fit_shell's line) FLARE, DROP, DOME = 0.05, 0.06, 0.017 # of the crown's extent (its two furthest points): a plate's skirt out from and back of its crown, and its centre's rise. A template's proportions, not readings: the crown is what is solved TRACE_KEYS = ("camera", "box", "frame", "from", "to", "side", "line") diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index eed579d..8fc71b9 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -294,9 +294,13 @@ Where a corner's depth comes from, in this order: - **the views**, where two or more see it and one pixel moves the point their sight lines meet at less than `share` x the plate's extent, the prior's own scale. Past that the views alone hold the corner looser than the - plane would and are not used as its start. The line is metres a pixel, so it moves with lens and range: a - 1.2 m plate 17.6 m off at 663 px reads 0.74 of the scale at 19 degrees and 2.77 at 5, where its corners landed - 0.25 to 1.5 m off; through a lens three times as long it reads 0.66 at 7 degrees and blocks. + plane would and are not used as its start. That factor of 1 is the prior's own unit, not a derived value; the + tests pin it between a plate that blocks and one that is refused. The line is metres a pixel, so it moves + with lens and range: a 1.2 m plate 17.6 m off at 663 px has three corners started at 0.72 of the scale with + its views 19 degrees apart, 0.83 at 16.5, 1.24 at 11 and 2.73 at 5. With no plane given it blocks down to + 16.5 degrees (73 mm from the truth) and is refused at 11, where it would have stood 104 mm off: the line + switches blocking and refusal, it is no cliff in accuracy. At 5 degrees its corners landed 0.25 to 1.5 m off; + through a lens three times as long it starts at 0.65 at 7 degrees and blocks. - **the mirror plane**, for a seam corner whose sight line crosses x = 0 at 24 degrees or more. - **a plane**, for the rest: `plane` (`x,y,z; nx,ny,nz`, a point and the normal, in the frame), or with none given the plane through the corners the views and the seam decide, three or more. A corner one view sees is lifted @@ -342,36 +346,62 @@ from the others (name it in `seam`, or trace it where the views agree), a side n sheet the cage's parser does not take, and a result that could pass the 16000 characters a receipt carries. Measured against a known truth (`tests/test_reference.py` BlockTests, Python 3.13 on Starfire; -`tests/fixtures/spectre_truth.json`). SPECTRE's pass-3 roof, a hard mirrored cage of 11 vertices, was built by -`brokkr_kitbash.shell`, rendered in Blender 5.3 through SPECTRE's two solved cameras at the sheet's pixel size, -and its edges traced off the renders: the ridge in the side view, the lip, outer edge and rear edge in the -hero's mirrored half and the side view, 62 degrees apart. The side view's pixel is 27.6 mm across at the plate. +`tests/fixtures/spectre_truth.json`), on one plate through one pair of views. SPECTRE's pass-3 roof, a hard +mirrored cage of 11 vertices, was built by `brokkr_kitbash.shell` and rendered in Blender 5.3 through SPECTRE's +two solved cameras at the sheet's pixel size. Its edges were traced off the renders: the ridge in the side +view, the lip, outer edge and rear edge in the hero's mirrored half and the side view, 62 degrees apart. The +side view's pixel is 27.6 mm across at the plate. -| traces | worst corner from the truth | -| --- | --- | -| as taken off the renders (up to 2.5 px from the truth's projection) | 39 mm | -| every point 1 px off, 12 draws | 69 mm median, 96 mm at most | -| every point 2 px off, 12 draws | 125 mm median, 190 mm at most | +How the traces were taken. No hand drew them. A search follows a seed polyline, takes the strongest brightness +step within a window across each edge, lays a straight stroke through the steps found on each segment, and ends +each stroke where it crosses its neighbours. The seed is the truth's projection moved off the answer, twelve +draws a family: the whole seed by 0.5, 1 or 1.5 px in a drawn direction (a 2.5 px window), or each of its +vertices by a normal draw of 1 or 2 px (3.5 px) or 3 px (6 px). The takes' points end up 2.1 to 30.7 px from the +truth's projection, 6.8 at the median: two strokes that run nearly along each other cross far from the corner. +Every corner is named. -With every corner named, the worst corner of a blocked plate stood within 3.5 x the noise x the coarser view's -pixel, on a floor of 1.4 of that pixel from the render itself. That is one plate through one pair of views, not -a law. It is not a multiple of `m_per_px`: the same readings are 4.6 to 7.5 x noise x a view-decided corner's -`m_per_px`, and a seam corner 98 mm off reports 0.0008 m a pixel, because `m_per_px` is depth along the sight -line and most of this error lies across it. With only four corners named, the roof's ridge and outer edge are -one side each and are built as smooth runs through their hard knees: explained within `tol`, 196 mm from the -true edges (5.2 px is 144 mm there). Name a hard corner as a corner. +| seed | window | blocked of 12 | worst traced point, px: median, most | worst corner, mm: median, most | worst corner over worst point x 27.6 mm, at most | +| --- | --- | --- | --- | --- | --- | +| moved 0.5 px as one | 2.5 px | 12 | 6.5, 30.7 | 173, 929 | 1.12 | +| moved 1 px as one | 2.5 px | 12 | 7.1, 30.4 | 225, 916 | 1.16 | +| moved 1.5 px as one | 2.5 px | 11 | 6.6, 16.5 | 148, 450 | 1.18 | +| each vertex 1 px | 3.5 px | 10 | 4.8, 15.9 | 79, 458 | 1.04 | +| each vertex 2 px | 3.5 px | 10 | 5.3, 17.6 | 131, 342 | 1.06 | +| each vertex 3 px | 6 px | 7 | 10.2, 20.1 | 215, 436 | 1.11 | + +What holds: the worst corner of a blocked plate stood within about 1.2 x the furthest any traced point stood +from the truth's projection x the coarser view's pixel (1.18 over the 62 that blocked, which the test holds to +1.42). No family stands out of it, and the three draws that grew a side read 0.51, 0.75 and 1.08. It is a +reading on one plate and one pair of views, not a law, and it says a plate is as good as its worst traced +point: one stroke end 30 px off puts a corner 0.9 m off, and nothing in the report says so, because that trace +is explained. The ten not blocked were refused, nine at a side not explained at six points and one at the +cage's parser. No bound is given in the traces' rms: against it the same readings run 0.57 to 5.3. The same +search seeded on the truth's projection itself, with a 2.5 px window, reads 39 mm; that is the window ending +every stroke within 2.5 px of the answer, and it is not an accuracy. + +The error is not a multiple of `m_per_px` either: a seam corner 98 mm off reports 0.0008 m a pixel, because +`m_per_px` is depth along the sight line and most of this error lies across it. With only four corners named, +the roof's ridge and outer edge are one side each and are built as smooth runs through their hard knees: +explained within `tol`, 196 mm from the true edges (5.2 px is 144 mm there). Name a hard corner as a corner. Fairness, 0.2 x a side's chord, is set by known truth at traced noise. Over ten cells at 1 and 2 px (the rendered -roof with four corners named, with and without closing strokes moved 3 px, and a bowed pentagon at 60 and 30 -degrees and in one view), the mean of the cells' 90th percentiles and the worst draw, in mm: +roof with four corners named, its strokes those of the search seeded on the truth with the noise added, with +and without closing strokes moved 3 px, and a bowed pentagon at 60 and 30 degrees and in one view), 168 draws: +the mean of the cells' 90th percentiles and the worst draw, in mm, over the draws that blocked, and the draws +refused, which no percentile counts: | FAIR | 0.1 | 0.15 | 0.2 | 0.25 | 0.3 | 0.4 | 0.5 | 1 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | mean 90th percentile | 194 | 184 | 178 | 178 | 179 | 186 | 193 | 196 | | worst draw | 301 | 275 | 273 | 272 | 312 | 382 | 494 | 577 | +| refused of 168 | 19 | 20 | 23 | 24 | 24 | 25 | 26 | 27 | -From exact traces weaker fairness is nearer the truth (a pentagon bowed 35% of its sides: 42 mm at 0.2, 16 at -0.5, 12 with none). +A higher FAIR, which is weaker fairness, refuses more draws, so each column's percentiles are +over a different set. On other seeds (Soul's probe, verdict cut-trace-block.s2, FAIR 0.1, 0.2, 0.3, 0.5) the +mean 90th percentile read 216, 188, 216, 250, the worst draw 542, 855, 679, 807 and the refused 18, 21, 26, +27: 0.2 is lowest by the 90th percentile on both sets of seeds and not by the worst draw on the second. From +exact traces weaker fairness is nearer the truth (a pentagon bowed 35% of its sides: 42 mm at 0.2, 16 at 0.5, +12 with none). Agreement with other fits, which is not accuracy. SPECTRE's second-pass roof from its hand traces: the ridge 7.3 mm at most and the brow a median of 8.4 mm from the cage `fit_shell` had fitted to the same pixels; with diff --git a/surfaces/blender/tests/fixtures/spectre_truth.json b/surfaces/blender/tests/fixtures/spectre_truth.json index 1597893..dcd97e4 100644 --- a/surfaces/blender/tests/fixtures/spectre_truth.json +++ b/surfaces/blender/tests/fixtures/spectre_truth.json @@ -1 +1 @@ -{"note":"SPECTRE's roof (spectre_cages.roof at nibu/fable-spectre-3 14d834c: a hard mirrored cage of 11 vertices) built by brokkr_kitbash.shell at one level with the hull's jaw, flank and cheeks (thickness 0.1, bevel 0.016), rendered by Blender 5.3's Workbench through spectre_skel.cameras() at the sheet's own pixel size (hero 756 x 706, side 264 x 348), the hull posed per view by frames. truth is the cage: Blender built each of its vertices within built_off_m of it (the bevel). strokes are the roof's edges traced from the two renders, not projected: along each edge the drawn edge is the strongest brightness step within 2.5 px across it, a straight stroke is laid through the steps found on each segment, and strokes meet where they cross. drawn is the least share of a segment's length where a step was found, off_projection_px how far the stroke's points stand from the truth's projection. The ridge is traced in the side view only: the hero draws no step along it (its two facets shade alike). closing marks the strokes an agent closes the outline with (the rear edge, and the lip in the side view, half drawn).","cameras":{"hero":{"C":[-9.721115556958573,18.859090658741355,5.242272804029844],"R":[[-0.862189601405842,-0.5065857195259607,0.0],[0.034125232508362004,-0.05807984607580026,0.9977285201827507],[-0.5054350202883507,0.8602311551276064,0.06736319480204615]],"f":1785.0,"c":[378.0,353.0]},"side":{"C":[60.84416742645475,1.422308134553987,3.13474760877321],"R":[[3.061616997868383e-16,1.0,0.0],[0.011634411213376642,-3.5620111131064444e-18,0.9999323179474289],[0.9999323179474289,-3.0614097813457806e-16,-0.011634411213376642]],"f":2200.0,"c":[892.0,532.0]}},"frames":{"hero":[[1.0,0.0,0.0,0.0],[0.0,0.9986295347545738,0.052335956242943835,-0.2773805680876023],[0.0,-0.052335956242943835,0.9986295347545738,0.007263465800758873],[0.0,0.0,0.0,1.0]],"side":[[1.0,0.0,0.0,0.0],[0.0,1.0,0.0,0.0],[0.0,-0.0,1.0,0.0],[0.0,0.0,0.0,1.0]]},"plates":{"roof":{"loop":["ridge_rear","r4","r3","r2","r1","nose","a","b","c","d","e"],"seam":["ridge_rear","r4","r3","r2","r1","nose"],"truth":{"nose":[0.0,3.33,6.34],"r1":[0.0,2.82,6.735],"r2":[0.0,1.76,7.05],"r3":[0.0,1.0,7.5],"r4":[0.0,-0.8,7.8],"ridge_rear":[0.0,-1.9,7.95],"a":[0.77,2.57,6.475],"b":[0.6,1.9,6.83],"c":[0.69,1.0,7.34],"d":[0.64,-0.8,7.65],"e":[0.62,-1.9,7.8]},"built_off_m":0.0151,"strokes":[{"view":"side","side":1,"through":["ridge_rear","r4","r3","r2","r1","nose"],"line":[[772.01,383.39],[811.74,388.89],[876.96,399.88],[904.51,416.13],[941.84,427.31],[961.08,441.58]],"closing":false,"drawn":1.0,"off_projection_px":0.69},{"view":"hero","side":-1,"through":["nose","a"],"line":[[325.08,142.53],[427.02,126.4]],"closing":false,"drawn":1.0,"off_projection_px":0.86},{"view":"side","side":1,"through":["nose","a"],"line":[[961.51,439.35],[933.43,437.76]],"closing":true,"drawn":0.53,"off_projection_px":2.49},{"view":"hero","side":-1,"through":["a","b","c","d","e"],"line":[[426.46,125.71],[442.01,93.62],[487.59,47.65],[551.9,26.85],[587.64,18.75]],"closing":false,"drawn":0.71,"off_projection_px":0.98},{"view":"side","side":1,"through":["a","b","c","d","e"],"line":[[933.68,435.98],[908.72,424.05],[876.26,405.25],[810.61,394.34],[770.7,387.55]],"closing":false,"drawn":0.76,"off_projection_px":1.64},{"view":"hero","side":-1,"through":["e","ridge_rear"],"line":[[587.54,18.26],[541.95,9.26]],"closing":true,"drawn":1.0,"off_projection_px":0.09},{"view":"side","side":1,"through":["e","ridge_rear"],"line":[[769.96,387.04],[772.42,383.77]],"closing":true,"drawn":1.0,"off_projection_px":0.82}]}}} \ No newline at end of file +{"note":"SPECTRE's roof (spectre_cages.roof at nibu/fable-spectre-3 14d834c: a hard mirrored cage of 11 vertices) built by brokkr_kitbash.shell at one level with the hull's jaw, flank and cheeks (thickness 0.1, bevel 0.016), rendered by Blender 5.3's Workbench through spectre_skel.cameras() at the sheet's own pixel size (hero 756 x 706, side 264 x 348), the hull posed per view by frames. truth is the cage: Blender built each of its vertices within built_off_m of it (the bevel). One plate, one pair of views. A stroke is an edge of the roof traced from a render by a search, not projected: along a seed polyline the drawn edge is the strongest brightness step within reach px across it, a straight stroke is laid through the steps found on each segment, and strokes meet where they cross. Every seed here is made from the truth's projection, so no trace here is a hand's. takes are that search from a seed that is not on the answer, twelve draws a family (families): offset_px moves the whole seed that far in a drawn direction, jitter_px moves each seed vertex by a normal draw of that many px, reach_px is the window. A take's lines are its strokes in the order of strokes. How far a take's points stand from the truth's projection is not stored: read it from truth and cameras. The accuracy readings are taken from takes. strokes[].line is the same search seeded on the truth's projection itself with a 2.5 px window: every point stands within 2.5 px of the answer because the window ends there (off_projection_px), so it measures no accuracy; it is the base the fairness readings add noise to. drawn is the least share of a segment's length where a step was found. The ridge is traced in the side view only: the hero draws no step along it (its two facets shade alike). closing marks the strokes an agent closes the outline with (the rear edge, and the lip in the side view, half drawn).","cameras":{"hero":{"C":[-9.721115556958573,18.859090658741355,5.242272804029844],"R":[[-0.862189601405842,-0.5065857195259607,0.0],[0.034125232508362004,-0.05807984607580026,0.9977285201827507],[-0.5054350202883507,0.8602311551276064,0.06736319480204615]],"f":1785.0,"c":[378.0,353.0]},"side":{"C":[60.84416742645475,1.422308134553987,3.13474760877321],"R":[[3.061616997868383e-16,1.0,0.0],[0.011634411213376642,-3.5620111131064444e-18,0.9999323179474289],[0.9999323179474289,-3.0614097813457806e-16,-0.011634411213376642]],"f":2200.0,"c":[892.0,532.0]}},"frames":{"hero":[[1.0,0.0,0.0,0.0],[0.0,0.9986295347545738,0.052335956242943835,-0.2773805680876023],[0.0,-0.052335956242943835,0.9986295347545738,0.007263465800758873],[0.0,0.0,0.0,1.0]],"side":[[1.0,0.0,0.0,0.0],[0.0,1.0,0.0,0.0],[0.0,-0.0,1.0,0.0],[0.0,0.0,0.0,1.0]]},"plates":{"roof":{"loop":["ridge_rear","r4","r3","r2","r1","nose","a","b","c","d","e"],"seam":["ridge_rear","r4","r3","r2","r1","nose"],"truth":{"nose":[0.0,3.33,6.34],"r1":[0.0,2.82,6.735],"r2":[0.0,1.76,7.05],"r3":[0.0,1.0,7.5],"r4":[0.0,-0.8,7.8],"ridge_rear":[0.0,-1.9,7.95],"a":[0.77,2.57,6.475],"b":[0.6,1.9,6.83],"c":[0.69,1.0,7.34],"d":[0.64,-0.8,7.65],"e":[0.62,-1.9,7.8]},"built_off_m":0.0151,"strokes":[{"view":"side","side":1,"through":["ridge_rear","r4","r3","r2","r1","nose"],"line":[[772.01,383.39],[811.74,388.89],[876.96,399.88],[904.51,416.13],[941.84,427.31],[961.08,441.58]],"closing":false,"drawn":1.0,"off_projection_px":0.69},{"view":"hero","side":-1,"through":["nose","a"],"line":[[325.08,142.53],[427.02,126.4]],"closing":false,"drawn":1.0,"off_projection_px":0.86},{"view":"side","side":1,"through":["nose","a"],"line":[[961.51,439.35],[933.43,437.76]],"closing":true,"drawn":0.53,"off_projection_px":2.49},{"view":"hero","side":-1,"through":["a","b","c","d","e"],"line":[[426.46,125.71],[442.01,93.62],[487.59,47.65],[551.9,26.85],[587.64,18.75]],"closing":false,"drawn":0.71,"off_projection_px":0.98},{"view":"side","side":1,"through":["a","b","c","d","e"],"line":[[933.68,435.98],[908.72,424.05],[876.26,405.25],[810.61,394.34],[770.7,387.55]],"closing":false,"drawn":0.76,"off_projection_px":1.64},{"view":"hero","side":-1,"through":["e","ridge_rear"],"line":[[587.54,18.26],[541.95,9.26]],"closing":true,"drawn":1.0,"off_projection_px":0.09},{"view":"side","side":1,"through":["e","ridge_rear"],"line":[[769.96,387.04],[772.42,383.77]],"closing":true,"drawn":1.0,"off_projection_px":0.82}],"families":{"offset 0.5":{"offset_px":0.5,"jitter_px":0.0,"reach_px":2.5},"offset 1":{"offset_px":1.0,"jitter_px":0.0,"reach_px":2.5},"offset 1.5":{"offset_px":1.5,"jitter_px":0.0,"reach_px":2.5},"jitter 1":{"offset_px":0.0,"jitter_px":1.0,"reach_px":3.5},"jitter 2":{"offset_px":0.0,"jitter_px":2.0,"reach_px":3.5},"jitter 3":{"offset_px":0.0,"jitter_px":3.0,"reach_px":6.0}},"takes":[{"family":"offset 0.5","lines":[[[772.2,383.42],[811.92,388.9],[876.83,399.81],[904.5,416.12],[941.9,427.27],[961.01,441.57]],[[325.38,142.38],[427.34,126.41]],[[961.4,440.48],[933.67,437.39]],[[427.13,125.47],[441.7,94.0],[487.6,47.66],[552.26,26.84],[587.98,18.69]],[[933.75,435.9],[907.77,423.92],[886.76,406.74],[810.85,394.02],[770.76,388.61]],[[587.72,18.19],[542.1,9.36]],[[769.97,386.53],[772.44,383.26]]]},{"family":"offset 0.5","lines":[[[772.44,383.47],[812.17,388.91],[876.72,399.75],[904.86,416.32],[941.65,427.12],[961.25,441.79]],[[325.56,142.4],[427.51,126.37]],[[961.82,439.84],[933.81,437.93]],[[427.74,125.91],[442.92,92.86],[487.36,47.76],[552.41,26.85],[588.09,18.5]],[[934.12,435.85],[909.12,424.03],[846.1,400.04],[811.15,393.65],[771.07,388.12]],[[587.95,18.37],[542.38,9.29]],[[769.95,386.71],[772.42,383.44]]]},{"family":"offset 0.5","lines":[[[772.32,383.47],[812.07,388.87],[876.79,399.78],[904.63,416.24],[942.07,427.3],[961.38,441.96]],[[325.27,142.42],[427.22,126.4]],[[960.78,443.98],[934.02,436.83]],[[427.91,126.68],[443.16,92.38],[487.75,47.59],[552.04,26.8],[587.79,18.66]],[[934.41,435.5],[908.74,424.97],[876.48,405.41],[811.05,393.6],[771.07,387.23]],[[587.88,18.31],[542.29,9.34]],[[770.14,387.44],[771.99,383.96]]]},{"family":"offset 0.5","lines":[[[771.89,383.3],[811.61,388.91],[876.95,399.87],[904.42,416.1],[942.18,427.41],[961.12,441.73]],[[324.82,142.53],[426.77,126.48]],[[961.4,439.48],[933.35,437.72]],[[426.07,126.07],[442.1,93.47],[487.78,47.57],[551.62,27.02],[587.32,18.64]],[[933.81,435.81],[908.63,424.33],[876.73,405.49],[810.58,393.7],[770.64,387.08]],[[587.45,18.21],[541.85,9.28]],[[770.15,387.64],[772.01,384.16]]]},{"family":"offset 0.5","lines":[[[772.21,383.42],[811.93,388.9],[876.98,399.83],[904.42,416.1],[941.91,427.28],[961.02,441.57]],[[325.39,142.37],[427.35,126.43]],[[961.41,440.49],[933.68,437.39]],[[426.58,125.21],[441.98,93.74],[487.53,47.69],[552.27,26.85],[587.99,18.69]],[[933.76,435.91],[907.78,423.92],[886.77,406.75],[810.86,394.02],[770.77,388.62]],[[587.73,18.21],[542.12,9.34]],[[769.98,386.54],[772.45,383.27]]]},{"family":"offset 0.5","lines":[[[771.65,383.25],[811.36,388.87],[876.64,399.62],[904.14,415.98],[942.73,427.49],[960.43,441.62]],[[324.82,142.51],[426.77,126.49]],[[960.88,440.26],[933.14,437.24]],[[426.31,125.41],[442.09,93.58],[487.52,47.7],[551.72,27.03],[587.38,18.65]],[[932.92,436.43],[908.62,423.23],[876.42,405.26],[810.29,393.97],[770.2,388.47]],[[587.15,18.2],[541.58,9.14]],[[769.87,386.74],[772.33,383.47]]]},{"family":"offset 0.5","lines":[[[772.49,383.45],[812.22,388.9],[876.83,399.77],[904.9,416.37],[942.01,427.24],[961.3,441.88]],[[325.57,142.42],[427.52,126.36]],[[961.99,439.4],[933.83,438.1]],[[427.84,126.06],[443.72,92.04],[487.52,47.65],[552.38,26.76],[588.13,18.66]],[[934.21,435.86],[909.1,424.23],[865.97,403.51],[811.19,393.71],[771.19,387.54]],[[588.0,18.41],[542.43,9.29]],[[769.98,386.83],[772.44,383.56]]]},{"family":"offset 0.5","lines":[[[771.68,383.23],[811.38,388.85],[876.76,399.69],[903.91,415.88],[942.71,427.54],[960.46,441.6]],[[324.84,142.49],[426.8,126.51]],[[960.91,440.24],[933.16,437.22]],[[426.38,125.4],[442.02,93.67],[487.56,47.66],[551.75,27.01],[587.42,18.7]],[[932.95,436.41],[908.63,423.23],[876.12,405.13],[810.32,393.9],[770.22,388.5]],[[587.17,18.19],[541.59,9.18]],[[769.9,386.72],[772.36,383.45]]]},{"family":"offset 0.5","lines":[[[772.25,383.46],[811.98,388.92],[876.91,399.83],[904.47,416.14],[941.69,427.2],[961.08,441.58]],[[325.43,142.4],[427.39,126.39]],[[961.41,440.69],[933.75,437.32]],[[428.93,126.33],[440.99,94.8],[487.38,47.73],[552.32,26.89],[587.99,18.52]],[[933.56,436.42],[901.54,418.82],[886.96,406.9],[810.91,394.03],[770.82,388.56]],[[587.76,18.29],[542.17,9.3]],[[770.03,386.57],[772.49,383.3]]]},{"family":"offset 0.5","lines":[[[771.53,383.24],[811.24,388.84],[876.58,399.58],[904.17,416.02],[942.85,427.52],[960.44,441.65]],[[324.62,142.52],[426.58,126.51]],[[960.9,439.76],[932.95,437.6]],[[426.45,125.79],[441.79,93.8],[487.6,47.65],[551.53,27.17],[587.16,18.59]],[[932.88,436.46],[908.59,423.25],[875.88,405.1],[810.15,394.08],[770.1,388.35]],[[587.06,18.11],[541.47,9.15]],[[769.95,387.07],[772.41,383.8]]]},{"family":"offset 0.5","lines":[[[772.42,383.43],[812.16,388.89],[876.93,399.84],[904.27,416.12],[942.08,427.28],[961.16,441.84]],[[325.55,142.39],[427.5,126.39]],[[961.81,439.81],[933.8,437.89]],[[427.99,126.0],[443.14,92.61],[487.44,47.72],[552.39,26.8],[588.14,18.74]],[[934.1,435.81],[909.17,423.85],[846.58,400.19],[811.09,393.93],[771.07,387.95]],[[587.93,18.35],[542.35,9.31]],[[769.94,386.67],[772.4,383.4]]]},{"family":"offset 0.5","lines":[[[772.33,383.51],[812.08,388.88],[876.82,399.78],[904.64,416.23],[942.09,427.29],[961.32,442.05]],[[325.28,142.4],[427.24,126.39]],[[960.8,443.97],[934.04,436.82]],[[427.93,126.67],[443.15,92.44],[487.67,47.63],[552.06,26.82],[587.8,18.6]],[[934.42,435.49],[908.75,424.96],[876.43,405.39],[811.06,393.59],[771.09,387.21]],[[587.89,18.32],[542.3,9.33]],[[770.16,387.43],[772.01,383.95]]]},{"family":"offset 1","lines":[[[772.38,383.52],[812.11,388.89],[876.84,399.81],[904.83,416.31],[942.18,427.33],[960.91,441.6]],[[325.71,142.43],[427.64,126.27]],[[961.44,440.94],[933.91,436.99]],[[428.47,125.55],[441.32,94.29],[487.61,47.67],[552.65,26.96],[588.05,17.44]],[[933.56,436.34],[910.35,421.18],[883.52,404.14],[811.37,391.86],[771.25,386.44]],[[587.86,18.35],[542.28,9.3]],[[770.86,386.31],[772.71,382.84]]]},{"family":"offset 1","lines":[[[772.88,383.51],[812.61,388.99],[876.65,399.68],[904.32,416.04],[942.18,427.32],[961.32,442.13]],[[326.04,142.31],[427.99,126.28]],[[962.04,440.73],[934.48,436.94]],[[428.18,125.72],[444.66,90.92],[487.59,47.69],[552.89,26.74],[588.51,18.1]],[[934.37,436.1],[907.56,423.63],[893.73,408.05],[811.51,394.23],[771.43,388.8]],[[588.36,18.49],[542.8,9.39]],[[770.34,386.51],[772.19,383.03]]]},{"family":"offset 1","lines":[[[772.65,383.46],[812.39,388.94],[876.82,399.73],[904.34,416.05],[942.59,427.45],[961.6,442.44]],[[325.47,142.41],[427.42,126.35]],[[961.0,444.6],[934.13,437.91]],[[427.59,126.83],[445.86,89.66],[487.8,47.56],[552.21,26.89],[587.94,18.52]],[[934.72,435.82],[909.21,425.01],[876.03,405.2],[811.39,393.52],[771.33,387.7]],[[588.2,18.5],[542.65,9.31]],[[769.78,387.65],[772.25,384.38]]]},{"family":"offset 1","lines":[[[771.77,383.24],[811.49,388.88],[876.89,399.84],[904.68,416.21],[942.07,427.36],[961.19,441.87]],[[324.56,142.56],[426.51,126.49]],[[959.98,445.09],[933.45,436.97]],[[426.3,126.73],[441.67,94.0],[487.55,47.72],[551.34,27.15],[587.03,18.65]],[[933.85,435.82],[908.65,424.4],[876.74,405.47],[810.48,393.57],[770.52,386.97]],[[587.34,18.23],[541.76,9.21]],[[770.27,388.2],[770.89,384.31]]]},{"family":"offset 1","lines":[[[772.4,383.5],[812.13,388.9],[876.76,399.76],[904.85,416.33],[942.01,427.29],[960.92,441.62]],[[325.72,142.4],[427.66,126.28]],[[961.46,440.95],[933.93,437.01]],[[428.01,125.33],[442.44,93.14],[487.66,47.67],[552.66,26.92],[588.11,17.62]],[[933.58,436.35],[910.33,421.26],[883.76,404.19],[811.39,391.87],[771.26,386.46]],[[587.88,18.34],[542.3,9.3]],[[770.87,386.32],[772.73,382.85]]]},{"family":"offset 1","lines":[[[771.27,383.3],[811.0,388.69],[876.81,399.69],[904.09,415.97],[942.56,427.46],[960.12,441.21]],[[324.56,142.57],[426.51,126.52]],[[960.58,439.78],[932.8,436.92]],[[426.52,125.27],[441.98,93.72],[487.52,47.66],[551.5,27.03],[587.16,18.71]],[[932.95,435.37],[907.74,423.91],[875.71,405.13],[810.04,392.94],[770.09,386.54]],[[586.76,18.15],[541.19,9.06]],[[770.02,386.52],[772.49,383.25]]]},{"family":"offset 1","lines":[[[772.97,383.51],[812.69,389.02],[876.68,399.67],[904.44,416.06],[942.77,427.5],[961.42,442.31]],[[326.06,142.3],[428.01,126.29]],[[962.46,439.42],[934.42,437.65]],[[428.37,126.02],[444.86,90.74],[487.7,47.65],[552.88,26.74],[588.51,18.09]],[[934.28,436.62],[909.84,423.7],[865.62,403.38],[811.61,394.21],[771.51,388.82]],[[588.46,18.51],[542.9,9.39]],[[770.0,386.61],[772.47,383.35]]]},{"family":"offset 1","lines":[[[771.32,383.28],[811.04,388.72],[876.68,399.65],[904.47,416.1],[942.73,427.49],[960.11,441.26]],[[324.61,142.54],[426.56,126.51]],[[960.5,440.31],[932.82,436.99]],[[426.55,125.22],[442.02,93.68],[487.58,47.65],[551.59,27.15],[587.15,18.42]],[[932.67,435.98],[908.29,422.93],[846.42,400.1],[810.09,392.9],[770.14,386.5]],[[586.81,18.11],[541.22,9.13]],[[770.07,386.48],[772.54,383.21]]]},{"family":"offset 1","lines":[[[772.51,383.46],[812.23,388.91],[876.74,399.77],[904.73,416.26],[941.61,427.14],[961.08,441.58]],[[325.8,142.4],[427.74,126.26]],[[961.72,440.29],[933.92,437.49]],[[428.2,125.45],[442.54,93.09],[487.55,47.71],[552.68,26.71],[588.39,18.56]],[[933.79,436.17],[910.34,421.48],[884.05,404.29],[811.47,391.93],[771.35,386.52]],[[587.97,18.39],[542.4,9.31]],[[770.96,386.39],[772.82,382.91]]]},{"family":"offset 1","lines":[[[771.02,383.27],[810.76,388.68],[876.86,399.74],[904.4,416.13],[942.65,427.42],[960.08,441.36]],[[324.18,142.65],[426.12,126.55]],[[960.37,439.85],[932.44,437.61]],[[426.31,125.81],[441.98,93.65],[487.56,47.71],[551.09,27.16],[586.76,18.83]],[[933.06,435.03],[907.48,424.33],[876.4,405.34],[809.73,393.46],[769.76,387.12]],[[586.56,18.08],[540.99,9.0]],[[769.94,387.09],[772.41,383.82]]]},{"family":"offset 1","lines":[[[772.84,383.49],[812.57,388.93],[876.79,399.72],[904.29,416.07],[942.26,427.34],[961.29,442.06]],[[326.02,142.33],[427.97,126.29]],[[961.99,440.73],[934.44,436.9]],[[428.18,125.66],[444.73,90.87],[487.62,47.63],[552.91,26.88],[588.47,17.98]],[[934.34,436.02],[907.53,423.56],[893.85,408.15],[811.5,394.0],[771.41,388.62]],[[588.32,18.48],[542.75,9.4]],[[770.54,386.51],[772.39,383.04]]]},{"family":"offset 1","lines":[[[772.68,383.48],[812.42,388.91],[876.78,399.73],[904.17,415.97],[942.84,427.54],[961.58,442.49]],[[325.51,142.42],[427.45,126.36]],[[961.07,444.43],[934.13,438.01]],[[427.49,126.74],[446.69,88.83],[487.73,47.61],[552.24,26.89],[587.99,18.58]],[[934.77,435.77],[909.21,425.05],[875.82,405.12],[811.44,393.35],[771.35,387.83]],[[588.22,18.51],[542.67,9.34]],[[769.81,387.63],[772.28,384.36]]]},{"family":"offset 1.5","lines":[[[772.59,383.45],[812.3,388.9],[876.74,399.75],[904.64,416.2],[942.2,427.33],[960.82,441.61]],[[326.01,142.31],[427.96,126.27]],[[962.0,439.23],[933.97,437.4]],[[427.07,124.34],[441.96,93.73],[487.53,47.7],[552.97,26.75],[588.54,18.06]],[[933.73,436.07],[910.55,420.86],[883.11,403.6],[811.77,390.32],[771.8,383.78]],[[588.01,18.42],[542.45,9.3]],[[770.96,385.83],[773.42,382.56]]]},{"family":"offset 1.5","lines":[[[773.33,383.49],[813.03,389.11],[876.97,399.84],[904.66,416.2],[942.31,427.31],[961.51,442.32]],[[326.53,142.28],[428.47,126.17]],[[962.46,440.77],[934.8,437.37]],[[428.39,125.43],[447.02,88.59],[487.6,47.66],[553.35,26.52],[589.05,18.22]],[[934.53,436.54],[911.04,421.91],[889.4,407.36],[812.1,393.19],[772.14,386.78]],[[588.76,18.65],[543.23,9.4]],[[770.8,386.33],[772.66,382.86]]]},{"family":"offset 1.5","lines":[[[772.97,383.5],[812.71,389.0],[876.73,399.67],[904.28,416.09],[942.16,427.27],[962.07,442.61]],[[325.67,142.41],[427.61,126.31]],[[961.31,444.86],[934.5,437.91]],[[427.38,127.02],[454.3,81.22],[487.71,47.61],[552.35,26.85],[588.14,18.66]],[[935.06,436.12],[909.68,425.04],[875.86,405.06],[811.7,393.66],[771.61,388.05]],[[588.54,18.55],[542.98,9.4]],[[770.27,388.15],[770.9,384.26]]]},{"family":"offset 1.5","lines":[[[771.63,383.3],[811.37,388.86],[876.51,399.68],[904.66,416.18],[941.93,427.28],[961.35,441.87]],[[324.31,142.65],[426.24,126.48]],[[959.87,445.24],[933.24,437.5]],[[425.74,127.02],[442.09,93.56],[487.6,47.67],[551.05,27.26],[586.78,18.87]],[[933.87,435.86],[908.75,424.32],[876.43,405.31],[810.3,394.0],[770.17,388.62]],[[587.25,18.2],[541.66,9.21]],[[770.47,388.79],[770.48,384.7]]]},{"family":"offset 1.5","lines":[[[772.61,383.47],[812.33,388.92],[876.75,399.76],[904.85,416.33],[942.11,427.26],[960.85,441.63]],[[326.04,142.32],[427.99,126.26]],[[961.99,439.39],[934.01,437.36]],[[427.11,124.36],[441.9,93.83],[487.44,47.73],[552.99,26.75],[588.56,18.02]],[[933.76,436.09],[910.56,420.9],[883.16,403.62],[811.8,390.33],[771.83,383.8]],[[588.04,18.42],[542.48,9.31]],[[770.59,385.72],[773.67,382.66]]]},{"family":"offset 1.5","lines":[[[770.9,383.26],[810.62,388.7],[876.71,399.71],[904.73,416.23],[941.66,427.18],[959.91,440.69]],[[324.3,142.61],[426.25,126.53]],[[960.31,439.19],[932.23,437.57]],[[426.48,125.02],[442.21,93.48],[487.53,47.69],[551.31,27.12],[586.96,18.88]],[[932.22,435.78],[908.35,421.82],[875.6,402.76],[809.89,391.58],[769.77,386.16]],[[586.39,18.01],[540.81,9.0]],[[770.56,386.43],[772.41,382.95]]]},{"family":"offset 1.5","lines":[[[773.45,383.55],[813.16,389.14],[877.01,399.88],[904.47,416.16],[942.92,427.55],[961.64,442.62]],[[326.56,142.29],[428.5,126.17]],[[962.73,440.33],[934.88,437.75]],[[426.47,124.84],[445.79,93.32],[487.63,47.63],[553.33,26.48],[589.02,18.1]],[[934.76,436.61],[905.93,422.03],[891.61,407.68],[812.1,394.21],[772.01,388.73]],[[588.92,18.65],[543.38,9.42]],[[770.42,386.53],[772.27,383.06]]]},{"family":"offset 1.5","lines":[[[770.96,383.31],[810.7,388.65],[876.9,399.77],[904.54,416.19],[941.96,427.26],[959.9,440.75]],[[324.38,142.52],[426.34,126.56]],[[960.48,438.72],[932.22,437.88]],[[426.54,124.96],[442.16,93.59],[487.56,47.63],[551.44,27.32],[586.77,17.63]],[[932.25,435.81],[908.44,421.72],[875.67,402.7],[809.96,391.52],[769.84,386.1]],[[586.45,18.02],[540.87,8.99]],[[771.03,386.5],[772.27,382.82]]]},{"family":"offset 1.5","lines":[[[772.76,383.46],[812.48,388.91],[876.73,399.75],[904.85,416.32],[941.56,427.1],[961.09,441.59]],[[326.15,142.28],[428.11,126.27]],[[962.11,439.54],[934.17,437.34]],[[427.21,124.44],[441.83,93.91],[487.53,47.7],[553.11,26.79],[588.64,17.91]],[[933.85,436.26],[910.69,421.0],[878.05,400.54],[812.12,389.32],[771.96,383.9]],[[588.18,18.49],[542.63,9.32]],[[770.88,385.86],[773.35,382.6]]]},{"family":"offset 1.5","lines":[[[770.54,383.13],[810.25,388.72],[876.65,399.75],[904.84,416.23],[942.11,427.34],[959.96,440.76]],[[323.74,142.75],[425.66,126.57]],[[960.12,438.76],[931.82,438.03]],[[426.23,125.87],[441.87,93.85],[487.61,47.62],[550.67,27.23],[586.36,19.05]],[[932.24,435.55],[907.49,423.24],[876.19,405.23],[809.18,393.83],[769.09,388.4]],[[586.06,18.0],[540.49,8.96]],[[769.93,387.11],[772.4,383.85]]]},{"family":"offset 1.5","lines":[[[773.27,383.46],[812.97,389.09],[877.14,399.86],[904.47,416.16],[942.4,427.35],[961.41,442.28]],[[326.5,142.25],[428.45,126.21]],[[962.4,440.72],[934.75,437.28]],[[428.19,125.24],[446.87,88.77],[487.56,47.65],[553.32,26.48],[589.0,18.11]],[[934.58,436.23],[910.75,422.28],[884.29,404.35],[812.22,392.09],[772.1,386.67]],[[588.7,18.61],[543.15,9.42]],[[770.99,386.3],[772.85,382.83]]]},{"family":"offset 1.5","lines":[[[773.01,383.49],[812.75,389.03],[876.71,399.68],[904.43,416.13],[942.34,427.39],[962.07,442.64]],[[325.73,142.43],[427.66,126.27]],[[961.35,444.86],[934.48,438.14]],[[425.82,126.24],[463.98,71.46],[487.68,47.63],[552.4,26.8],[588.22,18.74]],[[935.05,436.2],[909.79,424.89],[876.13,405.22],[811.71,393.9],[771.74,387.46]],[[588.58,18.56],[543.03,9.38]],[[770.17,388.06],[771.41,384.38]]]},{"family":"jitter 1","lines":[[[772.12,383.36],[812.38,388.95],[876.64,399.72],[904.88,416.31],[941.79,427.17],[960.67,441.38]],[[322.85,142.87],[425.92,126.58]],[[959.74,444.8],[934.1,438.03]],[[425.54,126.74],[461.82,73.68],[487.52,47.72],[551.49,27.31],[586.89,17.54]],[[933.07,434.97],[908.5,424.76],[876.66,405.06],[810.0,394.04],[771.52,388.76]],[[586.68,18.04],[543.4,9.59]],[[771.0,386.99],[773.43,385.58]]]},{"family":"jitter 1","lines":[[[772.4,383.5],[811.89,388.85],[877.17,399.89],[903.95,415.96],[942.28,427.37],[961.26,441.95]],[[324.38,142.63],[426.45,126.46]],[[961.25,440.31],[932.58,437.89]],[[425.77,125.03],[444.91,94.21],[487.53,47.7],[551.82,26.91],[587.78,18.62]],[[935.34,436.46],[909.28,424.33],[873.98,403.97],[810.81,388.11],[771.26,383.55]],[[586.22,18.0],[541.69,9.22]],[[769.81,387.13],[772.6,383.31]]]},{"family":"jitter 1","lines":[[[772.14,383.41],[810.97,388.79],[876.72,399.66],[904.18,416.03],[942.62,427.52],[961.38,442.16]],[[324.86,142.52],[427.48,126.37]],[[961.93,439.36],[933.26,438.01]],[[425.78,125.2],[445.07,94.15],[487.62,47.64],[554.44,26.95],[585.42,15.2]],[[934.72,435.73],[907.97,425.3],[892.02,407.68],[810.6,394.1],[769.39,388.19]],[[588.19,18.49],[540.98,8.97]],[[770.59,388.47],[770.49,384.36]]]},{"family":"jitter 1","lines":[[[773.53,383.55],[812.05,388.92],[877.11,399.85],[904.01,415.96],[943.04,427.59],[960.8,442.08]],[[324.9,142.53],[426.05,126.56]],[[960.69,444.57],[934.41,437.42]],[[425.84,126.96],[460.45,75.05],[487.63,47.61],[553.77,26.38],[587.21,18.87]],[[933.13,435.03],[906.32,424.87],[900.15,409.21],[808.47,391.64],[770.34,382.96]],[[587.95,18.41],[541.3,9.05]],[[769.84,386.41],[772.46,383.53]]]},{"family":"jitter 1","lines":[[[771.35,383.29],[813.47,389.1],[876.84,399.78],[904.57,416.14],[942.22,427.34],[961.92,442.37]],[[325.3,142.42],[425.24,126.69]],[[958.23,445.25],[932.92,436.75]],[[425.81,125.02],[445.39,93.95],[487.56,47.68],[552.2,27.06],[588.54,17.07]],[[933.69,435.48],[907.66,424.37],[879.64,407.18],[812.35,388.44],[770.32,383.68]],[[588.41,18.58],[541.16,9.01]],[[770.02,386.77],[772.36,383.84]]]},{"family":"jitter 1","lines":[[[771.0,383.3],[811.57,388.82],[877.26,399.89],[903.83,415.9],[941.6,427.14],[960.73,441.29]],[[323.88,142.64],[427.55,126.38]],[[961.4,438.02],[932.61,438.53]],[[427.66,127.16],[444.46,91.3],[487.38,47.77],[550.45,27.25],[586.72,18.86]],[[932.98,434.89],[909.33,422.55],[876.01,399.99],[810.2,388.64],[771.36,383.21]],[[588.78,18.61],[540.1,8.81]],[[769.7,387.37],[773.51,382.26]]]},{"family":"jitter 1","lines":[[[773.21,383.5],[809.22,388.45],[876.87,399.78],[904.24,416.06],[942.28,427.33],[960.57,441.47]],[[324.19,142.65],[426.27,126.51]],[[961.76,445.52],[933.49,438.74]],[[427.35,125.79],[446.24,89.36],[487.56,47.7],[552.42,26.76],[588.72,18.56]],[[934.36,435.46],[910.15,423.01],[877.33,400.12],[811.09,388.89],[771.72,384.11]],[[587.2,18.17],[541.58,9.18]],[[770.59,388.97],[770.49,384.13]]]},{"family":"jitter 1","lines":[[[772.04,383.34],[811.34,388.87],[876.73,399.66],[904.72,416.38],[942.56,427.22],[961.26,442.33]],[[325.29,142.41],[426.89,126.44]],[[959.01,443.53],[931.63,435.84]],[[425.93,126.1],[442.08,93.63],[487.53,47.65],[549.7,27.54],[587.54,18.64]],[[932.17,435.43],[908.81,421.43],[876.17,399.37],[810.68,394.6],[769.9,388.78]],[[587.65,18.31],[540.79,8.99]],[[772.1,385.76],[772.83,383.74]]]},{"family":"jitter 1","lines":[[[770.11,383.06],[810.35,388.69],[876.85,399.77],[904.0,415.92],[941.8,427.18],[961.53,441.96]],[[325.69,142.43],[426.28,126.47]],[[960.17,445.68],[932.68,436.68]],[[427.32,126.19],[443.61,92.07],[487.58,47.61],[551.72,27.04],[585.57,19.06]],[[932.38,435.14],[909.14,424.73],[881.48,408.27],[812.99,388.6],[768.67,383.05]],[[588.52,18.48],[540.26,8.84]],[[769.95,386.66],[772.06,383.99]]]},{"family":"jitter 1","lines":[[[771.26,383.25],[810.21,388.63],[876.87,399.85],[904.86,416.34],[942.57,427.36],[960.48,441.57]],[[324.61,142.51],[427.79,126.31]],[[959.87,444.94],[933.02,438.97]],[[427.23,126.44],[447.59,88.03],[487.54,47.67],[552.98,26.98],[588.33,17.23]],[[933.74,436.09],[907.13,423.09],[876.42,405.32],[810.81,393.6],[770.83,386.95]],[[587.8,18.34],[541.61,9.14]],[[769.77,387.08],[771.22,385.51]]]},{"family":"jitter 1","lines":[[[770.81,383.25],[811.02,388.74],[876.73,399.71],[904.47,416.12],[941.58,427.12],[960.24,440.88]],[[324.76,142.51],[426.27,126.58]],[[961.62,437.4],[933.39,438.69]],[[427.97,125.83],[443.16,92.64],[487.48,47.66],[551.28,27.16],[588.41,18.41]],[[933.06,435.04],[908.57,424.73],[876.26,405.37],[810.94,393.52],[771.34,387.05]],[[586.77,18.13],[542.78,9.42]],[[769.83,388.33],[772.77,382.47]]]},{"family":"jitter 1","lines":[[[772.14,383.44],[812.87,389.03],[876.8,399.68],[903.84,415.87],[942.52,427.37],[961.73,442.59]],[[325.76,142.4],[426.57,126.45]],[[961.16,444.61],[933.48,437.89]],[[428.02,125.43],[443.38,92.34],[487.45,47.74],[551.75,26.99],[586.17,18.97]],[[934.44,436.1],[907.18,423.82],[887.59,406.88],[811.3,394.38],[771.18,382.81]],[[587.92,18.35],[542.72,9.38]],[[770.07,386.47],[770.24,383.75]]]},{"family":"jitter 2","lines":[[[772.22,383.42],[813.02,389.08],[877.05,399.84],[904.59,416.26],[942.16,427.27],[960.3,441.17]],[[320.62,143.24],[424.82,126.72]],[[959.31,444.76],[934.64,438.68]],[[426.47,128.58],[445.5,90.14],[487.52,47.67],[550.97,27.19],[586.62,18.71]],[[931.81,435.27],[909.03,423.97],[873.61,404.68],[809.39,393.84],[772.46,387.55]],[[585.88,18.0],[544.92,9.76]],[[771.27,386.68],[774.89,387.54]]]},{"family":"jitter 2","lines":[[[772.72,383.37],[812.07,388.94],[877.14,399.89],[904.05,415.94],[942.85,427.53],[961.36,442.41]],[[323.68,142.77],[425.9,126.54]],[[961.86,437.41],[931.81,437.68]],[[426.35,125.02],[463.47,72.1],[488.69,46.85],[551.76,27.09],[587.92,18.48]],[[937.39,437.12],[909.61,424.84],[873.93,403.92],[810.16,387.65],[771.27,383.47]],[[584.89,17.78],[541.42,9.12]],[[769.89,387.3],[773.03,382.91]]]},{"family":"jitter 2","lines":[[[772.31,383.54],[810.24,388.48],[877.01,399.81],[904.31,416.06],[942.28,427.38],[961.88,442.5]],[[324.64,142.57],[427.93,126.25]],[[962.58,438.38],[933.2,437.76]],[[426.71,125.46],[460.97,74.53],[487.55,47.71],[556.85,26.25],[583.7,13.9]],[[935.48,436.03],[908.63,425.74],[895.16,408.38],[810.65,393.7],[767.91,389.45]],[[589.01,18.7],[539.9,8.76]],[[770.53,389.83],[770.44,385.59]]]},{"family":"jitter 2","lines":[[[774.77,383.51],[812.31,388.96],[877.02,399.78],[901.34,413.41],[942.05,437.68],[962.28,438.4]],[[324.71,142.49],[425.08,126.77]],[[962.98,436.86],[934.82,439.43]],[[426.15,128.65],[455.08,80.49],[487.61,47.64],[555.65,25.99],[586.77,18.7]],[[932.23,434.75],[910.29,425.63],[876.12,405.29],[805.46,393.48],[769.56,381.46]],[[588.39,18.55],[540.58,8.87]],[[770.27,386.2],[773.57,382.79]]]},{"family":"jitter 2","lines":[[[770.68,383.19],[815.2,389.36],[876.91,399.81],[904.7,416.23],[942.88,427.61],[962.59,443.37]],[[325.55,142.39],[423.53,127.01]],[[956.5,445.36],[932.21,436.18]],[[428.2,126.0],[452.64,82.95],[487.62,47.57],[552.56,27.33],[589.15,14.26]],[[933.16,436.14],[907.37,422.9],[880.16,407.51],[813.21,388.35],[769.47,383.23]],[[589.34,18.74],[540.34,8.82]],[[769.9,386.78],[772.26,384.01]]]},{"family":"jitter 2","lines":[[[769.91,383.09],[811.41,388.82],[876.96,399.75],[904.05,416.01],[941.79,427.22],[960.61,441.09]],[[322.61,142.91],[428.15,126.19]],[[960.99,438.23],[932.09,438.01]],[[425.78,127.16],[441.92,93.81],[487.64,47.62],[549.02,27.66],[585.82,19.09]],[[931.92,434.56],[909.13,422.39],[875.75,399.77],[808.94,388.44],[771.43,383.27]],[[590.05,18.79],[538.21,8.49]],[[769.15,387.65],[774.61,380.81]]]},{"family":"jitter 2","lines":[[[774.25,383.74],[806.7,388.03],[877.08,399.74],[903.84,415.85],[942.88,427.62],[960.24,441.35]],[[323.3,142.75],[425.54,126.67]],[[963.41,445.83],[933.72,439.06]],[[426.45,125.05],[441.76,93.76],[488.48,46.97],[552.92,26.83],[589.76,17.79]],[[934.72,435.58],[910.76,423.29],[876.55,399.7],[810.78,388.65],[772.3,383.83]],[[587.01,18.28],[541.21,9.04]],[[770.53,390.77],[770.68,385.0]]]},{"family":"jitter 2","lines":[[[772.04,383.35],[810.99,388.76],[876.67,399.69],[904.27,416.04],[942.07,427.31],[961.93,442.45]],[[325.48,142.42],[426.79,126.5]],[[958.02,441.66],[929.53,435.11]],[[425.72,126.74],[442.17,93.54],[487.53,47.71],[547.49,28.16],[587.48,18.74]],[[930.64,434.91],[907.72,420.86],[874.99,398.69],[810.91,393.88],[769.3,388.59]],[[587.77,18.31],[539.62,8.78]],[[773.45,384.21],[773.69,383.86]]]},{"family":"jitter 2","lines":[[[768.15,382.85],[808.98,388.41],[876.69,399.8],[904.71,416.2],[941.72,427.2],[962.03,442.35]],[[326.24,142.25],[425.56,126.69]],[[960.32,446.17],[931.69,436.58]],[[426.11,125.9],[442.3,93.29],[487.69,47.6],[551.52,27.14],[583.6,19.56]],[[931.32,435.1],[909.68,424.59],[883.45,409.45],[814.46,388.63],[766.09,382.63]],[[589.49,18.74],[538.56,8.47]],[[770.15,386.19],[772.58,383.54]]]},{"family":"jitter 2","lines":[[[770.52,383.19],[808.68,388.4],[877.07,399.89],[904.05,415.88],[942.03,427.3],[960.77,441.44]],[[324.08,142.73],[428.53,126.12]],[[959.55,444.87],[932.91,438.85]],[[427.32,126.84],[444.7,91.11],[487.49,47.63],[553.94,26.59],[589.34,17.06]],[[933.98,436.05],[905.41,422.34],[876.53,405.42],[810.8,394.29],[771.62,382.7]],[[588.12,18.47],[541.22,9.02]],[[768.8,386.86],[770.48,387.39]]]},{"family":"jitter 2","lines":[[[769.62,383.0],[810.3,388.67],[876.94,399.84],[904.47,416.13],[941.53,427.09],[959.33,440.25]],[[324.45,142.6],[425.53,126.64]],[[961.58,437.66],[933.45,439.23]],[[426.83,124.71],[441.87,93.83],[487.56,47.62],[550.65,27.23],[589.22,18.29]],[[932.17,435.12],[909.07,424.02],[876.09,405.26],[811.14,393.67],[771.95,386.79]],[[586.02,18.03],[543.61,9.53]],[[768.83,389.33],[773.87,381.4]]]},{"family":"jitter 2","lines":[[[772.16,383.35],[814.04,389.19],[876.79,399.72],[904.99,416.37],[941.48,427.02],[962.78,443.02]],[[326.44,142.28],[426.14,126.54]],[[962.08,444.53],[933.49,438.01]],[[427.13,124.01],[442.1,93.45],[488.28,47.22],[551.55,27.04],[584.71,19.31]],[[935.11,436.57],[903.98,421.78],[887.88,406.88],[811.89,394.99],[771.11,382.08]],[[588.3,18.5],[543.37,9.49]],[[769.41,385.63],[768.51,383.88]]]},{"family":"jitter 3","lines":[[[772.31,383.49],[813.67,389.13],[876.81,399.74],[904.94,416.36],[942.35,427.42],[959.91,441.02]],[[318.41,143.66],[423.72,126.86]],[[958.86,445.41],[935.2,438.92]],[[425.56,129.65],[444.03,98.8],[488.4,53.87],[550.24,27.28],[585.5,13.71]],[[930.85,434.97],[910.37,422.01],[876.12,399.69],[809.28,388.33],[773.2,384.35]],[[585.27,17.76],[546.41,10.16]],[[773.33,383.61],[780.24,383.54]]]},{"family":"jitter 3","lines":[[[772.95,383.45],[812.3,388.98],[877.36,399.89],[904.38,416.15],[945.16,428.12],[960.17,444.39]],[[322.96,142.82],[425.36,126.68]],[[959.95,446.06],[931.38,435.86]],[[427.94,125.75],[447.08,96.2],[481.18,49.65],[551.69,27.53],[587.39,14.17]],[[939.54,440.33],[900.17,418.37],[881.11,400.55],[809.23,388.5],[771.26,383.28]],[[583.58,17.4],[541.11,9.08]],[[769.75,387.38],[773.21,382.44]]]},{"family":"jitter 3","lines":[[[772.55,383.47],[809.52,388.44],[877.24,399.98],[904.14,416.03],[942.73,427.48],[962.27,443.03]],[[324.4,142.62],[428.38,126.18]],[[962.19,441.42],[934.64,431.68]],[[426.23,125.09],[446.62,96.02],[488.37,53.83],[558.24,22.24],[582.07,12.88]],[[936.24,436.35],[913.23,424.12],[875.44,399.4],[811.46,389.08],[768.07,382.68]],[[590.04,18.83],[538.72,8.56]],[[770.24,391.23],[770.72,387.13]]]},{"family":"jitter 3","lines":[[[775.58,383.68],[812.53,389.01],[876.51,399.61],[899.98,412.31],[942.17,441.76],[961.03,444.66]],[[324.54,142.58],[424.1,126.88]],[[961.94,442.84],[936.82,434.97]],[[423.84,129.18],[446.09,96.76],[489.62,52.55],[558.79,31.29],[586.41,18.58]],[[931.37,434.41],[912.33,424.01],[890.19,407.71],[804.05,390.46],[767.77,382.53]],[[588.88,18.66],[539.78,8.76]],[[770.34,385.16],[775.29,382.09]]]},{"family":"jitter 3","lines":[[[770.02,383.1],[816.92,389.68],[876.39,399.65],[904.85,416.22],[944.56,428.1],[958.57,450.52]],[[325.82,142.46],[421.86,127.14]],[[954.99,445.43],[931.2,435.94]],[[427.97,125.69],[444.15,98.81],[497.33,44.53],[552.89,27.42],[589.7,11.38]],[[933.08,435.69],[906.38,423.02],[863.44,397.56],[813.84,389.14],[768.6,382.91]],[[590.3,18.92],[539.47,8.73]],[[770.04,387.68],[771.79,383.89]]]},{"family":"jitter 3","lines":[[[768.75,382.84],[811.26,388.8],[876.91,399.72],[904.46,416.15],[942.91,427.51],[960.65,441.39]],[[321.36,143.53],[428.83,125.94]],[[960.87,437.12],[931.73,436.42]],[[426.49,128.4],[444.65,97.92],[486.8,55.51],[547.51,28.18],[584.03,15.02]],[[930.88,434.26],[908.84,422.34],[876.91,399.9],[807.66,388.22],[771.5,383.29]],[[591.32,19.0],[536.32,8.2]],[[768.81,388.07],[775.92,379.49]]]},{"family":"jitter 3","lines":[[[775.08,383.84],[804.15,387.73],[877.15,399.87],[904.49,416.14],[941.04,427.02],[960.32,440.76]],[[322.43,142.96],[424.82,126.72]],[[964.57,448.15],[934.39,437.63]],[[427.96,125.8],[445.87,95.78],[482.99,48.91],[553.36,26.84],[590.74,15.65]],[[932.76,439.56],[923.51,426.67],[876.24,399.74],[810.44,388.66],[772.87,383.48]],[[587.09,18.19],[540.82,8.99]],[[770.32,392.64],[770.5,385.79]]]},{"family":"jitter 3","lines":[[[772.03,383.41],[810.65,388.71],[876.89,399.76],[904.1,415.98],[942.77,427.47],[962.18,443.12]],[[325.65,142.41],[426.69,126.47]],[[955.4,445.22],[927.74,433.26]],[[425.49,127.45],[442.05,93.5],[487.75,47.61],[545.36,29.39],[586.77,14.23]],[[928.03,436.24],[917.62,423.8],[876.87,399.81],[811.68,388.97],[769.8,382.94]],[[587.89,18.34],[538.45,8.53]],[[774.81,382.66],[774.55,383.98]]]},{"family":"jitter 3","lines":[[[766.17,382.52],[807.57,388.26],[876.46,399.76],[904.94,416.19],[942.02,427.28],[962.54,442.86]],[[326.77,142.18],[424.8,126.76]],[[960.32,447.33],[931.05,435.56]],[[426.64,126.3],[448.42,87.22],[488.14,47.05],[552.57,32.63],[582.36,25.03]],[[931.95,420.86],[914.61,427.44],[874.37,404.19],[815.97,388.49],[763.51,382.27]],[[590.49,18.9],[536.82,8.27]],[[770.41,385.24],[773.95,382.68]]]},{"family":"jitter 3","lines":[[[769.78,383.13],[807.15,388.12],[876.86,399.84],[904.93,416.35],[942.52,427.42],[960.97,442.06]],[[323.39,142.65],[429.3,126.17]],[[958.78,446.76],[933.26,436.55]],[[425.52,126.39],[441.89,102.24],[497.39,44.48],[554.99,26.5],[589.53,13.53]],[[937.62,426.62],[906.11,415.8],[873.1,401.87],[811.96,388.86],[771.59,383.35]],[[588.54,18.5],[540.77,8.94]],[[771.29,384.14],[772.31,387.4]]]},{"family":"jitter 3","lines":[[[768.34,383.02],[809.62,388.44],[876.6,399.66],[904.61,416.22],[941.65,427.14],[958.44,439.58]],[[324.14,142.7],[424.82,126.71]],[[961.88,437.84],[933.52,440.08]],[[428.45,125.19],[453.91,81.73],[490.19,45.06],[551.18,32.7],[590.87,21.85]],[[934.82,425.1],[907.11,417.06],[899.61,413.06],[812.48,388.4],[773.09,383.53]],[[585.32,17.79],[544.4,9.73]],[[768.9,390.66],[774.21,380.09]]]},{"family":"jitter 3","lines":[[[772.06,383.54],[815.22,389.34],[876.79,399.75],[904.5,416.18],[942.54,427.38],[963.4,443.87]],[[327.12,142.16],[425.71,126.65]],[[962.85,445.63],[933.36,438.91]],[[428.59,124.08],[456.81,78.68],[487.74,47.67],[551.44,28.06],[582.39,13.41]],[[936.05,436.4],[908.73,421.99],[876.18,399.62],[813.71,389.19],[770.56,383.14]],[[588.7,18.64],[543.93,9.54]],[[768.75,384.79],[766.77,384.0]]]}]}}} \ No newline at end of file diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index c79085c..a5bd8f6 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -778,14 +778,16 @@ def blocked_plate(views, traces, **more): return core.block_plate(views, {"corners": PLATE}, traces, kit.sheet, **more) -def rendered(name, corners, sigma=0.0, close=0.0, seed=0): +def rendered(name, corners, sigma=0.0, close=0.0, seed=0, take=None): """(views, plate, traces, the true sides, the fixture's plate) of a plate of tests/fixtures/spectre_truth.json with `corners` of its loop named: each stroke traced from the renders is cut at the named corners it passes - through, every point `sigma` px off, a closing stroke moved `close` px as one.""" + through, every point `sigma` px off, a closing stroke moved `close` px as one. The strokes are the fixture's + own, searched from the truth's projection, or those of its `take`, searched from a seed off it.""" fixture = json.loads((Path(__file__).resolve().parent / "fixtures" / "spectre_truth.json").read_text(encoding="utf-8")) plate, rng, views, traces = fixture["plates"][name], np.random.default_rng(seed), [], [] - for stroke in plate["strokes"]: - line = np.array(stroke["line"]) + (rng.normal(0, sigma, (len(stroke["line"]), 2)) if sigma else 0.0) + for k, stroke in enumerate(plate["strokes"]): + line = np.array(stroke["line"] if take is None else plate["takes"][take]["lines"][k]) + line = line + (rng.normal(0, sigma, line.shape) if sigma else 0.0) if stroke["closing"] and close: turn = rng.uniform(0, 2 * math.pi) line = line + close * np.array([math.cos(turn), math.sin(turn)]) @@ -802,6 +804,15 @@ def rendered(name, corners, sigma=0.0, close=0.0, seed=0): return views, {"corners": named, "mirror": True, "seam": [corner for corner in plate["seam"] if corner in corners]}, traces, sides, (fixture, plate) +def off_projection(fixture, plate, take): + """The furthest a point of a take's strokes stands from the truth's projection, px.""" + worst = 0.0 + for stroke, line in zip(plate["strokes"], plate["takes"][take]["lines"]): + drawn = core.seen(fixture["cameras"][stroke["view"]], fixture["frames"][stroke["view"]], np.array([plate["truth"][corner] for corner in stroke["through"]]) * [stroke["side"], 1, 1]) + worst = max(worst, float(np.linalg.norm(np.array(line) - drawn, axis=1).max())) + return worst + + def off_rendered(out, sides): """(the furthest a blocked corner stands from its own, the furthest a side as built and its true edge, a polyline through the truth's corners, stand apart either way), metres.""" @@ -828,7 +839,7 @@ class BlockTests(unittest.TestCase): S1 a seam point labelled mirror whatever its share test_a_seam_corner_says_what_decided_it S2 a seam corner never sent to the plane's guard test_a_seam_corner_says_what_decided_it I1 a side's label from its first point only, never plane test_a_side_says_what_decided_its_inner_points - T06 START 0.6, T3 START 3.3 test_views_5_degrees_apart_take_their_depth_from_a_plane_or_are_refused + T06, T08, T2, T26, T3 START 0.6, 0.8, 2.0, 2.6, 3.3 test_views_5_degrees_apart_take_their_depth_from_a_plane_or_are_refused K1 a skirt of fixed metres test_a_plate_keeps_its_proportions_at_any_size What the blocking is worth against a known truth is test_the_rendered_roof_blocks_from_traces_of_its_renders: @@ -854,14 +865,23 @@ class BlockTests(unittest.TestCase): kit.sheet(out["sheet"]) def test_views_5_degrees_apart_take_their_depth_from_a_plane_or_are_refused(self): - """block-low-parallax, T06, T3. The views start a corner where one pixel moves their meeting point less than - core.START x share x the plate's extent, the prior's own scale. At Paladin's lens and range that reads 0.74 - of the scale at 19 degrees (test_a_twisted_bowed_plate_blocks_from_two_views blocks there; T06 refuses it) - and 2.77 at 5, where the corners triangulate 0.25 to 1.5 m off: no corner is started. With a plane every - corner is decided by it (prior_share 0.795 to 0.838); with none the plate is refused naming the corners (T3 - blocks it). The line is metres a pixel, not degrees: through a lens three times as long the same plate 7 - degrees apart reads 0.66 and blocks from its views, 60.5 mm from the truth (65.0 at 19 degrees through the - short lens).""" + """block-low-parallax, T06, T3, T08, T2, T26 (Soul s2, start-unpinned-and-comment-stale). The views start a + corner where one pixel moves their meeting point less than core.START x share x the plate's extent, the + prior's own scale; with no plane a plate blocks when three corners start. START is 1, the prior's own + unit: it is not derived from a measurement, it is pinned between two. At Paladin's lens and range the + pentagon's third corner starts at START 0.724 with the views 19 degrees apart, 0.831 at 16.5, 1.241 at 11 + and 2.729 at 5. So at 16.5 degrees it blocks with no plane (73.0 mm from the truth) and at 11 it is + refused naming its corners: 1 stands 1.20 over the one reading and 1.24 under the other, the two's + geometric mean within 2%. START 0.6 and 0.8 refuse the 16.5 degrees; 2.0, 2.6 and 3.3 block the 11 (104.4 + mm off; the line switches blocking and refusal and is no cliff in accuracy). At 5 degrees the corners + triangulate 0.25 to 1.5 m off: with a plane every corner is decided by it (prior_share 0.795 to 0.838), + with none the plate is refused. The line is metres a pixel, not degrees: through a lens three times as + long the same plate 7 degrees apart starts at 0.648 and blocks from its views, 60.5 mm from the truth + (65.0 at 19 degrees through the short lens).""" + sides = pentagon(0.08) + self.assertEqual(blocked_plate(*plate_traces([plate_camera(0), plate_camera(16.5)], sides, 0.5))["plane"]["from"], "corners") + with self.assertRaisesRegex(core.ReferenceFitError, r"^plane: none was given, and 'c0', 'c1', 'c2', 'c3', 'c4' are decided by no view"): + blocked_plate(*plate_traces([plate_camera(0), plate_camera(11)], sides, 0.5)) views, traces = plate_traces([plate_camera(0), plate_camera(5)], pentagon(0.08), 0.5) out = blocked_plate(views, traces, plane=ON_Y) self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["plane"] * 5) @@ -1008,41 +1028,50 @@ class BlockTests(unittest.TestCase): self.assertEqual(out["sheet"]["poles"], [seam[0], seam[1], len(out["sheet"]["verts"]) - 1]) def test_the_rendered_roof_blocks_from_traces_of_its_renders(self): - """block-truth (Soul s1, real-readings-not-accuracy), M3. SPECTRE's pass-3 roof, a hard mirrored cage of 11 - known vertices, built by brokkr_kitbash.shell, rendered through SPECTRE's two solved cameras at the - sheet's pixel size and its edges traced off the renders (tests/fixtures/spectre_truth.json says how). The - ridge is traced in the side view alone, the lip, the outer edge and the rear edge in the hero's mirrored - half and in the side view, 62 degrees apart; the side view's pixel is 27.6 mm across at the plate, the - hero's 11.6. + """block-truth (Soul s1, real-readings-not-accuracy; Soul s2, bound-premise-seeded-by-truth), M3. SPECTRE's + pass-3 roof, a hard mirrored cage of 11 known vertices, built by brokkr_kitbash.shell, rendered through + SPECTRE's two solved cameras at the sheet's pixel size and its edges traced off the renders: one plate, + one pair of views. The ridge is traced in the side view alone, the lip, the outer edge and the rear edge + in the hero's mirrored half and in the side view, 62 degrees apart; the side view's pixel is 27.6 mm + across at the plate, the hero's 11.6. - Every corner named: the ridge's six are decided by the mirror plane, the outer edge's five by the views - (prior_share 0.038 at most). From the traces as taken the worst corner stands 39.1 mm from the truth, 1.42 - of the side view's pixels (Blender builds the cage's vertices up to 15.1 mm inside it, the bevel; a - stroke stands up to 2.5 px from the truth's projection). With every traced point 1 px off, twelve draws: - 68.6 mm at the median, 96.1 at most; 2 px: 125.1 and 190.1. That is 3.5 x the noise x the coarser view's - pixel, and the bounds are tolerances 1.2 over it: no mutant is claimed by a margin here (M1 reads 49.3, - 116.6 and 206.5, under 1.3 away). M3 lands the ridge off x = 0 and is refused. The same readings are 4.6 - to 7.5 x noise x a view-decided corner's m_per_px, and a seam corner's m_per_px (0.0008) says nothing of - its 98 mm: m_per_px is a depth sensitivity, and most of this error lies across the sight line.""" + The traces are the fixture's takes (tests/fixtures/spectre_truth.json says how): a search for the + strongest brightness step across each edge, from a seed that is not on the answer. Six families of twelve + draws: the truth's projection moved as one by 0.5, 1 and 1.5 px in a drawn direction (a 2.5 px window), + and each of its vertices moved by a normal draw of 1 and 2 px (3.5 px) and of 3 px (6 px). Such a take's + points stand 2.1 to 30.7 px from the truth's projection, 6.8 at the median: a stroke ends where it + crosses its neighbours, and two that run nearly along each other cross far off. 62 of the 72 block (12, + 12, 11, 10, 10, 7 by family; nine are refused at a side not explained at six points, one at the cage's + parser), every one with the ridge's six corners decided by the mirror plane and the outer edge's five by + the views (prior_share 0.037 at most). + + What holds: a blocked plate's worst corner stands within 1.18 x its take's worst point x the coarser + view's pixel (1.12, 1.16, 1.18, 1.04, 1.06, 1.11 by family), 33 to 929 mm, 142 at the median; the bound is + a tolerance 1.2 over that, and no mutant is claimed by a margin (M1 reads 1.31). No family stands out of + it: the three draws that grow a side stand at 0.51, 0.75 and 1.08. M3 lands the ridge off x = 0 and every + take is refused. No bound is stated in the takes' rms: a take's worst corner follows its worst point, + and against the rms the same readings reach 5.3. A search seeded on the truth's projection itself is no + reading: its 2.5 px window ends its strokes 2.5 px off and its plate 39 mm off.""" corners = ["ridge_rear", "r4", "r3", "r2", "r1", "nose", "a", "b", "c", "d", "e"] views, plate, traces, sides, (fixture, record) = rendered("roof", corners) middle = np.mean(list(record["truth"].values()), axis=0) pixel = max(float(np.linalg.norm(np.array(cam["C"]) - middle)) / cam["f"] for cam in fixture["cameras"].values()) self.assertAlmostEqual(pixel, 0.0276, places=4) - out = core.block_plate(views, plate, traces, kit.sheet) - self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["mirror"] * 6 + ["views"] * 5) - self.assertLess(max(corner["prior_share"] for corner in out["corners"]), core.VIEWS / 1.2) - self.assertGreater(min(corner["parallax_deg"] for corner in out["corners"][6:]), 59) - self.assertEqual([side["points"] for side in out["sides"]], [2] * 11) - self.assertEqual(float(np.abs(np.array(out["sheet"]["verts"])[:6, 0]).max()), 0.0) - self.assertLess(off_rendered(out, sides)[0], 1.7 * pixel) - for sigma in (1.0, 2.0): - worst = [] - for seed in range(12): - views, plate, traces, sides, _ = rendered("roof", corners, sigma, seed=seed) - worst.append(off_rendered(core.block_plate(views, plate, traces, kit.sheet), sides)[0]) - self.assertLess(max(worst), 4.2 * sigma * pixel, sigma) - self.assertLess(float(np.median(worst)), 2.8 * sigma * pixel, sigma) + self.assertEqual(len(record["takes"]), 72) + blocked = 0 + for take in range(len(record["takes"])): + views, plate, traces, sides, _ = rendered("roof", corners, take=take) + try: + out = core.block_plate(views, plate, traces, kit.sheet) + except core.ReferenceFitError: + continue + blocked += 1 + self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["mirror"] * 6 + ["views"] * 5, take) + self.assertLess(max(corner["prior_share"] for corner in out["corners"]), core.VIEWS / 1.2, take) + self.assertGreater(min(corner["parallax_deg"] for corner in out["corners"][6:]), 59, take) + self.assertEqual(max(abs(float(np.array(out["sheet"]["verts"])[chain[0], 0])) for chain in crown_chains(out)[:6]), 0.0, take) + self.assertLess(off_rendered(out, sides)[0], 1.42 * off_projection(fixture, record, take) * pixel, take) + self.assertGreaterEqual(blocked, 52) def test_fairness_is_set_by_the_rendered_roof(self): """fair (Soul s1, fair-default-tuned-to-a-fit), F5, M4, M2. The rendered roof with four corners named @@ -1054,7 +1083,10 @@ class BlockTests(unittest.TestCase): of 196.9 and 369.5, separation 1.37 each side. Over ten cells of known truth at 1 and 2 px (this roof four ways, and the bowed pentagon at 60 and 30 degrees and in one view) the mean of the cells' 90th percentiles reads 194, 184, 178, 178, 179, 186, 193, 196 mm at FAIR 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 1 and the - worst draw 301, 275, 273, 272, 312, 382, 494, 577: 0.2 stands at the low of both. From exact traces weaker + worst draw 301, 275, 273, 272, 312, 382, 494, 577, over the draws that blocked: 19, 20, 23, 24, 24, 25, + 26, 27 of the 168 are refused and counted in neither. On Soul's seeds (verdict cut-trace-block.s2) 0.2 is + again lowest by the 90th percentile and not by the worst draw. The roof's strokes here are the fixture's + own, searched from the truth's projection, with the noise added on top. From exact traces weaker fairness is nearer the truth (the bowed pentagon: 41.6 mm at 0.2, 16.2 at 0.5, 12.1 with none); nobody traces exactly, and at 1 px the difference is 16 mm at 60 degrees and the other way at 30.""" corners = ["ridge_rear", "nose", "a", "e"] From c430a6e46460e558c8c73f84cc4ad6d544143e9e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 13:00:47 +0100 Subject: [PATCH 200/223] tests/test_reference.py, docs/reference.md: the rendered roof's bound read where a trace has no outlier, every point as far off the truth's projection: 1.505 with each view moved as one (144 directions), 1.58 and 1.67 searched by stroke and by point, M1 2.865; worst corner <= 2.08 x the worst traced point x the coarser pixel, the geometric mean, on one plate and one pair of views; eight families of takes named (1.11 to 1.33), FAIR 0.2 a point on a plateau 0.1 to 0.3, START's upper reading between 1.22 and 1.23 (cut trace-block, Soul s3) Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/core.py | 2 +- surfaces/blender/docs/reference.md | 64 ++++++++++------ .../blender/tests/fixtures/spectre_truth.json | 2 +- surfaces/blender/tests/test_reference.py | 74 ++++++++++++++----- 4 files changed, 100 insertions(+), 42 deletions(-) diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index 18af047..eba3289 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -748,7 +748,7 @@ def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=TOL): FAIR = 0.2 # a side's second differences of this share of its chord cost what one pixel of miss does (0.02 held a bowed side straight; docs/reference.md) K_MAX = 6 # points a side grows to before its trace is refused as fit_runs refuses it SQUARE = 0.4 # the cosine between a plane's normal and a sight line under which a trace is not lifted onto it: past 66 degrees the lift stretches over 2.5 times -START = 1.0 # a corner's views start it where one pixel moves their meeting point less than this x share x the plate's extent, the prior's own scale: past it the views alone hold the corner looser than the plane would. 1 is the prior's own unit, not a derived value: tests/test_reference.py BlockTests pins it between a plate that must block (its third corner starts at 0.831, views 16.5 degrees apart at Paladin's lens and range) and one that must be refused (1.241, 11 degrees) +START = 1.0 # a corner's views start it where one pixel moves their meeting point less than this x share x the plate's extent, the prior's own scale: past it the views alone hold the corner looser than the plane would. 1 is the prior's own unit, not a derived value: tests/test_reference.py BlockTests pins it between a plate that must block (its third corner starts at 0.831, views 16.5 degrees apart at Paladin's lens and range) and one that must be refused (11 degrees: it turns to blocked between 1.22 and 1.23) VIEWS = 0.2 # a prior_share under this: the views decide the point (fit_shell's line) FLARE, DROP, DOME = 0.05, 0.06, 0.017 # of the crown's extent (its two furthest points): a plate's skirt out from and back of its crown, and its centre's rise. A template's proportions, not readings: the crown is what is solved TRACE_KEYS = ("camera", "box", "frame", "from", "to", "side", "line") diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index 8fc71b9..24d0846 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -297,7 +297,7 @@ Where a corner's depth comes from, in this order: plane would and are not used as its start. That factor of 1 is the prior's own unit, not a derived value; the tests pin it between a plate that blocks and one that is refused. The line is metres a pixel, so it moves with lens and range: a 1.2 m plate 17.6 m off at 663 px has three corners started at 0.72 of the scale with - its views 19 degrees apart, 0.83 at 16.5, 1.24 at 11 and 2.73 at 5. With no plane given it blocks down to + its views 19 degrees apart, 0.83 at 16.5, between 1.22 and 1.23 at 11 and 2.73 at 5. With no plane given it blocks down to 16.5 degrees (73 mm from the truth) and is refused at 11, where it would have stood 104 mm off: the line switches blocking and refusal, it is no cliff in accuracy. At 5 degrees its corners landed 0.25 to 1.5 m off; through a lens three times as long it starts at 0.65 at 7 degrees and blocks. @@ -354,30 +354,45 @@ side view's pixel is 27.6 mm across at the plate. How the traces were taken. No hand drew them. A search follows a seed polyline, takes the strongest brightness step within a window across each edge, lays a straight stroke through the steps found on each segment, and ends -each stroke where it crosses its neighbours. The seed is the truth's projection moved off the answer, twelve -draws a family: the whole seed by 0.5, 1 or 1.5 px in a drawn direction (a 2.5 px window), or each of its -vertices by a normal draw of 1 or 2 px (3.5 px) or 3 px (6 px). The takes' points end up 2.1 to 30.7 px from the -truth's projection, 6.8 at the median: two strokes that run nearly along each other cross far from the corner. -Every corner is named. +each stroke where it crosses its neighbours. The seed is the truth's projection moved off the answer, in eight +families: the whole seed by 0.5, 1 or 1.5 px in a drawn direction (a 2.5 px window), or each of its vertices by +a normal draw of 1 or 2 px (3.5 px), 2 px (5 px), 3 px (6 px) or 4 px (8 px). Every corner is named. A take's +worst point stands far from the truth's projection, 3 to 12 px at the families' medians: two strokes that run +nearly along each other cross far from the corner. Forty fresh draws a family (the fixture holds twelve of +each of six, 72 takes, which the test blocks; the 2 px, 5 px and the 4 px, 8 px families are in neither): -| seed | window | blocked of 12 | worst traced point, px: median, most | worst corner, mm: median, most | worst corner over worst point x 27.6 mm, at most | +| seed | window | blocked of 40 | worst traced point, px: median, most | worst corner, mm: median, most | worst corner over worst point x 27.6 mm, at most | | --- | --- | --- | --- | --- | --- | -| moved 0.5 px as one | 2.5 px | 12 | 6.5, 30.7 | 173, 929 | 1.12 | -| moved 1 px as one | 2.5 px | 12 | 7.1, 30.4 | 225, 916 | 1.16 | -| moved 1.5 px as one | 2.5 px | 11 | 6.6, 16.5 | 148, 450 | 1.18 | -| each vertex 1 px | 3.5 px | 10 | 4.8, 15.9 | 79, 458 | 1.04 | -| each vertex 2 px | 3.5 px | 10 | 5.3, 17.6 | 131, 342 | 1.06 | -| each vertex 3 px | 6 px | 7 | 10.2, 20.1 | 215, 436 | 1.11 | +| moved 0.5 px as one | 2.5 px | 40 | 3.4, 30.2 | 47, 913 | 1.11 | +| moved 1 px as one | 2.5 px | 39 | 3.5, 30.4 | 67, 916 | 1.15 | +| moved 1.5 px as one | 2.5 px | 39 | 3.6, 24.9 | 66, 370 | 1.19 | +| each vertex 1 px | 3.5 px | 35 | 8.5, 28.2 | 171, 559 | 1.13 | +| each vertex 2 px | 3.5 px | 35 | 9.1, 28.8 | 153, 745 | 1.14 | +| each vertex 2 px | 5 px | 30 | 9.4, 41.5 | 170, 512 | 1.25 | +| each vertex 3 px | 6 px | 17 | 10.2, 73.6 | 231, 2038 | 1.15 | +| each vertex 4 px | 8 px | 8 | 12.0, 29.0 | 322, 417 | 1.33 | -What holds: the worst corner of a blocked plate stood within about 1.2 x the furthest any traced point stood -from the truth's projection x the coarser view's pixel (1.18 over the 62 that blocked, which the test holds to -1.42). No family stands out of it, and the three draws that grew a side read 0.51, 0.75 and 1.08. It is a -reading on one plate and one pair of views, not a law, and it says a plate is as good as its worst traced -point: one stroke end 30 px off puts a corner 0.9 m off, and nothing in the report says so, because that trace -is explained. The ten not blocked were refused, nine at a side not explained at six points and one at the -cage's parser. No bound is given in the traces' rms: against it the same readings run 0.57 to 5.3. The same -search seeded on the truth's projection itself, with a 2.5 px window, reads 39 mm; that is the window ending -every stroke within 2.5 px of the answer, and it is not an accuracy. +The fixture's 72 takes read 1.18 at most (62 block; nine are refused at a side not explained at six points, +one at the cage's parser). These ratios are not the bound. A take's worst point is one far crossing, and it +inflates what the corner is measured against: the worst a trace does for its worst point is to have no +outlier, every point the same d px off the truth's projection. With no search, the truth's projection moved: + +| every traced point d px off | worst corner over d x 27.6 mm, at most | +| --- | --- | +| each view moved as one, 12 directions by 12, at 1, 2, 3 px (all 144 block) | 1.505, 1.504, 1.502 (1.10 at the median) | +| each stroke its own direction, searched | 1.58 | +| each point its own direction, searched, at 1 and 3 px | 1.67, 1.66 | + +The bound: worst corner <= 2.08 x d x pixel, d the furthest any traced point stands from the truth's +projection and pixel the coarser view's. 2.08 is the geometric mean of the 1.505 and of 2.865, what the +blocking reads on the same 144 without its end terms; it stands 1.25 over the worst a search found, which is +not the worst there is, and 1.57 over the worst family of takes. The test holds the 144, the searched worst +at 1 and 3 px and the 72 takes to it. It is a reading on one plate through one pair of views, 62 degrees +apart, not a law, and it says a plate is as good as its worst traced point: one stroke end 30 px off puts a +corner 0.9 m off, and nothing in the report says so, because that trace is explained. No bound is given in +the traces' rms: against it the fixture's takes run 0.57 to 5.3. The same search seeded on the truth's +projection itself, with a 2.5 px window, reads 39 mm; that is the window ending every stroke within 2.5 px of +the answer, and it is not an accuracy. The error is not a multiple of `m_per_px` either: a seam corner 98 mm off reports 0.0008 m a pixel, because `m_per_px` is depth along the sight line and most of this error lies across it. With only four corners named, @@ -399,7 +414,10 @@ refused, which no percentile counts: A higher FAIR, which is weaker fairness, refuses more draws, so each column's percentiles are over a different set. On other seeds (Soul's probe, verdict cut-trace-block.s2, FAIR 0.1, 0.2, 0.3, 0.5) the mean 90th percentile read 216, 188, 216, 250, the worst draw 542, 855, 679, 807 and the refused 18, 21, 26, -27: 0.2 is lowest by the 90th percentile on both sets of seeds and not by the worst draw on the second. From +27; on a third (verdict cut-trace-block.s3, all eight) 196, 196, 195, 202, 199, 220, 234, 255, the worst draw +652, 876, 690, 843, 871, 500, 673, 741 and the refused 10, 15, 20, 20, 22, 22, 23, 23. FAIR is flat from 0.1 +to 0.3 and worse above: 0.2 and 0.25 tie in the table, and 0.1 to 0.2 stand within 1 mm on the third set. 0.2 +is kept as a point on that plateau, not a resolved lowest. From exact traces weaker fairness is nearer the truth (a pentagon bowed 35% of its sides: 42 mm at 0.2, 16 at 0.5, 12 with none). diff --git a/surfaces/blender/tests/fixtures/spectre_truth.json b/surfaces/blender/tests/fixtures/spectre_truth.json index dcd97e4..590a4fd 100644 --- a/surfaces/blender/tests/fixtures/spectre_truth.json +++ b/surfaces/blender/tests/fixtures/spectre_truth.json @@ -1 +1 @@ -{"note":"SPECTRE's roof (spectre_cages.roof at nibu/fable-spectre-3 14d834c: a hard mirrored cage of 11 vertices) built by brokkr_kitbash.shell at one level with the hull's jaw, flank and cheeks (thickness 0.1, bevel 0.016), rendered by Blender 5.3's Workbench through spectre_skel.cameras() at the sheet's own pixel size (hero 756 x 706, side 264 x 348), the hull posed per view by frames. truth is the cage: Blender built each of its vertices within built_off_m of it (the bevel). One plate, one pair of views. A stroke is an edge of the roof traced from a render by a search, not projected: along a seed polyline the drawn edge is the strongest brightness step within reach px across it, a straight stroke is laid through the steps found on each segment, and strokes meet where they cross. Every seed here is made from the truth's projection, so no trace here is a hand's. takes are that search from a seed that is not on the answer, twelve draws a family (families): offset_px moves the whole seed that far in a drawn direction, jitter_px moves each seed vertex by a normal draw of that many px, reach_px is the window. A take's lines are its strokes in the order of strokes. How far a take's points stand from the truth's projection is not stored: read it from truth and cameras. The accuracy readings are taken from takes. strokes[].line is the same search seeded on the truth's projection itself with a 2.5 px window: every point stands within 2.5 px of the answer because the window ends there (off_projection_px), so it measures no accuracy; it is the base the fairness readings add noise to. drawn is the least share of a segment's length where a step was found. The ridge is traced in the side view only: the hero draws no step along it (its two facets shade alike). closing marks the strokes an agent closes the outline with (the rear edge, and the lip in the side view, half drawn).","cameras":{"hero":{"C":[-9.721115556958573,18.859090658741355,5.242272804029844],"R":[[-0.862189601405842,-0.5065857195259607,0.0],[0.034125232508362004,-0.05807984607580026,0.9977285201827507],[-0.5054350202883507,0.8602311551276064,0.06736319480204615]],"f":1785.0,"c":[378.0,353.0]},"side":{"C":[60.84416742645475,1.422308134553987,3.13474760877321],"R":[[3.061616997868383e-16,1.0,0.0],[0.011634411213376642,-3.5620111131064444e-18,0.9999323179474289],[0.9999323179474289,-3.0614097813457806e-16,-0.011634411213376642]],"f":2200.0,"c":[892.0,532.0]}},"frames":{"hero":[[1.0,0.0,0.0,0.0],[0.0,0.9986295347545738,0.052335956242943835,-0.2773805680876023],[0.0,-0.052335956242943835,0.9986295347545738,0.007263465800758873],[0.0,0.0,0.0,1.0]],"side":[[1.0,0.0,0.0,0.0],[0.0,1.0,0.0,0.0],[0.0,-0.0,1.0,0.0],[0.0,0.0,0.0,1.0]]},"plates":{"roof":{"loop":["ridge_rear","r4","r3","r2","r1","nose","a","b","c","d","e"],"seam":["ridge_rear","r4","r3","r2","r1","nose"],"truth":{"nose":[0.0,3.33,6.34],"r1":[0.0,2.82,6.735],"r2":[0.0,1.76,7.05],"r3":[0.0,1.0,7.5],"r4":[0.0,-0.8,7.8],"ridge_rear":[0.0,-1.9,7.95],"a":[0.77,2.57,6.475],"b":[0.6,1.9,6.83],"c":[0.69,1.0,7.34],"d":[0.64,-0.8,7.65],"e":[0.62,-1.9,7.8]},"built_off_m":0.0151,"strokes":[{"view":"side","side":1,"through":["ridge_rear","r4","r3","r2","r1","nose"],"line":[[772.01,383.39],[811.74,388.89],[876.96,399.88],[904.51,416.13],[941.84,427.31],[961.08,441.58]],"closing":false,"drawn":1.0,"off_projection_px":0.69},{"view":"hero","side":-1,"through":["nose","a"],"line":[[325.08,142.53],[427.02,126.4]],"closing":false,"drawn":1.0,"off_projection_px":0.86},{"view":"side","side":1,"through":["nose","a"],"line":[[961.51,439.35],[933.43,437.76]],"closing":true,"drawn":0.53,"off_projection_px":2.49},{"view":"hero","side":-1,"through":["a","b","c","d","e"],"line":[[426.46,125.71],[442.01,93.62],[487.59,47.65],[551.9,26.85],[587.64,18.75]],"closing":false,"drawn":0.71,"off_projection_px":0.98},{"view":"side","side":1,"through":["a","b","c","d","e"],"line":[[933.68,435.98],[908.72,424.05],[876.26,405.25],[810.61,394.34],[770.7,387.55]],"closing":false,"drawn":0.76,"off_projection_px":1.64},{"view":"hero","side":-1,"through":["e","ridge_rear"],"line":[[587.54,18.26],[541.95,9.26]],"closing":true,"drawn":1.0,"off_projection_px":0.09},{"view":"side","side":1,"through":["e","ridge_rear"],"line":[[769.96,387.04],[772.42,383.77]],"closing":true,"drawn":1.0,"off_projection_px":0.82}],"families":{"offset 0.5":{"offset_px":0.5,"jitter_px":0.0,"reach_px":2.5},"offset 1":{"offset_px":1.0,"jitter_px":0.0,"reach_px":2.5},"offset 1.5":{"offset_px":1.5,"jitter_px":0.0,"reach_px":2.5},"jitter 1":{"offset_px":0.0,"jitter_px":1.0,"reach_px":3.5},"jitter 2":{"offset_px":0.0,"jitter_px":2.0,"reach_px":3.5},"jitter 3":{"offset_px":0.0,"jitter_px":3.0,"reach_px":6.0}},"takes":[{"family":"offset 0.5","lines":[[[772.2,383.42],[811.92,388.9],[876.83,399.81],[904.5,416.12],[941.9,427.27],[961.01,441.57]],[[325.38,142.38],[427.34,126.41]],[[961.4,440.48],[933.67,437.39]],[[427.13,125.47],[441.7,94.0],[487.6,47.66],[552.26,26.84],[587.98,18.69]],[[933.75,435.9],[907.77,423.92],[886.76,406.74],[810.85,394.02],[770.76,388.61]],[[587.72,18.19],[542.1,9.36]],[[769.97,386.53],[772.44,383.26]]]},{"family":"offset 0.5","lines":[[[772.44,383.47],[812.17,388.91],[876.72,399.75],[904.86,416.32],[941.65,427.12],[961.25,441.79]],[[325.56,142.4],[427.51,126.37]],[[961.82,439.84],[933.81,437.93]],[[427.74,125.91],[442.92,92.86],[487.36,47.76],[552.41,26.85],[588.09,18.5]],[[934.12,435.85],[909.12,424.03],[846.1,400.04],[811.15,393.65],[771.07,388.12]],[[587.95,18.37],[542.38,9.29]],[[769.95,386.71],[772.42,383.44]]]},{"family":"offset 0.5","lines":[[[772.32,383.47],[812.07,388.87],[876.79,399.78],[904.63,416.24],[942.07,427.3],[961.38,441.96]],[[325.27,142.42],[427.22,126.4]],[[960.78,443.98],[934.02,436.83]],[[427.91,126.68],[443.16,92.38],[487.75,47.59],[552.04,26.8],[587.79,18.66]],[[934.41,435.5],[908.74,424.97],[876.48,405.41],[811.05,393.6],[771.07,387.23]],[[587.88,18.31],[542.29,9.34]],[[770.14,387.44],[771.99,383.96]]]},{"family":"offset 0.5","lines":[[[771.89,383.3],[811.61,388.91],[876.95,399.87],[904.42,416.1],[942.18,427.41],[961.12,441.73]],[[324.82,142.53],[426.77,126.48]],[[961.4,439.48],[933.35,437.72]],[[426.07,126.07],[442.1,93.47],[487.78,47.57],[551.62,27.02],[587.32,18.64]],[[933.81,435.81],[908.63,424.33],[876.73,405.49],[810.58,393.7],[770.64,387.08]],[[587.45,18.21],[541.85,9.28]],[[770.15,387.64],[772.01,384.16]]]},{"family":"offset 0.5","lines":[[[772.21,383.42],[811.93,388.9],[876.98,399.83],[904.42,416.1],[941.91,427.28],[961.02,441.57]],[[325.39,142.37],[427.35,126.43]],[[961.41,440.49],[933.68,437.39]],[[426.58,125.21],[441.98,93.74],[487.53,47.69],[552.27,26.85],[587.99,18.69]],[[933.76,435.91],[907.78,423.92],[886.77,406.75],[810.86,394.02],[770.77,388.62]],[[587.73,18.21],[542.12,9.34]],[[769.98,386.54],[772.45,383.27]]]},{"family":"offset 0.5","lines":[[[771.65,383.25],[811.36,388.87],[876.64,399.62],[904.14,415.98],[942.73,427.49],[960.43,441.62]],[[324.82,142.51],[426.77,126.49]],[[960.88,440.26],[933.14,437.24]],[[426.31,125.41],[442.09,93.58],[487.52,47.7],[551.72,27.03],[587.38,18.65]],[[932.92,436.43],[908.62,423.23],[876.42,405.26],[810.29,393.97],[770.2,388.47]],[[587.15,18.2],[541.58,9.14]],[[769.87,386.74],[772.33,383.47]]]},{"family":"offset 0.5","lines":[[[772.49,383.45],[812.22,388.9],[876.83,399.77],[904.9,416.37],[942.01,427.24],[961.3,441.88]],[[325.57,142.42],[427.52,126.36]],[[961.99,439.4],[933.83,438.1]],[[427.84,126.06],[443.72,92.04],[487.52,47.65],[552.38,26.76],[588.13,18.66]],[[934.21,435.86],[909.1,424.23],[865.97,403.51],[811.19,393.71],[771.19,387.54]],[[588.0,18.41],[542.43,9.29]],[[769.98,386.83],[772.44,383.56]]]},{"family":"offset 0.5","lines":[[[771.68,383.23],[811.38,388.85],[876.76,399.69],[903.91,415.88],[942.71,427.54],[960.46,441.6]],[[324.84,142.49],[426.8,126.51]],[[960.91,440.24],[933.16,437.22]],[[426.38,125.4],[442.02,93.67],[487.56,47.66],[551.75,27.01],[587.42,18.7]],[[932.95,436.41],[908.63,423.23],[876.12,405.13],[810.32,393.9],[770.22,388.5]],[[587.17,18.19],[541.59,9.18]],[[769.9,386.72],[772.36,383.45]]]},{"family":"offset 0.5","lines":[[[772.25,383.46],[811.98,388.92],[876.91,399.83],[904.47,416.14],[941.69,427.2],[961.08,441.58]],[[325.43,142.4],[427.39,126.39]],[[961.41,440.69],[933.75,437.32]],[[428.93,126.33],[440.99,94.8],[487.38,47.73],[552.32,26.89],[587.99,18.52]],[[933.56,436.42],[901.54,418.82],[886.96,406.9],[810.91,394.03],[770.82,388.56]],[[587.76,18.29],[542.17,9.3]],[[770.03,386.57],[772.49,383.3]]]},{"family":"offset 0.5","lines":[[[771.53,383.24],[811.24,388.84],[876.58,399.58],[904.17,416.02],[942.85,427.52],[960.44,441.65]],[[324.62,142.52],[426.58,126.51]],[[960.9,439.76],[932.95,437.6]],[[426.45,125.79],[441.79,93.8],[487.6,47.65],[551.53,27.17],[587.16,18.59]],[[932.88,436.46],[908.59,423.25],[875.88,405.1],[810.15,394.08],[770.1,388.35]],[[587.06,18.11],[541.47,9.15]],[[769.95,387.07],[772.41,383.8]]]},{"family":"offset 0.5","lines":[[[772.42,383.43],[812.16,388.89],[876.93,399.84],[904.27,416.12],[942.08,427.28],[961.16,441.84]],[[325.55,142.39],[427.5,126.39]],[[961.81,439.81],[933.8,437.89]],[[427.99,126.0],[443.14,92.61],[487.44,47.72],[552.39,26.8],[588.14,18.74]],[[934.1,435.81],[909.17,423.85],[846.58,400.19],[811.09,393.93],[771.07,387.95]],[[587.93,18.35],[542.35,9.31]],[[769.94,386.67],[772.4,383.4]]]},{"family":"offset 0.5","lines":[[[772.33,383.51],[812.08,388.88],[876.82,399.78],[904.64,416.23],[942.09,427.29],[961.32,442.05]],[[325.28,142.4],[427.24,126.39]],[[960.8,443.97],[934.04,436.82]],[[427.93,126.67],[443.15,92.44],[487.67,47.63],[552.06,26.82],[587.8,18.6]],[[934.42,435.49],[908.75,424.96],[876.43,405.39],[811.06,393.59],[771.09,387.21]],[[587.89,18.32],[542.3,9.33]],[[770.16,387.43],[772.01,383.95]]]},{"family":"offset 1","lines":[[[772.38,383.52],[812.11,388.89],[876.84,399.81],[904.83,416.31],[942.18,427.33],[960.91,441.6]],[[325.71,142.43],[427.64,126.27]],[[961.44,440.94],[933.91,436.99]],[[428.47,125.55],[441.32,94.29],[487.61,47.67],[552.65,26.96],[588.05,17.44]],[[933.56,436.34],[910.35,421.18],[883.52,404.14],[811.37,391.86],[771.25,386.44]],[[587.86,18.35],[542.28,9.3]],[[770.86,386.31],[772.71,382.84]]]},{"family":"offset 1","lines":[[[772.88,383.51],[812.61,388.99],[876.65,399.68],[904.32,416.04],[942.18,427.32],[961.32,442.13]],[[326.04,142.31],[427.99,126.28]],[[962.04,440.73],[934.48,436.94]],[[428.18,125.72],[444.66,90.92],[487.59,47.69],[552.89,26.74],[588.51,18.1]],[[934.37,436.1],[907.56,423.63],[893.73,408.05],[811.51,394.23],[771.43,388.8]],[[588.36,18.49],[542.8,9.39]],[[770.34,386.51],[772.19,383.03]]]},{"family":"offset 1","lines":[[[772.65,383.46],[812.39,388.94],[876.82,399.73],[904.34,416.05],[942.59,427.45],[961.6,442.44]],[[325.47,142.41],[427.42,126.35]],[[961.0,444.6],[934.13,437.91]],[[427.59,126.83],[445.86,89.66],[487.8,47.56],[552.21,26.89],[587.94,18.52]],[[934.72,435.82],[909.21,425.01],[876.03,405.2],[811.39,393.52],[771.33,387.7]],[[588.2,18.5],[542.65,9.31]],[[769.78,387.65],[772.25,384.38]]]},{"family":"offset 1","lines":[[[771.77,383.24],[811.49,388.88],[876.89,399.84],[904.68,416.21],[942.07,427.36],[961.19,441.87]],[[324.56,142.56],[426.51,126.49]],[[959.98,445.09],[933.45,436.97]],[[426.3,126.73],[441.67,94.0],[487.55,47.72],[551.34,27.15],[587.03,18.65]],[[933.85,435.82],[908.65,424.4],[876.74,405.47],[810.48,393.57],[770.52,386.97]],[[587.34,18.23],[541.76,9.21]],[[770.27,388.2],[770.89,384.31]]]},{"family":"offset 1","lines":[[[772.4,383.5],[812.13,388.9],[876.76,399.76],[904.85,416.33],[942.01,427.29],[960.92,441.62]],[[325.72,142.4],[427.66,126.28]],[[961.46,440.95],[933.93,437.01]],[[428.01,125.33],[442.44,93.14],[487.66,47.67],[552.66,26.92],[588.11,17.62]],[[933.58,436.35],[910.33,421.26],[883.76,404.19],[811.39,391.87],[771.26,386.46]],[[587.88,18.34],[542.3,9.3]],[[770.87,386.32],[772.73,382.85]]]},{"family":"offset 1","lines":[[[771.27,383.3],[811.0,388.69],[876.81,399.69],[904.09,415.97],[942.56,427.46],[960.12,441.21]],[[324.56,142.57],[426.51,126.52]],[[960.58,439.78],[932.8,436.92]],[[426.52,125.27],[441.98,93.72],[487.52,47.66],[551.5,27.03],[587.16,18.71]],[[932.95,435.37],[907.74,423.91],[875.71,405.13],[810.04,392.94],[770.09,386.54]],[[586.76,18.15],[541.19,9.06]],[[770.02,386.52],[772.49,383.25]]]},{"family":"offset 1","lines":[[[772.97,383.51],[812.69,389.02],[876.68,399.67],[904.44,416.06],[942.77,427.5],[961.42,442.31]],[[326.06,142.3],[428.01,126.29]],[[962.46,439.42],[934.42,437.65]],[[428.37,126.02],[444.86,90.74],[487.7,47.65],[552.88,26.74],[588.51,18.09]],[[934.28,436.62],[909.84,423.7],[865.62,403.38],[811.61,394.21],[771.51,388.82]],[[588.46,18.51],[542.9,9.39]],[[770.0,386.61],[772.47,383.35]]]},{"family":"offset 1","lines":[[[771.32,383.28],[811.04,388.72],[876.68,399.65],[904.47,416.1],[942.73,427.49],[960.11,441.26]],[[324.61,142.54],[426.56,126.51]],[[960.5,440.31],[932.82,436.99]],[[426.55,125.22],[442.02,93.68],[487.58,47.65],[551.59,27.15],[587.15,18.42]],[[932.67,435.98],[908.29,422.93],[846.42,400.1],[810.09,392.9],[770.14,386.5]],[[586.81,18.11],[541.22,9.13]],[[770.07,386.48],[772.54,383.21]]]},{"family":"offset 1","lines":[[[772.51,383.46],[812.23,388.91],[876.74,399.77],[904.73,416.26],[941.61,427.14],[961.08,441.58]],[[325.8,142.4],[427.74,126.26]],[[961.72,440.29],[933.92,437.49]],[[428.2,125.45],[442.54,93.09],[487.55,47.71],[552.68,26.71],[588.39,18.56]],[[933.79,436.17],[910.34,421.48],[884.05,404.29],[811.47,391.93],[771.35,386.52]],[[587.97,18.39],[542.4,9.31]],[[770.96,386.39],[772.82,382.91]]]},{"family":"offset 1","lines":[[[771.02,383.27],[810.76,388.68],[876.86,399.74],[904.4,416.13],[942.65,427.42],[960.08,441.36]],[[324.18,142.65],[426.12,126.55]],[[960.37,439.85],[932.44,437.61]],[[426.31,125.81],[441.98,93.65],[487.56,47.71],[551.09,27.16],[586.76,18.83]],[[933.06,435.03],[907.48,424.33],[876.4,405.34],[809.73,393.46],[769.76,387.12]],[[586.56,18.08],[540.99,9.0]],[[769.94,387.09],[772.41,383.82]]]},{"family":"offset 1","lines":[[[772.84,383.49],[812.57,388.93],[876.79,399.72],[904.29,416.07],[942.26,427.34],[961.29,442.06]],[[326.02,142.33],[427.97,126.29]],[[961.99,440.73],[934.44,436.9]],[[428.18,125.66],[444.73,90.87],[487.62,47.63],[552.91,26.88],[588.47,17.98]],[[934.34,436.02],[907.53,423.56],[893.85,408.15],[811.5,394.0],[771.41,388.62]],[[588.32,18.48],[542.75,9.4]],[[770.54,386.51],[772.39,383.04]]]},{"family":"offset 1","lines":[[[772.68,383.48],[812.42,388.91],[876.78,399.73],[904.17,415.97],[942.84,427.54],[961.58,442.49]],[[325.51,142.42],[427.45,126.36]],[[961.07,444.43],[934.13,438.01]],[[427.49,126.74],[446.69,88.83],[487.73,47.61],[552.24,26.89],[587.99,18.58]],[[934.77,435.77],[909.21,425.05],[875.82,405.12],[811.44,393.35],[771.35,387.83]],[[588.22,18.51],[542.67,9.34]],[[769.81,387.63],[772.28,384.36]]]},{"family":"offset 1.5","lines":[[[772.59,383.45],[812.3,388.9],[876.74,399.75],[904.64,416.2],[942.2,427.33],[960.82,441.61]],[[326.01,142.31],[427.96,126.27]],[[962.0,439.23],[933.97,437.4]],[[427.07,124.34],[441.96,93.73],[487.53,47.7],[552.97,26.75],[588.54,18.06]],[[933.73,436.07],[910.55,420.86],[883.11,403.6],[811.77,390.32],[771.8,383.78]],[[588.01,18.42],[542.45,9.3]],[[770.96,385.83],[773.42,382.56]]]},{"family":"offset 1.5","lines":[[[773.33,383.49],[813.03,389.11],[876.97,399.84],[904.66,416.2],[942.31,427.31],[961.51,442.32]],[[326.53,142.28],[428.47,126.17]],[[962.46,440.77],[934.8,437.37]],[[428.39,125.43],[447.02,88.59],[487.6,47.66],[553.35,26.52],[589.05,18.22]],[[934.53,436.54],[911.04,421.91],[889.4,407.36],[812.1,393.19],[772.14,386.78]],[[588.76,18.65],[543.23,9.4]],[[770.8,386.33],[772.66,382.86]]]},{"family":"offset 1.5","lines":[[[772.97,383.5],[812.71,389.0],[876.73,399.67],[904.28,416.09],[942.16,427.27],[962.07,442.61]],[[325.67,142.41],[427.61,126.31]],[[961.31,444.86],[934.5,437.91]],[[427.38,127.02],[454.3,81.22],[487.71,47.61],[552.35,26.85],[588.14,18.66]],[[935.06,436.12],[909.68,425.04],[875.86,405.06],[811.7,393.66],[771.61,388.05]],[[588.54,18.55],[542.98,9.4]],[[770.27,388.15],[770.9,384.26]]]},{"family":"offset 1.5","lines":[[[771.63,383.3],[811.37,388.86],[876.51,399.68],[904.66,416.18],[941.93,427.28],[961.35,441.87]],[[324.31,142.65],[426.24,126.48]],[[959.87,445.24],[933.24,437.5]],[[425.74,127.02],[442.09,93.56],[487.6,47.67],[551.05,27.26],[586.78,18.87]],[[933.87,435.86],[908.75,424.32],[876.43,405.31],[810.3,394.0],[770.17,388.62]],[[587.25,18.2],[541.66,9.21]],[[770.47,388.79],[770.48,384.7]]]},{"family":"offset 1.5","lines":[[[772.61,383.47],[812.33,388.92],[876.75,399.76],[904.85,416.33],[942.11,427.26],[960.85,441.63]],[[326.04,142.32],[427.99,126.26]],[[961.99,439.39],[934.01,437.36]],[[427.11,124.36],[441.9,93.83],[487.44,47.73],[552.99,26.75],[588.56,18.02]],[[933.76,436.09],[910.56,420.9],[883.16,403.62],[811.8,390.33],[771.83,383.8]],[[588.04,18.42],[542.48,9.31]],[[770.59,385.72],[773.67,382.66]]]},{"family":"offset 1.5","lines":[[[770.9,383.26],[810.62,388.7],[876.71,399.71],[904.73,416.23],[941.66,427.18],[959.91,440.69]],[[324.3,142.61],[426.25,126.53]],[[960.31,439.19],[932.23,437.57]],[[426.48,125.02],[442.21,93.48],[487.53,47.69],[551.31,27.12],[586.96,18.88]],[[932.22,435.78],[908.35,421.82],[875.6,402.76],[809.89,391.58],[769.77,386.16]],[[586.39,18.01],[540.81,9.0]],[[770.56,386.43],[772.41,382.95]]]},{"family":"offset 1.5","lines":[[[773.45,383.55],[813.16,389.14],[877.01,399.88],[904.47,416.16],[942.92,427.55],[961.64,442.62]],[[326.56,142.29],[428.5,126.17]],[[962.73,440.33],[934.88,437.75]],[[426.47,124.84],[445.79,93.32],[487.63,47.63],[553.33,26.48],[589.02,18.1]],[[934.76,436.61],[905.93,422.03],[891.61,407.68],[812.1,394.21],[772.01,388.73]],[[588.92,18.65],[543.38,9.42]],[[770.42,386.53],[772.27,383.06]]]},{"family":"offset 1.5","lines":[[[770.96,383.31],[810.7,388.65],[876.9,399.77],[904.54,416.19],[941.96,427.26],[959.9,440.75]],[[324.38,142.52],[426.34,126.56]],[[960.48,438.72],[932.22,437.88]],[[426.54,124.96],[442.16,93.59],[487.56,47.63],[551.44,27.32],[586.77,17.63]],[[932.25,435.81],[908.44,421.72],[875.67,402.7],[809.96,391.52],[769.84,386.1]],[[586.45,18.02],[540.87,8.99]],[[771.03,386.5],[772.27,382.82]]]},{"family":"offset 1.5","lines":[[[772.76,383.46],[812.48,388.91],[876.73,399.75],[904.85,416.32],[941.56,427.1],[961.09,441.59]],[[326.15,142.28],[428.11,126.27]],[[962.11,439.54],[934.17,437.34]],[[427.21,124.44],[441.83,93.91],[487.53,47.7],[553.11,26.79],[588.64,17.91]],[[933.85,436.26],[910.69,421.0],[878.05,400.54],[812.12,389.32],[771.96,383.9]],[[588.18,18.49],[542.63,9.32]],[[770.88,385.86],[773.35,382.6]]]},{"family":"offset 1.5","lines":[[[770.54,383.13],[810.25,388.72],[876.65,399.75],[904.84,416.23],[942.11,427.34],[959.96,440.76]],[[323.74,142.75],[425.66,126.57]],[[960.12,438.76],[931.82,438.03]],[[426.23,125.87],[441.87,93.85],[487.61,47.62],[550.67,27.23],[586.36,19.05]],[[932.24,435.55],[907.49,423.24],[876.19,405.23],[809.18,393.83],[769.09,388.4]],[[586.06,18.0],[540.49,8.96]],[[769.93,387.11],[772.4,383.85]]]},{"family":"offset 1.5","lines":[[[773.27,383.46],[812.97,389.09],[877.14,399.86],[904.47,416.16],[942.4,427.35],[961.41,442.28]],[[326.5,142.25],[428.45,126.21]],[[962.4,440.72],[934.75,437.28]],[[428.19,125.24],[446.87,88.77],[487.56,47.65],[553.32,26.48],[589.0,18.11]],[[934.58,436.23],[910.75,422.28],[884.29,404.35],[812.22,392.09],[772.1,386.67]],[[588.7,18.61],[543.15,9.42]],[[770.99,386.3],[772.85,382.83]]]},{"family":"offset 1.5","lines":[[[773.01,383.49],[812.75,389.03],[876.71,399.68],[904.43,416.13],[942.34,427.39],[962.07,442.64]],[[325.73,142.43],[427.66,126.27]],[[961.35,444.86],[934.48,438.14]],[[425.82,126.24],[463.98,71.46],[487.68,47.63],[552.4,26.8],[588.22,18.74]],[[935.05,436.2],[909.79,424.89],[876.13,405.22],[811.71,393.9],[771.74,387.46]],[[588.58,18.56],[543.03,9.38]],[[770.17,388.06],[771.41,384.38]]]},{"family":"jitter 1","lines":[[[772.12,383.36],[812.38,388.95],[876.64,399.72],[904.88,416.31],[941.79,427.17],[960.67,441.38]],[[322.85,142.87],[425.92,126.58]],[[959.74,444.8],[934.1,438.03]],[[425.54,126.74],[461.82,73.68],[487.52,47.72],[551.49,27.31],[586.89,17.54]],[[933.07,434.97],[908.5,424.76],[876.66,405.06],[810.0,394.04],[771.52,388.76]],[[586.68,18.04],[543.4,9.59]],[[771.0,386.99],[773.43,385.58]]]},{"family":"jitter 1","lines":[[[772.4,383.5],[811.89,388.85],[877.17,399.89],[903.95,415.96],[942.28,427.37],[961.26,441.95]],[[324.38,142.63],[426.45,126.46]],[[961.25,440.31],[932.58,437.89]],[[425.77,125.03],[444.91,94.21],[487.53,47.7],[551.82,26.91],[587.78,18.62]],[[935.34,436.46],[909.28,424.33],[873.98,403.97],[810.81,388.11],[771.26,383.55]],[[586.22,18.0],[541.69,9.22]],[[769.81,387.13],[772.6,383.31]]]},{"family":"jitter 1","lines":[[[772.14,383.41],[810.97,388.79],[876.72,399.66],[904.18,416.03],[942.62,427.52],[961.38,442.16]],[[324.86,142.52],[427.48,126.37]],[[961.93,439.36],[933.26,438.01]],[[425.78,125.2],[445.07,94.15],[487.62,47.64],[554.44,26.95],[585.42,15.2]],[[934.72,435.73],[907.97,425.3],[892.02,407.68],[810.6,394.1],[769.39,388.19]],[[588.19,18.49],[540.98,8.97]],[[770.59,388.47],[770.49,384.36]]]},{"family":"jitter 1","lines":[[[773.53,383.55],[812.05,388.92],[877.11,399.85],[904.01,415.96],[943.04,427.59],[960.8,442.08]],[[324.9,142.53],[426.05,126.56]],[[960.69,444.57],[934.41,437.42]],[[425.84,126.96],[460.45,75.05],[487.63,47.61],[553.77,26.38],[587.21,18.87]],[[933.13,435.03],[906.32,424.87],[900.15,409.21],[808.47,391.64],[770.34,382.96]],[[587.95,18.41],[541.3,9.05]],[[769.84,386.41],[772.46,383.53]]]},{"family":"jitter 1","lines":[[[771.35,383.29],[813.47,389.1],[876.84,399.78],[904.57,416.14],[942.22,427.34],[961.92,442.37]],[[325.3,142.42],[425.24,126.69]],[[958.23,445.25],[932.92,436.75]],[[425.81,125.02],[445.39,93.95],[487.56,47.68],[552.2,27.06],[588.54,17.07]],[[933.69,435.48],[907.66,424.37],[879.64,407.18],[812.35,388.44],[770.32,383.68]],[[588.41,18.58],[541.16,9.01]],[[770.02,386.77],[772.36,383.84]]]},{"family":"jitter 1","lines":[[[771.0,383.3],[811.57,388.82],[877.26,399.89],[903.83,415.9],[941.6,427.14],[960.73,441.29]],[[323.88,142.64],[427.55,126.38]],[[961.4,438.02],[932.61,438.53]],[[427.66,127.16],[444.46,91.3],[487.38,47.77],[550.45,27.25],[586.72,18.86]],[[932.98,434.89],[909.33,422.55],[876.01,399.99],[810.2,388.64],[771.36,383.21]],[[588.78,18.61],[540.1,8.81]],[[769.7,387.37],[773.51,382.26]]]},{"family":"jitter 1","lines":[[[773.21,383.5],[809.22,388.45],[876.87,399.78],[904.24,416.06],[942.28,427.33],[960.57,441.47]],[[324.19,142.65],[426.27,126.51]],[[961.76,445.52],[933.49,438.74]],[[427.35,125.79],[446.24,89.36],[487.56,47.7],[552.42,26.76],[588.72,18.56]],[[934.36,435.46],[910.15,423.01],[877.33,400.12],[811.09,388.89],[771.72,384.11]],[[587.2,18.17],[541.58,9.18]],[[770.59,388.97],[770.49,384.13]]]},{"family":"jitter 1","lines":[[[772.04,383.34],[811.34,388.87],[876.73,399.66],[904.72,416.38],[942.56,427.22],[961.26,442.33]],[[325.29,142.41],[426.89,126.44]],[[959.01,443.53],[931.63,435.84]],[[425.93,126.1],[442.08,93.63],[487.53,47.65],[549.7,27.54],[587.54,18.64]],[[932.17,435.43],[908.81,421.43],[876.17,399.37],[810.68,394.6],[769.9,388.78]],[[587.65,18.31],[540.79,8.99]],[[772.1,385.76],[772.83,383.74]]]},{"family":"jitter 1","lines":[[[770.11,383.06],[810.35,388.69],[876.85,399.77],[904.0,415.92],[941.8,427.18],[961.53,441.96]],[[325.69,142.43],[426.28,126.47]],[[960.17,445.68],[932.68,436.68]],[[427.32,126.19],[443.61,92.07],[487.58,47.61],[551.72,27.04],[585.57,19.06]],[[932.38,435.14],[909.14,424.73],[881.48,408.27],[812.99,388.6],[768.67,383.05]],[[588.52,18.48],[540.26,8.84]],[[769.95,386.66],[772.06,383.99]]]},{"family":"jitter 1","lines":[[[771.26,383.25],[810.21,388.63],[876.87,399.85],[904.86,416.34],[942.57,427.36],[960.48,441.57]],[[324.61,142.51],[427.79,126.31]],[[959.87,444.94],[933.02,438.97]],[[427.23,126.44],[447.59,88.03],[487.54,47.67],[552.98,26.98],[588.33,17.23]],[[933.74,436.09],[907.13,423.09],[876.42,405.32],[810.81,393.6],[770.83,386.95]],[[587.8,18.34],[541.61,9.14]],[[769.77,387.08],[771.22,385.51]]]},{"family":"jitter 1","lines":[[[770.81,383.25],[811.02,388.74],[876.73,399.71],[904.47,416.12],[941.58,427.12],[960.24,440.88]],[[324.76,142.51],[426.27,126.58]],[[961.62,437.4],[933.39,438.69]],[[427.97,125.83],[443.16,92.64],[487.48,47.66],[551.28,27.16],[588.41,18.41]],[[933.06,435.04],[908.57,424.73],[876.26,405.37],[810.94,393.52],[771.34,387.05]],[[586.77,18.13],[542.78,9.42]],[[769.83,388.33],[772.77,382.47]]]},{"family":"jitter 1","lines":[[[772.14,383.44],[812.87,389.03],[876.8,399.68],[903.84,415.87],[942.52,427.37],[961.73,442.59]],[[325.76,142.4],[426.57,126.45]],[[961.16,444.61],[933.48,437.89]],[[428.02,125.43],[443.38,92.34],[487.45,47.74],[551.75,26.99],[586.17,18.97]],[[934.44,436.1],[907.18,423.82],[887.59,406.88],[811.3,394.38],[771.18,382.81]],[[587.92,18.35],[542.72,9.38]],[[770.07,386.47],[770.24,383.75]]]},{"family":"jitter 2","lines":[[[772.22,383.42],[813.02,389.08],[877.05,399.84],[904.59,416.26],[942.16,427.27],[960.3,441.17]],[[320.62,143.24],[424.82,126.72]],[[959.31,444.76],[934.64,438.68]],[[426.47,128.58],[445.5,90.14],[487.52,47.67],[550.97,27.19],[586.62,18.71]],[[931.81,435.27],[909.03,423.97],[873.61,404.68],[809.39,393.84],[772.46,387.55]],[[585.88,18.0],[544.92,9.76]],[[771.27,386.68],[774.89,387.54]]]},{"family":"jitter 2","lines":[[[772.72,383.37],[812.07,388.94],[877.14,399.89],[904.05,415.94],[942.85,427.53],[961.36,442.41]],[[323.68,142.77],[425.9,126.54]],[[961.86,437.41],[931.81,437.68]],[[426.35,125.02],[463.47,72.1],[488.69,46.85],[551.76,27.09],[587.92,18.48]],[[937.39,437.12],[909.61,424.84],[873.93,403.92],[810.16,387.65],[771.27,383.47]],[[584.89,17.78],[541.42,9.12]],[[769.89,387.3],[773.03,382.91]]]},{"family":"jitter 2","lines":[[[772.31,383.54],[810.24,388.48],[877.01,399.81],[904.31,416.06],[942.28,427.38],[961.88,442.5]],[[324.64,142.57],[427.93,126.25]],[[962.58,438.38],[933.2,437.76]],[[426.71,125.46],[460.97,74.53],[487.55,47.71],[556.85,26.25],[583.7,13.9]],[[935.48,436.03],[908.63,425.74],[895.16,408.38],[810.65,393.7],[767.91,389.45]],[[589.01,18.7],[539.9,8.76]],[[770.53,389.83],[770.44,385.59]]]},{"family":"jitter 2","lines":[[[774.77,383.51],[812.31,388.96],[877.02,399.78],[901.34,413.41],[942.05,437.68],[962.28,438.4]],[[324.71,142.49],[425.08,126.77]],[[962.98,436.86],[934.82,439.43]],[[426.15,128.65],[455.08,80.49],[487.61,47.64],[555.65,25.99],[586.77,18.7]],[[932.23,434.75],[910.29,425.63],[876.12,405.29],[805.46,393.48],[769.56,381.46]],[[588.39,18.55],[540.58,8.87]],[[770.27,386.2],[773.57,382.79]]]},{"family":"jitter 2","lines":[[[770.68,383.19],[815.2,389.36],[876.91,399.81],[904.7,416.23],[942.88,427.61],[962.59,443.37]],[[325.55,142.39],[423.53,127.01]],[[956.5,445.36],[932.21,436.18]],[[428.2,126.0],[452.64,82.95],[487.62,47.57],[552.56,27.33],[589.15,14.26]],[[933.16,436.14],[907.37,422.9],[880.16,407.51],[813.21,388.35],[769.47,383.23]],[[589.34,18.74],[540.34,8.82]],[[769.9,386.78],[772.26,384.01]]]},{"family":"jitter 2","lines":[[[769.91,383.09],[811.41,388.82],[876.96,399.75],[904.05,416.01],[941.79,427.22],[960.61,441.09]],[[322.61,142.91],[428.15,126.19]],[[960.99,438.23],[932.09,438.01]],[[425.78,127.16],[441.92,93.81],[487.64,47.62],[549.02,27.66],[585.82,19.09]],[[931.92,434.56],[909.13,422.39],[875.75,399.77],[808.94,388.44],[771.43,383.27]],[[590.05,18.79],[538.21,8.49]],[[769.15,387.65],[774.61,380.81]]]},{"family":"jitter 2","lines":[[[774.25,383.74],[806.7,388.03],[877.08,399.74],[903.84,415.85],[942.88,427.62],[960.24,441.35]],[[323.3,142.75],[425.54,126.67]],[[963.41,445.83],[933.72,439.06]],[[426.45,125.05],[441.76,93.76],[488.48,46.97],[552.92,26.83],[589.76,17.79]],[[934.72,435.58],[910.76,423.29],[876.55,399.7],[810.78,388.65],[772.3,383.83]],[[587.01,18.28],[541.21,9.04]],[[770.53,390.77],[770.68,385.0]]]},{"family":"jitter 2","lines":[[[772.04,383.35],[810.99,388.76],[876.67,399.69],[904.27,416.04],[942.07,427.31],[961.93,442.45]],[[325.48,142.42],[426.79,126.5]],[[958.02,441.66],[929.53,435.11]],[[425.72,126.74],[442.17,93.54],[487.53,47.71],[547.49,28.16],[587.48,18.74]],[[930.64,434.91],[907.72,420.86],[874.99,398.69],[810.91,393.88],[769.3,388.59]],[[587.77,18.31],[539.62,8.78]],[[773.45,384.21],[773.69,383.86]]]},{"family":"jitter 2","lines":[[[768.15,382.85],[808.98,388.41],[876.69,399.8],[904.71,416.2],[941.72,427.2],[962.03,442.35]],[[326.24,142.25],[425.56,126.69]],[[960.32,446.17],[931.69,436.58]],[[426.11,125.9],[442.3,93.29],[487.69,47.6],[551.52,27.14],[583.6,19.56]],[[931.32,435.1],[909.68,424.59],[883.45,409.45],[814.46,388.63],[766.09,382.63]],[[589.49,18.74],[538.56,8.47]],[[770.15,386.19],[772.58,383.54]]]},{"family":"jitter 2","lines":[[[770.52,383.19],[808.68,388.4],[877.07,399.89],[904.05,415.88],[942.03,427.3],[960.77,441.44]],[[324.08,142.73],[428.53,126.12]],[[959.55,444.87],[932.91,438.85]],[[427.32,126.84],[444.7,91.11],[487.49,47.63],[553.94,26.59],[589.34,17.06]],[[933.98,436.05],[905.41,422.34],[876.53,405.42],[810.8,394.29],[771.62,382.7]],[[588.12,18.47],[541.22,9.02]],[[768.8,386.86],[770.48,387.39]]]},{"family":"jitter 2","lines":[[[769.62,383.0],[810.3,388.67],[876.94,399.84],[904.47,416.13],[941.53,427.09],[959.33,440.25]],[[324.45,142.6],[425.53,126.64]],[[961.58,437.66],[933.45,439.23]],[[426.83,124.71],[441.87,93.83],[487.56,47.62],[550.65,27.23],[589.22,18.29]],[[932.17,435.12],[909.07,424.02],[876.09,405.26],[811.14,393.67],[771.95,386.79]],[[586.02,18.03],[543.61,9.53]],[[768.83,389.33],[773.87,381.4]]]},{"family":"jitter 2","lines":[[[772.16,383.35],[814.04,389.19],[876.79,399.72],[904.99,416.37],[941.48,427.02],[962.78,443.02]],[[326.44,142.28],[426.14,126.54]],[[962.08,444.53],[933.49,438.01]],[[427.13,124.01],[442.1,93.45],[488.28,47.22],[551.55,27.04],[584.71,19.31]],[[935.11,436.57],[903.98,421.78],[887.88,406.88],[811.89,394.99],[771.11,382.08]],[[588.3,18.5],[543.37,9.49]],[[769.41,385.63],[768.51,383.88]]]},{"family":"jitter 3","lines":[[[772.31,383.49],[813.67,389.13],[876.81,399.74],[904.94,416.36],[942.35,427.42],[959.91,441.02]],[[318.41,143.66],[423.72,126.86]],[[958.86,445.41],[935.2,438.92]],[[425.56,129.65],[444.03,98.8],[488.4,53.87],[550.24,27.28],[585.5,13.71]],[[930.85,434.97],[910.37,422.01],[876.12,399.69],[809.28,388.33],[773.2,384.35]],[[585.27,17.76],[546.41,10.16]],[[773.33,383.61],[780.24,383.54]]]},{"family":"jitter 3","lines":[[[772.95,383.45],[812.3,388.98],[877.36,399.89],[904.38,416.15],[945.16,428.12],[960.17,444.39]],[[322.96,142.82],[425.36,126.68]],[[959.95,446.06],[931.38,435.86]],[[427.94,125.75],[447.08,96.2],[481.18,49.65],[551.69,27.53],[587.39,14.17]],[[939.54,440.33],[900.17,418.37],[881.11,400.55],[809.23,388.5],[771.26,383.28]],[[583.58,17.4],[541.11,9.08]],[[769.75,387.38],[773.21,382.44]]]},{"family":"jitter 3","lines":[[[772.55,383.47],[809.52,388.44],[877.24,399.98],[904.14,416.03],[942.73,427.48],[962.27,443.03]],[[324.4,142.62],[428.38,126.18]],[[962.19,441.42],[934.64,431.68]],[[426.23,125.09],[446.62,96.02],[488.37,53.83],[558.24,22.24],[582.07,12.88]],[[936.24,436.35],[913.23,424.12],[875.44,399.4],[811.46,389.08],[768.07,382.68]],[[590.04,18.83],[538.72,8.56]],[[770.24,391.23],[770.72,387.13]]]},{"family":"jitter 3","lines":[[[775.58,383.68],[812.53,389.01],[876.51,399.61],[899.98,412.31],[942.17,441.76],[961.03,444.66]],[[324.54,142.58],[424.1,126.88]],[[961.94,442.84],[936.82,434.97]],[[423.84,129.18],[446.09,96.76],[489.62,52.55],[558.79,31.29],[586.41,18.58]],[[931.37,434.41],[912.33,424.01],[890.19,407.71],[804.05,390.46],[767.77,382.53]],[[588.88,18.66],[539.78,8.76]],[[770.34,385.16],[775.29,382.09]]]},{"family":"jitter 3","lines":[[[770.02,383.1],[816.92,389.68],[876.39,399.65],[904.85,416.22],[944.56,428.1],[958.57,450.52]],[[325.82,142.46],[421.86,127.14]],[[954.99,445.43],[931.2,435.94]],[[427.97,125.69],[444.15,98.81],[497.33,44.53],[552.89,27.42],[589.7,11.38]],[[933.08,435.69],[906.38,423.02],[863.44,397.56],[813.84,389.14],[768.6,382.91]],[[590.3,18.92],[539.47,8.73]],[[770.04,387.68],[771.79,383.89]]]},{"family":"jitter 3","lines":[[[768.75,382.84],[811.26,388.8],[876.91,399.72],[904.46,416.15],[942.91,427.51],[960.65,441.39]],[[321.36,143.53],[428.83,125.94]],[[960.87,437.12],[931.73,436.42]],[[426.49,128.4],[444.65,97.92],[486.8,55.51],[547.51,28.18],[584.03,15.02]],[[930.88,434.26],[908.84,422.34],[876.91,399.9],[807.66,388.22],[771.5,383.29]],[[591.32,19.0],[536.32,8.2]],[[768.81,388.07],[775.92,379.49]]]},{"family":"jitter 3","lines":[[[775.08,383.84],[804.15,387.73],[877.15,399.87],[904.49,416.14],[941.04,427.02],[960.32,440.76]],[[322.43,142.96],[424.82,126.72]],[[964.57,448.15],[934.39,437.63]],[[427.96,125.8],[445.87,95.78],[482.99,48.91],[553.36,26.84],[590.74,15.65]],[[932.76,439.56],[923.51,426.67],[876.24,399.74],[810.44,388.66],[772.87,383.48]],[[587.09,18.19],[540.82,8.99]],[[770.32,392.64],[770.5,385.79]]]},{"family":"jitter 3","lines":[[[772.03,383.41],[810.65,388.71],[876.89,399.76],[904.1,415.98],[942.77,427.47],[962.18,443.12]],[[325.65,142.41],[426.69,126.47]],[[955.4,445.22],[927.74,433.26]],[[425.49,127.45],[442.05,93.5],[487.75,47.61],[545.36,29.39],[586.77,14.23]],[[928.03,436.24],[917.62,423.8],[876.87,399.81],[811.68,388.97],[769.8,382.94]],[[587.89,18.34],[538.45,8.53]],[[774.81,382.66],[774.55,383.98]]]},{"family":"jitter 3","lines":[[[766.17,382.52],[807.57,388.26],[876.46,399.76],[904.94,416.19],[942.02,427.28],[962.54,442.86]],[[326.77,142.18],[424.8,126.76]],[[960.32,447.33],[931.05,435.56]],[[426.64,126.3],[448.42,87.22],[488.14,47.05],[552.57,32.63],[582.36,25.03]],[[931.95,420.86],[914.61,427.44],[874.37,404.19],[815.97,388.49],[763.51,382.27]],[[590.49,18.9],[536.82,8.27]],[[770.41,385.24],[773.95,382.68]]]},{"family":"jitter 3","lines":[[[769.78,383.13],[807.15,388.12],[876.86,399.84],[904.93,416.35],[942.52,427.42],[960.97,442.06]],[[323.39,142.65],[429.3,126.17]],[[958.78,446.76],[933.26,436.55]],[[425.52,126.39],[441.89,102.24],[497.39,44.48],[554.99,26.5],[589.53,13.53]],[[937.62,426.62],[906.11,415.8],[873.1,401.87],[811.96,388.86],[771.59,383.35]],[[588.54,18.5],[540.77,8.94]],[[771.29,384.14],[772.31,387.4]]]},{"family":"jitter 3","lines":[[[768.34,383.02],[809.62,388.44],[876.6,399.66],[904.61,416.22],[941.65,427.14],[958.44,439.58]],[[324.14,142.7],[424.82,126.71]],[[961.88,437.84],[933.52,440.08]],[[428.45,125.19],[453.91,81.73],[490.19,45.06],[551.18,32.7],[590.87,21.85]],[[934.82,425.1],[907.11,417.06],[899.61,413.06],[812.48,388.4],[773.09,383.53]],[[585.32,17.79],[544.4,9.73]],[[768.9,390.66],[774.21,380.09]]]},{"family":"jitter 3","lines":[[[772.06,383.54],[815.22,389.34],[876.79,399.75],[904.5,416.18],[942.54,427.38],[963.4,443.87]],[[327.12,142.16],[425.71,126.65]],[[962.85,445.63],[933.36,438.91]],[[428.59,124.08],[456.81,78.68],[487.74,47.67],[551.44,28.06],[582.39,13.41]],[[936.05,436.4],[908.73,421.99],[876.18,399.62],[813.71,389.19],[770.56,383.14]],[[588.7,18.64],[543.93,9.54]],[[768.75,384.79],[766.77,384.0]]]}]}}} \ No newline at end of file +{"note":"SPECTRE's roof (spectre_cages.roof at nibu/fable-spectre-3 14d834c: a hard mirrored cage of 11 vertices) built by brokkr_kitbash.shell at one level with the hull's jaw, flank and cheeks (thickness 0.1, bevel 0.016), rendered by Blender 5.3's Workbench through spectre_skel.cameras() at the sheet's own pixel size (hero 756 x 706, side 264 x 348), the hull posed per view by frames. truth is the cage: Blender built each of its vertices within built_off_m of it (the bevel). One plate, one pair of views. A stroke is an edge of the roof traced from a render by a search, not projected: along a seed polyline the drawn edge is the strongest brightness step within reach px across it, a straight stroke is laid through the steps found on each segment, and strokes meet where they cross. Every seed here is made from the truth's projection, so no trace here is a hand's. takes are that search from a seed that is not on the answer, twelve draws a family (families): offset_px moves the whole seed that far in a drawn direction, jitter_px moves each seed vertex by a normal draw of that many px, reach_px is the window. A take's lines are its strokes in the order of strokes. How far a take's points stand from the truth's projection is not stored: read it from truth and cameras. What takes read is read from takes; the bound is read with no search, from the truth's projection with every point moved as far (test_every_point_as_far_off_bounds_the_rendered_roof). strokes[].line is the same search seeded on the truth's projection itself with a 2.5 px window: every point stands within 2.5 px of the answer because the window ends there (off_projection_px), so it measures no accuracy; it is the base the fairness readings add noise to. drawn is the least share of a segment's length where a step was found. The ridge is traced in the side view only: the hero draws no step along it (its two facets shade alike). closing marks the strokes an agent closes the outline with (the rear edge, and the lip in the side view, half drawn).","cameras":{"hero":{"C":[-9.721115556958573,18.859090658741355,5.242272804029844],"R":[[-0.862189601405842,-0.5065857195259607,0.0],[0.034125232508362004,-0.05807984607580026,0.9977285201827507],[-0.5054350202883507,0.8602311551276064,0.06736319480204615]],"f":1785.0,"c":[378.0,353.0]},"side":{"C":[60.84416742645475,1.422308134553987,3.13474760877321],"R":[[3.061616997868383e-16,1.0,0.0],[0.011634411213376642,-3.5620111131064444e-18,0.9999323179474289],[0.9999323179474289,-3.0614097813457806e-16,-0.011634411213376642]],"f":2200.0,"c":[892.0,532.0]}},"frames":{"hero":[[1.0,0.0,0.0,0.0],[0.0,0.9986295347545738,0.052335956242943835,-0.2773805680876023],[0.0,-0.052335956242943835,0.9986295347545738,0.007263465800758873],[0.0,0.0,0.0,1.0]],"side":[[1.0,0.0,0.0,0.0],[0.0,1.0,0.0,0.0],[0.0,-0.0,1.0,0.0],[0.0,0.0,0.0,1.0]]},"plates":{"roof":{"loop":["ridge_rear","r4","r3","r2","r1","nose","a","b","c","d","e"],"seam":["ridge_rear","r4","r3","r2","r1","nose"],"truth":{"nose":[0.0,3.33,6.34],"r1":[0.0,2.82,6.735],"r2":[0.0,1.76,7.05],"r3":[0.0,1.0,7.5],"r4":[0.0,-0.8,7.8],"ridge_rear":[0.0,-1.9,7.95],"a":[0.77,2.57,6.475],"b":[0.6,1.9,6.83],"c":[0.69,1.0,7.34],"d":[0.64,-0.8,7.65],"e":[0.62,-1.9,7.8]},"built_off_m":0.0151,"strokes":[{"view":"side","side":1,"through":["ridge_rear","r4","r3","r2","r1","nose"],"line":[[772.01,383.39],[811.74,388.89],[876.96,399.88],[904.51,416.13],[941.84,427.31],[961.08,441.58]],"closing":false,"drawn":1.0,"off_projection_px":0.69},{"view":"hero","side":-1,"through":["nose","a"],"line":[[325.08,142.53],[427.02,126.4]],"closing":false,"drawn":1.0,"off_projection_px":0.86},{"view":"side","side":1,"through":["nose","a"],"line":[[961.51,439.35],[933.43,437.76]],"closing":true,"drawn":0.53,"off_projection_px":2.49},{"view":"hero","side":-1,"through":["a","b","c","d","e"],"line":[[426.46,125.71],[442.01,93.62],[487.59,47.65],[551.9,26.85],[587.64,18.75]],"closing":false,"drawn":0.71,"off_projection_px":0.98},{"view":"side","side":1,"through":["a","b","c","d","e"],"line":[[933.68,435.98],[908.72,424.05],[876.26,405.25],[810.61,394.34],[770.7,387.55]],"closing":false,"drawn":0.76,"off_projection_px":1.64},{"view":"hero","side":-1,"through":["e","ridge_rear"],"line":[[587.54,18.26],[541.95,9.26]],"closing":true,"drawn":1.0,"off_projection_px":0.09},{"view":"side","side":1,"through":["e","ridge_rear"],"line":[[769.96,387.04],[772.42,383.77]],"closing":true,"drawn":1.0,"off_projection_px":0.82}],"families":{"offset 0.5":{"offset_px":0.5,"jitter_px":0.0,"reach_px":2.5},"offset 1":{"offset_px":1.0,"jitter_px":0.0,"reach_px":2.5},"offset 1.5":{"offset_px":1.5,"jitter_px":0.0,"reach_px":2.5},"jitter 1":{"offset_px":0.0,"jitter_px":1.0,"reach_px":3.5},"jitter 2":{"offset_px":0.0,"jitter_px":2.0,"reach_px":3.5},"jitter 3":{"offset_px":0.0,"jitter_px":3.0,"reach_px":6.0}},"takes":[{"family":"offset 0.5","lines":[[[772.2,383.42],[811.92,388.9],[876.83,399.81],[904.5,416.12],[941.9,427.27],[961.01,441.57]],[[325.38,142.38],[427.34,126.41]],[[961.4,440.48],[933.67,437.39]],[[427.13,125.47],[441.7,94.0],[487.6,47.66],[552.26,26.84],[587.98,18.69]],[[933.75,435.9],[907.77,423.92],[886.76,406.74],[810.85,394.02],[770.76,388.61]],[[587.72,18.19],[542.1,9.36]],[[769.97,386.53],[772.44,383.26]]]},{"family":"offset 0.5","lines":[[[772.44,383.47],[812.17,388.91],[876.72,399.75],[904.86,416.32],[941.65,427.12],[961.25,441.79]],[[325.56,142.4],[427.51,126.37]],[[961.82,439.84],[933.81,437.93]],[[427.74,125.91],[442.92,92.86],[487.36,47.76],[552.41,26.85],[588.09,18.5]],[[934.12,435.85],[909.12,424.03],[846.1,400.04],[811.15,393.65],[771.07,388.12]],[[587.95,18.37],[542.38,9.29]],[[769.95,386.71],[772.42,383.44]]]},{"family":"offset 0.5","lines":[[[772.32,383.47],[812.07,388.87],[876.79,399.78],[904.63,416.24],[942.07,427.3],[961.38,441.96]],[[325.27,142.42],[427.22,126.4]],[[960.78,443.98],[934.02,436.83]],[[427.91,126.68],[443.16,92.38],[487.75,47.59],[552.04,26.8],[587.79,18.66]],[[934.41,435.5],[908.74,424.97],[876.48,405.41],[811.05,393.6],[771.07,387.23]],[[587.88,18.31],[542.29,9.34]],[[770.14,387.44],[771.99,383.96]]]},{"family":"offset 0.5","lines":[[[771.89,383.3],[811.61,388.91],[876.95,399.87],[904.42,416.1],[942.18,427.41],[961.12,441.73]],[[324.82,142.53],[426.77,126.48]],[[961.4,439.48],[933.35,437.72]],[[426.07,126.07],[442.1,93.47],[487.78,47.57],[551.62,27.02],[587.32,18.64]],[[933.81,435.81],[908.63,424.33],[876.73,405.49],[810.58,393.7],[770.64,387.08]],[[587.45,18.21],[541.85,9.28]],[[770.15,387.64],[772.01,384.16]]]},{"family":"offset 0.5","lines":[[[772.21,383.42],[811.93,388.9],[876.98,399.83],[904.42,416.1],[941.91,427.28],[961.02,441.57]],[[325.39,142.37],[427.35,126.43]],[[961.41,440.49],[933.68,437.39]],[[426.58,125.21],[441.98,93.74],[487.53,47.69],[552.27,26.85],[587.99,18.69]],[[933.76,435.91],[907.78,423.92],[886.77,406.75],[810.86,394.02],[770.77,388.62]],[[587.73,18.21],[542.12,9.34]],[[769.98,386.54],[772.45,383.27]]]},{"family":"offset 0.5","lines":[[[771.65,383.25],[811.36,388.87],[876.64,399.62],[904.14,415.98],[942.73,427.49],[960.43,441.62]],[[324.82,142.51],[426.77,126.49]],[[960.88,440.26],[933.14,437.24]],[[426.31,125.41],[442.09,93.58],[487.52,47.7],[551.72,27.03],[587.38,18.65]],[[932.92,436.43],[908.62,423.23],[876.42,405.26],[810.29,393.97],[770.2,388.47]],[[587.15,18.2],[541.58,9.14]],[[769.87,386.74],[772.33,383.47]]]},{"family":"offset 0.5","lines":[[[772.49,383.45],[812.22,388.9],[876.83,399.77],[904.9,416.37],[942.01,427.24],[961.3,441.88]],[[325.57,142.42],[427.52,126.36]],[[961.99,439.4],[933.83,438.1]],[[427.84,126.06],[443.72,92.04],[487.52,47.65],[552.38,26.76],[588.13,18.66]],[[934.21,435.86],[909.1,424.23],[865.97,403.51],[811.19,393.71],[771.19,387.54]],[[588.0,18.41],[542.43,9.29]],[[769.98,386.83],[772.44,383.56]]]},{"family":"offset 0.5","lines":[[[771.68,383.23],[811.38,388.85],[876.76,399.69],[903.91,415.88],[942.71,427.54],[960.46,441.6]],[[324.84,142.49],[426.8,126.51]],[[960.91,440.24],[933.16,437.22]],[[426.38,125.4],[442.02,93.67],[487.56,47.66],[551.75,27.01],[587.42,18.7]],[[932.95,436.41],[908.63,423.23],[876.12,405.13],[810.32,393.9],[770.22,388.5]],[[587.17,18.19],[541.59,9.18]],[[769.9,386.72],[772.36,383.45]]]},{"family":"offset 0.5","lines":[[[772.25,383.46],[811.98,388.92],[876.91,399.83],[904.47,416.14],[941.69,427.2],[961.08,441.58]],[[325.43,142.4],[427.39,126.39]],[[961.41,440.69],[933.75,437.32]],[[428.93,126.33],[440.99,94.8],[487.38,47.73],[552.32,26.89],[587.99,18.52]],[[933.56,436.42],[901.54,418.82],[886.96,406.9],[810.91,394.03],[770.82,388.56]],[[587.76,18.29],[542.17,9.3]],[[770.03,386.57],[772.49,383.3]]]},{"family":"offset 0.5","lines":[[[771.53,383.24],[811.24,388.84],[876.58,399.58],[904.17,416.02],[942.85,427.52],[960.44,441.65]],[[324.62,142.52],[426.58,126.51]],[[960.9,439.76],[932.95,437.6]],[[426.45,125.79],[441.79,93.8],[487.6,47.65],[551.53,27.17],[587.16,18.59]],[[932.88,436.46],[908.59,423.25],[875.88,405.1],[810.15,394.08],[770.1,388.35]],[[587.06,18.11],[541.47,9.15]],[[769.95,387.07],[772.41,383.8]]]},{"family":"offset 0.5","lines":[[[772.42,383.43],[812.16,388.89],[876.93,399.84],[904.27,416.12],[942.08,427.28],[961.16,441.84]],[[325.55,142.39],[427.5,126.39]],[[961.81,439.81],[933.8,437.89]],[[427.99,126.0],[443.14,92.61],[487.44,47.72],[552.39,26.8],[588.14,18.74]],[[934.1,435.81],[909.17,423.85],[846.58,400.19],[811.09,393.93],[771.07,387.95]],[[587.93,18.35],[542.35,9.31]],[[769.94,386.67],[772.4,383.4]]]},{"family":"offset 0.5","lines":[[[772.33,383.51],[812.08,388.88],[876.82,399.78],[904.64,416.23],[942.09,427.29],[961.32,442.05]],[[325.28,142.4],[427.24,126.39]],[[960.8,443.97],[934.04,436.82]],[[427.93,126.67],[443.15,92.44],[487.67,47.63],[552.06,26.82],[587.8,18.6]],[[934.42,435.49],[908.75,424.96],[876.43,405.39],[811.06,393.59],[771.09,387.21]],[[587.89,18.32],[542.3,9.33]],[[770.16,387.43],[772.01,383.95]]]},{"family":"offset 1","lines":[[[772.38,383.52],[812.11,388.89],[876.84,399.81],[904.83,416.31],[942.18,427.33],[960.91,441.6]],[[325.71,142.43],[427.64,126.27]],[[961.44,440.94],[933.91,436.99]],[[428.47,125.55],[441.32,94.29],[487.61,47.67],[552.65,26.96],[588.05,17.44]],[[933.56,436.34],[910.35,421.18],[883.52,404.14],[811.37,391.86],[771.25,386.44]],[[587.86,18.35],[542.28,9.3]],[[770.86,386.31],[772.71,382.84]]]},{"family":"offset 1","lines":[[[772.88,383.51],[812.61,388.99],[876.65,399.68],[904.32,416.04],[942.18,427.32],[961.32,442.13]],[[326.04,142.31],[427.99,126.28]],[[962.04,440.73],[934.48,436.94]],[[428.18,125.72],[444.66,90.92],[487.59,47.69],[552.89,26.74],[588.51,18.1]],[[934.37,436.1],[907.56,423.63],[893.73,408.05],[811.51,394.23],[771.43,388.8]],[[588.36,18.49],[542.8,9.39]],[[770.34,386.51],[772.19,383.03]]]},{"family":"offset 1","lines":[[[772.65,383.46],[812.39,388.94],[876.82,399.73],[904.34,416.05],[942.59,427.45],[961.6,442.44]],[[325.47,142.41],[427.42,126.35]],[[961.0,444.6],[934.13,437.91]],[[427.59,126.83],[445.86,89.66],[487.8,47.56],[552.21,26.89],[587.94,18.52]],[[934.72,435.82],[909.21,425.01],[876.03,405.2],[811.39,393.52],[771.33,387.7]],[[588.2,18.5],[542.65,9.31]],[[769.78,387.65],[772.25,384.38]]]},{"family":"offset 1","lines":[[[771.77,383.24],[811.49,388.88],[876.89,399.84],[904.68,416.21],[942.07,427.36],[961.19,441.87]],[[324.56,142.56],[426.51,126.49]],[[959.98,445.09],[933.45,436.97]],[[426.3,126.73],[441.67,94.0],[487.55,47.72],[551.34,27.15],[587.03,18.65]],[[933.85,435.82],[908.65,424.4],[876.74,405.47],[810.48,393.57],[770.52,386.97]],[[587.34,18.23],[541.76,9.21]],[[770.27,388.2],[770.89,384.31]]]},{"family":"offset 1","lines":[[[772.4,383.5],[812.13,388.9],[876.76,399.76],[904.85,416.33],[942.01,427.29],[960.92,441.62]],[[325.72,142.4],[427.66,126.28]],[[961.46,440.95],[933.93,437.01]],[[428.01,125.33],[442.44,93.14],[487.66,47.67],[552.66,26.92],[588.11,17.62]],[[933.58,436.35],[910.33,421.26],[883.76,404.19],[811.39,391.87],[771.26,386.46]],[[587.88,18.34],[542.3,9.3]],[[770.87,386.32],[772.73,382.85]]]},{"family":"offset 1","lines":[[[771.27,383.3],[811.0,388.69],[876.81,399.69],[904.09,415.97],[942.56,427.46],[960.12,441.21]],[[324.56,142.57],[426.51,126.52]],[[960.58,439.78],[932.8,436.92]],[[426.52,125.27],[441.98,93.72],[487.52,47.66],[551.5,27.03],[587.16,18.71]],[[932.95,435.37],[907.74,423.91],[875.71,405.13],[810.04,392.94],[770.09,386.54]],[[586.76,18.15],[541.19,9.06]],[[770.02,386.52],[772.49,383.25]]]},{"family":"offset 1","lines":[[[772.97,383.51],[812.69,389.02],[876.68,399.67],[904.44,416.06],[942.77,427.5],[961.42,442.31]],[[326.06,142.3],[428.01,126.29]],[[962.46,439.42],[934.42,437.65]],[[428.37,126.02],[444.86,90.74],[487.7,47.65],[552.88,26.74],[588.51,18.09]],[[934.28,436.62],[909.84,423.7],[865.62,403.38],[811.61,394.21],[771.51,388.82]],[[588.46,18.51],[542.9,9.39]],[[770.0,386.61],[772.47,383.35]]]},{"family":"offset 1","lines":[[[771.32,383.28],[811.04,388.72],[876.68,399.65],[904.47,416.1],[942.73,427.49],[960.11,441.26]],[[324.61,142.54],[426.56,126.51]],[[960.5,440.31],[932.82,436.99]],[[426.55,125.22],[442.02,93.68],[487.58,47.65],[551.59,27.15],[587.15,18.42]],[[932.67,435.98],[908.29,422.93],[846.42,400.1],[810.09,392.9],[770.14,386.5]],[[586.81,18.11],[541.22,9.13]],[[770.07,386.48],[772.54,383.21]]]},{"family":"offset 1","lines":[[[772.51,383.46],[812.23,388.91],[876.74,399.77],[904.73,416.26],[941.61,427.14],[961.08,441.58]],[[325.8,142.4],[427.74,126.26]],[[961.72,440.29],[933.92,437.49]],[[428.2,125.45],[442.54,93.09],[487.55,47.71],[552.68,26.71],[588.39,18.56]],[[933.79,436.17],[910.34,421.48],[884.05,404.29],[811.47,391.93],[771.35,386.52]],[[587.97,18.39],[542.4,9.31]],[[770.96,386.39],[772.82,382.91]]]},{"family":"offset 1","lines":[[[771.02,383.27],[810.76,388.68],[876.86,399.74],[904.4,416.13],[942.65,427.42],[960.08,441.36]],[[324.18,142.65],[426.12,126.55]],[[960.37,439.85],[932.44,437.61]],[[426.31,125.81],[441.98,93.65],[487.56,47.71],[551.09,27.16],[586.76,18.83]],[[933.06,435.03],[907.48,424.33],[876.4,405.34],[809.73,393.46],[769.76,387.12]],[[586.56,18.08],[540.99,9.0]],[[769.94,387.09],[772.41,383.82]]]},{"family":"offset 1","lines":[[[772.84,383.49],[812.57,388.93],[876.79,399.72],[904.29,416.07],[942.26,427.34],[961.29,442.06]],[[326.02,142.33],[427.97,126.29]],[[961.99,440.73],[934.44,436.9]],[[428.18,125.66],[444.73,90.87],[487.62,47.63],[552.91,26.88],[588.47,17.98]],[[934.34,436.02],[907.53,423.56],[893.85,408.15],[811.5,394.0],[771.41,388.62]],[[588.32,18.48],[542.75,9.4]],[[770.54,386.51],[772.39,383.04]]]},{"family":"offset 1","lines":[[[772.68,383.48],[812.42,388.91],[876.78,399.73],[904.17,415.97],[942.84,427.54],[961.58,442.49]],[[325.51,142.42],[427.45,126.36]],[[961.07,444.43],[934.13,438.01]],[[427.49,126.74],[446.69,88.83],[487.73,47.61],[552.24,26.89],[587.99,18.58]],[[934.77,435.77],[909.21,425.05],[875.82,405.12],[811.44,393.35],[771.35,387.83]],[[588.22,18.51],[542.67,9.34]],[[769.81,387.63],[772.28,384.36]]]},{"family":"offset 1.5","lines":[[[772.59,383.45],[812.3,388.9],[876.74,399.75],[904.64,416.2],[942.2,427.33],[960.82,441.61]],[[326.01,142.31],[427.96,126.27]],[[962.0,439.23],[933.97,437.4]],[[427.07,124.34],[441.96,93.73],[487.53,47.7],[552.97,26.75],[588.54,18.06]],[[933.73,436.07],[910.55,420.86],[883.11,403.6],[811.77,390.32],[771.8,383.78]],[[588.01,18.42],[542.45,9.3]],[[770.96,385.83],[773.42,382.56]]]},{"family":"offset 1.5","lines":[[[773.33,383.49],[813.03,389.11],[876.97,399.84],[904.66,416.2],[942.31,427.31],[961.51,442.32]],[[326.53,142.28],[428.47,126.17]],[[962.46,440.77],[934.8,437.37]],[[428.39,125.43],[447.02,88.59],[487.6,47.66],[553.35,26.52],[589.05,18.22]],[[934.53,436.54],[911.04,421.91],[889.4,407.36],[812.1,393.19],[772.14,386.78]],[[588.76,18.65],[543.23,9.4]],[[770.8,386.33],[772.66,382.86]]]},{"family":"offset 1.5","lines":[[[772.97,383.5],[812.71,389.0],[876.73,399.67],[904.28,416.09],[942.16,427.27],[962.07,442.61]],[[325.67,142.41],[427.61,126.31]],[[961.31,444.86],[934.5,437.91]],[[427.38,127.02],[454.3,81.22],[487.71,47.61],[552.35,26.85],[588.14,18.66]],[[935.06,436.12],[909.68,425.04],[875.86,405.06],[811.7,393.66],[771.61,388.05]],[[588.54,18.55],[542.98,9.4]],[[770.27,388.15],[770.9,384.26]]]},{"family":"offset 1.5","lines":[[[771.63,383.3],[811.37,388.86],[876.51,399.68],[904.66,416.18],[941.93,427.28],[961.35,441.87]],[[324.31,142.65],[426.24,126.48]],[[959.87,445.24],[933.24,437.5]],[[425.74,127.02],[442.09,93.56],[487.6,47.67],[551.05,27.26],[586.78,18.87]],[[933.87,435.86],[908.75,424.32],[876.43,405.31],[810.3,394.0],[770.17,388.62]],[[587.25,18.2],[541.66,9.21]],[[770.47,388.79],[770.48,384.7]]]},{"family":"offset 1.5","lines":[[[772.61,383.47],[812.33,388.92],[876.75,399.76],[904.85,416.33],[942.11,427.26],[960.85,441.63]],[[326.04,142.32],[427.99,126.26]],[[961.99,439.39],[934.01,437.36]],[[427.11,124.36],[441.9,93.83],[487.44,47.73],[552.99,26.75],[588.56,18.02]],[[933.76,436.09],[910.56,420.9],[883.16,403.62],[811.8,390.33],[771.83,383.8]],[[588.04,18.42],[542.48,9.31]],[[770.59,385.72],[773.67,382.66]]]},{"family":"offset 1.5","lines":[[[770.9,383.26],[810.62,388.7],[876.71,399.71],[904.73,416.23],[941.66,427.18],[959.91,440.69]],[[324.3,142.61],[426.25,126.53]],[[960.31,439.19],[932.23,437.57]],[[426.48,125.02],[442.21,93.48],[487.53,47.69],[551.31,27.12],[586.96,18.88]],[[932.22,435.78],[908.35,421.82],[875.6,402.76],[809.89,391.58],[769.77,386.16]],[[586.39,18.01],[540.81,9.0]],[[770.56,386.43],[772.41,382.95]]]},{"family":"offset 1.5","lines":[[[773.45,383.55],[813.16,389.14],[877.01,399.88],[904.47,416.16],[942.92,427.55],[961.64,442.62]],[[326.56,142.29],[428.5,126.17]],[[962.73,440.33],[934.88,437.75]],[[426.47,124.84],[445.79,93.32],[487.63,47.63],[553.33,26.48],[589.02,18.1]],[[934.76,436.61],[905.93,422.03],[891.61,407.68],[812.1,394.21],[772.01,388.73]],[[588.92,18.65],[543.38,9.42]],[[770.42,386.53],[772.27,383.06]]]},{"family":"offset 1.5","lines":[[[770.96,383.31],[810.7,388.65],[876.9,399.77],[904.54,416.19],[941.96,427.26],[959.9,440.75]],[[324.38,142.52],[426.34,126.56]],[[960.48,438.72],[932.22,437.88]],[[426.54,124.96],[442.16,93.59],[487.56,47.63],[551.44,27.32],[586.77,17.63]],[[932.25,435.81],[908.44,421.72],[875.67,402.7],[809.96,391.52],[769.84,386.1]],[[586.45,18.02],[540.87,8.99]],[[771.03,386.5],[772.27,382.82]]]},{"family":"offset 1.5","lines":[[[772.76,383.46],[812.48,388.91],[876.73,399.75],[904.85,416.32],[941.56,427.1],[961.09,441.59]],[[326.15,142.28],[428.11,126.27]],[[962.11,439.54],[934.17,437.34]],[[427.21,124.44],[441.83,93.91],[487.53,47.7],[553.11,26.79],[588.64,17.91]],[[933.85,436.26],[910.69,421.0],[878.05,400.54],[812.12,389.32],[771.96,383.9]],[[588.18,18.49],[542.63,9.32]],[[770.88,385.86],[773.35,382.6]]]},{"family":"offset 1.5","lines":[[[770.54,383.13],[810.25,388.72],[876.65,399.75],[904.84,416.23],[942.11,427.34],[959.96,440.76]],[[323.74,142.75],[425.66,126.57]],[[960.12,438.76],[931.82,438.03]],[[426.23,125.87],[441.87,93.85],[487.61,47.62],[550.67,27.23],[586.36,19.05]],[[932.24,435.55],[907.49,423.24],[876.19,405.23],[809.18,393.83],[769.09,388.4]],[[586.06,18.0],[540.49,8.96]],[[769.93,387.11],[772.4,383.85]]]},{"family":"offset 1.5","lines":[[[773.27,383.46],[812.97,389.09],[877.14,399.86],[904.47,416.16],[942.4,427.35],[961.41,442.28]],[[326.5,142.25],[428.45,126.21]],[[962.4,440.72],[934.75,437.28]],[[428.19,125.24],[446.87,88.77],[487.56,47.65],[553.32,26.48],[589.0,18.11]],[[934.58,436.23],[910.75,422.28],[884.29,404.35],[812.22,392.09],[772.1,386.67]],[[588.7,18.61],[543.15,9.42]],[[770.99,386.3],[772.85,382.83]]]},{"family":"offset 1.5","lines":[[[773.01,383.49],[812.75,389.03],[876.71,399.68],[904.43,416.13],[942.34,427.39],[962.07,442.64]],[[325.73,142.43],[427.66,126.27]],[[961.35,444.86],[934.48,438.14]],[[425.82,126.24],[463.98,71.46],[487.68,47.63],[552.4,26.8],[588.22,18.74]],[[935.05,436.2],[909.79,424.89],[876.13,405.22],[811.71,393.9],[771.74,387.46]],[[588.58,18.56],[543.03,9.38]],[[770.17,388.06],[771.41,384.38]]]},{"family":"jitter 1","lines":[[[772.12,383.36],[812.38,388.95],[876.64,399.72],[904.88,416.31],[941.79,427.17],[960.67,441.38]],[[322.85,142.87],[425.92,126.58]],[[959.74,444.8],[934.1,438.03]],[[425.54,126.74],[461.82,73.68],[487.52,47.72],[551.49,27.31],[586.89,17.54]],[[933.07,434.97],[908.5,424.76],[876.66,405.06],[810.0,394.04],[771.52,388.76]],[[586.68,18.04],[543.4,9.59]],[[771.0,386.99],[773.43,385.58]]]},{"family":"jitter 1","lines":[[[772.4,383.5],[811.89,388.85],[877.17,399.89],[903.95,415.96],[942.28,427.37],[961.26,441.95]],[[324.38,142.63],[426.45,126.46]],[[961.25,440.31],[932.58,437.89]],[[425.77,125.03],[444.91,94.21],[487.53,47.7],[551.82,26.91],[587.78,18.62]],[[935.34,436.46],[909.28,424.33],[873.98,403.97],[810.81,388.11],[771.26,383.55]],[[586.22,18.0],[541.69,9.22]],[[769.81,387.13],[772.6,383.31]]]},{"family":"jitter 1","lines":[[[772.14,383.41],[810.97,388.79],[876.72,399.66],[904.18,416.03],[942.62,427.52],[961.38,442.16]],[[324.86,142.52],[427.48,126.37]],[[961.93,439.36],[933.26,438.01]],[[425.78,125.2],[445.07,94.15],[487.62,47.64],[554.44,26.95],[585.42,15.2]],[[934.72,435.73],[907.97,425.3],[892.02,407.68],[810.6,394.1],[769.39,388.19]],[[588.19,18.49],[540.98,8.97]],[[770.59,388.47],[770.49,384.36]]]},{"family":"jitter 1","lines":[[[773.53,383.55],[812.05,388.92],[877.11,399.85],[904.01,415.96],[943.04,427.59],[960.8,442.08]],[[324.9,142.53],[426.05,126.56]],[[960.69,444.57],[934.41,437.42]],[[425.84,126.96],[460.45,75.05],[487.63,47.61],[553.77,26.38],[587.21,18.87]],[[933.13,435.03],[906.32,424.87],[900.15,409.21],[808.47,391.64],[770.34,382.96]],[[587.95,18.41],[541.3,9.05]],[[769.84,386.41],[772.46,383.53]]]},{"family":"jitter 1","lines":[[[771.35,383.29],[813.47,389.1],[876.84,399.78],[904.57,416.14],[942.22,427.34],[961.92,442.37]],[[325.3,142.42],[425.24,126.69]],[[958.23,445.25],[932.92,436.75]],[[425.81,125.02],[445.39,93.95],[487.56,47.68],[552.2,27.06],[588.54,17.07]],[[933.69,435.48],[907.66,424.37],[879.64,407.18],[812.35,388.44],[770.32,383.68]],[[588.41,18.58],[541.16,9.01]],[[770.02,386.77],[772.36,383.84]]]},{"family":"jitter 1","lines":[[[771.0,383.3],[811.57,388.82],[877.26,399.89],[903.83,415.9],[941.6,427.14],[960.73,441.29]],[[323.88,142.64],[427.55,126.38]],[[961.4,438.02],[932.61,438.53]],[[427.66,127.16],[444.46,91.3],[487.38,47.77],[550.45,27.25],[586.72,18.86]],[[932.98,434.89],[909.33,422.55],[876.01,399.99],[810.2,388.64],[771.36,383.21]],[[588.78,18.61],[540.1,8.81]],[[769.7,387.37],[773.51,382.26]]]},{"family":"jitter 1","lines":[[[773.21,383.5],[809.22,388.45],[876.87,399.78],[904.24,416.06],[942.28,427.33],[960.57,441.47]],[[324.19,142.65],[426.27,126.51]],[[961.76,445.52],[933.49,438.74]],[[427.35,125.79],[446.24,89.36],[487.56,47.7],[552.42,26.76],[588.72,18.56]],[[934.36,435.46],[910.15,423.01],[877.33,400.12],[811.09,388.89],[771.72,384.11]],[[587.2,18.17],[541.58,9.18]],[[770.59,388.97],[770.49,384.13]]]},{"family":"jitter 1","lines":[[[772.04,383.34],[811.34,388.87],[876.73,399.66],[904.72,416.38],[942.56,427.22],[961.26,442.33]],[[325.29,142.41],[426.89,126.44]],[[959.01,443.53],[931.63,435.84]],[[425.93,126.1],[442.08,93.63],[487.53,47.65],[549.7,27.54],[587.54,18.64]],[[932.17,435.43],[908.81,421.43],[876.17,399.37],[810.68,394.6],[769.9,388.78]],[[587.65,18.31],[540.79,8.99]],[[772.1,385.76],[772.83,383.74]]]},{"family":"jitter 1","lines":[[[770.11,383.06],[810.35,388.69],[876.85,399.77],[904.0,415.92],[941.8,427.18],[961.53,441.96]],[[325.69,142.43],[426.28,126.47]],[[960.17,445.68],[932.68,436.68]],[[427.32,126.19],[443.61,92.07],[487.58,47.61],[551.72,27.04],[585.57,19.06]],[[932.38,435.14],[909.14,424.73],[881.48,408.27],[812.99,388.6],[768.67,383.05]],[[588.52,18.48],[540.26,8.84]],[[769.95,386.66],[772.06,383.99]]]},{"family":"jitter 1","lines":[[[771.26,383.25],[810.21,388.63],[876.87,399.85],[904.86,416.34],[942.57,427.36],[960.48,441.57]],[[324.61,142.51],[427.79,126.31]],[[959.87,444.94],[933.02,438.97]],[[427.23,126.44],[447.59,88.03],[487.54,47.67],[552.98,26.98],[588.33,17.23]],[[933.74,436.09],[907.13,423.09],[876.42,405.32],[810.81,393.6],[770.83,386.95]],[[587.8,18.34],[541.61,9.14]],[[769.77,387.08],[771.22,385.51]]]},{"family":"jitter 1","lines":[[[770.81,383.25],[811.02,388.74],[876.73,399.71],[904.47,416.12],[941.58,427.12],[960.24,440.88]],[[324.76,142.51],[426.27,126.58]],[[961.62,437.4],[933.39,438.69]],[[427.97,125.83],[443.16,92.64],[487.48,47.66],[551.28,27.16],[588.41,18.41]],[[933.06,435.04],[908.57,424.73],[876.26,405.37],[810.94,393.52],[771.34,387.05]],[[586.77,18.13],[542.78,9.42]],[[769.83,388.33],[772.77,382.47]]]},{"family":"jitter 1","lines":[[[772.14,383.44],[812.87,389.03],[876.8,399.68],[903.84,415.87],[942.52,427.37],[961.73,442.59]],[[325.76,142.4],[426.57,126.45]],[[961.16,444.61],[933.48,437.89]],[[428.02,125.43],[443.38,92.34],[487.45,47.74],[551.75,26.99],[586.17,18.97]],[[934.44,436.1],[907.18,423.82],[887.59,406.88],[811.3,394.38],[771.18,382.81]],[[587.92,18.35],[542.72,9.38]],[[770.07,386.47],[770.24,383.75]]]},{"family":"jitter 2","lines":[[[772.22,383.42],[813.02,389.08],[877.05,399.84],[904.59,416.26],[942.16,427.27],[960.3,441.17]],[[320.62,143.24],[424.82,126.72]],[[959.31,444.76],[934.64,438.68]],[[426.47,128.58],[445.5,90.14],[487.52,47.67],[550.97,27.19],[586.62,18.71]],[[931.81,435.27],[909.03,423.97],[873.61,404.68],[809.39,393.84],[772.46,387.55]],[[585.88,18.0],[544.92,9.76]],[[771.27,386.68],[774.89,387.54]]]},{"family":"jitter 2","lines":[[[772.72,383.37],[812.07,388.94],[877.14,399.89],[904.05,415.94],[942.85,427.53],[961.36,442.41]],[[323.68,142.77],[425.9,126.54]],[[961.86,437.41],[931.81,437.68]],[[426.35,125.02],[463.47,72.1],[488.69,46.85],[551.76,27.09],[587.92,18.48]],[[937.39,437.12],[909.61,424.84],[873.93,403.92],[810.16,387.65],[771.27,383.47]],[[584.89,17.78],[541.42,9.12]],[[769.89,387.3],[773.03,382.91]]]},{"family":"jitter 2","lines":[[[772.31,383.54],[810.24,388.48],[877.01,399.81],[904.31,416.06],[942.28,427.38],[961.88,442.5]],[[324.64,142.57],[427.93,126.25]],[[962.58,438.38],[933.2,437.76]],[[426.71,125.46],[460.97,74.53],[487.55,47.71],[556.85,26.25],[583.7,13.9]],[[935.48,436.03],[908.63,425.74],[895.16,408.38],[810.65,393.7],[767.91,389.45]],[[589.01,18.7],[539.9,8.76]],[[770.53,389.83],[770.44,385.59]]]},{"family":"jitter 2","lines":[[[774.77,383.51],[812.31,388.96],[877.02,399.78],[901.34,413.41],[942.05,437.68],[962.28,438.4]],[[324.71,142.49],[425.08,126.77]],[[962.98,436.86],[934.82,439.43]],[[426.15,128.65],[455.08,80.49],[487.61,47.64],[555.65,25.99],[586.77,18.7]],[[932.23,434.75],[910.29,425.63],[876.12,405.29],[805.46,393.48],[769.56,381.46]],[[588.39,18.55],[540.58,8.87]],[[770.27,386.2],[773.57,382.79]]]},{"family":"jitter 2","lines":[[[770.68,383.19],[815.2,389.36],[876.91,399.81],[904.7,416.23],[942.88,427.61],[962.59,443.37]],[[325.55,142.39],[423.53,127.01]],[[956.5,445.36],[932.21,436.18]],[[428.2,126.0],[452.64,82.95],[487.62,47.57],[552.56,27.33],[589.15,14.26]],[[933.16,436.14],[907.37,422.9],[880.16,407.51],[813.21,388.35],[769.47,383.23]],[[589.34,18.74],[540.34,8.82]],[[769.9,386.78],[772.26,384.01]]]},{"family":"jitter 2","lines":[[[769.91,383.09],[811.41,388.82],[876.96,399.75],[904.05,416.01],[941.79,427.22],[960.61,441.09]],[[322.61,142.91],[428.15,126.19]],[[960.99,438.23],[932.09,438.01]],[[425.78,127.16],[441.92,93.81],[487.64,47.62],[549.02,27.66],[585.82,19.09]],[[931.92,434.56],[909.13,422.39],[875.75,399.77],[808.94,388.44],[771.43,383.27]],[[590.05,18.79],[538.21,8.49]],[[769.15,387.65],[774.61,380.81]]]},{"family":"jitter 2","lines":[[[774.25,383.74],[806.7,388.03],[877.08,399.74],[903.84,415.85],[942.88,427.62],[960.24,441.35]],[[323.3,142.75],[425.54,126.67]],[[963.41,445.83],[933.72,439.06]],[[426.45,125.05],[441.76,93.76],[488.48,46.97],[552.92,26.83],[589.76,17.79]],[[934.72,435.58],[910.76,423.29],[876.55,399.7],[810.78,388.65],[772.3,383.83]],[[587.01,18.28],[541.21,9.04]],[[770.53,390.77],[770.68,385.0]]]},{"family":"jitter 2","lines":[[[772.04,383.35],[810.99,388.76],[876.67,399.69],[904.27,416.04],[942.07,427.31],[961.93,442.45]],[[325.48,142.42],[426.79,126.5]],[[958.02,441.66],[929.53,435.11]],[[425.72,126.74],[442.17,93.54],[487.53,47.71],[547.49,28.16],[587.48,18.74]],[[930.64,434.91],[907.72,420.86],[874.99,398.69],[810.91,393.88],[769.3,388.59]],[[587.77,18.31],[539.62,8.78]],[[773.45,384.21],[773.69,383.86]]]},{"family":"jitter 2","lines":[[[768.15,382.85],[808.98,388.41],[876.69,399.8],[904.71,416.2],[941.72,427.2],[962.03,442.35]],[[326.24,142.25],[425.56,126.69]],[[960.32,446.17],[931.69,436.58]],[[426.11,125.9],[442.3,93.29],[487.69,47.6],[551.52,27.14],[583.6,19.56]],[[931.32,435.1],[909.68,424.59],[883.45,409.45],[814.46,388.63],[766.09,382.63]],[[589.49,18.74],[538.56,8.47]],[[770.15,386.19],[772.58,383.54]]]},{"family":"jitter 2","lines":[[[770.52,383.19],[808.68,388.4],[877.07,399.89],[904.05,415.88],[942.03,427.3],[960.77,441.44]],[[324.08,142.73],[428.53,126.12]],[[959.55,444.87],[932.91,438.85]],[[427.32,126.84],[444.7,91.11],[487.49,47.63],[553.94,26.59],[589.34,17.06]],[[933.98,436.05],[905.41,422.34],[876.53,405.42],[810.8,394.29],[771.62,382.7]],[[588.12,18.47],[541.22,9.02]],[[768.8,386.86],[770.48,387.39]]]},{"family":"jitter 2","lines":[[[769.62,383.0],[810.3,388.67],[876.94,399.84],[904.47,416.13],[941.53,427.09],[959.33,440.25]],[[324.45,142.6],[425.53,126.64]],[[961.58,437.66],[933.45,439.23]],[[426.83,124.71],[441.87,93.83],[487.56,47.62],[550.65,27.23],[589.22,18.29]],[[932.17,435.12],[909.07,424.02],[876.09,405.26],[811.14,393.67],[771.95,386.79]],[[586.02,18.03],[543.61,9.53]],[[768.83,389.33],[773.87,381.4]]]},{"family":"jitter 2","lines":[[[772.16,383.35],[814.04,389.19],[876.79,399.72],[904.99,416.37],[941.48,427.02],[962.78,443.02]],[[326.44,142.28],[426.14,126.54]],[[962.08,444.53],[933.49,438.01]],[[427.13,124.01],[442.1,93.45],[488.28,47.22],[551.55,27.04],[584.71,19.31]],[[935.11,436.57],[903.98,421.78],[887.88,406.88],[811.89,394.99],[771.11,382.08]],[[588.3,18.5],[543.37,9.49]],[[769.41,385.63],[768.51,383.88]]]},{"family":"jitter 3","lines":[[[772.31,383.49],[813.67,389.13],[876.81,399.74],[904.94,416.36],[942.35,427.42],[959.91,441.02]],[[318.41,143.66],[423.72,126.86]],[[958.86,445.41],[935.2,438.92]],[[425.56,129.65],[444.03,98.8],[488.4,53.87],[550.24,27.28],[585.5,13.71]],[[930.85,434.97],[910.37,422.01],[876.12,399.69],[809.28,388.33],[773.2,384.35]],[[585.27,17.76],[546.41,10.16]],[[773.33,383.61],[780.24,383.54]]]},{"family":"jitter 3","lines":[[[772.95,383.45],[812.3,388.98],[877.36,399.89],[904.38,416.15],[945.16,428.12],[960.17,444.39]],[[322.96,142.82],[425.36,126.68]],[[959.95,446.06],[931.38,435.86]],[[427.94,125.75],[447.08,96.2],[481.18,49.65],[551.69,27.53],[587.39,14.17]],[[939.54,440.33],[900.17,418.37],[881.11,400.55],[809.23,388.5],[771.26,383.28]],[[583.58,17.4],[541.11,9.08]],[[769.75,387.38],[773.21,382.44]]]},{"family":"jitter 3","lines":[[[772.55,383.47],[809.52,388.44],[877.24,399.98],[904.14,416.03],[942.73,427.48],[962.27,443.03]],[[324.4,142.62],[428.38,126.18]],[[962.19,441.42],[934.64,431.68]],[[426.23,125.09],[446.62,96.02],[488.37,53.83],[558.24,22.24],[582.07,12.88]],[[936.24,436.35],[913.23,424.12],[875.44,399.4],[811.46,389.08],[768.07,382.68]],[[590.04,18.83],[538.72,8.56]],[[770.24,391.23],[770.72,387.13]]]},{"family":"jitter 3","lines":[[[775.58,383.68],[812.53,389.01],[876.51,399.61],[899.98,412.31],[942.17,441.76],[961.03,444.66]],[[324.54,142.58],[424.1,126.88]],[[961.94,442.84],[936.82,434.97]],[[423.84,129.18],[446.09,96.76],[489.62,52.55],[558.79,31.29],[586.41,18.58]],[[931.37,434.41],[912.33,424.01],[890.19,407.71],[804.05,390.46],[767.77,382.53]],[[588.88,18.66],[539.78,8.76]],[[770.34,385.16],[775.29,382.09]]]},{"family":"jitter 3","lines":[[[770.02,383.1],[816.92,389.68],[876.39,399.65],[904.85,416.22],[944.56,428.1],[958.57,450.52]],[[325.82,142.46],[421.86,127.14]],[[954.99,445.43],[931.2,435.94]],[[427.97,125.69],[444.15,98.81],[497.33,44.53],[552.89,27.42],[589.7,11.38]],[[933.08,435.69],[906.38,423.02],[863.44,397.56],[813.84,389.14],[768.6,382.91]],[[590.3,18.92],[539.47,8.73]],[[770.04,387.68],[771.79,383.89]]]},{"family":"jitter 3","lines":[[[768.75,382.84],[811.26,388.8],[876.91,399.72],[904.46,416.15],[942.91,427.51],[960.65,441.39]],[[321.36,143.53],[428.83,125.94]],[[960.87,437.12],[931.73,436.42]],[[426.49,128.4],[444.65,97.92],[486.8,55.51],[547.51,28.18],[584.03,15.02]],[[930.88,434.26],[908.84,422.34],[876.91,399.9],[807.66,388.22],[771.5,383.29]],[[591.32,19.0],[536.32,8.2]],[[768.81,388.07],[775.92,379.49]]]},{"family":"jitter 3","lines":[[[775.08,383.84],[804.15,387.73],[877.15,399.87],[904.49,416.14],[941.04,427.02],[960.32,440.76]],[[322.43,142.96],[424.82,126.72]],[[964.57,448.15],[934.39,437.63]],[[427.96,125.8],[445.87,95.78],[482.99,48.91],[553.36,26.84],[590.74,15.65]],[[932.76,439.56],[923.51,426.67],[876.24,399.74],[810.44,388.66],[772.87,383.48]],[[587.09,18.19],[540.82,8.99]],[[770.32,392.64],[770.5,385.79]]]},{"family":"jitter 3","lines":[[[772.03,383.41],[810.65,388.71],[876.89,399.76],[904.1,415.98],[942.77,427.47],[962.18,443.12]],[[325.65,142.41],[426.69,126.47]],[[955.4,445.22],[927.74,433.26]],[[425.49,127.45],[442.05,93.5],[487.75,47.61],[545.36,29.39],[586.77,14.23]],[[928.03,436.24],[917.62,423.8],[876.87,399.81],[811.68,388.97],[769.8,382.94]],[[587.89,18.34],[538.45,8.53]],[[774.81,382.66],[774.55,383.98]]]},{"family":"jitter 3","lines":[[[766.17,382.52],[807.57,388.26],[876.46,399.76],[904.94,416.19],[942.02,427.28],[962.54,442.86]],[[326.77,142.18],[424.8,126.76]],[[960.32,447.33],[931.05,435.56]],[[426.64,126.3],[448.42,87.22],[488.14,47.05],[552.57,32.63],[582.36,25.03]],[[931.95,420.86],[914.61,427.44],[874.37,404.19],[815.97,388.49],[763.51,382.27]],[[590.49,18.9],[536.82,8.27]],[[770.41,385.24],[773.95,382.68]]]},{"family":"jitter 3","lines":[[[769.78,383.13],[807.15,388.12],[876.86,399.84],[904.93,416.35],[942.52,427.42],[960.97,442.06]],[[323.39,142.65],[429.3,126.17]],[[958.78,446.76],[933.26,436.55]],[[425.52,126.39],[441.89,102.24],[497.39,44.48],[554.99,26.5],[589.53,13.53]],[[937.62,426.62],[906.11,415.8],[873.1,401.87],[811.96,388.86],[771.59,383.35]],[[588.54,18.5],[540.77,8.94]],[[771.29,384.14],[772.31,387.4]]]},{"family":"jitter 3","lines":[[[768.34,383.02],[809.62,388.44],[876.6,399.66],[904.61,416.22],[941.65,427.14],[958.44,439.58]],[[324.14,142.7],[424.82,126.71]],[[961.88,437.84],[933.52,440.08]],[[428.45,125.19],[453.91,81.73],[490.19,45.06],[551.18,32.7],[590.87,21.85]],[[934.82,425.1],[907.11,417.06],[899.61,413.06],[812.48,388.4],[773.09,383.53]],[[585.32,17.79],[544.4,9.73]],[[768.9,390.66],[774.21,380.09]]]},{"family":"jitter 3","lines":[[[772.06,383.54],[815.22,389.34],[876.79,399.75],[904.5,416.18],[942.54,427.38],[963.4,443.87]],[[327.12,142.16],[425.71,126.65]],[[962.85,445.63],[933.36,438.91]],[[428.59,124.08],[456.81,78.68],[487.74,47.67],[551.44,28.06],[582.39,13.41]],[[936.05,436.4],[908.73,421.99],[876.18,399.62],[813.71,389.19],[770.56,383.14]],[[588.7,18.64],[543.93,9.54]],[[768.75,384.79],[766.77,384.0]]]}]}}} \ No newline at end of file diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index a5bd8f6..db7fcf5 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -778,15 +778,21 @@ def blocked_plate(views, traces, **more): return core.block_plate(views, {"corners": PLATE}, traces, kit.sheet, **more) -def rendered(name, corners, sigma=0.0, close=0.0, seed=0, take=None): +def rendered(name, corners, sigma=0.0, close=0.0, seed=0, take=None, off=None): """(views, plate, traces, the true sides, the fixture's plate) of a plate of tests/fixtures/spectre_truth.json with `corners` of its loop named: each stroke traced from the renders is cut at the named corners it passes through, every point `sigma` px off, a closing stroke moved `close` px as one. The strokes are the fixture's - own, searched from the truth's projection, or those of its `take`, searched from a seed off it.""" + own, searched from the truth's projection, or those of its `take`, searched from a seed off it, or with + `off` (d, degrees) no search at all: the truth's projection, each point of each stroke in turn moved d px + in its own direction.""" fixture = json.loads((Path(__file__).resolve().parent / "fixtures" / "spectre_truth.json").read_text(encoding="utf-8")) plate, rng, views, traces = fixture["plates"][name], np.random.default_rng(seed), [], [] + turns = iter(np.radians(off[1])) if off else None for k, stroke in enumerate(plate["strokes"]): line = np.array(stroke["line"] if take is None else plate["takes"][take]["lines"][k]) + if off: + line = core.seen(fixture["cameras"][stroke["view"]], fixture["frames"][stroke["view"]], np.array([plate["truth"][corner] for corner in stroke["through"]]) * [stroke["side"], 1, 1]) + line = line + off[0] * np.array([[math.cos(turn), math.sin(turn)] for _, turn in zip(line, turns)]) line = line + (rng.normal(0, sigma, line.shape) if sigma else 0.0) if stroke["closing"] and close: turn = rng.uniform(0, 2 * math.pi) @@ -829,7 +835,7 @@ class BlockTests(unittest.TestCase): """block_plate: a plate's first cage from traces of its outline. Bounds follow lodur:ruling:deterministic-bound-margin; the other numbers are tolerances round a known truth. Mutants, each run once on a copy: - M1 no end terms test_spectre_roof_and_cheek + M1 no end terms test_spectre_roof_and_cheek, test_every_point_as_far_off_bounds_the_rendered_roof M2 a point prior (fit_shell's) for the plane distance test_one_view_and_a_plane_block_a_bowed_plate, test_fairness_is_set_by_the_rendered_roof M3 a seam corner's x free test_spectre_roof_and_cheek, test_the_rendered_roof_blocks_from_traces_of_its_renders M4 no fairness test_fairness_is_set_by_the_rendered_roof @@ -869,10 +875,11 @@ class BlockTests(unittest.TestCase): corner where one pixel moves their meeting point less than core.START x share x the plate's extent, the prior's own scale; with no plane a plate blocks when three corners start. START is 1, the prior's own unit: it is not derived from a measurement, it is pinned between two. At Paladin's lens and range the - pentagon's third corner starts at START 0.724 with the views 19 degrees apart, 0.831 at 16.5, 1.241 at 11 - and 2.729 at 5. So at 16.5 degrees it blocks with no plane (73.0 mm from the truth) and at 11 it is - refused naming its corners: 1 stands 1.20 over the one reading and 1.24 under the other, the two's - geometric mean within 2%. START 0.6 and 0.8 refuse the 16.5 degrees; 2.0, 2.6 and 3.3 block the 11 (104.4 + pentagon's third corner starts at START 0.724 with the views 19 degrees apart, 0.831 at 16.5 and 2.729 at 5; + at 11 this test's plate (0.5 px, seed 7) turns from refused to blocked between START 1.22 and 1.23. So + at 16.5 degrees it blocks with no plane (73.0 mm from the truth) and at 11 it is refused naming its + corners: 1 stands 1.20 over the one reading and 1.22 under the other, the two's geometric mean within + 1%. START 0.6 and 0.8 refuse the 16.5 degrees; 2.0, 2.6 and 3.3 block the 11 (104.4 mm off; the line switches blocking and refusal and is no cliff in accuracy). At 5 degrees the corners triangulate 0.25 to 1.5 m off: with a plane every corner is decided by it (prior_share 0.795 to 0.838), with none the plate is refused. The line is metres a pixel, not degrees: through a lens three times as @@ -1045,13 +1052,14 @@ class BlockTests(unittest.TestCase): parser), every one with the ridge's six corners decided by the mirror plane and the outer edge's five by the views (prior_share 0.037 at most). - What holds: a blocked plate's worst corner stands within 1.18 x its take's worst point x the coarser - view's pixel (1.12, 1.16, 1.18, 1.04, 1.06, 1.11 by family), 33 to 929 mm, 142 at the median; the bound is - a tolerance 1.2 over that, and no mutant is claimed by a margin (M1 reads 1.31). No family stands out of - it: the three draws that grow a side stand at 0.51, 0.75 and 1.08. M3 lands the ridge off x = 0 and every - take is refused. No bound is stated in the takes' rms: a take's worst corner follows its worst point, - and against the rms the same readings reach 5.3. A search seeded on the truth's projection itself is no - reading: its 2.5 px window ends its strokes 2.5 px off and its plate 39 mm off.""" + What the takes read: a blocked plate's worst corner over its take's worst point x the coarser view's + pixel is 1.18 at most (1.12, 1.16, 1.18, 1.04, 1.06, 1.11 by family), 33 to 929 mm, 142 at the median; + the three draws that grow a side stand at 0.51, 0.75 and 1.08. That is no bound: a take's worst point is + one far crossing, and it inflates the denominator (Soul s3, bound-is-the-takes-outliers). The bound is + BOUND, set by test_every_point_as_far_off_bounds_the_rendered_roof, and the takes are held to it. M3 + lands the ridge off x = 0 and every take is refused. No bound is stated in the takes' rms: against the + rms the same readings reach 5.3. A search seeded on the truth's projection itself is no reading: its + 2.5 px window ends its strokes 2.5 px off and its plate 39 mm off.""" corners = ["ridge_rear", "r4", "r3", "r2", "r1", "nose", "a", "b", "c", "d", "e"] views, plate, traces, sides, (fixture, record) = rendered("roof", corners) middle = np.mean(list(record["truth"].values()), axis=0) @@ -1070,9 +1078,40 @@ class BlockTests(unittest.TestCase): self.assertLess(max(corner["prior_share"] for corner in out["corners"]), core.VIEWS / 1.2, take) self.assertGreater(min(corner["parallax_deg"] for corner in out["corners"][6:]), 59, take) self.assertEqual(max(abs(float(np.array(out["sheet"]["verts"])[chain[0], 0])) for chain in crown_chains(out)[:6]), 0.0, take) - self.assertLess(off_rendered(out, sides)[0], 1.42 * off_projection(fixture, record, take) * pixel, take) + self.assertLess(off_rendered(out, sides)[0], self.BOUND * off_projection(fixture, record, take) * pixel, take) self.assertGreaterEqual(blocked, 52) + BOUND = 2.08 # a blocked plate's worst corner, in its worst traced point x the coarser view's pixel: one plate, one pair of views + FAR = [0, 107, 45, 33, 216, 300, 270, 165, 99, 150, 45, 30, 90, 270, 180, 285, 345, 270, 90, 240, 125, 184, 321, 279] # degrees, a point: the worst a search found + + def test_every_point_as_far_off_bounds_the_rendered_roof(self): + """block-bound (Soul s3, bound-is-the-takes-outliers, bound-families-left-out), M1. The worst a trace + does for its worst point is to have no outlier: every point of every stroke the same d px off the + truth's projection. No search, no renders: the rendered roof's truth drawn through its two cameras and + moved. Each view moved as one, 12 directions by 12 at 1 px: all 144 block and the worst corner stands + 1.005 to 1.505 x d x the coarser view's pixel off (1.096 at the median; 1.504 and 1.502 at 2 and 3 px). + M1 reads 2.865 there: BOUND, 2.08, is the geometric mean, separation 1.38 each side. Each stroke its own + direction reaches 1.582 (a coordinate ascent over 12 and 36 directions, six starts) and each point its + own 1.666 at 1 px and 1.659 at 3: FAR, a coordinate ascent over 8 directions from nine starts, which + end at 1.57 to 1.65, the best refined over 24. FAR is the worst found, not the worst there is; BOUND + stands 1.25 over it and claims no mutant there (M1 reads 1.994). The eight families of searched takes, + 40 fresh draws each, read 1.11 to 1.33 (docs/reference.md), every one under the 1.505.""" + corners = ["ridge_rear", "r4", "r3", "r2", "r1", "nose", "a", "b", "c", "d", "e"] + _, _, _, _, (fixture, record) = rendered("roof", corners) + middle = np.mean(list(record["truth"].values()), axis=0) + pixel = max(float(np.linalg.norm(np.array(cam["C"]) - middle)) / cam["f"] for cam in fixture["cameras"].values()) + + def reads(d, degrees): + views, plate, traces, sides, _ = rendered("roof", corners, off=(d, degrees)) + return off_rendered(core.block_plate(views, plate, traces, kit.sheet), sides)[0] / (d * pixel) + + moved = [reads(1.0, [side if stroke["view"] == "side" else hero for stroke in record["strokes"] for _ in stroke["through"]]) + for hero in range(0, 360, 30) for side in range(0, 360, 30)] + self.assertLess(max(moved), self.BOUND) + for d in (1.0, 3.0): + self.assertLess(1.6, reads(d, self.FAR), d) # still the far draw + self.assertLess(reads(d, self.FAR), self.BOUND, d) + def test_fairness_is_set_by_the_rendered_roof(self): """fair (Soul s1, fair-default-tuned-to-a-fit), F5, M4, M2. The rendered roof with four corners named (ridge_rear, nose, a, e), so the ridge and the outer edge are one side each and grow through their knees: @@ -1084,8 +1123,9 @@ class BlockTests(unittest.TestCase): ways, and the bowed pentagon at 60 and 30 degrees and in one view) the mean of the cells' 90th percentiles reads 194, 184, 178, 178, 179, 186, 193, 196 mm at FAIR 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 1 and the worst draw 301, 275, 273, 272, 312, 382, 494, 577, over the draws that blocked: 19, 20, 23, 24, 24, 25, - 26, 27 of the 168 are refused and counted in neither. On Soul's seeds (verdict cut-trace-block.s2) 0.2 is - again lowest by the 90th percentile and not by the worst draw. The roof's strokes here are the fixture's + 26, 27 of the 168 are refused and counted in neither. FAIR is flat from 0.1 to 0.3: 0.2 and 0.25 + tie here, and on Soul's seeds (verdict cut-trace-block.s3) 0.1, 0.15 and 0.2 read 196, 196, 195. 0.2 is + kept as a point on that plateau, not a resolved lowest (docs/reference.md has all three sets). The roof's strokes here are the fixture's own, searched from the truth's projection, with the noise added on top. From exact traces weaker fairness is nearer the truth (the bowed pentagon: 41.6 mm at 0.2, 16.2 at 0.5, 12.1 with none); nobody traces exactly, and at 1 px the difference is 16 mm at 60 degrees and the other way at 30.""" From 76a425c0d2d1444cf32c673b95471b53d5ebd84d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 13:04:04 +0100 Subject: [PATCH 201/223] brokkr_kitbash core: a ram's dead centre is read, no solve answers the other assembly; joint_rows; the refusals reach a test close_loop scales a ram's revolute column by its lever with the slide at 0, so FOLLOW_SINGULAR reads the ram's lever over its closed lever and fires at the rod's end on the barrel's pin; an iterate on the other side of the Jacobian's determinant from its seed is refused as past the dead centre. 120 random rams: 4 wrong-side answers before, 0 after. core.joint_rows derives the joints report's rows, so mutants J7, J8 and J11 die in the unit run; J5, J9 and J10 die on ownership patterns. FollowTests reaches the no-convergence refusal, binds FOLLOW_ITERATIONS to its rule and reads the closing error FOLLOW_TOLERANCE bounds (the 3e-10 mutant reads 2.5e-10). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/core.py | 60 +++++++++++--- surfaces/blender/tests/test_kitbash.py | 100 ++++++++++++++++++++++-- 2 files changed, 144 insertions(+), 16 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 0473318..b1ddab5 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1583,16 +1583,23 @@ def closure_residual(world_a, socket_a: dict, world_b, socket_b: dict) -> float: HELD = 1e-5 # a connection or a closure holds when its residual is at most this: the add-on's HELD is this one # close_loop's three bounds, each read in FollowTests (lodur:ruling:deterministic-bound-margin). # Metres of in-plane closure error Newton stops at. Shipped worst error of an accepted solve 4.1e-11; the least -# error it was still iterating on 2.5e-10; the geometric mean, -# separation 2.4 each side (read by an instrumented copy over FollowTests' solves). +# error it was still iterating on 2.5e-10, which a tolerance of 3e-10 accepts; the geometric mean, separation 2.4 +# each side. FollowTests reads both from the solved frames: its sweep's worst error is under 1.0e-10. FOLLOW_TOLERANCE = 1e-10 # Newton steps one solve may take. Shipped worst 4 (a driver step of 5 degrees toward a dead centre, and one solve -# across a 40 degree jump); a rule, four times the worst. +# across a 40 degree jump); a rule, four times the worst, which FollowTests asserts of its sweep. FOLLOW_ITERATIONS = 16 -# The smaller singular value of the Jacobian with its two columns scaled to unit length (so a linkage's size and the -# metres-per-degree of a revolute column do not move it): about sin(angle between the columns) / sqrt(2), 0 at a dead -# centre, where the two unknowns move the closing pin along one line. Shipped least over the solves that are accepted -# 0.184; the greatest a refused solve reads 0.047 (the four-bar 6.7 degrees from straight); the geometric mean, separation 2.0 each side. +# The smaller singular value of the Jacobian with each column scaled by its lever: about sin(angle between the columns) +# / sqrt(2) for two revolute joints, 0 at a dead centre, where the two unknowns move the closing pin along one line. A +# revolute column is scaled to unit length (so a linkage's size and the metres-per-degree of a column do not move +# it), but for a ram, a revolute joint and then a prismatic one, by its lever with the slide at 0: that column is across +# the slide wherever the rod's end is on the bore's axis, and its dead centre is the rod's end on the barrel's pin, +# where the column vanishes; so a ram reads its lever over its closed lever, 1 at most. The reading is negative once +# the pair stands on the other assembly from its seed (the Jacobian's determinant about the pin has changed sign: an +# elbow bent the other way, a rod's end past its barrel's pin). Shipped least over the solves that are accepted 0.184 +# (the four-bar 30 degrees back from rest; a ram at 0.184 of its closed lever is accepted too); the greatest a refused +# solve reads 0.047 (the four-bar 6.7 degrees from straight; a ram at 0.047 of its closed lever); the geometric mean, +# separation 2.0 each side. FOLLOW_SINGULAR = 0.093 @@ -1606,8 +1613,9 @@ def close_loop(base_world, joints, closing: dict, target_world, seed) -> tuple[t z x (q - o) pi / 180 for the joint's pin z through o, a prismatic one z), from `seed`: the root found is the one on the seed's assembly branch when the seed is near, so a caller steps its input. Refuses, naming which: pins that are not parallel (each revolute z along the target's z, each prismatic z across it, the closing z opposed - to it: the loop is planar); a dead centre (FOLLOW_SINGULAR); no convergence in FOLLOW_ITERATIONS; and a loop - that closes in the plane and misses along the pin (closure_residual over HELD).""" + to it: the loop is planar); a dead centre (FOLLOW_SINGULAR), and an iterate past one, on the other assembly from + the seed, so no solve answers the other branch; no convergence in FOLLOW_ITERATIONS; and a loop that closes in + the plane and misses along the pin (closure_residual over HELD).""" base, target = np.asarray(base_world, dtype=np.float64), np.asarray(target_world, dtype=np.float64) (parent_1, child_1, kind_1), (parent_2, child_2, kind_2) = joints n, values = target[:3, 2], np.array([float(seed[0]), float(seed[1])], dtype=np.float64) @@ -1629,14 +1637,22 @@ def close_loop(base_world, joints, closing: dict, target_world, seed) -> tuple[t if float(np.abs(end[:3, 2] + n).max()) > HELD: raise KitError(f"the loop is not planar: closing socket {closing['name']!r} does not face the pin it closes on " f"(normals off by {float(np.abs(end[:3, 2] + n).max()):.6g})") + ram, side = (kind_1, kind_2) == ("revolute", "prismatic"), None for iteration in range(FOLLOW_ITERATIONS + 1): at_1, at_2, end = placed(values) error = target[:3, 3] - end[:3, 3] error = error - n * (error @ n) J = np.stack([np.cross(at[:3, 2], end[:3, 3] - at[:3, 3]) * (math.pi / 180.0) if kind == "revolute" else at[:3, 2] for kind, at in ((kind_1, at_1), (kind_2, at_2))], axis=1) - lengths = np.linalg.norm(J, axis=0) - singular = 0.0 if lengths.min() < 1e-12 else float(np.linalg.svd(J / lengths, compute_uv=False)[-1]) + levers = np.linalg.norm(J, axis=0) + if ram: # the barrel's lever with the rod's slide at 0 + levers[0] = np.linalg.norm(np.cross(at_1[:3, 2], placed((values[0], 0.0))[2][:3, 3] - at_1[:3, 3])) * (math.pi / 180.0) + singular = 0.0 if levers.min() < 1e-12 else float(np.linalg.svd(J / levers, compute_uv=False)[-1]) + here = float(n @ np.cross(J[:, 0], J[:, 1])) > 0.0 + side = here if side is None else side + if here != side: + raise KitError(f"the loop is past a dead centre (the step takes the two joints that move closing socket {closing['name']!r} to their " + f"other assembly: conditioning {singular:.3g} on that side)") if singular < FOLLOW_SINGULAR: raise KitError(f"the loop is at a dead centre (its two joints move closing socket {closing['name']!r} along one line: " f"conditioning {singular:.3g}, under {FOLLOW_SINGULAR:g})") @@ -1652,6 +1668,28 @@ def close_loop(base_world, joints, closing: dict, target_world, seed) -> tuple[t return (float(values[0]), float(values[1])), iteration +def joint_rows(root_world, entries) -> tuple[list, int]: + """(the rows of a joints report, how many rigid connections folded into them). `entries` is every connection of + a tree in an order where a part comes after its parent: (id, the parent part's id, part name, parent socket, the + parent's 4x4 world, DOF kind or None for rigid, value, joint record, driven: what the report says drives it, or + None). A row is a revolute or prismatic connection; its parent is the nearest one above it (a rigid connection + belongs to the joint above it), its axis and origin the parent socket's z and origin in the frame of root_world, + and min and max what the limits leave of the value either way.""" + frame, nearest, rows, rigid = np.linalg.inv(np.asarray(root_world, dtype=np.float64)), {}, [], 0 + for name, parent, part_name, socket, parent_world, kind, value, record, driven in entries: + if kind is None: + nearest[name], rigid = nearest.get(parent), rigid + 1 + continue + at = frame @ np.asarray(parent_world, dtype=np.float64) @ socket["matrix"] + limits = record["limits"] and [round(v, 6) for v in record["limits"]] + rows.append({"id": name, "parent": nearest.get(parent), "part": part_name, "socket": f"{parent}:{socket['name']}", "kind": kind, + "axis": [round(float(v), 6) for v in at[:3, 2]], "origin": [round(float(v), 6) for v in at[:3, 3]], "value": round(value, 6), + "limits": limits, "min": limits and round(record["limits"][0] - value, 6), "max": limits and round(record["limits"][1] - value, 6), + "mechanism": record["mechanism"], "compliance": record["compliance"], "driven": driven}) + nearest[name] = name + return rows, rigid + + EQUAL, SLACK = 0.01, 1e-9 # 'equal' sizes may differ by 1 percent of the larger; SLACK keeps a size at the limit inside it diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 029da85..a8c4e41 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1594,6 +1594,35 @@ class JointRecordTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, "it reaches -1.000000 m to 1.000000 m"): core.reach_roll(np.eye(4), ident, ident, (0.0, 1.0, 0.0), (1.0, 0.0, 0.0), 1.5, 0.0, (0.0, 90.0)) + def test_joint_rows_are_the_tree_s_dof_connections_in_the_root_s_frame(self): + """core.joint_rows, what brokkr_kitbash.joints reports: a barrel on a strut's pin (revolute), its rod (prismatic) + and, on a root turned and moved in the world, a rigid part between two joints. Mutants J7 (a row's parent the + part's parent, not the nearest joint above: 'Plate'), J8 (min and max the limits themselves: -20 and 60 for + -50 and 30) and J11 (axis and origin in the world's frame: the origin stands 5.4 m off).""" + parts = self.kit["parts"] + strut, barrel, rod = (core.build(parts[name], {}) for name in ("strut", "ram_barrel", "ram_rod")) + socket = lambda built, name: next(s for s in built.sockets if s["name"] == name) # noqa: E731 + root = np.eye(4) + root[:3, :3] = core._rotation((20.0, -35.0, 50.0)) + root[:3, 3] = (1.0, -2.0, 5.0) + barrel_world = root @ core.mate(socket(strut, "end_b"), socket(barrel, "base"), 30.0) + record = {"limits": (-20.0, 60.0), "mechanism": "elbow", "compliance": None} + free = {"limits": None, "mechanism": None, "compliance": None} + rows, rigid = core.joint_rows(root, [ + ("Barrel", "Root", "ram_barrel", socket(strut, "end_b"), root, "revolute", 30.0, record, None), + ("Plate", "Barrel", "bracket", socket(barrel, "port_cap"), barrel_world, None, 0.0, free, None), + ("Rod", "Plate", "ram_rod", socket(barrel, "bore"), barrel_world, "prismatic", 0.125, free, {"by": "Barrel", "kind": "ratio", "k": 0.001, "offset": 0.095})]) + self.assertEqual(rigid, 1) + self.assertEqual([(row["id"], row["parent"], row["kind"], row["socket"]) for row in rows], + [("Barrel", None, "revolute", "Root:end_b"), ("Rod", "Barrel", "prismatic", "Plate:bore")]) + self.assertEqual((rows[0]["value"], rows[0]["limits"], rows[0]["min"], rows[0]["max"], rows[0]["mechanism"], rows[0]["driven"]), (30.0, [-20.0, 60.0], -50.0, 30.0, "elbow", None)) + self.assertEqual((rows[1]["value"], rows[1]["limits"], rows[1]["min"], rows[1]["max"], rows[1]["driven"]["by"]), (0.125, None, None, None, "Barrel")) + pin = socket(strut, "end_b")["matrix"] + self.assertEqual((rows[0]["axis"], rows[0]["origin"]), ([round(float(v), 6) for v in pin[:3, 2]], [round(float(v), 6) for v in pin[:3, 3]])) # in the root's frame: the socket as the part has it + bore = core.mate(socket(strut, "end_b"), socket(barrel, "base"), 30.0) @ socket(barrel, "bore")["matrix"] + self.assertEqual((rows[1]["axis"], rows[1]["origin"]), ([round(float(v), 6) for v in bore[:3, 2]], [round(float(v), 6) for v in bore[:3, 3]])) + self.assertGreater(float(np.linalg.norm((root @ pin)[:3, 3] - pin[:3, 3])), 5.0) # the world's frame is not the root's here + def test_limit_slack_sits_between_a_typed_end_and_the_least_refused(self): """joint-records-lows. core.LIMIT_SLACK at the midpoint of its readings (2.4e-07), read 1.2 either side: a slack of 1.9e-08 loses float32(-20.1) and the value 2e-07 off; one of 2e-06 or 2.9e-06 (or the 1e-06 there @@ -1618,6 +1647,7 @@ class FollowTests(unittest.TestCase): PHI = 2.8e-7 # degrees between the rocker's roll change and ram.pose's phi. shipped 1.9e-10; least mutant 4.0e-4 (T1); separation 1.4e3 each side SLID = 5.6e-10 # metres between the rod's slide and |pin - base| less the closed length. shipped 5.4e-13; least mutant 5.9e-7 (T1); separation 1.0e3 each side BRANCH = 1e-6 # degrees between one solve across a jump and the stepped answer. shipped 4e-12 (both converge to FOLLOW_TOLERANCE); a rule: the other branch stands tens of degrees off + CLOSED = 1.0e-10 # metres an accepted solve's closing origin stands from the pin, read from the frames. shipped worst 4.1e-11; a FOLLOW_TOLERANCE of 3e-10 reads 2.5e-10; separation 2.5 each side @classmethod def setUpClass(cls): @@ -1666,7 +1696,7 @@ class FollowTests(unittest.TestCase): return float(np.linalg.svd(np.stack(columns, axis=1), compute_uv=False)[-1]) def stepped(self, deltas): - seed, worst = self.REST, {"phi": 0.0, "iterations": 0, "conditioning": math.inf} + seed, worst = self.REST, {"phi": 0.0, "iterations": 0, "conditioning": math.inf, "closed": 0.0} rest = (core.mate(self.rocker_pin, self.rocker["end_a"], self.REST[0]) @ self.rocker["end_b"]["matrix"])[:3, 3] four_bar = self.ram.Mechanism("four_bar", pivot=self.ground["matrix"][:3, 3], axis=self.ground["matrix"][:3, 2], lo=-90, hi=130, a=np.array([0.3, 0.0, -0.4]), rocker=self.rocker_pin["matrix"][:3, 3], p=rest, c=self.crank_pin(self.D0)[:3, 3], d=rest) @@ -1674,15 +1704,21 @@ class FollowTests(unittest.TestCase): seed, iterations = self.solve(self.D0 + delta, seed) worst["phi"] = max(worst["phi"], abs(seed[0] - self.REST[0] - math.degrees(self.ram.pose(four_bar, delta).phi[0]))) worst["iterations"], worst["conditioning"] = max(worst["iterations"], iterations), min(worst["conditioning"], self.conditioning(seed)) + worst["closed"] = max(worst["closed"], float(np.linalg.norm(self.crank_pin(self.D0 + delta)[:3, 3] - self.coupler_end(self.rocker_pin, seed)[:3, 3]))) return seed, worst def test_a_four_bar_loop_matches_ram_pose(self): """loop-matches-ram-pose. 56 driver steps of 5 degrees, +120 and back to -30. Mutant F1 (a revolute Jacobian column's sign flipped: no solve converges). The readings here are the shipped side of core's three bounds: - conditioning least 0.184 (at -30), iterations at most 4 (the step to -30).""" + conditioning least 0.184 (at -30), iterations at most 4 (the step to -30), and the closing origin 4.1e-11 m + from the pin at worst: a FOLLOW_TOLERANCE of 3e-10 stops one step short on 2.5e-10. FOLLOW_ITERATIONS is its + rule, four times the worst.""" _, worst = self.stepped([*np.arange(0.0, 121.0, 5.0), *np.arange(120.0, -31.0, -5.0)]) self.assertLess(worst["phi"], self.PHI) self.assertEqual(worst["iterations"], 4) + self.assertEqual(core.FOLLOW_ITERATIONS, 4 * worst["iterations"]) + self.assertLess(worst["closed"], self.CLOSED) + self.assertLess(worst["closed"], core.FOLLOW_TOLERANCE) self.assertAlmostEqual(worst["conditioning"], 0.184, delta=0.001) self.assertGreater(worst["conditioning"], 1.2 * core.FOLLOW_SINGULAR) @@ -1699,14 +1735,46 @@ class FollowTests(unittest.TestCase): self.assertLess(worst, self.SLID) self.assertGreater(seed[1] - self.RAM_REST[1], 0.2) # the rod moved + def test_a_ram_s_dead_centre_is_its_rod_end_on_the_barrel_pin(self): + """A ram's conditioning is its lever over its lever closed, and its dead centre the rod's end on the barrel's + pin: drawn in along its own line the ram is accepted at 0.184 of the closed lever and refused at 0.047, the two + readings core.FOLLOW_SINGULAR sits between; and one solve to a pin on the far side of the barrel's, which + Newton answers in one step with the rod's end through the pin, is refused as past the dead centre and not + answered. Mutants C1 (the ram's revolute column scaled to unit length as a four-bar's: it reads 1 at 0.047) + and C2 (the side not read: the far pin is answered at a slide of -1.2 closed levers).""" + base, rest = self.barrel_pin["matrix"][:3, 3], self.crank_pin(self.D0, "end_b_back") + closed = float(np.linalg.norm(self.rod_end(self.barrel_pin, (self.RAM_REST[0], 0.0))[:3, 3] - base)) + along = (rest[:3, 3] - base) / np.linalg.norm(rest[:3, 3] - base) + + def pin(lever): + target = rest.copy() + target[:3, 3] = base + along * lever * closed + return target + + seed = self.RAM_REST + for lever in (1.0, 0.8, 0.6, 0.4, 0.3, 0.184): + seed, _ = core.close_loop(np.eye(4), self.ram_loop, self.rod["rod_end"], pin(lever), seed) + self.assertAlmostEqual(seed[1], (lever - 1.0) * closed, delta=self.SLID) + self.assertAlmostEqual(seed[0], self.RAM_REST[0], delta=self.BRANCH) + self.assertGreater(0.184, 1.2 * core.FOLLOW_SINGULAR) + self.assertLess(0.047, core.FOLLOW_SINGULAR / 1.2) + with self.assertRaisesRegex(core.KitError, r"^the loop is at a dead centre \(its two joints move closing socket 'rod_end' along one line: conditioning 0\.047, under 0\.093\)$"): + core.close_loop(np.eye(4), self.ram_loop, self.rod["rod_end"], pin(0.047), seed) + with self.assertRaisesRegex(core.KitError, r"^the loop is past a dead centre \(the step takes the two joints that move closing socket 'rod_end' to their other assembly: " + r"conditioning 0\.184 on that side\)$"): + core.close_loop(np.eye(4), self.ram_loop, self.rod["rod_end"], pin(-0.184), seed) + def test_a_dead_centre_is_refused(self): """loop-refusals. Stepping the crank back, rocker and coupler straighten: the step to -35 stands 6.7 degrees - from straight, conditioning 0.047, the refused side of core.FOLLOW_SINGULAR; past it no pose closes the loop.""" + from straight, conditioning 0.047, the refused side of core.FOLLOW_SINGULAR; past it no pose closes the loop, + and at -60 Newton's first step bends the pair the other way, which is refused as past the dead centre.""" seed, _ = self.stepped(np.arange(0.0, -31.0, -5.0)) self.assertLess(0.047, core.FOLLOW_SINGULAR / 1.2) - for delta in (-35.0, -40.0, -60.0): + for delta in (-35.0, -40.0): with self.assertRaisesRegex(core.KitError, r"^the loop is at a dead centre \(its two joints move closing socket 'end_b' along one line"): self.solve(self.D0 + delta, seed) + with self.assertRaisesRegex(core.KitError, r"^the loop is past a dead centre \(the step takes the two joints that move closing socket 'end_b' to their other assembly"): + self.solve(self.D0 - 60.0, seed) near, _ = self.stepped(np.arange(0.0, -34.0, -1.0)) # by single degrees it is accepted to -33, and -34 reads 0.092 self.assertAlmostEqual(self.conditioning(near), 0.1212, delta=0.001) with self.assertRaisesRegex(core.KitError, r"conditioning 0\.0919, under 0\.093\)$"): @@ -1731,6 +1799,15 @@ class FollowTests(unittest.TestCase): core.close_loop(np.eye(4), self.four_bar, self.coupler["end_b"], missed, self.REST) self.assertEqual(self.solve(self.D0, self.REST), (self.REST, 0)) # at rest it holds: no step is taken + def test_a_loop_that_does_not_converge_is_refused(self): + """loop-refusals. A pin 3.9 m out of the reach of a 0.9 and a 0.7 strut, where Newton from rest neither + straightens the pair nor bends it the other way in FOLLOW_ITERATIONS steps: refused by its own name, with + how far off it stands.""" + target = self.crank_pin(self.D0) + target[:3, 3] += (-1.2, 0.0, 3.8) + with self.assertRaisesRegex(core.KitError, r"^the loop did not close in 16 steps \(closing socket 'end_b' stands 3\.94584 m off in the plane\)$"): + core.close_loop(np.eye(4), self.four_bar, self.coupler["end_b"], target, self.REST) + def test_stepping_keeps_the_assembly_branch(self): """branch-kept. One solve across a 40 degree jump lands on the stepped answer; one solve from near the toggle (-32) across 49 degrees does not: Newton's first step throws the pair through the dead centre, where it is @@ -2458,6 +2535,17 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(source.count("core.close_loop("), 1) self.assertIn("core.close_loop(", source.split("\ndef driven(")[1].split("\n\n\n")[0]) self.assertEqual(source.count("write_connections(["), 2) # write_connection, and follow clearing a statement + # every entry is checked before one is written (mutant J5, a refusal raised after the writes; F5 is its live twin): the writer's loop runs over the + # checks' whole answer and raises nothing itself, and the checks write nothing + self.assertIn(" for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in connection_checks(entries):\n child.parent = parent\n", writer) + self.assertNotIn("raise ", writer) + checks = source.split("\ndef connection_checks(")[1].split("\n\n\n")[0] + self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|\w+\[\w+\]\s*=(?!=)|\bdel ", checks)) + self.assertEqual(checks.count("raise Refused("), 1) + # a hose keeps no roll range of its own (mutant J9, a default range for a pin that states no limits): it reads the record's limits and refuses without them + hose = source.split("class BROKKR_KITBASH_OT_hose(")[1].split("\n\n\n")[0] + self.assertEqual(re.findall(r"[^\n]*\blimits\s*=(?!=)[^\n]*", hose), [' limits = joint_record(child)["limits"] # the roll range the hose is proven over is the pin\'s own: its connection\'s limits']) + self.assertIn(' if limits is None:\n raise Refused(f"{child.name!r} on {child.parent.name!r}: the pin the hose crosses states no limits', hose) pose = source.split("\ndef pose(")[1].split("\n\n\n")[0] self.assertLess(pose.index("if follows is not None and not keeps:"), pose.index("= solve(child")) self.assertEqual(source.count("keeps=True"), 1) @@ -2638,7 +2726,9 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(assigned, [" obj[CLOSE], obj[CLOSE_TO], obj[CLOSE_TO_SOCKET] = self.socket, other, self.other_socket"]) self.assertIn(assigned[0], bodies["close"]) deleted = re.findall(r"[^\n]*\(SOCKET, PARENT_SOCKET, ROLL, \*RECORD, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET\)[^\n]*\n[^\n]*\n\s*del obj\[key\]", source) - self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and hold's kit_frozen + self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and hold's kit_frozen; mutant J10 (detach's keys without kit_min) dies on the first + record = re.search(r"^RECORD = \((.*)\)$", source, re.M).group(1).split(", ") + self.assertEqual(record, ["SLIDE", "LIMIT_MIN", "LIMIT_MAX", "MECHANISM", "COMPLIANCE", "FOLLOWS", "FOLLOWS_DRIVER"]) # the whole joint record: what detach clears self.assertEqual(source.count("CLOSE_TO]"), 1) # the one subscript write above; every read goes through .get placing = r"matrix_basis|matrix_world\s*=(?!=)|matrix_parent_inverse|\.parent\s*=(?!=)|\bseat\(|\.location|\.rotation" self.assertIsNone(re.search(placing, bodies["close"])) From 56730c0c87036a6a90aeebc48ff7535d4f3b819f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 13:04:04 +0100 Subject: [PATCH 202/223] brokkr_kitbash: follow refuses a loop whose ends depend on more than one driver; joints pages unlimited with its rows follow names the driver and every other input between a loop's two ends: a follower of another driver, or a joint with travel that follows nothing. A joint both ends hang from, and one held by limits of one value, are not inputs. The torque link fixture holds its lug by limits [90, 90]: one row with travel that nothing drives, nothing unlimited. joints builds its rows in core.joint_rows; unlimited lists the ids of the rows a report carries and is counted with them, so a report is never over a receipt and always carries a row. Live kitbash_follows: 76 checks; both halves of the loop-ends rule, the two second-driver refusals, the free lug, a hinge above both ends, and a tree of 264 unlimited joints with 62-character names. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 71 +++++++---- .../brokkr_kitbash/brokkr_actions.json | 4 +- .../blender/tests/live/kitbash_follows.py | 114 ++++++++++++++---- .../tests/live/kitbash_follows.result.json | 60 ++++++++- 4 files changed, 199 insertions(+), 50 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index bc64a05..70a2126 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -70,7 +70,9 @@ a pointer to the driver. A follower's kit_roll or kit_slide is then derived: by for the closing part of a loop and its parent, by solving the two so the closure holds (core.close_loop, over the kit's socket frames at stored params: no pin is stored). pose() derives every follower of a driver in the driver's own action (driven) and write_connections writes them with it, all or none; roll, aim, reach and slide on a follower -are refused. A follower has one driver and a driver is never a follower. No Blender driver or constraint is made. +are refused. A follower has one driver and a driver is never a follower; follow refuses a loop whose two ends +depend on any joint that is not its driver, a follower of its driver or held by limits of one value, so one driver's +pose is all a loop's value is a function of. No Blender driver or constraint is made. """ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (5, 3, 0), "category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."} @@ -822,13 +824,15 @@ def bounded(report: dict, advice: str) -> dict: return report -def fitted(report: dict, key: str, rows: list) -> list: +def fitted(report: dict, key: str, rows: list, beside=None) -> list: """The rows of one list of a report that fit what a receipt carries beside the rest of the report, in order; those left off the end are counted in report[key + 'Omitted']. The one rule that trims a report's rows to a receipt: - the scene keeps what the rows would have said.""" + the scene keeps what the rows would have said. `beside(row)` is what a caller adds to the report for a row it + keeps (joints: its id in `unlimited`), counted with the row.""" kept, size = [], len(json.dumps(report, separators=(",", ":"))) + 2 * len(key) + 24 for row in rows: - size += len(json.dumps(row, separators=(",", ":"))) + 1 + extra = None if beside is None else beside(row) + size += sum(len(json.dumps(value, separators=(",", ":"))) + 1 for value in (row, extra) if value is not None) if size > REPORT_LIMIT: report[key + "Omitted"] = len(rows) - len(kept) break @@ -1205,38 +1209,36 @@ class BROKKR_KITBASH_OT_joints(PolishOperator): @kit_work def work(self, context): - root, kits, rows, rigid_count = mesh_object(self.object_name), {}, [], 0 + root, kits, entries = mesh_object(self.object_name), {}, [] built_part(root, kits) - frame = np.linalg.inv(np.array(root.matrix_world, dtype=np.float64)) - todo = [(root, None)] - while todo: # depth first, children by name: a joint's parent joint is the nearest DOF connection above it, and rigid connections fold into it - child, above = todo.pop() + todo = [root] + while todo: # depth first, children by name: the order core.joint_rows reads a joint's parent joint in + child = todo.pop() if child != root or link(child) is not None and child.parent is not None and PART in child.parent: # the root's own joint comes first, parent null part, built = built_part(child, kits) stated = link(child) parent_socket, _ = mated(child.parent, *built_part(child.parent, kits), child, part, built, stated) kind = dof(child.parent, parent_socket) - if kind is None: - rigid_count += child != root - else: - record, value = joint_record(child), stated[2] if kind == "revolute" else stated[3] - at = frame @ np.array(child.parent.matrix_world, dtype=np.float64) @ parent_socket["matrix"] - limits, follows = record["limits"] and [round(v, 6) for v in record["limits"]], record["follows"] - rows.append({"id": child.name, "parent": above, "part": part["name"], "socket": f"{child.parent.name}:{stated[1]}", "kind": kind, - "axis": [round(float(v), 6) for v in at[:3, 2]], "origin": [round(float(v), 6) for v in at[:3, 3]], "value": round(value, 6), - "limits": limits, "min": limits and round(record["limits"][0] - value, 6), "max": limits and round(record["limits"][1] - value, 6), - "mechanism": record["mechanism"], "compliance": record["compliance"], - "driven": follows and {"by": follows["driver"] and follows["driver"].name, "kind": follows["kind"], "k": follows["k"], "offset": follows["offset"]}}) - above = child.name - todo += [(below, above) for below in sorted(attached(child), key=lambda o: o.name, reverse=True)] + if kind is not None or child != root: + record = joint_record(child) + follows = record["follows"] + entries.append((child.name, child.parent.name, part["name"], parent_socket, np.array(child.parent.matrix_world, dtype=np.float64), kind, + stated[2] if kind == "revolute" else stated[3], record, + follows and {"by": follows["driver"] and follows["driver"].name, "kind": follows["kind"], "k": follows["k"], "offset": follows["offset"]})) + todo += sorted(attached(child), key=lambda o: o.name, reverse=True) + rows, rigid_count = core.joint_rows(np.array(root.matrix_world, dtype=np.float64), entries) + ids = [row["id"] for row in rows] report = {"schema": "brokkr.joints", "version": 2, "root": root.name, "frame": "the root object's: Blender axes (+Z up), metres", "rigid": rigid_count, - "unlimited": [row["id"] for row in rows if row["limits"] is None and row["driven"] is None], "next": "x" * 63} + "unlimited": [], "next": max(ids, key=lambda name: len(json.dumps(name)), default=None)} if self.after: - ids = [row["id"] for row in rows] if self.after not in ids: raise Refused(f"after {self.after!r} is not the id of a joint under {root.name!r}: it is the `next` of the report before, or empty.") rows = rows[ids.index(self.after) + 1:] - report["joints"] = fitted(report, "joints", rows) + + def unlimited(row): + return row["id"] if row["limits"] is None and row["driven"] is None else None + report["joints"] = fitted(report, "joints", rows, unlimited) # a row and its id in `unlimited` are kept or left together: the list pages with the rows + report["unlimited"] = [row["id"] for row in report["joints"] if unlimited(row) is not None] report["next"] = report["joints"][-1]["id"] if "jointsOmitted" in report and report["joints"] else None return report @@ -1317,6 +1319,25 @@ class BROKKR_KITBASH_OT_follow(PolishOperator): if moves(ends[0]) == moves(ends[1]): raise Refused(f"the loop's two ends, {ends[0].name!r} (the base) and {ends[1].name!r} (closed on), {'both move' if moves(ends[0]) else 'neither moves'} with " f"{driver.name!r}: exactly one of them is the driver, follows it, or hangs from one that does; nothing changed.") + chains = [[], []] # each end and what it hangs from, up to the root + for found, o in zip(chains, ends): + while o is not None: + found.append(o) + o = o.parent + others = {} # {a part whose pose moves one end against the other, and is not the driver: why}, from the joints under the ends' nearest common part + for o in (o for found in chains for o in found if not (o in chains[0] and o in chains[1])): + its, limits = joint_record(o)["follows"], joint_record(o)["limits"] + if connection_kind(o)[0] is None or o == driver or its is not None and its["driver"] in (None, driver): + continue + if its is not None: + others.setdefault(its["driver"], f"{o.name!r} follows it") + elif limits is None or limits[0] < limits[1]: # limits of one value hold a joint still: a pin with no travel + others.setdefault(o, "it follows nothing and its joint has travel, so it is posed by hand") + if others: + raise Refused(f"the loop's two ends, {ends[0].name!r} (the base) and {ends[1].name!r} (closed on), depend on more than one driver: {driver.name!r} and " + f"{', '.join(f'{o.name!r} ({why})' for o, why in sorted(others.items(), key=lambda item: item[0].name))}. A follower takes its value from " + "one driver, and a pose of another would open the loop: let every joint between the two ends be the driver, follow it, or be held by " + "limits of one value; nothing changed.") follows = {"driver": driver, "kind": given["kind"], "k": float(given["k"]) if ratio else None, "offset": float(given["offset"]) if ratio else None} entries, moved = driven(driver, driver_sockets, driver_stated, driver_stated[2], driver_stated[3], None, {o: follows for o in pair}) write_connections(entries) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index f70394f..1c52b58 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -360,7 +360,7 @@ }, { "name": "brokkr_kitbash.joints", - "doc": "The joints of the tree of kit parts attached under a root part, as {schema: brokkr.joints, version: 2, root, frame, rigid, unlimited, next, joints}. A row per revolute or prismatic connection, depth first with children by name, so a joint's parent row comes before it; a root that itself states a revolute or prismatic connection has its own row first, parent null: id (the child object), parent (the id of the nearest joint above, or null: rigid connections fold into it and are counted in rigid), part, socket ('Object:socket', the parent socket), kind, axis and origin (that socket's z and origin in the root object's frame: Blender axes, +Z up, metres), value (the roll in degrees or the slide in metres now), limits ([lo, hi] or null), min and max (the limits less the value: the travel either way from this pose), mechanism, compliance and driven (null, or {by: the driver's id, kind: ratio | loop, k, offset}: the value is derived from the driver's, so a rig makes a driven bone and not a DOF). kind is revolute or prismatic: Aetheria's ShipJoint calls them rotate and slide, one to one. unlimited lists the ids of the rows that are not driven and state no limits, in the whole tree: an exporter that needs limits refuses by this one field. Axis, origin and order are derived at each report from the kits and the parent tree; nothing stores them. Rows a receipt cannot carry are counted in jointsOmitted, and next is then the id of the last row carried (else null): call again with after set to it for the rows that follow. after refuses an id that is no row's. Refuses a connection that cannot be read. Evaluates no modifier.", + "doc": "The joints of the tree of kit parts attached under a root part, as {schema: brokkr.joints, version: 2, root, frame, rigid, unlimited, next, joints}. A row per revolute or prismatic connection, depth first with children by name, so a joint's parent row comes before it; a root that itself states a revolute or prismatic connection has its own row first, parent null: id (the child object), parent (the id of the nearest joint above, or null: rigid connections fold into it and are counted in rigid), part, socket ('Object:socket', the parent socket), kind, axis and origin (that socket's z and origin in the root object's frame: Blender axes, +Z up, metres), value (the roll in degrees or the slide in metres now), limits ([lo, hi] or null), min and max (the limits less the value: the travel either way from this pose), mechanism, compliance and driven (null, or {by: the driver's id, kind: ratio | loop, k, offset}: the value is derived from the driver's, so a rig makes a driven bone and not a DOF). kind is revolute or prismatic: Aetheria's ShipJoint calls them rotate and slide, one to one. unlimited lists the ids of the rows this report carries that are not driven and state no limits: an exporter that needs limits refuses by this one field of each report. Axis, origin and order are derived at each report from the kits and the parent tree; nothing stores them. Rows a receipt cannot carry are counted in jointsOmitted, and next is then the id of the last row carried (else null): call again with after set to it for the rows that follow and their unlimited ids; a report is never over a receipt and always carries a row. after refuses an id that is no row's. Refuses a connection that cannot be read. Evaluates no modifier.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", @@ -384,7 +384,7 @@ }, { "name": "brokkr_kitbash.follow", - "doc": "State that an attached kit part's joint follows another's: its roll or slide is then derived from the driver's whenever the driver is posed, and roll, aim, reach and slide on it are refused. record is JSON. {\"driver\": name, \"kind\": \"ratio\", \"k\": number, \"offset\": number}: the value is k x the driver's value + offset (a kneecap at k 0.5, a pinion at minus ring over pinion, a crosshead's slide in metres per degree of a roll); the driver states limits, so its value is one number. {\"driver\": name, \"kind\": \"loop\"}: object_name is a part that states a closure that holds; its joint and its parent's are the two unknowns solved so the closure keeps holding (a rocker and coupler closing on a crank; a ram's barrel and rod closing on the part it pushes; a torque link's two arms), and both follow the driver. Exactly one end of the loop, the parent's parent or the part closed on, moves with the driver: it is the driver, follows it, or hangs from one that does. The loop is planar: its pins are parallel. null clears the statement, and a loop partner's with it. The follower moves at once and the report's followers lists every follower of the driver as {part, value}. Refuses, with nothing changed: a rigid connection; a driver that is the follower, below it, or itself a follower; a follower that already follows or that drives another; a ratio whose driver states no limits; a value outside the follower's own limits; a loop with no closure that holds, with both ends or neither moving with the driver, that is not planar, or at a dead centre (its two joints in line). Nothing stores a pin or a linkage: a loop is solved from the kits' socket frames each time, and no Blender driver or constraint is made.", + "doc": "State that an attached kit part's joint follows another's: its roll or slide is then derived from the driver's whenever the driver is posed, and roll, aim, reach and slide on it are refused. record is JSON. {\"driver\": name, \"kind\": \"ratio\", \"k\": number, \"offset\": number}: the value is k x the driver's value + offset (a kneecap at k 0.5, a pinion at minus ring over pinion, a crosshead's slide in metres per degree of a roll); the driver states limits, so its value is one number. {\"driver\": name, \"kind\": \"loop\"}: object_name is a part that states a closure that holds; its joint and its parent's are the two unknowns solved so the closure keeps holding (a rocker and coupler closing on a crank; a ram's barrel and rod closing on the part it pushes; a torque link's two arms), and both follow the driver. Exactly one end of the loop, the parent's parent or the part closed on, moves with the driver: it is the driver, follows it, or hangs from one that does. The driver is the one input the two ends depend on: every revolute or prismatic joint between an end and the part both ends hang from is the driver, follows it, or is held by limits of one value (a torque link's lug on its rod: limits [90, 90]). The loop is planar: its pins are parallel. null clears the statement, and a loop partner's with it. The follower moves at once and the report's followers lists every follower of the driver as {part, value}. Refuses, with nothing changed: a rigid connection; a driver that is the follower, below it, or itself a follower; a follower that already follows or that drives another; a ratio whose driver states no limits; a value outside the follower's own limits; a loop with no closure that holds, with both ends or neither moving with the driver, whose ends depend on more than one driver (another driver's follower, or a joint with travel that follows nothing: both are named), that is not planar, or at or past a dead centre (its two joints in line, a ram's rod end on its barrel's pin, or a step that would take the pair to its other assembly). Nothing stores a pin or a linkage: a loop is solved from the kits' socket frames each time, and no Blender driver or constraint is made.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/tests/live/kitbash_follows.py b/surfaces/blender/tests/live/kitbash_follows.py index 2189d2e..d7ae4d0 100644 --- a/surfaces/blender/tests/live/kitbash_follows.py +++ b/surfaces/blender/tests/live/kitbash_follows.py @@ -12,10 +12,13 @@ inside one try: an uncaught error is a failed check that names the check before The scene, every strut 0.09 wide so its pins take a ram's: a four-bar (Crank on the root Ground, Rocker on the root Base, Coupler closing on the crank); a ram (A_Barrel on the root Pad, A_Rod in its bore, closing on the rocker), named to sort before the four-bar it waits on; ratio followers of the crank (Cap, Pinion, and X_Rod's slide in X_Barrel); a -torque link (T_Rod sliding in the root T_Barrel, T_Upper and T_Lower closing on T_Lug, a strut pinned on the rod's -rod_end_back: a strut's two pins face one way, so two arms from the barrel's pin cannot face the rod's own); Idle -and Tip for the refusals; a chain of 80 struts for a joints report over a receipt. Bounds follow -lodur:ruling:deterministic-bound-margin, both readings beside each; the result file carries the readings. +torque link (T_Rod sliding in the root T_Barrel, T_Upper and T_Lower closing on T_Lug, a strut on the rod's +rod_end_back held at 90 degrees by limits of that one value: a strut's two pins face one way, so two arms from the +barrel's pin cannot face the rod's own, and the kit has no rigid lug); a second crank (Crank2 on the root Ground2) +whose ram closes on the rocker, and a loop hung from its own driver (K3, B3, Rk3, Cp3 on the root G3), for the +one-driver refusals; Idle and Tip for the refusals; a tree of 264 struts with 62-character names for a joints +report over several receipts. Bounds follow lodur:ruling:deterministic-bound-margin, both readings beside each; the +result file carries the readings. """ import importlib.util import json @@ -207,6 +210,8 @@ try: return core.close_loop(world(base), four_bar, socket(coupler, "end_b"), crank_pin(roll), seed) # --- parts for the refusals --------------------------------------------------------------------------------------------- + far = np.eye(4) + far[:3, 3] = [0.0, -8.0, 0.0] place("Idle", "strut", W), place("Tip", "strut", W), place("Loose", "strut", W) attach("Idle", "end_a", "Ground", "end_b", 15.0) attach("Tip", "end_a", "Idle", "end_b", 0.0) @@ -216,6 +221,24 @@ try: loop = '{"driver": "Crank", "kind": "loop"}' refused("a loop whose two ends both stand still when the driver moves (F7)", "brokkr_kitbash.follow", {"object_name": "Coupler", "record": '{"driver": "Idle", "kind": "loop"}'}, "'Base' (the base) and 'Crank' (closed on), neither moves with 'Idle'") + place("G3", "strut", W + "length=0.8", far @ far @ far @ turn) + k3, b3, rk3, cp3 = place("K3", "strut", W + "length=0.5"), place("B3", "strut", W + "length=0.8"), place("Rk3", "strut", W + "length=0.9"), place("Cp3", "strut", W + "length=0.7") + attach("K3", "end_a", "G3", "end_a", 10.0) + attach("B3", "end_a", "K3", "end_a_back", 0.0) + hung = None + for guess in ((g0, g1) for g0 in range(-180, 180, 45) for g1 in range(-180, 180, 45)): # a pose at which a rocker and coupler on B3 close on K3 + try: + hung, _ = core.close_loop(world(b3), [(socket(b3, "end_b"), socket(rk3, "end_a"), "revolute"), (socket(rk3, "end_b_back"), socket(cp3, "end_a"), "revolute")], + socket(cp3, "end_b"), frame(k3, "end_b"), (float(guess[0]), float(guess[1]))) + break + except core.KitError: + continue + attach("Rk3", "end_a", "B3", "end_b", core._wrapped(hung[0]) if hung else 0.0) + attach("Cp3", "end_a", "Rk3", "end_b_back", core._wrapped(hung[1]) if hung else 0.0) + receipt, report = send("brokkr_kitbash.close", object_name="Cp3", socket="end_b", other_name="K3", other_socket="end_b") + check("a loop whose base hangs from the part it closes on stands closed", hung is not None and receipt["status"] == "accepted" and report["closure"]["holds"] is True, [hung, receipt["message"]]) + refused("a loop whose two ends both move with the driver (F7, the other half)", "brokkr_kitbash.follow", {"object_name": "Cp3", "record": '{"driver": "K3", "kind": "loop"}'}, + "'B3' (the base) and 'K3' (closed on), both move with 'K3'") refused("a loop follower that states no closure", "brokkr_kitbash.follow", {"object_name": "Rocker", "record": loop}, "'Rocker' states no closure that holds") refused("a follower on a rigid connection", "brokkr_kitbash.follow", {"object_name": "Brk", "record": '{"driver": "Crank", "kind": "ratio", "k": 1, "offset": 0}'}, "socket type 'mount' states no dof") @@ -331,8 +354,29 @@ try: seed = stepped(solve_four_bar, seed, 120.0, D0, 5.0) a_barrel, a_rod = place("A_Barrel", "ram_barrel"), place("A_Rod", "ram_rod") - def rod_end(pad_world, values): - return pad_world @ core.mate(socket(ground, "end_a"), socket(a_barrel, "base"), values[0]) @ core.mate(socket(a_barrel, "bore"), socket(a_rod, "piston"), 0.0, values[1]) @ socket(a_rod, "rod_end")["matrix"] + def rod_end(pad_world, values, pin=None): + return (pad_world @ core.mate(pin or socket(ground, "end_a"), socket(a_barrel, "base"), values[0]) @ core.mate(socket(a_barrel, "bore"), socket(a_rod, "piston"), 0.0, values[1]) + @ socket(a_rod, "rod_end")["matrix"]) + + # one driver: a ram on a second crank closes on the rocker, which follows the first (the probe of finding second-driver-loop-opens) + place("S_Barrel", "ram_barrel"), place("S_Rod", "ram_rod") + crank2 = place("Crank2", "strut", W + "length=0.4") + shift = np.eye(4) + shift[:3, 3] = frame(rocker, "end_b_back")[:3, 3] - rod_end(turn, RAM_REST, socket(crank2, "end_b"))[:3, 3] + place("Ground2", "strut", W + "length=0.8", shift @ turn @ np.linalg.inv(core.mate(socket(ground, "end_a"), socket(crank2, "end_a"), 20.0))) + attach("Crank2", "end_a", "Ground2", "end_a", 20.0) + attach("S_Barrel", "base", "Crank2", "end_b", RAM_REST[0]) + attach("S_Rod", "piston", "S_Barrel", "bore", 0.0) + send("brokkr_kitbash.slide", object_name="S_Rod", slide=RAM_REST[1]) + receipt, report = send("brokkr_kitbash.close", object_name="S_Rod", socket="rod_end", other_name="Rocker", other_socket="end_b_back") + check("a ram on a second crank stands closed on the rocker", receipt["status"] == "accepted" and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) + refused("a loop whose ends depend on two drivers: its base is its own driver and the part it closes on follows another", "brokkr_kitbash.follow", + {"object_name": "S_Rod", "record": '{"driver": "Crank2", "kind": "loop"}'}, + "'Crank2' (the base) and 'Rocker' (closed on), depend on more than one driver: 'Crank2' and 'Crank' ('Rocker' follows it)", "A follower takes its value from one driver") + refused("and with the crank as the driver: the ram's base hangs from the second crank, which is posed by hand", "brokkr_kitbash.follow", {"object_name": "S_Rod", "record": loop}, + "depend on more than one driver: 'Crank' and 'Crank2' (it follows nothing and its joint has travel, so it is posed by hand)") + receipt, _ = send("brokkr_kitbash.detach", object_name="S_Rod") + check("the refused ram is detached, and the rocker's pin is free again", receipt["status"] == "accepted" and "kit_close" not in bpy.data.objects["S_Rod"], receipt["message"]) shift = np.eye(4) shift[:3, 3] = frame(rocker, "end_b_back")[:3, 3] - rod_end(turn, RAM_REST)[:3, 3] @@ -363,8 +407,6 @@ try: and [row for row in report["closures"] if not row["holds"]] == [], [receipt["message"], R["readings"], a_barrel["kit_roll"], a_rod["kit_slide"], ram_seed]) # --- a torque link: a slide drives two arms --------------------------------------------------------------------------------- - far = np.eye(4) - far[:3, 3] = [0.0, -8.0, 0.0] t_barrel, t_rod = place("T_Barrel", "ram_barrel", "", far @ turn), place("T_Rod", "ram_rod") t_upper, t_lower, t_lug = place("T_Upper", "strut", W + "length=0.5"), place("T_Lower", "strut", W + "length=0.5"), place("T_Lug", "strut", W + "length=0.3") attach("T_Rod", "piston", "T_Barrel", "bore", 0.0) @@ -392,6 +434,11 @@ try: attach("T_Upper", "end_a", "T_Barrel", "base_back", arms[0]) attach("T_Lower", "end_a", "T_Upper", "end_b", arms[1]) send("brokkr_kitbash.close", object_name="T_Lower", socket="end_b", other_name="T_Lug", other_socket="end_b") + refused("a loop that closes on a part hung from the driver by a free pin: the lug's roll is a second input (the probe of finding torque-link-lug-is-a-free-dof)", "brokkr_kitbash.follow", + {"object_name": "T_Lower", "record": '{"driver": "T_Rod", "kind": "loop"}'}, + "'T_Barrel' (the base) and 'T_Lug' (closed on), depend on more than one driver: 'T_Rod' and 'T_Lug' (it follows nothing and its joint has travel, so it is posed by hand)") + receipt, report = send("brokkr_kitbash.joint", object_name="T_Lug", record='{"limits": [90, 90], "mechanism": "lug"}') + check("limits of one value hold the lug on the rod: a pin with no travel", receipt["status"] == "accepted" and report["connection"]["limits"] == [90.0, 90.0], receipt["message"]) receipt, report = send("brokkr_kitbash.follow", object_name="T_Lower", record='{"driver": "T_Rod", "kind": "loop"}') check("the arms follow the rod's slide as a loop: its base is the barrel, above the driver, and it closes on a part that hangs from the driver", receipt["status"] == "accepted" and [f["part"] for f in report["followers"]] == ["T_Upper", "T_Lower"], [receipt["message"], report and report.get("followers")]) @@ -404,6 +451,20 @@ try: and max(reading("solved", turned(t_upper["kit_roll"], arms[0])), reading("solved", turned(t_lower["kit_roll"], arms[1]))) < SOLVED and report["closures"][0]["holds"] is True, [receipt["message"], R["readings"], t_upper["kit_roll"], t_lower["kit_roll"], arms]) refused("a slide outside the driver's limits", "brokkr_kitbash.slide", {"object_name": "T_Rod", "slide": 0.4}, "its slide 0.4 is outside the joint's limits 0 to 0.3") + refused("a roll of the held lug: no pose opens the torque link", "brokkr_kitbash.roll", {"object_name": "T_Lug", "roll": 100.0}, "'T_Lug' on 'T_Rod': its roll 100 is outside the joint's limits 90 to 90") + receipt, joints = send("brokkr_kitbash.joints", object_name="T_Barrel") + check("the torque link has one degree of freedom: the rod's slide is its one row with travel that nothing drives, the lug has none, the arms are driven, and no row is unlimited", + receipt["status"] == "accepted" and [(row["id"], row["kind"], row["driven"] and row["driven"]["by"], row["min"], row["max"]) for row in joints["joints"]] == [ + ("T_Rod", "prismatic", None, -0.11, 0.19), ("T_Lug", "revolute", None, 0.0, 0.0), ("T_Upper", "revolute", "T_Rod", None, None), ("T_Lower", "revolute", "T_Rod", None, None)] + and joints["unlimited"] == [] and reading("closed", apart(t_lower, "end_b", t_lug, "end_b")) < CLOSED, [receipt["message"], joints]) + place("T_Mount", "strut", W, far @ far @ far @ far @ turn) + hinged = attach("T_Barrel", "base", "T_Mount", "end_a", 25.0) + receipt, report = send("brokkr_kitbash.follow", object_name="T_Lower", record="null") + cleared = receipt["status"] == "accepted" and report["cleared"] == ["T_Upper", "T_Lower"] + receipt, report = send("brokkr_kitbash.follow", object_name="T_Lower", record='{"driver": "T_Rod", "kind": "loop"}') + check("a joint both ends of a loop hang from is not one the loop depends on: the barrel hung on a free hinge, the arms follow the rod again", + hinged and cleared and receipt["status"] == "accepted" and [f["part"] for f in report["followers"]] == ["T_Upper", "T_Lower"] + and reading("closed", apart(t_lower, "end_b", t_lug, "end_b")) < CLOSED, [hinged, cleared, receipt["message"]]) # --- joints, version 2 ---------------------------------------------------------------------------------------------------------- receipt, joints = send("brokkr_kitbash.joints", object_name="Ground") @@ -422,20 +483,31 @@ try: and joints["joints"][0]["compliance"] == {"damping_ratio": 0.6, "hertz": 3.0} and joints["rigid"] == 0, joints) receipt, joints = send("brokkr_kitbash.joints", object_name="Ground", after="Idle") check("after carries the rows after an id (F12)", receipt["status"] == "accepted" and [row["id"] for row in joints["joints"]] == ["Tip", "Pinion", "X_Barrel", "X_Rod"] - and joints["joints"][0]["parent"] == "Idle" and joints["unlimited"] == ["Idle", "Tip", "Pinion", "X_Barrel"], joints) + and joints["joints"][0]["parent"] == "Idle" and joints["unlimited"] == ["Tip", "Pinion", "X_Barrel"], joints) refused("after an id that is no row's", "brokkr_kitbash.joints", {"object_name": "Ground", "after": "Base"}, "after 'Base' is not the id of a joint under 'Ground'") - place("L00", "strut", W + "length=0.3", far @ far @ turn) - for index in range(1, 81): - place(f"L{index:02d}", "strut", W + "length=0.3") - attach(f"L{index:02d}", "end_a", f"L{index - 1:02d}", "end_b", 7.0) - receipt, first = send("brokkr_kitbash.joints", object_name="L00") - carried = [row["id"] for row in (first or {}).get("joints", [])] - receipt, second = send("brokkr_kitbash.joints", object_name="L00", after=(first or {}).get("next") or "") - R["readings"]["rows in one receipt"] = len(carried) - check("a tree of 80 joints is two reports: the first counts what it omits and names the last id it carries as next, and after it the second carries the rest", - receipt["status"] == "accepted" and 0 < len(carried) < 80 and first["jointsOmitted"] == 80 - len(carried) and first["next"] == carried[-1] - and carried + [row["id"] for row in second["joints"]] == [f"L{index:02d}" for index in range(1, 81)] and second["next"] is None and "jointsOmitted" not in second - and len(first["unlimited"]) == 80, [receipt["message"], len(carried), first and first.get("next"), second and [row["id"] for row in second["joints"]][:3]]) + long = [f"Actuator_joint_name_that_is_long_but_legal_in_blender_{index:04d}_x" for index in range(265)] # 62 characters, of the 63 Blender takes + place(long[0], "strut", W + "length=0.3", far @ far @ turn) + place(long[1], "strut", W + "length=0.3") + attach(long[1], "end_a", long[0], "end_a", 7.0) + for chain, on in enumerate(("end_a", "end_a_back", "end_b", "end_b_back")): # four chains of 66 on the root's four pins: 264 joints, none limited + for index in range(max(2, chain * 66 + 1), chain * 66 + 67): # copies of the one attached by the actions, each stating its own connection: the report reads what is stated + copy = bpy.data.objects[long[1]].copy() + copy.name, copy.parent = long[index], bpy.data.objects[long[0] if index == chain * 66 + 1 else long[index - 1]] + copy["kit_parent_socket"] = on if index == chain * 66 + 1 else "end_b" + bpy.context.scene.collection.objects.link(copy) + pages, after = [], "" + for _ in range(2): # the first two reports; each costs a pass over the 264 parts + receipt, page = send("brokkr_kitbash.joints", object_name=long[0], after=after) + pages.append((receipt["status"], len(receipt.get("hostResult") or ""), page or {})) + after = (page or {}).get("next") or "" + carried = [[row["id"] for row in page.get("joints", [])] for _, _, page in pages] + R["readings"]["rows in the first receipt"], R["readings"]["longest receipt"] = len(carried[0]), max(size for _, size, _ in pages) + check("a tree of 264 unlimited joints with long names, whose ids alone are over a receipt, is many reports and none over a receipt: each carries rows, the ids of its own " + "rows as unlimited, a count of what it omits and the last id it carries as next, and after it the next carries on", + all(status == "accepted" and size <= 16000 and page.get("joints") and page["unlimited"] == ids and page["next"] == ids[-1] for (status, size, page), ids in zip(pages, carried)) + and sum(len(json.dumps(name)) + 1 for name in long[1:]) > 16000 and [name for ids in carried for name in ids] == long[1:len(carried[0]) + len(carried[1]) + 1] + and [page["jointsOmitted"] for _, _, page in pages] == [264 - len(carried[0]), 264 - len(carried[0]) - len(carried[1])], + [[(status, size, len(ids), page.get("jointsOmitted"), page.get("next")) for (status, size, page), ids in zip(pages, carried)]]) # --- the joint-records Lows ------------------------------------------------------------------------------------------------- send("brokkr_kitbash.joint", object_name="Idle", record='{"limits": [0, 30]}') diff --git a/surfaces/blender/tests/live/kitbash_follows.result.json b/surfaces/blender/tests/live/kitbash_follows.result.json index 9c9bd7a..49065f4 100644 --- a/surfaces/blender/tests/live/kitbash_follows.result.json +++ b/surfaces/blender/tests/live/kitbash_follows.result.json @@ -16,6 +16,16 @@ "ok": true, "detail": null }, + { + "name": "a loop whose base hangs from the part it closes on stands closed", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a loop whose two ends both move with the driver (F7, the other half)", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: a loop follower that states no closure", "ok": true, @@ -196,6 +206,26 @@ "ok": true, "detail": null }, + { + "name": "a ram on a second crank stands closed on the rocker", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a loop whose ends depend on two drivers: its base is its own driver and the part it closes on follows another", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: and with the crank as the driver: the ram's base hangs from the second crank, which is posed by hand", + "ok": true, + "detail": null + }, + { + "name": "the refused ram is detached, and the rocker's pin is free again", + "ok": true, + "detail": null + }, { "name": "a ram on its own ground pin closes on the rocker and follows the crank: the end it closes on follows the driver", "ok": true, @@ -221,6 +251,16 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: a loop that closes on a part hung from the driver by a free pin: the lug's roll is a second input (the probe of finding torque-link-lug-is-a-free-dof)", + "ok": true, + "detail": null + }, + { + "name": "limits of one value hold the lug on the rod: a pin with no travel", + "ok": true, + "detail": null + }, { "name": "the arms follow the rod's slide as a loop: its base is the barrel, above the driver, and it closes on a part that hangs from the driver", "ok": true, @@ -246,6 +286,21 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: a roll of the held lug: no pose opens the torque link", + "ok": true, + "detail": null + }, + { + "name": "the torque link has one degree of freedom: the rod's slide is its one row with travel that nothing drives, the lug has none, the arms are driven, and no row is unlimited", + "ok": true, + "detail": null + }, + { + "name": "a joint both ends of a loop hang from is not one the loop depends on: the barrel hung on a free hinge, the arms follow the rod again", + "ok": true, + "detail": null + }, { "name": "joints is version 2: a driven row names what drives it (F6), and unlimited lists the rows that are not driven and state no limits", "ok": true, @@ -272,7 +327,7 @@ "detail": null }, { - "name": "a tree of 80 joints is two reports: the first counts what it omits and names the last id it carries as next, and after it the second carries the rest", + "name": "a tree of 264 unlimited joints with long names, whose ids alone are over a receipt, is many reports and none over a receipt: each carries rows, the ids of its own rows as unlimited, a count of what it omits and the last id it carries as next, and after it the next carries on", "ok": true, "detail": null }, @@ -331,6 +386,7 @@ "readings": { "closed": 6.4e-07, "jump": 49.0, + "longest receipt": 16000.0, "ram closed at 110": 2.9e-07, "ram closed at 45": 5.3e-07, "ram closed at 60": 2.8e-07, @@ -338,7 +394,7 @@ "ram solved at 45": 0.0, "ram solved at 60": 0.0, "ratio": 0.0, - "rows in one receipt": 62.0, + "rows in the first receipt": 33.0, "slid": 1e-07, "solved": 3.3e-05 }, From 21f783b37cb820c43de244204433ca2705173365 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 13:04:05 +0100 Subject: [PATCH 203/223] docs/kitbash.md: one driver per loop, a ram's dead centre, unlimited in pages; kitbash.result.json carries follow kitbash_assembly, kitbash_hose and kitbash_pose were run again at this tree and their result files are unchanged byte for byte. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 41 +++++++++++++------ .../blender/tests/live/kitbash.result.json | 1 + 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index d10f017..54a965a 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -218,7 +218,14 @@ follower outside its own limits, or a loop that cannot close, refuses the pose w A loop has exactly two unknowns, the closing part's joint and its parent's, and it is planar: each revolute pin is parallel to the pin it closes on and each slide runs across it. Exactly one of its two ends (the parent's parent, -and the part closed on) moves with the driver: it is the driver, follows it, or hangs from one that does. Nothing +and the part closed on) moves with the driver: it is the driver, follows it, or hangs from one that does. And the +driver is the only input the two ends depend on: every revolute or prismatic joint between an end and the part the +two ends share (or the root, when they share none) is the driver, follows it, or is held by limits of one value. A +joint there that follows another driver, or that follows nothing and has travel, would open the loop when it is +posed, so `follow` refuses the loop and names the driver and each other input; it does not solve a loop for two +drivers. A torque link is the case: the kit has no rigid lug, and a strut's two pins face one way, so the lower arm +closes on a strut pinned to the rod's end, and that pin is held by limits of one value (`[90, 90]`) before the +arms follow the rod's slide. Nothing stores a pin position or a linkage record: `core.close_loop` solves the pair from the kits' socket frames at the parts' stored params each time, by Newton's method on the closing pin's error in the loop's plane with the analytic Jacobian. That is the position analysis of the kinematics texts (Nikravesh, *Computer-Aided Analysis of Mechanical @@ -229,14 +236,22 @@ seeded by the one before, and only the last step is written: the linkage stays o Loops are solved in an order where a loop's base and the part it closes on are already placed (a ram closing on a four-bar's rocker waits for the four-bar); loops that wait on each other are refused. At a dead centre, where the pair's two joints move the closing pin along one line, the pose is refused naming the driver's value and the -closing part: the bound is 0.093 on the smaller singular value of the Jacobian with unit columns, which is the two -joints within about 7.6 degrees of in line (the four-bar of `tests/test_kitbash.py` reads 0.184 at its last -accepted step and 0.047 at the first refused one). +closing part: the bound is 0.093 on the smaller singular value of the Jacobian with each column scaled by its lever. +For two revolute joints the columns are unit vectors and the reading is the two joints within about 7.6 degrees of +in line (the four-bar of `tests/test_kitbash.py` reads 0.184 at its last accepted step and 0.047 at the first +refused one). A ram's dead centre is its rod's end on its barrel's pin, where the barrel's roll is undefined, and +its two columns are across each other everywhere else, so the barrel's column is scaled by its lever with the slide +at 0 and the reading is the ram's lever over its closed lever: a ram drawn in to 0.184 of its closed lever is +accepted and one at 0.047 refused. The sign of the Jacobian's determinant about the pin is the assembly branch (an +elbow bent one way or the other, a rod's end on one side of its barrel's pin or the other), and a Newton step that +lands on the other sign from its seed is refused as past the dead centre, so no pose answers the other branch. +A ram with limits never comes near either: its slide leaves its limits first. What followers give up: a loop of three or more unknowns, or one out of a plane, is not solved (follow-up `kit-follows-wider-loops`); a follower does not drive another; `set_params` never derives a follower again, so a -loop it opens reads `holds: false` until its driver is posed; and a part above a loop that is posed by hand opens -it the same way. A connection's row in a report carries `follows: {driver, kind, k, offset, holds, reason}`: +loop it opens reads `holds: false` until its driver is posed; and the one-driver rule is checked when a loop is +stated, so a part attached, detached, cleared of its statement or given wider limits afterwards between a loop's +ends can still open it, and reads the same way. A connection's row in a report carries `follows: {driver, kind, k, offset, holds, reason}`: `holds` is false, with a reason, when the value stands off the ratio, the loop's closure does not hold, or the driver is gone or states no revolute or prismatic connection. Detaching a driver leaves its followers' statements; detaching a loop follower clears its partner's. No Blender driver or constraint is made: a follower's @@ -274,10 +289,12 @@ the object the part hangs from: rigid connections fold into it and are counted i frame. `min` and `max` are the limits less the value, the travel either way from the pose the report was taken at, which is the shape of Aetheria's `ShipJoint` (`Min` and `Max` about rest). `driven` is null, or what the row follows (`by` the driver's id, `kind`, `k`, `offset`): a driven row's value is derived, so a rig makes a driven bone for it -and not a degree of freedom. `unlimited` lists the ids of the rows in the whole tree that are not driven and state -no limits, so an exporter that needs limits on every degree of freedom refuses by reading one field. A tree whose -rows a receipt cannot carry (about 60 rows) is read in pages: `jointsOmitted` counts the rows left off, `next` is -then the id of the last row carried, and a call with `after` set to it carries the rows that follow. +and not a degree of freedom. `unlimited` lists the ids of the rows this report carries that are not driven and +state no limits, so an exporter that needs limits on every degree of freedom refuses by reading one field of each +report. A tree whose rows a receipt cannot carry (about 60 rows, 33 with names of 62 characters) is read in pages: +`jointsOmitted` counts the rows left off, `next` is then the id of the last row carried, and a call with `after` +set to it carries the rows that follow, with their own `unlimited`. A row and its id in `unlimited` are kept or left +off together, so a report is never over a receipt and always carries a row. `ShipJoint` is ruled to gain a kind per degree of freedom and an optional spring (aetheria-release:ruling:shipjoint-gains-kind-and-spring), and the rows map to it one to one: `revolute` is its @@ -1324,7 +1341,7 @@ under such load (five runs), and reading a 336-face part takes 27 to 37 ms. | `brokkr_kitbash.joint` | `object_name`, `record` (a JSON object of any of `limits`: `[lo, hi]` or null; `mechanism`: a label or null; `compliance`: `{hertz, damping_ratio}` or null) | States the joint record of an attached part's connection; a key left out keeps what is stated and null clears it. A follower keeps its derived value, and a driver's followers are derived again. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits over a turn or past 360, prismatic limits past 10 m, and compliance on a revolute joint or without limits. Reports the part and `closures` as `roll` does | | `brokkr_kitbash.slide` | `object_name`, `slide` (metres, -10 to 10) | Slides an attached part along its parent socket's normal on a prismatic connection, where it hangs, and every follower of it with it. Refuses a revolute or rigid connection naming its socket type, a slide outside the joint's limits, and a follower. Reports the part and `closures` as `roll` does | | `brokkr_kitbash.joints` | `object_name` (the root, a kit part), `after` (default empty: an id, the `next` of the report before) | Reports the joints of the tree attached under the root as `brokkr.joints` version 2: a row per revolute or prismatic connection, parents first and the root's own first when it states one, with `id`, `parent`, `part`, `socket`, `kind`, `axis`, `origin`, `value`, `limits`, `min`, `max`, `mechanism`, `compliance` and `driven`, in the root's frame, and `unlimited` and `next` beside them ("Joint records"). With `after`, the rows after that id. Changes nothing and evaluates no modifier. | -| `brokkr_kitbash.follow` | `object_name` (the follower; for a loop, the part that states the closure), `record` (JSON: `{driver, kind: "ratio", k, offset}`, `{driver, kind: "loop"}` or null) | States that the part's joint follows the driver's, by a ratio or by keeping its closure closed with its parent's joint, and moves it there at once; null clears the statement, and a loop partner's with it ("Followers"). Refuses a rigid connection, a driver that is the follower, below it or itself a follower, a follower that already follows or drives another, a ratio whose driver states no limits, and a loop without a closure that holds, with both ends or neither moving with the driver, that is not planar or that stands at a dead centre. Reports the part, `followers` and `closures`. | +| `brokkr_kitbash.follow` | `object_name` (the follower; for a loop, the part that states the closure), `record` (JSON: `{driver, kind: "ratio", k, offset}`, `{driver, kind: "loop"}` or null) | States that the part's joint follows the driver's, by a ratio or by keeping its closure closed with its parent's joint, and moves it there at once; null clears the statement, and a loop partner's with it ("Followers"). Refuses a rigid connection, a driver that is the follower, below it or itself a follower, a follower that already follows or drives another, a ratio whose driver states no limits, and a loop without a closure that holds, with both ends or neither moving with the driver, whose ends depend on another driver or on a joint posed by hand, that is not planar or that stands at a dead centre. Reports the part, `followers` and `closures`. | | `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. | | `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added; `booleansOmitted` counts rows a receipt had no room for) 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), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans` (with `booleansOmitted`, as `boolean`). | @@ -1464,4 +1481,4 @@ re-parameterised, a beam seated on a bracket), `tests/live/kitbash_assembly.py` `set_params` on assemblies, a braced leg closed by `close`, boolean, and freeze and thaw with what a frozen part costs), `tests/live/kitbash_shell.py` (`cut` and `cut_many` on a cage that is not a kit part, a part on a cutter's floor, the three Boolean modifiers, an object in no collection), `tests/live/kitbash_pose.py` (roll, aim, reach and joint records) and `tests/live/kitbash_follows.py` -(followers: a four-bar, a ram closing on its rocker, ratios, a torque link, and a joints report in pages). +(followers: a four-bar, a ram closing on its rocker, ratios, a torque link, the one-driver refusals, and a joints report in pages). diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index d468d78..ee64773 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -518,6 +518,7 @@ "brokkr_kitbash.joint", "brokkr_kitbash.slide", "brokkr_kitbash.joints", + "brokkr_kitbash.follow", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", From 1be1bfc1e62710e27e644a35b65290cb65a75c8c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 13:55:42 +0100 Subject: [PATCH 204/223] brokkr_kitbash: the one-driver rule is read before every write of a connection and before detach one_driver reads every loop in the scene as the write would leave it. write_connections and detach ask it, so attach, detach, clearing a follower, widened or cleared limits and any pose refuse a second driver between a stated loop's ends, naming both. follow's own copy of the rule is gone. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 98 ++++++++++++++----- .../blender/tests/live/kitbash_follows.py | 33 ++++++- .../tests/live/kitbash_follows.result.json | 40 ++++++++ surfaces/blender/tests/test_kitbash.py | 15 ++- 4 files changed, 153 insertions(+), 33 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 70a2126..b4c008f 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -222,19 +222,23 @@ def dof(parent, parent_socket: dict): return core.load_kit(str(parent.get(KIT, "")))["socketTypes"][parent_socket["type"]].get("dof") -def connection_kind(obj) -> tuple: +def connection_kind(obj, kits=None) -> tuple: """(DOF kind, parent socket type) of the connection a child states, from the parent's kit by the socket's name alone (a socket's type is the same at every params), or (None, None) when it cannot be read: no parent, a - parent that is no kit part, a socket the part does not have.""" + parent that is no kit part, a socket the part does not have. `kits` is kit_part_of's: one call's read of each + kit file.""" try: - kit = core.load_kit(str(obj.parent.get(KIT, ""))) + name, kits = str(obj.parent.get(KIT, "")), {} if kits is None else kits + if name not in kits: + kits[name] = core.load_kit(name) + kit = kits[name] socket_type = next(s["type"] for s in core.part(kit, str(obj.parent[PART]))["sockets"] if s["name"] == obj.get(PARENT_SOCKET)) return kit["socketTypes"][socket_type].get("dof"), socket_type except (AttributeError, KeyError, StopIteration, core.KitError): return None, None -def joint_record(obj) -> dict: +def joint_record(obj, kits=None) -> dict: """The joint record a child's connection states, {limits: (lo, hi) or None, mechanism, compliance, follows}: degrees of its roll on a revolute joint, metres of its slide on a prismatic one; follows is None or {driver (the object, None once it is gone, as closure's other part), kind 'ratio' | 'loop', k, offset}. Every report, the joints report, the @@ -255,7 +259,7 @@ def joint_record(obj) -> dict: "follows": {"driver": driver if isinstance(driver, bpy.types.Object) and driver.users_collection else None, "kind": follows["kind"], "k": float(follows["k"]) if ratio else None, "offset": float(follows["offset"]) if ratio else None} if ratio or follows == {"kind": "loop"} else None} - kind, socket_type = connection_kind(obj) + kind, socket_type = connection_kind(obj, kits) for field in ("limits", "mechanism", "compliance", "follows"): # limits first: a compliance is read beside the limits that stand alone = {**dict.fromkeys(record), "limits": record["limits"] if field == "compliance" else None, field: record[field]} if record[field] is not None and record_refusal(kind, socket_type, alone) is not None: @@ -391,8 +395,11 @@ def write_connections(entries) -> None: properties and its joint record, kit_follows and its driver pointer with it. Every entry is checked (connection_checks) before any is written, so one refusal leaves every part as it stood. attach, set_params, roll, aim, reach, slide, joint and follow write a connection here and nowhere else, so what a joint record may - be, and that a follower's value is written with its driver's, is decided here.""" - for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in connection_checks(entries): + be, and that a follower's value is written with its driver's, is decided here. So is the one-driver rule: the + scene as these entries would leave it is read by one_driver before any is written, whatever the action.""" + checked = connection_checks(entries) + one_driver({child: (parent, kind, record) for child, parent, _, _, _, _, _, kind, record in checked}) + for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in checked: child.parent = parent seat(child, core.mate(*sockets, roll, slide)) child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll @@ -423,6 +430,60 @@ def followers(driver) -> list: key=lambda o: o.name) +def one_driver(stating: dict) -> None: + """The one-driver rule, over every loop in the scene as it would stand after a write: the driver of a loop is + the only input its two ends (the parent follower's parent, and the part closed on) depend on. `stating` is + {part: (its parent, its connection's DOF kind, its joint record)} for each connection about to be written, and + (None, None, None) for one about to be cleared; every other part is read from the scene. Each revolute or + prismatic joint between an end and the nearest part both ends hang from (or the root, when they share none) is + the driver, follows it, or is held by limits of one value: a pin with no travel, which is what a real torque + link's lug is, there to stop the rod rolling in its barrel. A joint there that follows another driver, or that + follows nothing and has travel, is a second driver: a pose of it would open the loop, so the write is refused + naming the loop's driver and each other one. A joint both ends hang from moves them together and is not + counted. A loop whose driver is gone or states no DOF connection is derived by nothing and is not read; it is + read again by the attach that gives the driver a connection. write_connections and detach ask here before + they write, so no action (attach, detach, clearing a follower, limits widened or cleared, any pose, a new + follow) leaves a loop with two drivers, and a scene edited by hand into one is refused its next write.""" + known, kits = {}, {} # each part's joint and each kit file are read once + + def parent(o): + return stating[o][0] if o in stating else o.parent + + def joint(o) -> tuple: + """(DOF kind, limits, follows) of the connection a part would state.""" + if o not in known: + kind, record = stating[o][1:] if o in stating else (connection_kind(o, kits)[0], None) + if kind is not None and o not in stating: + record = joint_record(o, kits) + known[o] = (kind, record["limits"], record["follows"]) if kind is not None else (None, None, None) + return known[o] + + for closing in sorted((o for o in bpy.data.objects if CLOSE in o and o.users_collection and (FOLLOWS in o or o in stating)), key=lambda o: o.name): + follows, upper, to = joint(closing)[2], parent(closing), closure(closing)[1] + driver = follows["driver"] if follows is not None and follows["kind"] == "loop" else None + if driver is None or to is None or upper is None or parent(upper) is None or joint(driver)[0] is None or joint(upper)[2] != follows: + continue + ends, chains = (parent(upper), to), [[], []] # each end and what it hangs from, up to the root + for found, o in zip(chains, ends): + while o is not None: + found.append(o) + o = parent(o) + others = {} # {a part whose pose moves one end against the other, and is not the driver: why} + for o in (o for found in chains for o in found if not (o in chains[0] and o in chains[1])): + kind, limits, its = joint(o) + if kind is None or o == driver or its is not None and its["driver"] in (None, driver): + continue + if its is not None: + others.setdefault(its["driver"], f"{o.name!r} follows it") + elif limits is None or limits[0] < limits[1]: # limits of one value hold a joint still + others.setdefault(o, "it follows nothing and its joint has travel, so it is posed by hand") + if others: + raise Refused(f"the two ends of the loop {closing.name!r} closes, {ends[0].name!r} (the base) and {ends[1].name!r} (closed on), depend on more than one driver: {driver.name!r} and " + f"{', '.join(f'{o.name!r} ({why})' for o, why in sorted(others.items(), key=lambda item: item[0].name))}. A follower takes its value from " + "one driver, and a pose of another would open the loop: every joint between the two ends is the driver, follows it, or is held by " + f"limits of one value. Give it that first, or clear the loop (brokkr_kitbash.follow on {closing.name!r} with record null); nothing changed.") + + def loop_pair(obj, stating=None): """(the parent follower, the closing follower) of the loop a loop follower is one of, or None when it has no partner. The closing follower states the closure and its parent is the other: both follow one driver as a @@ -1014,7 +1075,8 @@ class BROKKR_KITBASH_OT_attach(PolishOperator): class BROKKR_KITBASH_OT_detach(PolishOperator): """Clear a kit part's connection and the closure it states: it stays where it stands in the world, loses its parent, and the parts attached to it stay attached to it. A loop follower's partner stops following with it; a - driver's followers keep their statements and report that the driver states no DOF connection""" + driver's followers keep their statements and report that the driver states no DOF connection. Refused when it + would leave a loop with a second driver (one_driver): a part between a loop's end and the part both ends hang from""" bl_idname = "brokkr_kitbash.detach" bl_label = "Detach Kit Part" object_name: bpy.props.StringProperty(name="Object") @@ -1026,6 +1088,7 @@ class BROKKR_KITBASH_OT_detach(PolishOperator): raise Refused(f"{obj.name!r} is not attached (it has no {SOCKET} property) and states no closure; nothing changed.") part, built = built_part(obj) pair = loop_pair(obj) # a loop follower's partner follows nothing once the loop is gone + one_driver({obj: (None, None, None), **{o: (o.parent, connection_kind(o)[0], {**joint_record(o), "follows": None}) for o in pair or () if o != obj}}) if SOCKET in obj: world = obj.matrix_world.copy() obj.parent = None @@ -1319,25 +1382,6 @@ class BROKKR_KITBASH_OT_follow(PolishOperator): if moves(ends[0]) == moves(ends[1]): raise Refused(f"the loop's two ends, {ends[0].name!r} (the base) and {ends[1].name!r} (closed on), {'both move' if moves(ends[0]) else 'neither moves'} with " f"{driver.name!r}: exactly one of them is the driver, follows it, or hangs from one that does; nothing changed.") - chains = [[], []] # each end and what it hangs from, up to the root - for found, o in zip(chains, ends): - while o is not None: - found.append(o) - o = o.parent - others = {} # {a part whose pose moves one end against the other, and is not the driver: why}, from the joints under the ends' nearest common part - for o in (o for found in chains for o in found if not (o in chains[0] and o in chains[1])): - its, limits = joint_record(o)["follows"], joint_record(o)["limits"] - if connection_kind(o)[0] is None or o == driver or its is not None and its["driver"] in (None, driver): - continue - if its is not None: - others.setdefault(its["driver"], f"{o.name!r} follows it") - elif limits is None or limits[0] < limits[1]: # limits of one value hold a joint still: a pin with no travel - others.setdefault(o, "it follows nothing and its joint has travel, so it is posed by hand") - if others: - raise Refused(f"the loop's two ends, {ends[0].name!r} (the base) and {ends[1].name!r} (closed on), depend on more than one driver: {driver.name!r} and " - f"{', '.join(f'{o.name!r} ({why})' for o, why in sorted(others.items(), key=lambda item: item[0].name))}. A follower takes its value from " - "one driver, and a pose of another would open the loop: let every joint between the two ends be the driver, follow it, or be held by " - "limits of one value; nothing changed.") follows = {"driver": driver, "kind": given["kind"], "k": float(given["k"]) if ratio else None, "offset": float(given["offset"]) if ratio else None} entries, moved = driven(driver, driver_sockets, driver_stated, driver_stated[2], driver_stated[3], None, {o: follows for o in pair}) write_connections(entries) diff --git a/surfaces/blender/tests/live/kitbash_follows.py b/surfaces/blender/tests/live/kitbash_follows.py index d7ae4d0..7b2cb9e 100644 --- a/surfaces/blender/tests/live/kitbash_follows.py +++ b/surfaces/blender/tests/live/kitbash_follows.py @@ -13,10 +13,12 @@ The scene, every strut 0.09 wide so its pins take a ram's: a four-bar (Crank on Base, Coupler closing on the crank); a ram (A_Barrel on the root Pad, A_Rod in its bore, closing on the rocker), named to sort before the four-bar it waits on; ratio followers of the crank (Cap, Pinion, and X_Rod's slide in X_Barrel); a torque link (T_Rod sliding in the root T_Barrel, T_Upper and T_Lower closing on T_Lug, a strut on the rod's -rod_end_back held at 90 degrees by limits of that one value: a strut's two pins face one way, so two arms from the -barrel's pin cannot face the rod's own, and the kit has no rigid lug); a second crank (Crank2 on the root Ground2) +rod_end_back held at 90 degrees by limits of that one value. A real torque link exists to stop the rod rolling in its +barrel, so a lug with no travel is the mechanism and not a way around the kit; and a strut's two pins face one way, so +two arms from the barrel's pin cannot face the rod's own); a second crank (Crank2 on the root Ground2) whose ram closes on the rocker, and a loop hung from its own driver (K3, B3, Rk3, Cp3 on the root G3), for the -one-driver refusals; Idle and Tip for the refusals; a tree of 264 struts with 62-character names for a joints +one-driver refusals at the statement, and after it an attach, a clear, widened limits, a pose over limits written by hand and a +detach that would each give a stated loop a second driver; Idle and Tip for the refusals; a tree of 264 struts with 62-character names for a joints report over several receipts. Bounds follow lodur:ruling:deterministic-bound-margin, both readings beside each; the result file carries the readings. """ @@ -406,6 +408,16 @@ try: and [f["part"] for f in report["followers"]][-4:] == ["Rocker", "Coupler", "A_Barrel", "A_Rod"] and [row for row in report["closures"] if not row["holds"]] == [], [receipt["message"], R["readings"], a_barrel["kit_roll"], a_rod["kit_slide"], ram_seed]) + # --- one driver, after the loop is stated: each action that could give a loop a second one refuses it ------------------------- + place("P_Mount", "strut", W + "length=0.8", far @ far @ far @ far @ far @ turn) + refused("attach after the loop is stated: the ram's pad hung on a free pin is a second driver between the loop's ends", "brokkr_kitbash.attach", + {"object_name": "Pad", "socket": "end_b", "parent_name": "P_Mount", "parent_socket": "end_a", "roll": 0.0}, + "the two ends of the loop 'A_Rod' closes, 'Pad' (the base) and 'Rocker' (closed on), depend on more than one driver: 'Crank' and 'Pad' (it follows nothing and its joint has travel", + "clear the loop (brokkr_kitbash.follow on 'A_Rod' with record null)") + refused("clear after the loop is stated: the four-bar's rocker, no longer a follower, is a second driver of the ram that closes on it", "brokkr_kitbash.follow", + {"object_name": "Coupler", "record": "null"}, + "the two ends of the loop 'A_Rod' closes, 'Pad' (the base) and 'Rocker' (closed on), depend on more than one driver: 'Crank' and 'Rocker' (it follows nothing and its joint has travel") + # --- a torque link: a slide drives two arms --------------------------------------------------------------------------------- t_barrel, t_rod = place("T_Barrel", "ram_barrel", "", far @ turn), place("T_Rod", "ram_rod") t_upper, t_lower, t_lug = place("T_Upper", "strut", W + "length=0.5"), place("T_Lower", "strut", W + "length=0.5"), place("T_Lug", "strut", W + "length=0.3") @@ -452,6 +464,17 @@ try: and report["closures"][0]["holds"] is True, [receipt["message"], R["readings"], t_upper["kit_roll"], t_lower["kit_roll"], arms]) refused("a slide outside the driver's limits", "brokkr_kitbash.slide", {"object_name": "T_Rod", "slide": 0.4}, "its slide 0.4 is outside the joint's limits 0 to 0.3") refused("a roll of the held lug: no pose opens the torque link", "brokkr_kitbash.roll", {"object_name": "T_Lug", "roll": 100.0}, "'T_Lug' on 'T_Rod': its roll 100 is outside the joint's limits 90 to 90") + for label, limits in (("widened", "[80, 100]"), ("cleared", "null")): + refused(f"limits {label} after the loop is stated: the lug, given travel, is a second driver of the torque link", "brokkr_kitbash.joint", + {"object_name": "T_Lug", "record": '{"limits": %s}' % limits}, + "the two ends of the loop 'T_Lower' closes, 'T_Barrel' (the base) and 'T_Lug' (closed on), depend on more than one driver: 'T_Rod' and 'T_Lug' (it follows nothing and its joint has travel") + t_lug["kit_min"], t_lug["kit_max"] = 80.0, 100.0 # by hand, past every action: the next write of any pose reads the rule + refused("a pose of the driver after the lug's limits were widened by hand: the writer reads the rule before it writes", "brokkr_kitbash.slide", {"object_name": "T_Rod", "slide": 0.1}, + "depend on more than one driver: 'T_Rod' and 'T_Lug' (it follows nothing and its joint has travel") + refused("and a pose of the lug itself", "brokkr_kitbash.roll", {"object_name": "T_Lug", "roll": 95.0}, "depend on more than one driver: 'T_Rod' and 'T_Lug'") + t_lug["kit_min"], t_lug["kit_max"] = 90.0, 90.0 + receipt, report = send("brokkr_kitbash.slide", object_name="T_Rod", slide=0.11) + check("with the lug held again the driver is posed", receipt["status"] == "accepted" and report["closures"][0]["holds"] is True, receipt["message"]) receipt, joints = send("brokkr_kitbash.joints", object_name="T_Barrel") check("the torque link has one degree of freedom: the rod's slide is its one row with travel that nothing drives, the lug has none, the arms are driven, and no row is unlimited", receipt["status"] == "accepted" and [(row["id"], row["kind"], row["driven"] and row["driven"]["by"], row["min"], row["max"]) for row in joints["joints"]] == [ @@ -466,6 +489,10 @@ try: hinged and cleared and receipt["status"] == "accepted" and [f["part"] for f in report["followers"]] == ["T_Upper", "T_Lower"] and reading("closed", apart(t_lower, "end_b", t_lug, "end_b")) < CLOSED, [hinged, cleared, receipt["message"]]) + refused("detach after the loop is stated: the lug cut from the rod no longer hangs from the barrel, so the barrel's free hinge is a second driver", "brokkr_kitbash.detach", + {"object_name": "T_Lug"}, + "the two ends of the loop 'T_Lower' closes, 'T_Barrel' (the base) and 'T_Lug' (closed on), depend on more than one driver: 'T_Rod' and 'T_Barrel' (it follows nothing and its joint has travel") + # --- joints, version 2 ---------------------------------------------------------------------------------------------------------- receipt, joints = send("brokkr_kitbash.joints", object_name="Ground") table = {row["id"]: row for row in (joints or {}).get("joints", [])} diff --git a/surfaces/blender/tests/live/kitbash_follows.result.json b/surfaces/blender/tests/live/kitbash_follows.result.json index 49065f4..a8434ac 100644 --- a/surfaces/blender/tests/live/kitbash_follows.result.json +++ b/surfaces/blender/tests/live/kitbash_follows.result.json @@ -246,6 +246,16 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: attach after the loop is stated: the ram's pad hung on a free pin is a second driver between the loop's ends", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: clear after the loop is stated: the four-bar's rocker, no longer a follower, is a second driver of the ram that closes on it", + "ok": true, + "detail": null + }, { "name": "the torque link's rest pose is found: two arms from the barrel's pin to the lug on the rod", "ok": true, @@ -291,6 +301,31 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: limits widened after the loop is stated: the lug, given travel, is a second driver of the torque link", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: limits cleared after the loop is stated: the lug, given travel, is a second driver of the torque link", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a pose of the driver after the lug's limits were widened by hand: the writer reads the rule before it writes", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: and a pose of the lug itself", + "ok": true, + "detail": null + }, + { + "name": "with the lug held again the driver is posed", + "ok": true, + "detail": null + }, { "name": "the torque link has one degree of freedom: the rod's slide is its one row with travel that nothing drives, the lug has none, the arms are driven, and no row is unlimited", "ok": true, @@ -301,6 +336,11 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: detach after the loop is stated: the lug cut from the rod no longer hangs from the barrel, so the barrel's free hinge is a second driver", + "ok": true, + "detail": null + }, { "name": "joints is version 2: a driven row names what drives it (F6), and unlimited lists the rows that are not driven and state no limits", "ok": true, diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index a8c4e41..fe1cfeb 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -2537,12 +2537,21 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(source.count("write_connections(["), 2) # write_connection, and follow clearing a statement # every entry is checked before one is written (mutant J5, a refusal raised after the writes; F5 is its live twin): the writer's loop runs over the # checks' whole answer and raises nothing itself, and the checks write nothing - self.assertIn(" for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in connection_checks(entries):\n child.parent = parent\n", writer) + self.assertIn(" checked = connection_checks(entries)\n one_driver({child: (parent, kind, record) for child, parent, _, _, _, _, _, kind, record in checked})\n" + " for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in checked:\n child.parent = parent\n", writer) self.assertNotIn("raise ", writer) + # the one-driver rule has one owner, asked by the one writer and by detach before either writes, and it writes nothing: no action states its own + # copy (live: an attach, a clear, widened limits, a pose and a detach after the loop is stated are each refused) + rule = source.split("\ndef one_driver(")[1].split("\n\n\n")[0] + self.assertEqual((source.count("one_driver("), source.count("depend on more than one driver")), (3, 1)) + self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|\w+\[[A-Z_]+\]\s*=(?!=)|\bdel ", rule)) + detach = source.split("class BROKKR_KITBASH_OT_detach(")[1].split("class BROKKR_KITBASH_OT_")[0] + self.assertLess(detach.index("one_driver("), detach.index("obj.parent = None")) + self.assertLess(detach.index("one_driver("), detach.index("del obj[key]")) checks = source.split("\ndef connection_checks(")[1].split("\n\n\n")[0] self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|\w+\[\w+\]\s*=(?!=)|\bdel ", checks)) self.assertEqual(checks.count("raise Refused("), 1) - # a hose keeps no roll range of its own (mutant J9, a default range for a pin that states no limits): it reads the record's limits and refuses without them + # a hose keeps no roll range of its own (mutant J9, a default range for a pin that states no limits; live it dies in kitbash_hose.py, 'a pin with no limits'): it reads the record's limits and refuses without them hose = source.split("class BROKKR_KITBASH_OT_hose(")[1].split("\n\n\n")[0] self.assertEqual(re.findall(r"[^\n]*\blimits\s*=(?!=)[^\n]*", hose), [' limits = joint_record(child)["limits"] # the roll range the hose is proven over is the pin\'s own: its connection\'s limits']) self.assertIn(' if limits is None:\n raise Refused(f"{child.name!r} on {child.parent.name!r}: the pin the hose crosses states no limits', hose) @@ -2726,7 +2735,7 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(assigned, [" obj[CLOSE], obj[CLOSE_TO], obj[CLOSE_TO_SOCKET] = self.socket, other, self.other_socket"]) self.assertIn(assigned[0], bodies["close"]) deleted = re.findall(r"[^\n]*\(SOCKET, PARENT_SOCKET, ROLL, \*RECORD, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET\)[^\n]*\n[^\n]*\n\s*del obj\[key\]", source) - self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and hold's kit_frozen; mutant J10 (detach's keys without kit_min) dies on the first + self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 2, True)) # detach's keys, and hold's kit_frozen; mutant J10 (detach's keys without kit_min) dies on the first, and live in kitbash_pose.py, 'detach leaves none of the eight connection keys' record = re.search(r"^RECORD = \((.*)\)$", source, re.M).group(1).split(", ") self.assertEqual(record, ["SLIDE", "LIMIT_MIN", "LIMIT_MAX", "MECHANISM", "COMPLIANCE", "FOLLOWS", "FOLLOWS_DRIVER"]) # the whole joint record: what detach clears self.assertEqual(source.count("CLOSE_TO]"), 1) # the one subscript write above; every read goes through .get From 2ef289e76bce97ee5d449bb3c07e949941ea25b7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 13:55:42 +0100 Subject: [PATCH 205/223] docs/kitbash.md, action table: one driver per loop holds after the loop is stated; a torque link's lug has no travel Co-Authored-By: Claude Fable 5.2 --- .../blender/brokkr_kitbash/brokkr_actions.json | 8 ++++---- surfaces/blender/docs/kitbash.md | 18 +++++++++++++----- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 1c52b58..e83a183 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 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. The connection's DOF is its parent socket's type's (revolute, prismatic or rigid); it starts with no joint record: brokkr_kitbash.joint states one. 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, a loop, and a new pin or slide between the two ends of a loop that follows (a second driver: both are named; hold it or clear the loop first). The connection's DOF is its parent socket's type's (revolute, prismatic or rigid); it starts with no joint record: brokkr_kitbash.joint states one. Reports the child with its connection.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -160,7 +160,7 @@ }, { "name": "brokkr_kitbash.detach", - "doc": "Clear a kit part's connection and the closure it states: it keeps its place in the world and loses its parent; parts attached to it stay attached to it.", + "doc": "Clear a kit part's connection and the closure it states: it keeps its place in the world and loses its parent; parts attached to it stay attached to it. A loop follower's partner stops following with it. Refused, with nothing changed, when it would leave a loop that follows with a second driver: a part between one end of the loop and the part both ends hang from, whose going leaves a joint with travel between the ends (both drivers are named).", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -310,7 +310,7 @@ }, { "name": "brokkr_kitbash.joint", - "doc": "State the joint record of an attached kit part's connection. The connection's DOF is its parent socket's type's: revolute (its value is the roll, degrees) or prismatic (the slide, metres). record is a JSON object of any of limits ([lo, hi] or null), mechanism (a label of 1 to 32 a-z, 0-9 and _, or null) and compliance ({\"hertz\": over 0 to 30, \"damping_ratio\": 0 to 2} or null: a slide in the load path that settles under load, a record for a runtime, solved by nothing here); a key left out keeps what is stated and null clears it. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits spanning over 360 degrees or with an end past 360, prismatic limits with an end past 10 m, and compliance on a revolute joint or without limits. Moves nothing but a roll to its turn inside the limits: a follower keeps its derived value (limits that do not hold it are refused), and a driver's followers are derived again where it stands. Limits cannot be cleared from a driver a ratio follows. Reports the part and closures as roll does.", + "doc": "State the joint record of an attached kit part's connection. The connection's DOF is its parent socket's type's: revolute (its value is the roll, degrees) or prismatic (the slide, metres). record is a JSON object of any of limits ([lo, hi] or null), mechanism (a label of 1 to 32 a-z, 0-9 and _, or null) and compliance ({\"hertz\": over 0 to 30, \"damping_ratio\": 0 to 2} or null: a slide in the load path that settles under load, a record for a runtime, solved by nothing here); a key left out keeps what is stated and null clears it. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits spanning over 360 degrees or with an end past 360, prismatic limits with an end past 10 m, and compliance on a revolute joint or without limits. Moves nothing but a roll to its turn inside the limits: a follower keeps its derived value (limits that do not hold it are refused), and a driver's followers are derived again where it stands. Limits cannot be cleared from a driver a ratio follows, nor widened or cleared on a pin that limits of one value hold between the two ends of a loop that follows (it would be a second driver: both are named). Reports the part and closures as roll does.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -384,7 +384,7 @@ }, { "name": "brokkr_kitbash.follow", - "doc": "State that an attached kit part's joint follows another's: its roll or slide is then derived from the driver's whenever the driver is posed, and roll, aim, reach and slide on it are refused. record is JSON. {\"driver\": name, \"kind\": \"ratio\", \"k\": number, \"offset\": number}: the value is k x the driver's value + offset (a kneecap at k 0.5, a pinion at minus ring over pinion, a crosshead's slide in metres per degree of a roll); the driver states limits, so its value is one number. {\"driver\": name, \"kind\": \"loop\"}: object_name is a part that states a closure that holds; its joint and its parent's are the two unknowns solved so the closure keeps holding (a rocker and coupler closing on a crank; a ram's barrel and rod closing on the part it pushes; a torque link's two arms), and both follow the driver. Exactly one end of the loop, the parent's parent or the part closed on, moves with the driver: it is the driver, follows it, or hangs from one that does. The driver is the one input the two ends depend on: every revolute or prismatic joint between an end and the part both ends hang from is the driver, follows it, or is held by limits of one value (a torque link's lug on its rod: limits [90, 90]). The loop is planar: its pins are parallel. null clears the statement, and a loop partner's with it. The follower moves at once and the report's followers lists every follower of the driver as {part, value}. Refuses, with nothing changed: a rigid connection; a driver that is the follower, below it, or itself a follower; a follower that already follows or that drives another; a ratio whose driver states no limits; a value outside the follower's own limits; a loop with no closure that holds, with both ends or neither moving with the driver, whose ends depend on more than one driver (another driver's follower, or a joint with travel that follows nothing: both are named), that is not planar, or at or past a dead centre (its two joints in line, a ram's rod end on its barrel's pin, or a step that would take the pair to its other assembly). Nothing stores a pin or a linkage: a loop is solved from the kits' socket frames each time, and no Blender driver or constraint is made.", + "doc": "State that an attached kit part's joint follows another's: its roll or slide is then derived from the driver's whenever the driver is posed, and roll, aim, reach and slide on it are refused. record is JSON. {\"driver\": name, \"kind\": \"ratio\", \"k\": number, \"offset\": number}: the value is k x the driver's value + offset (a kneecap at k 0.5, a pinion at minus ring over pinion, a crosshead's slide in metres per degree of a roll); the driver states limits, so its value is one number. {\"driver\": name, \"kind\": \"loop\"}: object_name is a part that states a closure that holds; its joint and its parent's are the two unknowns solved so the closure keeps holding (a rocker and coupler closing on a crank; a ram's barrel and rod closing on the part it pushes; a torque link's two arms), and both follow the driver. Exactly one end of the loop, the parent's parent or the part closed on, moves with the driver: it is the driver, follows it, or hangs from one that does. The driver is the one input the two ends depend on: every revolute or prismatic joint between an end and the part both ends hang from is the driver, follows it, or is held by limits of one value (a torque link's lug on its rod: limits [90, 90]). The loop is planar: its pins are parallel. null clears the statement, and a loop partner's with it; it is refused for a follower between the two ends of another loop, which it would leave with a second driver. The one-driver rule is read again before every write of a connection and before detach, so no later attach, detach, clear, limits or pose breaks it. The follower moves at once and the report's followers lists every follower of the driver as {part, value}. Refuses, with nothing changed: a rigid connection; a driver that is the follower, below it, or itself a follower; a follower that already follows or that drives another; a ratio whose driver states no limits; a value outside the follower's own limits; a loop with no closure that holds, with both ends or neither moving with the driver, whose ends depend on more than one driver (another driver's follower, or a joint with travel that follows nothing: both are named), that is not planar, or at or past a dead centre (its two joints in line, a ram's rod end on its barrel's pin, or a step that would take the pair to its other assembly). Nothing stores a pin or a linkage: a loop is solved from the kits' socket frames each time, and no Blender driver or constraint is made.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 54a965a..34263e8 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -221,11 +221,19 @@ parallel to the pin it closes on and each slide runs across it. Exactly one of i and the part closed on) moves with the driver: it is the driver, follows it, or hangs from one that does. And the driver is the only input the two ends depend on: every revolute or prismatic joint between an end and the part the two ends share (or the root, when they share none) is the driver, follows it, or is held by limits of one value. A -joint there that follows another driver, or that follows nothing and has travel, would open the loop when it is -posed, so `follow` refuses the loop and names the driver and each other input; it does not solve a loop for two -drivers. A torque link is the case: the kit has no rigid lug, and a strut's two pins face one way, so the lower arm -closes on a strut pinned to the rod's end, and that pin is held by limits of one value (`[90, 90]`) before the -arms follow the rod's slide. Nothing +joint there that follows another driver, or that follows nothing and has travel, is a second driver: a pose of it +would open the loop, and nothing here solves a loop for two drivers. The rule is read over every loop in the scene +before each write, as the scene would stand after it (`one_driver`, asked by the one writer of connections and by +`detach`), so it holds after the loop is stated as it does when `follow` states it. Each of these is refused with +nothing changed, naming the loop's driver and each other one: `attach` of an end's root on a pin or a slide, +`detach` of a part between an end and the part both ends hang from, `follow` with null on a follower between the +ends, `joint` widening or clearing limits that held a pin there, and any pose once such a joint was written by +hand. To change a mechanism between a loop's ends, give the new joint its one driver or its one value first, or +clear the loop and state it again. A loop whose driver is detached is derived by nothing and is not read; the +attach that gives the driver a connection again reads it. A torque link is the case for limits of one value: a +real torque link exists to stop the rod rolling in its barrel, so its lug has no travel, and a strut pinned to +the rod's end and held by limits `[90, 90]` is that lug (a strut's two pins face one way, so the lower arm cannot +close on the rod's own pin). The lug is held before the arms follow the rod's slide. Nothing stores a pin position or a linkage record: `core.close_loop` solves the pair from the kits' socket frames at the parts' stored params each time, by Newton's method on the closing pin's error in the loop's plane with the analytic Jacobian. That is the position analysis of the kinematics texts (Nikravesh, *Computer-Aided Analysis of Mechanical From ed2ed9eeb84e2accac7ba884d3abda7da2f464d2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 14:29:40 +0100 Subject: [PATCH 206/223] brokkr_kitbash.plate: hard plates from a plate table, in numpy alone plate.py turns a brokkr.plates.v0 table into each plate's convex solid (by faces, slab, sections or points), its seeded detail panels, their corner bolts and its anchors' frames. The table alone decides the result: the hull is built here, facets are ordered in the table frame, seeds are data. Fixtures plates_bastion/paladin/raptor.json hold tables converted from the three mech branches (eeda8bf, c35e57e, 0c27103) and the truth each branch's own builder made in Blender 5.3. test_plate.py's KNOWN names the eleven fixture plates the truth cannot be met on (float32 solves, a corner bastion's builder lost, one tie Blender's loop order decided). Cut hard-plate-core (aetheria-release:cut_spec:cut-hard-plate-core.r1). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/plate.py | 802 +++++++ .../tests/fixtures/plates_bastion.json | 1326 +++++++++++ .../tests/fixtures/plates_paladin.json | 1943 +++++++++++++++++ .../blender/tests/fixtures/plates_raptor.json | 1336 ++++++++++++ surfaces/blender/tests/test_kitbash.py | 5 +- surfaces/blender/tests/test_plate.py | 484 ++++ 6 files changed, 5895 insertions(+), 1 deletion(-) create mode 100644 surfaces/blender/brokkr_kitbash/plate.py create mode 100644 surfaces/blender/tests/fixtures/plates_bastion.json create mode 100644 surfaces/blender/tests/fixtures/plates_paladin.json create mode 100644 surfaces/blender/tests/fixtures/plates_raptor.json create mode 100644 surfaces/blender/tests/test_plate.py diff --git a/surfaces/blender/brokkr_kitbash/plate.py b/surfaces/blender/brokkr_kitbash/plate.py new file mode 100644 index 0000000..5ad4b4d --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/plate.py @@ -0,0 +1,802 @@ +"""brokkr.plates.v0: {"schema": "brokkr.plates.v0", "plates": [row, ...]}, a table of hard armour plates. + +numpy and the standard library only, tested without Blender (tests/test_plate.py); docs/kitbash.md, Hard plates, +states the format in full. A hard plate is a convex faceted solid: every facet flat, every edge a chamfer the +caller's Bevel makes. This module turns one table into each plate's solid, its detail panels, their corner bolts +and the frames of its anchors. The table alone decides the result: coordinates are metres in the table's own frame +(no host and no world reach this module), every clad carries its seed as data, and facets are ordered by a rule on +the solid as built in the table frame. + +A row: name, mat, bevel, sides ("one" or "both"), mirror, exactly one solid form, clad, face, fits. + +Solid forms, each a set of points whose convex hull is the plate: + faces [{at, normal} | {through: [a, b, c], out}, ...]: the corners of what the half-spaces bound + slab {at, normal, up, right, outline, thick, taper, back, gap}: an outline drawn on the outer face, the + face's rim chamfered taper, the back face thick behind and scaled back about the outline's middle; + or {corners, names, inside, lift, ...}: the outer face is the least-squares plane of the corners, + outward away from `inside`, standing lift off them + sections [[z, w, y0, y1, c], ...]: chamfered rectangles down a limb + points [[x, y, z], ...] + +check(document) returns the table with every default written in, or raises PlateError naming the path. +build(table, side=1) returns one entry per plate built: name, solid (V, faces), facets, panels (V, faces), +bolts (V, faces), anchors, report. Both are pure: nothing is cached and nothing is written. +""" +from __future__ import annotations + +import math +import random +import re +from typing import Any + +import numpy as np + +from . import core + +SCHEMA = "brokkr.plates.v0" +ROWS = (1, 256) +OUTLINE = (3, 64) +FACES = (4, 32) +SECTIONS = (2, 16) +POINTS = (4, 64) +SELECTORS = (1, 8) +FITS = 64 +FAR = 1e3 # a corner of a faces row farther than this from the origin: the faces bound nothing useful +FLAT = 0.05 # a corners slab's points may stand off their plane by this share of their extent +MERGE = 0.5 # degrees: facets closer than this are one facet; a two-edged vertex turning less is dropped +TIE = 1e-9 # areas (m2) and lengths (m) closer than this are equal: the tie rules decide +OUTER = 0.97 # clad facets "outer": the facet's normal on the face's normal is over this +SHARE = (0.36, 0.64) # where a split panel's cut falls along the facet's longest edge +MITER = 0.3 # an inset corner moves at most c / MITER +PANEL_MIN = (0.25, 0.02) # a panel under this share of its facet, or under this many m2, is not made +SINK, CHAMFER = 0.02, 0.02 # a panel starts this far under its facet; its far rim is chamfered this much +BOLT = 0.028 +RANGES = {"thick": (0.001, 2.0), "taper": (0.0, 0.5), "back": (0.1, 1.5), "gap": (0.0, 0.5), "lift": (0.0, 1.0)} +KINDS = ("mark", "hose_port") + + +class PlateError(ValueError): + """The plate table breaks a rule of the format, or a row bounds no solid; the message names the path.""" + + +# --- reading the table ---------------------------------------------------------------------------------------------- +def _number(value: Any, path: str, low: float | None = None, high: float | None = None) -> float: + if not core.finite(value): + raise PlateError(f"{path}: {value!r} is not a finite number") + if (low is not None and value < low) or (high is not None and value > high): + raise PlateError(f"{path}: {value} is outside {low} to {high}") + return float(value) + + +def _vector(value: Any, path: str, size: int = 3) -> list[float]: + if not isinstance(value, (list, tuple)) or len(value) != size: + raise PlateError(f"{path}: wants {size} numbers") + return [_number(v, f"{path}[{i}]") for i, v in enumerate(value)] + + +def _object(value: Any, path: str, required: tuple[str, ...], optional: tuple[str, ...] = ()) -> dict: + if not isinstance(value, dict): + raise PlateError(f"{path}: wants an object") + for key in value: + if key not in required and key not in optional: + raise PlateError(f"{path}.{key}: unknown key (known: {', '.join(required + optional)})") + for key in required: + if key not in value: + raise PlateError(f"{path}.{key}: missing") + return value + + +def _list(value: Any, path: str, bounds: tuple[int, int]) -> list: + if not isinstance(value, (list, tuple)) or not bounds[0] <= len(value) <= bounds[1]: + raise PlateError(f"{path}: wants {bounds[0]} to {bounds[1]} entries") + return list(value) + + +def _area2(ring: np.ndarray) -> float: + x, y = ring[:, 0], ring[:, 1] + return 0.5 * float(np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y)) + + +def _crosses(ring: np.ndarray) -> bool: + def turn(a, b, c): + return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + n = len(ring) + for i in range(n): + a, b = ring[i], ring[(i + 1) % n] + for j in range(i + 2, n): + if (j + 1) % n == i: + continue + c, d = ring[j], ring[(j + 1) % n] + if turn(a, b, c) * turn(a, b, d) < 0 and turn(c, d, a) * turn(c, d, b) < 0: + return True + return False + + +def _width(ring: np.ndarray) -> float: + """The least width of an outline: over its edges, how far the farthest point stands from the edge's line.""" + least = math.inf + for i in range(len(ring)): + e = ring[(i + 1) % len(ring)] - ring[i] + off = (ring - ring[i]) @ (np.array([-e[1], e[0]]) / np.linalg.norm(e)) + least = min(least, float(off.max() - off.min())) + return least + + +def outline_points(outline: Any) -> list[list[float]]: + """An outline's points: the list as given, or {w, h, clip} as a w by h rectangle with its corners cut clip.""" + if isinstance(outline, dict): + w, h, c = outline["w"], outline["h"], outline["clip"] + if not c: + return [[-w / 2, h / 2], [w / 2, h / 2], [w / 2, -h / 2], [-w / 2, -h / 2]] + return [[-w / 2 + c, h / 2], [w / 2 - c, h / 2], [w / 2, h / 2 - c], [w / 2, -h / 2 + c], [w / 2 - c, -h / 2], [-w / 2 + c, -h / 2], [-w / 2, -h / 2 + c], [-w / 2, h / 2 - c]] + return [list(p) for p in outline] + + +def _check_ring(ring: np.ndarray, path: str) -> None: + if any(np.linalg.norm(ring[i] - ring[i - 1]) < TIE for i in range(len(ring))): + raise PlateError(f"{path}: two neighbouring points are the same point") + if abs(_area2(ring)) < 1e-12: + raise PlateError(f"{path}: the outline has zero area") + if _crosses(ring): + raise PlateError(f"{path}: the outline crosses itself") + + +def _check_slab(slab: Any, path: str) -> dict: + if isinstance(slab, dict) and "corners" in slab: + _object(slab, path, ("corners", "inside", "thick"), ("names", "lift", "taper", "back", "gap", "up")) + out = {"corners": [_vector(p, f"{path}.corners[{i}]") for i, p in enumerate(_list(slab["corners"], f"{path}.corners", OUTLINE))], "inside": _vector(slab["inside"], f"{path}.inside")} + if slab.get("names") is not None: + names = slab["names"] + if not isinstance(names, (list, tuple)) or len(names) != len(out["corners"]) or not all(isinstance(n, str) and n for n in names) or len(set(names)) != len(names): + raise PlateError(f"{path}.names: wants one distinct name per corner") + out["names"] = list(names) + out["lift"] = _number(slab.get("lift", 0.06), f"{path}.lift", *RANGES["lift"]) + else: + _object(slab, path, ("at", "normal", "outline", "thick"), ("up", "right", "taper", "back", "gap")) + out = {"at": _vector(slab["at"], f"{path}.at"), "normal": _vector(slab["normal"], f"{path}.normal")} + if slab.get("right") is not None: + out["right"] = _vector(slab["right"], f"{path}.right") + outline = slab["outline"] + if isinstance(outline, dict): + _object(outline, f"{path}.outline", ("w", "h", "clip")) + w, h = (_number(outline[k], f"{path}.outline.{k}", 1e-6, 1e3) for k in "wh") + out["outline"] = {"w": w, "h": h, "clip": _number(outline["clip"], f"{path}.outline.clip", 0.0, 0.5 * min(w, h) - 1e-9)} + else: + out["outline"] = [_vector(p, f"{path}.outline[{i}]", 2) for i, p in enumerate(_list(outline, f"{path}.outline", OUTLINE))] + out["up"] = _vector(slab.get("up", [0, 0, 1]), f"{path}.up") + for key, default in (("thick", None), ("taper", 0.04), ("back", 1.0), ("gap", 0.0)): + out[key] = _number(slab.get(key, default), f"{path}.{key}", *RANGES[key]) + return out + + +def _check_clad(clad: Any, row: dict, path: str) -> dict: + _object(clad, path, ("mat", "min_area", "lifts", "inset", "gap", "split", "seed"), ("facets", "floor", "bolt_r")) + out = {"mat": _name(clad["mat"], f"{path}.mat", 63, None)} + facets = clad.get("facets", "outer" if "slab" in row else None) + if facets is None: + raise PlateError(f"{path}.facets: missing (only a slab has a default, its outer face)") + if facets == "outer": + if "slab" not in row and "face" not in row: + raise PlateError(f"{path}.facets: \"outer\" wants a slab or a row with a face") + elif facets != "all": + picked = [] + if isinstance(facets, str): + raise PlateError(f"{path}.facets: wants \"outer\", \"all\" or selectors") + for i, sel in enumerate(_list(facets, f"{path}.facets", SELECTORS)): + at = f"{path}.facets[{i}]" + if isinstance(sel, dict) and "radial" in sel: + _object(sel, at, ("radial", "min_r", "cos")) + picked.append({"radial": _vector(sel["radial"], f"{at}.radial"), "min_r": _number(sel["min_r"], f"{at}.min_r", 0.0, FAR), "cos": _number(sel["cos"], f"{at}.cos", -1.0, 1.0)}) + else: + _object(sel, at, ("n", "cos")) + picked.append({"n": _vector(sel["n"], f"{at}.n"), "cos": _number(sel["cos"], f"{at}.cos", -1.0, 1.0)}) + axis = picked[-1].get("radial", picked[-1].get("n")) + if not np.linalg.norm(axis) > 0: + raise PlateError(f"{at}: the direction has no length") + facets = picked + out["facets"] = facets + if clad.get("floor") is not None: + out["floor"] = _number(clad["floor"], f"{path}.floor", -1.0, 1.0) + out["min_area"] = _number(clad["min_area"], f"{path}.min_area", 0.0, 1e6) + lifts = clad["lifts"] + if not isinstance(lifts, (list, tuple)) or len(lifts) != 2: + raise PlateError(f"{path}.lifts: wants two lifts") + out["lifts"] = [_number(v, f"{path}.lifts[{i}]", 0.0, 1.0) for i, v in enumerate(lifts)] + out["inset"] = _number(clad["inset"], f"{path}.inset", 0.0, 10.0) + out["gap"] = _number(clad["gap"], f"{path}.gap", 0.0, 10.0) + out["split"] = _number(clad["split"], f"{path}.split", 0.0, 1e6) + seed = clad["seed"] + whole = lambda v: isinstance(v, int) and not isinstance(v, bool) and 0 <= v < 2 ** 63 # noqa: E731 + if isinstance(seed, (list, tuple)): + if row["sides"] != "both": + raise PlateError(f"{path}.seed: a pair of seeds is for a row with sides \"both\"") + if len(seed) != 2 or not all(whole(v) for v in seed): + raise PlateError(f"{path}.seed: wants an integer or [right, left]") + seed = list(seed) + elif not whole(seed): + raise PlateError(f"{path}.seed: wants an integer or [right, left]") + out["seed"] = seed + out["bolt_r"] = _number(clad.get("bolt_r", BOLT), f"{path}.bolt_r", 0.001, 1.0) + return out + + +def _name(value: Any, path: str, most: int, pattern: str | None) -> str: + if not isinstance(value, str) or not 1 <= len(value) <= most or (pattern and not re.fullmatch(pattern, value)): + raise PlateError(f"{path}: wants a name of 1 to {most} characters" + (" from a-z A-Z 0-9 _ ." if pattern else "")) + return value + + +def _check_row(row: Any, path: str) -> dict: + forms = ("faces", "slab", "sections", "points") + _object(row, path, ("name", "mat"), ("bevel", "sides", "mirror", "clad", "face", "fits") + forms) + out = {"name": _name(row["name"], f"{path}.name", 48, r"[A-Za-z0-9_.]+"), "mat": _name(row["mat"], f"{path}.mat", 63, None), + "bevel": _number(row.get("bevel", 0.0), f"{path}.bevel", 0.0, 0.1), "sides": row.get("sides", "one"), "mirror": row.get("mirror", False)} + if out["sides"] not in ("one", "both"): + raise PlateError(f"{path}.sides: wants \"one\" or \"both\"") + if not isinstance(out["mirror"], bool): + raise PlateError(f"{path}.mirror: wants true or false") + given = [f for f in forms if f in row] + if len(given) != 1: + raise PlateError(f"{path}: wants exactly one solid form of {', '.join(forms)} (has {', '.join(given) or 'none'})") + form = given[0] + if form == "faces": + faces = [] + for i, face in enumerate(_list(row["faces"], f"{path}.faces", FACES)): + at = f"{path}.faces[{i}]" + if isinstance(face, dict) and "through" in face: + _object(face, at, ("through", "out")) + if not isinstance(face["through"], (list, tuple)) or len(face["through"]) != 3: + raise PlateError(f"{at}.through: wants three points") + faces.append({"through": [_vector(p, f"{at}.through[{k}]") for k, p in enumerate(face["through"])], "out": _vector(face["out"], f"{at}.out")}) + else: + _object(face, at, ("at", "normal")) + faces.append({"at": _vector(face["at"], f"{at}.at"), "normal": _vector(face["normal"], f"{at}.normal")}) + out["faces"] = faces + elif form == "slab": + out["slab"] = _check_slab(row["slab"], f"{path}.slab") + elif form == "sections": + out["sections"] = [_vector(s, f"{path}.sections[{i}]", 5) for i, s in enumerate(_list(row["sections"], f"{path}.sections", SECTIONS))] + else: + out["points"] = [_vector(p, f"{path}.points[{i}]") for i, p in enumerate(_list(row["points"], f"{path}.points", POINTS))] + if row.get("face") is not None: + if form == "slab": + raise PlateError(f"{path}.face: a slab's face is its outer face") + face = _object(row["face"], f"{path}.face", ("at", "normal"), ("up", "right")) + out["face"] = {"at": _vector(face["at"], f"{path}.face.at"), "normal": _vector(face["normal"], f"{path}.face.normal"), "up": _vector(face.get("up", [0, 0, 1]), f"{path}.face.up")} + if face.get("right") is not None: + out["face"]["right"] = _vector(face["right"], f"{path}.face.right") + out["clad"] = None if row.get("clad") is None else _check_clad(row["clad"], out, f"{path}.clad") + fits, names = [], set() + for i, fit in enumerate(_list(row.get("fits", []), f"{path}.fits", (0, FITS))): + at = f"{path}.fits[{i}]" + kind = fit.get("kind") if isinstance(fit, dict) else None + if kind not in KINDS: + raise PlateError(f"{at}.kind: {kind!r} is not a fit of this table (known: {', '.join(KINDS)})") + if form != "slab" and "face" not in out: + raise PlateError(f"{at}: a fit stands on a face; this row is no slab and names no face") + if kind == "mark": + _object(fit, at, ("kind", "id", "at", "height")) + entry = {"kind": kind, "id": _name(fit["id"], f"{at}.id", 63, None), "at": _vector(fit["at"], f"{at}.at", 2), "height": _number(fit["height"], f"{at}.height", 1e-4, 100.0)} + else: + _object(fit, at, ("kind", "name", "at"), ("lift",)) + entry = {"kind": kind, "name": _name(fit["name"], f"{at}.name", 63, None), "at": _vector(fit["at"], f"{at}.at", 2), "lift": _number(fit.get("lift", 0.0), f"{at}.lift", -1.0, 1.0)} + name = entry.get("id", entry.get("name")) + if name in names: + raise PlateError(f"{at}: a second anchor named {name!r} in this row") + names.add(name) + fits.append(entry) + out["fits"] = fits + return out + + +def check(document: Any) -> dict: + """The table with every default written in. Raises PlateError naming the path of what breaks the format, and + of a row that bounds no solid: every row's solid and anchors are made here once, at side +1, and build makes + them the same way, so build meets no refusal check has not.""" + table = _read(document) + for i, row in enumerate(table["plates"]): + points, face = _row_points(row, f"plates[{i}]") + hull(_mirrored(points, row["mirror"]), f"plates[{i}]") + for j, fit in enumerate(row["fits"]): + _frame(face[0], face[3], (0.0, 0.0, 1.0) if fit["kind"] == "mark" else face[2], f"plates[{i}].fits[{j}]") + return table + + +def _read(document: Any) -> dict: + _object(document, "document", ("schema", "plates")) + if document["schema"] != SCHEMA: + raise PlateError(f"document.schema: {document['schema']!r} is not {SCHEMA}") + rows = [_check_row(row, f"plates[{i}]") for i, row in enumerate(_list(document["plates"], "plates", ROWS))] + built: dict[str, int] = {} + for i, row in enumerate(rows): + for name in ((row["name"] + ".R", row["name"] + ".L") if row["sides"] == "both" else (row["name"],)): + if name in built: + raise PlateError(f"plates[{i}].name: {name!r} is built by plates[{built[name]}] too") + built[name] = i + return {"schema": SCHEMA, "plates": rows} + + +# --- points of a solid form ----------------------------------------------------------------------------------------- +def _frame(point, normal, up, path: str) -> np.ndarray: + try: + return core.surface_frame(point, normal, up) + except core.KitError as error: + raise PlateError(f"{path}: {error}") from None + + +def plane_basis(normal, up=(0.0, 0.0, 1.0), right=None, path: str = "plane"): + """(a, b, n): unit axes of the plane facing `normal`: b the in-plane part of `up`, a across it (b cross n), + turned to the side `right` points to where one is given, so an outline's +a is a named direction.""" + frame = _frame((0.0, 0.0, 0.0), normal, up, path) + a, b, n = frame[:3, 0].copy(), frame[:3, 1].copy(), frame[:3, 2].copy() + if right is not None and a @ np.asarray(right, dtype=np.float64) < 0: + a = -a + return a, b, n + + +def inset2d(ring, c: float) -> np.ndarray: + """A convex counter-clockwise outline moved in by c on every edge; a sharp corner moves at most c / MITER.""" + ring = np.asarray(ring, dtype=np.float64) + out = np.empty_like(ring) + for i in range(len(ring)): + p0, p1, p2 = ring[i - 1], ring[i], ring[(i + 1) % len(ring)] + e0, e1 = (p1 - p0) / np.linalg.norm(p1 - p0), (p2 - p1) / np.linalg.norm(p2 - p1) + n0, n1 = np.array([-e0[1], e0[0]]), np.array([-e1[1], e1[0]]) + miter = n0 + n1 + length = np.linalg.norm(miter) + miter = miter / length if length > 0 else n0 + out[i] = p1 + miter * (c / max(float(miter @ n0), MITER)) + return out + + +def slab_points(origin, a, b, n, outline, thick: float, taper: float, back: float, gap: float) -> np.ndarray: + """A slab's corners: the outline (either winding) drawn in gap, on the plane through origin; the face is that + ring moved in taper, the ring itself stands taper behind it, and the back ring thick behind, scaled back about + the ring's middle.""" + ring = np.asarray(outline, dtype=np.float64) + if _area2(ring) < 0: + ring = ring[::-1] + if gap: + ring = inset2d(ring, gap) + inner = inset2d(ring, taper) if taper else ring + middle = ring.mean(axis=0) + rear = middle + (ring - middle) * back + lift = lambda flat, z: origin + np.outer(flat[:, 0], a) + np.outer(flat[:, 1], b) + n * z # noqa: E731 + parts = [lift(inner, 0.0)] + ([lift(ring, -taper)] if taper else []) + [lift(rear, -thick)] + return np.vstack(parts) + + +def corners_of(planes, path: str = "faces") -> np.ndarray: + """The corners of the convex solid a set of faces [(n, d): kept where n.p <= d] bounds: every three faces' + meeting point inside all the others within 1e-6.""" + normals = np.array([p[0] for p in planes], dtype=np.float64) + offsets = np.array([p[1] for p in planes], dtype=np.float64) + out: list[np.ndarray] = [] + for i in range(len(planes)): + for j in range(i + 1, len(planes)): + for k in range(j + 1, len(planes)): + m = normals[[i, j, k]] + if abs(np.linalg.det(m)) < 1e-7: + continue + p = np.linalg.solve(m, offsets[[i, j, k]]) + if not np.all(normals @ p <= offsets + 1e-6): + continue + if np.linalg.norm(p) >= FAR: + raise PlateError(f"{path}: faces {i}, {j} and {k} meet {np.linalg.norm(p):.0f} m away: the faces do not close the solid") + if not any(np.linalg.norm(p - q) < 1e-5 for q in out): + out.append(p) + if len(out) < 4: + raise PlateError(f"{path}: {len(planes)} faces bound no solid ({len(out)} corners)") + return np.array(out) + + +def section_points(sections) -> np.ndarray: + """A housing's corners from its sections down a limb: [z, width, y0, y1, chamfer] each a chamfered rectangle.""" + out = [] + for z, w, y0, y1, c in sections: + out += [(x, y, z) for x, y in ((-w / 2 + c, y0), (w / 2 - c, y0), (w / 2, y0 + c), (w / 2, y1 - c), (w / 2 - c, y1), (-w / 2 + c, y1), (-w / 2, y1 - c), (-w / 2, y0 + c))] + return np.array(out, dtype=np.float64) + + +def _unit(v, path: str) -> np.ndarray: + v = np.asarray(v, dtype=np.float64) + length = np.linalg.norm(v) + if not length > 0: + raise PlateError(f"{path}: the direction has no length") + return v / length + + +def _row_points(row: dict, path: str): + """(points, face): the row's points at side +1 and its face (origin, a, b, n), None where it has none.""" + face = None + if "faces" in row: + planes = [] + for i, f in enumerate(row["faces"]): + if "through" in f: + a, b, c = (np.array(p) for p in f["through"]) + n = _unit(np.cross(b - a, c - a), f"{path}.faces[{i}].through") + if n @ np.array(f["out"]) < 0: + n = -n + planes.append((n, float(n @ a))) + else: + n = _unit(f["normal"], f"{path}.faces[{i}].normal") + planes.append((n, float(n @ np.array(f["at"])))) + points = corners_of(planes, f"{path}.faces") + elif "slab" in row: + slab, at = row["slab"], f"{path}.slab" + if "corners" in slab: + corners = np.array(slab["corners"]) + centre = corners.mean(axis=0) + n = np.linalg.svd(corners - centre)[2][2] + extent = max(float(np.linalg.norm(p - q)) for p in corners for q in corners) + if not extent > 0 or float(np.abs((corners - centre) @ n).max()) > FLAT * extent: + raise PlateError(f"{at}.corners: the corners stand more than {FLAT} of their extent off one plane: that is not a plate") + if n @ (centre - np.array(slab["inside"])) < 0: + n = -n + origin = centre + n * slab["lift"] + a, b, n = plane_basis(n, slab["up"], None, f"{at}.up") + ring = np.column_stack(((corners - origin) @ a, (corners - origin) @ b)) + else: + origin = np.array(slab["at"]) + a, b, n = plane_basis(slab["normal"], slab["up"], slab.get("right"), f"{at}.normal") + ring = np.array(outline_points(slab["outline"]), dtype=np.float64) + _check_ring(ring, f"{at}.{'corners' if 'corners' in slab else 'outline'}") + drawn = inset2d(ring if _area2(ring) > 0 else ring[::-1], slab["gap"]) if slab["gap"] else ring + if slab["gap"] and _area2(drawn) <= 0: + raise PlateError(f"{at}.gap: {slab['gap']} leaves nothing of the outline") + if slab["taper"] and 2 * slab["taper"] >= _width(drawn): + raise PlateError(f"{at}.taper: {slab['taper']} is half the outline's least width ({_width(drawn):.4f}) or more") + points = slab_points(origin, a, b, n, ring, slab["thick"], slab["taper"], slab["back"], slab["gap"]) + face = (origin, a, b, n) + elif "sections" in row: + points = section_points(row["sections"]) + else: + points = np.array(row["points"], dtype=np.float64) + if "face" in row: + f = row["face"] + a, b, n = plane_basis(f["normal"], f["up"], f.get("right"), f"{path}.face.normal") + face = (np.array(f["at"]), a, b, n) + return points, face + + +def _mirrored(points: np.ndarray, mirror: bool) -> np.ndarray: + if not mirror: + return points + return np.vstack([points, points[np.abs(points[:, 0]) > 1e-6] * (-1.0, 1.0, 1.0)]) + + +# --- the hull and its facets ------------------------------------------------------------------------------------------ +def _newell(loop: np.ndarray) -> np.ndarray: + return 0.5 * np.cross(loop, np.roll(loop, -1, axis=0)).sum(axis=0) + + +def _angle(a: np.ndarray, b: np.ndarray) -> float: + return math.degrees(math.atan2(float(np.linalg.norm(np.cross(a, b))), float(a @ b))) + + +def _lexical(point) -> tuple: + return tuple(round(float(c) / TIE) for c in point) + + +def hull(points, path: str = "points", merge: float = MERGE): + """(V, faces, facets): the convex hull of `points`. A facet is every supporting plane's point set, ordered by + angle; adjacent facets whose normals are within `merge` degrees are one facet, and a vertex left with two + edges turning less than `merge` is dropped. faces are wound outward; facets[i] is face i's + {"normal", "area", "centre"} (centre the mean of its vertices). Order: area descending, ties (TIE) by centre + x, y, z; each face starts at its least vertex by x, y, z.""" + P = np.asarray(points, dtype=np.float64) + keep: list[int] = [] + for i in range(len(P)): + if not any(np.linalg.norm(P[i] - P[k]) < TIE for k in keep): + keep.append(i) + P = P[keep] + n = len(P) + scale = float(np.linalg.norm(P.max(axis=0) - P.min(axis=0))) if n else 0.0 + eps = TIE * max(1.0, scale) + found: dict[frozenset, np.ndarray] = {} + probe = P[np.linspace(0, n - 1, min(n, 12)).astype(int)] if n else P + for i in range(n - 2): # every plane through point i and two later points, at once + J, K = np.triu_indices(n - i - 1, 1) + first, second = P[J + i + 1] - P[i], P[K + i + 1] - P[i] + normals = np.cross(first, second) + lengths = np.linalg.norm(normals, axis=1) + good = lengths > 1e-6 * np.linalg.norm(first, axis=1) * np.linalg.norm(second, axis=1) + for key in found: # a plane already found is not found again from its other points + if i in key: + inside = np.zeros(n, dtype=bool) + inside[list(key)] = True + good &= ~(inside[J + i + 1] & inside[K + i + 1]) + if not good.any(): + continue + normals = normals[good] / lengths[good, None] + part = (probe - P[i]) @ normals.T # a plane a few points stand on both sides of supports nothing + normals = normals[(part.max(axis=0) <= eps) | (part.min(axis=0) >= -eps)] + off = (P - P[i]) @ normals.T + above, below = off.max(axis=0) <= eps, off.min(axis=0) >= -eps + support = np.nonzero(above | below)[0] + if not len(support): + continue + on = np.abs(off[:, support]) <= eps + if on.all(axis=0).any(): + raise PlateError(f"{path}: the points lie in one plane: they bound no solid") + for c in np.unique(np.packbits(on, axis=0).T, axis=0, return_index=True)[1]: + key = frozenset(np.nonzero(on[:, c])[0].tolist()) + if key not in found: + found[key] = normals[support[c]] if above[support[c]] else -normals[support[c]] + if n < 4 or len(found) < 4: + raise PlateError(f"{path}: {n} distinct points bound no solid") + sets = [s for s in found if not any(s < t for t in found)] + loops, normals = [], [] + for on in sets: + normal = found[on] + idx = sorted(on) + centre = P[idx].mean(axis=0) + u = _unit(P[idx[0]] - centre if np.linalg.norm(P[idx[0]] - centre) > eps else P[idx[1]] - centre, path) + u = _unit(u - normal * (u @ normal), path) + v = np.cross(normal, u) + flat = np.column_stack(((P[idx] - centre) @ u, (P[idx] - centre) @ v)) + loops.append([idx[k] for k in _hull2d(flat, eps)]) + normals.append(normal) + # facets within `merge` degrees across an edge are one facet + group = list(range(len(loops))) + + def root(k: int) -> int: + while group[k] != k: + group[k] = group[group[k]] + k = group[k] + return k + owner: dict[tuple[int, int], int] = {} + for k, loop in enumerate(loops): + for a, b in zip(loop, loop[1:] + loop[:1]): + owner[(a, b)] = k + for (a, b), k in owner.items(): + other = owner.get((b, a)) + if other is not None and other > k and _angle(normals[k], normals[other]) < merge: + group[root(other)] = root(k) + merged: dict[int, list[int]] = {} + for k in range(len(loops)): + merged.setdefault(root(k), []).append(k) + faces: list[list[int]] = [] + for members in merged.values(): + inside = set(members) + step = {a: b for k in members for a, b in zip(loops[k], loops[k][1:] + loops[k][:1]) if owner.get((b, a)) not in inside} + start = min(step) + loop, at = [start], step[start] + while at != start and len(loop) <= len(step): + loop.append(at) + at = step.get(at, start) + if len(loop) != len(step) or len(loop) < 3: + raise PlateError(f"{path}: facets within {merge} degrees of each other do not make one outline") + faces.append(loop) + # a vertex left on two edges that run on straight is no corner + while True: + edges: dict[int, set[int]] = {} + for loop in faces: + for a, b in zip(loop, loop[1:] + loop[:1]): + edges.setdefault(a, set()).add(b) + edges.setdefault(b, set()).add(a) + gone = set() + for v, ends in edges.items(): + if len(ends) == 2 and not ends & gone: + a, b = sorted(ends) + if _angle(P[v] - P[a], P[b] - P[v]) < merge: + gone.add(v) + if not gone: + break + faces = [[v for v in loop if v not in gone] for loop in faces] + faces = [loop for loop in faces if len(loop) >= 3] + used = sorted({v for loop in faces for v in loop}) + slot = {v: k for k, v in enumerate(used)} + V = P[used] + rows = [] + for loop in faces: + loop = [slot[v] for v in loop] + first = min(range(len(loop)), key=lambda k: _lexical(V[loop[k]])) + loop = loop[first:] + loop[:first] + normal = _newell(V[loop]) + area = float(np.linalg.norm(normal)) + rows.append((loop, {"normal": normal / area, "area": area, "centre": V[loop].mean(axis=0)})) + rows.sort(key=lambda r: -r[1]["area"]) + ordered, k = [], 0 + while k < len(rows): + m = k + 1 + while m < len(rows) and rows[m - 1][1]["area"] - rows[m][1]["area"] <= TIE: + m += 1 + ordered += sorted(rows[k:m], key=lambda r: _lexical(r[1]["centre"]), reverse=True) + k = m + return V, [r[0] for r in ordered], [r[1] for r in ordered] + + +def _hull2d(flat: np.ndarray, eps: float) -> list[int]: + """The indices of a planar point set's convex outline, counter-clockwise: the points ordered by angle about + their middle, then every point that does not turn left by more than eps (one inside, or on a straight run) + left out until none is.""" + centre = flat.mean(axis=0) + loop = sorted(range(len(flat)), key=lambda k: math.atan2(flat[k][1] - centre[1], flat[k][0] - centre[0])) + changed = True + while changed and len(loop) > 3: + changed = False + for at in range(len(loop)): + a, b, c = flat[loop[at - 1]], flat[loop[at]], flat[loop[(at + 1) % len(loop)]] + if (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) <= eps * max(float(np.linalg.norm(c - a)), eps): + del loop[at] + changed = True + break + return loop + + +# --- detail panels and their bolts ------------------------------------------------------------------------------------ +class _Mesh: + def __init__(self): + self.verts: list[np.ndarray] = [] + self.faces: list[list[int]] = [] + + def add(self, verts, faces) -> None: + base = len(self.verts) + self.verts += [np.asarray(v, dtype=np.float64) for v in verts] + self.faces += [[base + k for k in face] for face in faces] + + def done(self): + return (np.array(self.verts, dtype=np.float64).reshape(-1, 3), self.faces) + + +def _stand(normal: np.ndarray): + """(x, y) across a facet whose normal is given: y the table's +z off the normal (its +y where the facet is + level), x = y cross normal. A panel's bolts are turned by it.""" + y = np.array([0.0, 0.0, 1.0]) - normal * normal[2] + if np.linalg.norm(y) < 1e-4: + y = np.array([0.0, 1.0, 0.0]) - normal * normal[1] + y = y / np.linalg.norm(y) + return np.cross(y, normal), y + + +def clip(poly: list[np.ndarray], point: np.ndarray, normal: np.ndarray) -> list[np.ndarray]: + """A convex polygon (3D points in one plane) kept on the side of a line the normal points away from.""" + out = [] + for i, a in enumerate(poly): + b = poly[(i + 1) % len(poly)] + da, db = float((a - point) @ normal), float((b - point) @ normal) + if da <= 0: + out.append(a) + if (da < 0) != (db < 0) and abs(da - db) > 1e-9: + out.append(a + (b - a) * (da / (da - db))) + return out + + +def prism(mesh: _Mesh, origin, x, y, z, outline: np.ndarray, depth: float, chamfer: float) -> None: + """A block on a counter-clockwise outline, drawn depth along z, its far rim chamfered.""" + c = min(chamfer, 0.45 * depth) + rings = [(outline, 0.0), (outline, depth - c), (inset2d(outline, c) if c > 1e-6 else outline, depth)] + n = len(outline) + verts = [origin + x * q[0] + y * q[1] + z * h for ring, h in rings for q in ring] + faces = [list(reversed(range(n))), [2 * n + k for k in range(n)]] + for low in (0, n): + faces += [[low + k, low + (k + 1) % n, low + n + (k + 1) % n, low + n + k] for k in range(n)] + mesh.add(verts, faces) + + +def hex_bolt(mesh: _Mesh, origin, x, y, z, r: float, depth: float) -> None: + """A hexagonal head centred on origin: r to its corners, depth along z, half each way.""" + ring = [(r * math.sin(k * math.pi / 3), r * math.cos(k * math.pi / 3)) for k in range(6)] + verts = [origin + x * q[0] + y * q[1] + z * h for h in (-depth / 2, depth / 2) for q in ring] + faces = [[0, 5, 4, 3, 2, 1], [6, 7, 8, 9, 10, 11]] + [[k, (k + 1) % 6, 6 + (k + 1) % 6, 6 + k] for k in range(6)] + faces = [list(reversed(f)) for f in faces] # the ring runs clockwise about z + mesh.add(verts, faces) + + +def panel(panels: _Mesh, bolts: _Mesh, polygon: list[np.ndarray], out: np.ndarray, lift: float, inset: float, bolt_r: float) -> bool: + """A raised panel on a flat convex polygon: the polygon moved in inset on every edge, standing lift over it from + SINK below, its far rim chamfered; a bolt inside each of its corners. False for a polygon too small for one.""" + pts = np.array(polygon) + centre = pts.mean(axis=0) + normal = np.cross(pts - centre, np.roll(pts, -1, axis=0) - centre).sum(axis=0) + if np.linalg.norm(normal) < 1e-9: + return False + normal = normal / np.linalg.norm(normal) + if normal @ out < 0: + pts, normal = pts[::-1], -normal + x, y = _stand(normal) + flat = np.column_stack(((pts - centre) @ x, (pts - centre) @ y)) + inner = inset2d(flat, inset) + if _area2(inner) < PANEL_MIN[0] * _area2(flat) or _area2(inner) < PANEL_MIN[1]: + return False + prism(panels, centre - normal * SINK, x, y, normal, inner, lift + SINK, CHAMFER) + for q in inset2d(inner, 3.2 * bolt_r): + hex_bolt(bolts, centre + x * q[0] + y * q[1] + normal * (lift + 0.3 * bolt_r), x, y, normal, bolt_r, 0.6 * bolt_r) + return True + + +def _longest(pts: list[np.ndarray]) -> int: + """The index of a polygon's longest edge; edges within TIE of it tie, and the tie goes to the edge whose middle + is least by x, y, z.""" + lengths = [float(np.linalg.norm(pts[(k + 1) % len(pts)] - pts[k])) for k in range(len(pts))] + top = max(lengths) + return max((k for k in range(len(pts)) if top - lengths[k] <= TIE), key=lambda k: _lexical((pts[k] + pts[(k + 1) % len(pts)]) / 2)) + + +def _selected(clad: dict, normal: np.ndarray, centre: np.ndarray, face_n, side: int) -> bool: + if "floor" in clad and normal[2] < clad["floor"]: + return False + if clad["facets"] == "all": + return True + if clad["facets"] == "outer": + return float(normal @ face_n) > OUTER + flip = np.array([float(side), 1.0, 1.0]) + for sel in clad["facets"]: + if "radial" in sel: + axis = _unit(sel["radial"], "radial") * flip + radial = centre - axis * (centre @ axis) + length = float(np.linalg.norm(radial)) + if length > sel["min_r"] and float(normal @ radial) / length > sel["cos"]: + return True + elif float(normal @ (_unit(sel["n"], "n") * flip)) > sel["cos"]: + return True + return False + + +def clad_layout(V: np.ndarray, faces, facets, clad: dict, seed: int, face_n, side: int): + """(panels, bolts, count, lift on the face): the detail plating of one solid. One seeded source draws, in facet + order: for a kept facet over `split`, where its cut falls (SHARE); for every kept facet, which lift comes + first.""" + rnd = random.Random(seed) + panels, bolts, made, on_face = _Mesh(), _Mesh(), 0, 0.0 + for loop, facet in zip(faces, facets): + if facet["area"] < clad["min_area"]: + continue + pts = [V[k] for k in loop] + if not _selected(clad, facet["normal"], facet["centre"], face_n, side): + continue + if facet["area"] > clad["split"]: + k = _longest(pts) + a, b = pts[k], pts[(k + 1) % len(pts)] + way = (b - a) / np.linalg.norm(b - a) + at = a + (b - a) * rnd.uniform(*SHARE) + parts = [clip(pts, at - way * clad["gap"] / 2, way), clip(pts, at + way * clad["gap"] / 2, -way)] + else: + parts = [pts] + order = list(clad["lifts"]) if rnd.random() < 0.5 else list(reversed(clad["lifts"])) + for i, part in enumerate(parts): + if len(part) >= 3 and panel(panels, bolts, part, facet["normal"], order[i % 2], clad["inset"], clad["bolt_r"]): + made += 1 + if face_n is not None and float(facet["normal"] @ face_n) > OUTER: + on_face = clad["lifts"][0] + return panels.done(), bolts.done(), made, on_face + + +# --- build ------------------------------------------------------------------------------------------------------------ +def build(table: Any, side: int = 1) -> list[dict]: + """One entry per plate built, in the table's order: a row with sides "both" is built at `side`, then at -side. + Side -1 negates x of every point before the hull, so facets, panels and anchors are those of the mirrored solid + as built; a clad selector's direction is mirrored with it. Names end .R at side +1 and .L at -1 on a two-sided + row. Each entry: {name, row (its index in the table), mat, bevel, side, solid: (V, faces), facets, panels: (V, faces), bolts: (V, faces), + anchors: [{kind, name, matrix, mirrored, height?}], report: {corners, facets, panels, bolts}}.""" + if side not in (1, -1): + raise PlateError(f"side: {side!r} is not 1 or -1") + table = _read(table) + built = [] + for i, row in enumerate(table["plates"]): + path = f"plates[{i}]" + points, face = _row_points(row, path) + for s in ((side, -side) if row["sides"] == "both" else (side,)): + flip = np.array([float(s), 1.0, 1.0]) + V, faces, facets = hull(_mirrored(points * flip, row["mirror"]), path) + face_n = None if face is None else face[3] * flip + clad, top = row["clad"], 0.0 + panels = bolts = (np.zeros((0, 3)), []) + made = 0 + if clad is not None: + seed = clad["seed"] if isinstance(clad["seed"], int) else clad["seed"][0 if s > 0 else 1] + panels, bolts, made, top = clad_layout(V, faces, facets, clad, seed, face_n, s) + anchors = [] + for j, fit in enumerate(row["fits"]): + origin, a, b, n = face + at = (origin + a * fit["at"][0] + b * fit["at"][1] + n * (top + fit.get("lift", 0.0))) * flip + up = (0.0, 0.0, 1.0) if fit["kind"] == "mark" else b * flip + anchor = {"kind": fit["kind"], "name": fit.get("id", fit.get("name")), "matrix": _frame(at, face_n, up, f"{path}.fits[{j}]").tolist(), "mirrored": s < 0} + if fit["kind"] == "mark": + anchor["height"] = fit["height"] + anchors.append(anchor) + built.append({"name": row["name"] + ((".R" if s > 0 else ".L") if row["sides"] == "both" else ""), "row": i, "mat": row["mat"], "bevel": row["bevel"], "side": s, + "solid": (V, faces), "facets": facets, "panels": panels, "bolts": bolts, "anchors": anchors, + "report": {"corners": len(V), "facets": len(faces), "panels": made, "bolts": len(bolts[0]) // 12}}) + return built diff --git a/surfaces/blender/tests/fixtures/plates_bastion.json b/surfaces/blender/tests/fixtures/plates_bastion.json new file mode 100644 index 0000000..703fc91 --- /dev/null +++ b/surfaces/blender/tests/fixtures/plates_bastion.json @@ -0,0 +1,1326 @@ +{"source": {"branch": "nibu/fable-bastion-2", "sha": "eeda8bf2defd411bebc2fd438d8934ba46e88614", "blender": "5.3.0"}, + "table": { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "Core.upper", + "mat": "gunmetal", + "bevel": 0.0, + "mirror": true, + "points": [ + [ + 0.0, + 5.3, + 5.3 + ], + [ + 2.2, + 5.0, + 5.3 + ], + [ + 4.3, + 3.6, + 5.3 + ], + [ + 4.5, + 0.9, + 5.2 + ], + [ + 4.5, + -1.4, + 5.4 + ], + [ + 4.3, + -2.8, + 5.6 + ], + [ + 3.6, + -4.4, + 5.8 + ], + [ + 2.2, + -5.0, + 5.9 + ], + [ + 0.0, + -5.0, + 5.9 + ], + [ + 0.0, + 3.4, + 6.8 + ], + [ + 2.2, + 3.4, + 6.8 + ], + [ + 4.0, + 3.0, + 6.6 + ], + [ + 4.2, + 0.9, + 6.8 + ], + [ + 4.2, + -1.4, + 6.8 + ], + [ + 3.9, + -2.8, + 6.8 + ], + [ + 3.2, + -4.2, + 6.8 + ], + [ + 0.0, + -4.6, + 6.9 + ], + [ + 2.6, + 2.6, + 7.3 + ], + [ + 2.6, + -2.6, + 7.3 + ], + [ + 0.0, + 3.4, + 7.0 + ] + ] + }, + { + "name": "Core.belly", + "mat": "gunmetal", + "bevel": 0.03, + "mirror": true, + "points": [ + [ + 2.3, + 4.7, + 5.3 + ], + [ + 2.3, + -4.9, + 5.9 + ], + [ + 1.7, + 4.0, + 3.6 + ], + [ + 1.8, + 2.2, + 3.3 + ], + [ + 1.8, + -2.6, + 3.35 + ], + [ + 1.5, + -4.6, + 4.0 + ], + [ + 1.2, + 4.9, + 3.7 + ] + ] + }, + { + "name": "Core.cheek_tray", + "mat": "gunmetal", + "bevel": 0.0, + "sides": "both", + "faces": [ + { + "at": [ + 2.2479736988984707, + 5.264865987629634, + 5.0 + ], + "normal": [ + 0.5429510753626048, + 0.839764329894162, + 0.0 + ] + }, + { + "at": [ + 1.6941636020286137, + 4.40830637113759, + 5.0 + ], + "normal": [ + -0.5429510753626048, + -0.839764329894162, + 0.0 + ] + }, + { + "at": [ + 0.0, + 0.0, + 4.9 + ], + "normal": [ + 0.0, + 0.0, + -1.0 + ] + }, + { + "at": [ + 0.0, + 0.0, + 5.3 + ], + "normal": [ + 0.0, + 0.0, + 1.0 + ] + }, + { + "at": [ + 2.5, + 0.0, + 0.0 + ], + "normal": [ + -1.0, + 0.0, + 0.0 + ] + }, + { + "at": [ + 4.750163376895761, + 0.8804114363827034, + 4.6936620832203895 + ], + "normal": [ + 1.0, + 0.07, + 0.38 + ] + } + ] + }, + { + "name": "Hull.Brow", + "mat": "olive", + "bevel": 0.04, + "mirror": true, + "points": [ + [ + 0.0, + 6.3, + 5.58 + ], + [ + 1.05, + 6.25, + 5.72 + ], + [ + 2.0, + 5.72, + 5.76 + ], + [ + 2.28, + 4.95, + 5.8 + ], + [ + 0.0, + 6.14, + 6.12 + ], + [ + 1.0, + 6.1, + 6.14 + ], + [ + 1.92, + 5.6, + 6.16 + ], + [ + 2.2, + 4.95, + 6.2 + ], + [ + 0.0, + 3.25, + 7.0 + ], + [ + 2.05, + 3.25, + 7.0 + ], + [ + 0.0, + 3.25, + 6.2 + ], + [ + 2.28, + 3.25, + 6.2 + ] + ], + "clad": { + "mat": "olive_light", + "facets": [ + { + "n": [ + 0, + 0, + 1 + ], + "cos": 0.6 + }, + { + "radial": [ + 0, + 0, + 1 + ], + "min_r": 1.0, + "cos": 0.25 + } + ], + "floor": -0.35, + "min_area": 0.9, + "lifts": [ + 0.045, + 0.075 + ], + "inset": 0.11, + "gap": 0.05, + "split": 2.2, + "seed": 2 + } + }, + { + "name": "Hull.Chin", + "mat": "olive", + "bevel": 0.04, + "mirror": true, + "points": [ + [ + 0.0, + 5.78, + 5.2 + ], + [ + 1.0, + 5.78, + 5.2 + ], + [ + 2.1, + 5.15, + 5.2 + ], + [ + 2.3, + 4.3, + 5.2 + ], + [ + 0.0, + 5.45, + 3.95 + ], + [ + 0.85, + 5.45, + 3.95 + ], + [ + 1.75, + 4.95, + 3.98 + ], + [ + 1.95, + 4.3, + 4.0 + ], + [ + 2.3, + 3.5, + 5.2 + ], + [ + 1.95, + 3.5, + 3.95 + ] + ], + "clad": { + "mat": "olive_light", + "facets": [ + { + "n": [ + 0, + 0, + 1 + ], + "cos": 0.6 + }, + { + "radial": [ + 0, + 0, + 1 + ], + "min_r": 1.0, + "cos": 0.25 + } + ], + "floor": -0.35, + "min_area": 0.9, + "lifts": [ + 0.045, + 0.075 + ], + "inset": 0.11, + "gap": 0.05, + "split": 2.2, + "seed": 7 + } + }, + { + "name": "Hull.Sill", + "mat": "olive_light", + "bevel": 0.02, + "mirror": true, + "points": [ + [ + 0.0, + 5.9, + 5.2 + ], + [ + 1.05, + 5.9, + 5.2 + ], + [ + 2.2, + 5.22, + 5.2 + ], + [ + 0.0, + 5.84, + 5.3 + ], + [ + 1.02, + 5.84, + 5.3 + ], + [ + 2.14, + 5.18, + 5.3 + ], + [ + 0.0, + 5.3, + 5.2 + ], + [ + 2.0, + 4.9, + 5.2 + ], + [ + 0.0, + 5.3, + 5.3 + ], + [ + 2.0, + 4.9, + 5.3 + ] + ] + }, + { + "name": "Hull.Jaw", + "mat": "olive_light", + "bevel": 0.03, + "mirror": true, + "points": [ + [ + 1.2, + 5.3, + 3.97 + ], + [ + 1.2, + 3.7, + 3.97 + ], + [ + 1.0, + 5.12, + 3.3 + ], + [ + 1.0, + 3.85, + 3.3 + ] + ] + }, + { + "name": "Hull.Cheek", + "mat": "olive", + "bevel": 0.04, + "sides": "both", + "faces": [ + { + "through": [ + [ + 2.4, + 5.5, + 5.25 + ], + [ + 4.72, + 4.0, + 5.25 + ], + [ + 2.38, + 5.2, + 6.2 + ] + ], + "out": [ + 0.5, + 1.0, + 0.2 + ] + }, + { + "at": [ + 4.93672112563192, + 0.8934704787942345, + 4.76455402774013 + ], + "normal": [ + 1.0, + 0.07, + 0.38 + ] + }, + { + "at": [ + 4.2, + 0.9, + 6.95 + ], + "normal": [ + 0.3, + 0.08, + 1.0 + ] + }, + { + "at": [ + 2.38, + 5.2, + 6.2 + ], + "normal": [ + 0.12, + 0.4, + 1.0 + ] + }, + { + "at": [ + 0.0, + 0.0, + 5.25 + ], + "normal": [ + 0.0, + 0.0, + -1.0 + ] + }, + { + "at": [ + 0.0, + 0.9, + 0.0 + ], + "normal": [ + 0.0, + -1.0, + 0.0 + ] + }, + { + "at": [ + 2.38, + 0.0, + 0.0 + ], + "normal": [ + -1.0, + 0.0, + 0.0 + ] + }, + { + "at": [ + 2.057666384578959, + 1.9719302852215022, + 0.0 + ], + "normal": [ + -0.7219882051154242, + -0.6919053632356148, + -0.0 + ] + } + ], + "clad": { + "mat": "olive_light", + "facets": [ + { + "n": [ + 0, + 0, + 1 + ], + "cos": 0.6 + }, + { + "radial": [ + 0, + 0, + 1 + ], + "min_r": 1.0, + "cos": 0.25 + } + ], + "floor": -0.35, + "min_area": 0.9, + "lifts": [ + 0.045, + 0.075 + ], + "inset": 0.11, + "gap": 0.05, + "split": 2.2, + "seed": [ + 4, + 3 + ] + } + }, + { + "name": "Hull.Skirt", + "mat": "olive", + "bevel": 0.035, + "sides": "both", + "points": [ + [ + 4.622999999999999, + 4.0, + 5.3 + ], + [ + 4.8016, + 3.62, + 4.9 + ], + [ + 5.1695, + 1.35, + 4.35 + ], + [ + 5.03, + 0.9, + 4.8 + ], + [ + 4.384, + 0.9, + 6.5 + ], + [ + 4.295, + 3.8, + 6.2 + ], + [ + 4.324507602022145, + 3.97910553214155, + 5.186572888768415 + ], + [ + 4.503107602022145, + 3.59910553214155, + 4.786572888768416 + ], + [ + 4.8710076020221456, + 1.3291055321415504, + 4.236572888768415 + ], + [ + 4.731507602022146, + 0.8791055321415502, + 4.686572888768415 + ], + [ + 4.085507602022146, + 0.8791055321415502, + 6.3865728887684154 + ], + [ + 3.9965076020221453, + 3.77910553214155, + 6.086572888768416 + ] + ] + }, + { + "name": "Hull.CheekLip", + "mat": "olive_light", + "bevel": 0.02, + "sides": "both", + "faces": [ + { + "at": [ + 2.4, + 5.5, + 5.0 + ], + "normal": [ + 0.5429510753626048, + 0.839764329894162, + 0.0 + ] + }, + { + "at": [ + 2.313127827941983, + 5.365637707216934, + 5.0 + ], + "normal": [ + -0.5429510753626048, + -0.839764329894162, + 0.0 + ] + }, + { + "at": [ + 0.0, + 0.0, + 4.84 + ], + "normal": [ + 0.0, + 0.0, + -1.0 + ] + }, + { + "at": [ + 0.0, + 0.0, + 4.99 + ], + "normal": [ + 0.0, + 0.0, + 1.0 + ] + }, + { + "at": [ + 2.45, + 0.0, + 0.0 + ], + "normal": [ + -1.0, + 0.0, + 0.0 + ] + }, + { + "at": [ + 4.93672112563192, + 0.8934704787942345, + 4.76455402774013 + ], + "normal": [ + 1.0, + 0.07, + 0.38 + ] + } + ] + }, + { + "name": "Hull.Quarter", + "mat": "olive", + "bevel": 0.04, + "sides": "both", + "faces": [ + { + "at": [ + 5.0, + -1.4, + 5.5 + ], + "normal": [ + 1.0, + -0.1, + 0.4 + ] + }, + { + "at": [ + 4.45, + -3.7, + 5.7 + ], + "normal": [ + 0.904, + -0.427, + 0.4 + ] + }, + { + "at": [ + 3.2, + -4.9, + 5.85 + ], + "normal": [ + 0.351, + -0.936, + 0.35 + ] + }, + { + "at": [ + 4.2, + -2.6, + 6.95 + ], + "normal": [ + 0.28, + -0.1, + 1.0 + ] + }, + { + "at": [ + 0.0, + -1.35, + 5.5 + ], + "normal": [ + 0.0, + -0.12, + -1.0 + ] + }, + { + "at": [ + 0.0, + -1.4, + 0.0 + ], + "normal": [ + 0.0, + 1.0, + 0.0 + ] + }, + { + "at": [ + 1.75, + 0.0, + 0.0 + ], + "normal": [ + -1.0, + 0.0, + 0.0 + ] + }, + { + "at": [ + 2.139533523229853, + -1.8827895004422703, + 0.0 + ], + "normal": [ + -0.7507135169227553, + 0.6606278948920247, + -0.0 + ] + } + ], + "clad": { + "mat": "olive_light", + "facets": [ + { + "n": [ + 0, + 0, + 1 + ], + "cos": 0.6 + }, + { + "radial": [ + 0, + 0, + 1 + ], + "min_r": 1.0, + "cos": 0.25 + } + ], + "floor": -0.35, + "min_area": 0.9, + "lifts": [ + 0.045, + 0.075 + ], + "inset": 0.11, + "gap": 0.05, + "split": 2.2, + "seed": [ + 15, + 14 + ] + } + }, + { + "name": "Hull.FlankRoof", + "mat": "olive_light", + "bevel": 0.03, + "sides": "both", + "faces": [ + { + "at": [ + 4.3, + 0.0, + 7.05 + ], + "normal": [ + 0.3, + 0.0, + 1.0 + ] + }, + { + "at": [ + 4.7, + 0.0, + 0.0 + ], + "normal": [ + 1.0, + 0.0, + 0.25 + ] + }, + { + "at": [ + 0.0, + 0.0, + 6.88 + ], + "normal": [ + 0.0, + 0.0, + -1.0 + ] + }, + { + "at": [ + 0.0, + 0.85, + 0.0 + ], + "normal": [ + 0.0, + 1.0, + 0.0 + ] + }, + { + "at": [ + 0.0, + -1.3, + 0.0 + ], + "normal": [ + 0.0, + -1.0, + 0.0 + ] + }, + { + "at": [ + 2.8, + 0.0, + 0.0 + ], + "normal": [ + -1.0, + 0.0, + 0.0 + ] + } + ], + "clad": { + "mat": "olive", + "facets": [ + { + "n": [ + 0, + 0, + 1 + ], + "cos": 0.6 + }, + { + "radial": [ + 0, + 0, + 1 + ], + "min_r": 1.0, + "cos": 0.25 + } + ], + "floor": -0.35, + "min_area": 0.9, + "lifts": [ + 0.045, + 0.075 + ], + "inset": 0.11, + "gap": 0.05, + "split": 2.2, + "seed": [ + 10, + 9 + ] + } + }, + { + "name": "Hull.FlankSill", + "mat": "olive", + "bevel": 0.03, + "sides": "both", + "faces": [ + { + "at": [ + 4.98, + 0.0, + 0.0 + ], + "normal": [ + 1.0, + 0.0, + 0.12 + ] + }, + { + "at": [ + 3.9, + 0.0, + 0.0 + ], + "normal": [ + -1.0, + 0.0, + 0.0 + ] + }, + { + "at": [ + 0.0, + 0.0, + 5.12 + ], + "normal": [ + 0.0, + 0.0, + -1.0 + ] + }, + { + "at": [ + 0.0, + 0.0, + 5.45 + ], + "normal": [ + 0.0, + 0.0, + 1.0 + ] + }, + { + "at": [ + 0.0, + 0.85, + 0.0 + ], + "normal": [ + 0.0, + 1.0, + 0.0 + ] + }, + { + "at": [ + 0.0, + -1.3, + 0.0 + ], + "normal": [ + 0.0, + -1.0, + 0.0 + ] + } + ] + }, + { + "name": "Hull.Tail", + "mat": "olive_light", + "bevel": 0.03, + "mirror": true, + "points": [ + [ + 1.72, + -2.75, + 7.5 + ], + [ + 1.72, + -5.0, + 7.3 + ], + [ + 1.72, + -2.75, + 7.15 + ], + [ + 1.72, + -5.0, + 7.0 + ] + ], + "clad": { + "mat": "olive", + "facets": [ + { + "n": [ + 0, + 0, + 1 + ], + "cos": 0.6 + }, + { + "radial": [ + 0, + 0, + 1 + ], + "min_r": 1.0, + "cos": 0.25 + } + ], + "floor": -0.35, + "min_area": 0.9, + "lifts": [ + 0.045, + 0.075 + ], + "inset": 0.11, + "gap": 0.05, + "split": 2.2, + "seed": 19 + } + }, + { + "name": "Hull.BellySide", + "mat": "olive_light", + "bevel": 0.03, + "sides": "both", + "points": [ + [ + 2.1, + 2.2, + 3.9 + ], + [ + 2.1, + -2.4, + 3.95 + ], + [ + 2.45, + 2.0, + 4.1 + ], + [ + 2.45, + -2.2, + 4.15 + ], + [ + 2.45, + 2.0, + 4.85 + ], + [ + 2.45, + -2.2, + 4.9 + ], + [ + 2.25, + 2.2, + 5.1 + ], + [ + 2.25, + -2.4, + 5.15 + ], + [ + 1.8, + 2.2, + 3.9 + ], + [ + 1.8, + -2.4, + 5.15 + ] + ], + "clad": { + "mat": "olive", + "facets": [ + { + "n": [ + 0, + 0, + 1 + ], + "cos": 0.6 + }, + { + "radial": [ + 0, + 0, + 1 + ], + "min_r": 1.0, + "cos": 0.25 + } + ], + "floor": -0.35, + "min_area": 0.9, + "lifts": [ + 0.045, + 0.075 + ], + "inset": 0.11, + "gap": 0.05, + "split": 2.2, + "seed": [ + 1, + 0 + ] + } + } + ] +}, + "cases": [ + {"side": 1, "truth": { + "Core.upper": {"solid":[[0.0,5.3000002,5.3000002],[2.2,5.0,5.3000002],[4.3000002,3.5999999,5.3000002],[4.5,0.9,5.1999998],[4.5,-1.4,5.4000001],[4.3000002,-2.8,5.5999999],[3.5999999,-4.4000001,5.8000002],[2.2,-5.0,5.9000001],[2.2,3.4000001,6.8000002],[4.0,3.0,6.5999999],[4.1999998,0.9,6.8000002],[4.1999998,-1.4,6.8000002],[3.9000001,-2.8,6.8000002],[3.2,-4.1999998,6.8000002],[0.0,-4.5999999,6.9000001],[2.5999999,2.5999999,7.3000002],[2.5999999,-2.5999999,7.3000002],[0.0,3.4000001,7.0],[-2.2,5.0,5.3000002],[-4.3000002,3.5999999,5.3000002],[-4.5,0.9,5.1999998],[-4.5,-1.4,5.4000001],[-4.3000002,-2.8,5.5999999],[-3.5999999,-4.4000001,5.8000002],[-2.2,-5.0,5.9000001],[-2.2,3.4000001,6.8000002],[-4.0,3.0,6.5999999],[-4.1999998,0.9,6.8000002],[-4.1999998,-1.4,6.8000002],[-3.9000001,-2.8,6.8000002],[-3.2,-4.1999998,6.8000002],[-2.5999999,2.5999999,7.3000002],[-2.5999999,-2.5999999,7.3000002]],"facets":54,"panels":[],"bolts":0}, + "Core.belly": {"solid":[[2.3,4.6999998,5.3000002],[2.3,-4.9000001,5.9000001],[1.7,4.0,3.5999999],[1.8,2.2,3.3],[1.8,-2.5999999,3.3499999],[1.5,-4.5999999,4.0],[1.2,4.9000001,3.7],[-2.3,4.6999998,5.3000002],[-2.3,-4.9000001,5.9000001],[-1.7,4.0,3.5999999],[-1.8,2.2,3.3],[-1.8,-2.5999999,3.3499999],[-1.5,-4.5999999,4.0],[-1.2,4.9000001,3.7]],"facets":18,"panels":[],"bolts":0}, + "Core.cheek_tray.R": {"solid":[[2.5,5.1019173,4.9000001],[4.4651914,3.8313196,4.9000001],[2.5,5.1019173,5.3000002],[4.3059859,3.9342542,5.3000002],[2.5,3.8872914,4.9000001],[4.5542455,2.5591156,4.9000001],[2.5,3.8872914,5.3000002],[4.39504,2.6620502,5.3000002]],"facets":6,"panels":[],"bolts":0}, + "Core.cheek_tray.L": {"solid":[[-2.5,5.1019173,4.9000001],[-4.4651914,3.8313196,4.9000001],[-2.5,5.1019173,5.3000002],[-4.3059859,3.9342542,5.3000002],[-2.5,3.8872914,4.9000001],[-4.5542455,2.5591156,4.9000001],[-2.5,3.8872914,5.3000002],[-4.39504,2.6620502,5.3000002]],"facets":6,"panels":[],"bolts":0}, + "Hull.Brow": {"solid":[[0.0,6.3000002,5.5799999],[1.05,6.25,5.7199998],[2.0,5.7199998,5.7600002],[2.28,4.9499998,5.8000002],[0.0,6.1399999,6.1199999],[1.0,6.0999999,6.1399999],[1.92,5.5999999,6.1599998],[2.2,4.9499998,6.1999998],[2.05,3.25,7.0],[2.28,3.25,6.1999998],[-1.05,6.25,5.7199998],[-2.0,5.7199998,5.7600002],[-2.28,4.9499998,5.8000002],[-1.0,6.0999999,6.1399999],[-1.92,5.5999999,6.1599998],[-2.2,4.9499998,6.1999998],[-2.05,3.25,7.0],[-2.28,3.25,6.1999998]],"facets":29,"panels":[[0.3885275,5.9889116,6.1526303],[-0.9221566,5.9889116,6.1526303],[-1.8945599,3.3495317,6.9490747],[0.3885272,3.3495317,6.9490747],[0.3885275,6.0105786,6.2244325],[-0.9221566,6.0105786,6.2244325],[-1.8945599,3.3711982,7.0208769],[0.3885272,3.3711982,7.0208769],[0.3685275,5.9972091,6.2493577],[-0.9080032,5.9972091,6.2493577],[-1.866298,3.3961234,7.0342464],[0.3685272,3.3961234,7.0342464],[1.8945597,3.3495317,6.9490747],[0.9221566,5.9889116,6.1526303],[0.6585274,5.9889116,6.1526303],[0.6585273,3.3495317,6.9490747],[1.8945597,3.3625317,6.992156],[0.9221566,6.0019116,6.1957116],[0.6585274,6.0019116,6.1957116],[0.6585273,3.3625317,6.992156],[1.866298,3.3874567,7.0055256],[0.9080032,5.9885426,6.2206364],[0.6785274,5.9885426,6.2206364],[0.6785272,3.3874567,7.0055256],[1.9754326,3.5847373,6.8687177],[1.811658,5.5343542,6.1817808],[1.1911595,5.8715816,6.168292],[1.9828436,3.60004,6.9103818],[1.8190689,5.5496569,6.2234454],[1.1985704,5.8868842,6.2099562],[1.9730231,3.6689181,6.9084315],[1.8035812,5.5455861,6.2492967],[1.2357996,5.8541627,6.2369537],[-1.811658,5.5343542,6.1817808],[-1.9754326,3.5847373,6.8687177],[-1.1911596,5.8715811,6.168292],[-1.8190689,5.5496569,6.2234454],[-1.9828436,3.60004,6.9103818],[-1.1985705,5.8868837,6.2099562],[-1.8035812,5.5455861,6.2492967],[-1.9730231,3.6689181,6.9084315],[-1.2357996,5.8541627,6.2369537]],"bolts":14}, + "Hull.Chin": {"solid":[[1.0,5.7800002,5.1999998],[2.0999999,5.1500001,5.1999998],[2.3,4.3000002,5.1999998],[0.85,5.4499998,3.95],[1.75,4.9499998,3.98],[1.95,4.3000002,4.0],[2.3,3.5,5.1999998],[1.95,3.5,3.95],[-1.0,5.7800002,5.1999998],[-2.0999999,5.1500001,5.1999998],[-2.3,4.3000002,5.1999998],[-0.85,5.4499998,3.95],[-1.75,4.9499998,3.98],[-1.95,4.3000002,4.0],[-2.3,3.5,5.1999998],[-1.95,3.5,3.95]],"facets":18,"panels":[[-0.3619034,5.6700001,5.1800003],[-0.9707303,5.6700001,5.1800003],[-2.0038681,5.0782938,5.1800003],[-2.1900001,4.2872334,5.1800003],[-2.1900001,3.6100001,5.1800003],[-0.3619035,3.6100001,5.1800003],[-0.3619034,5.6700001,5.2250004],[-0.9707303,5.6700001,5.2250004],[-2.0038681,5.0782938,5.2250004],[-2.1900001,4.2872334,5.2250004],[-2.1900001,3.6100001,5.2250004],[-0.3619035,3.6100001,5.2250004],[-0.3819034,5.6500001,5.2450004],[-0.9654085,5.6500001,5.2450004],[-1.9863894,5.0652566,5.2450004],[-2.1700001,4.2849121,5.2450004],[-2.1700001,3.6300001,5.2450004],[-0.3819035,3.6300001,5.2450004],[2.1900001,4.2872334,5.1800003],[2.0038681,5.0782938,5.1800003],[0.9707303,5.6700001,5.1800003],[-0.0919034,5.6700001,5.1800003],[-0.0919033,3.6100001,5.1800003],[2.1900001,3.6100001,5.1800003],[2.1900001,4.2872334,5.2550001],[2.0038681,5.0782938,5.2550001],[0.9707303,5.6700001,5.2550001],[-0.0919034,5.6700001,5.2550001],[-0.0919033,3.6100001,5.2550001],[2.1900001,3.6100001,5.2550001],[2.1700001,4.2849121,5.2750001],[1.9863894,5.0652566,5.2750001],[0.9654086,5.6500001,5.2750001],[-0.0719035,5.6500001,5.2750001],[-0.0719033,3.6300001,5.2750001],[2.1700001,3.6300001,5.2750001],[-0.8764993,5.7325845,5.0987487],[-0.0504766,5.7325845,5.0987487],[-0.0504766,5.4587402,4.061461],[-0.7520249,5.4587402,4.061461],[-0.8764993,5.7760935,5.0872622],[-0.0504766,5.7760935,5.0872622],[-0.0504766,5.5022492,4.0499744],[-0.7520249,5.5022492,4.0499744],[-0.8540447,5.7903261,5.06282],[-0.0704766,5.7903261,5.06282],[-0.0704766,5.5266919,4.0642071],[-0.7342112,5.5266919,4.0642071],[0.2195233,5.7325845,5.0987492],[0.8764993,5.7325845,5.0987492],[0.7520248,5.4587402,4.0614614],[0.2195233,5.4587402,4.0614614],[0.2195233,5.8051,5.0796051],[0.8764993,5.8051,5.0796051],[0.7520248,5.5312557,4.0423174],[0.2195233,5.5312557,4.0423174],[0.2395233,5.8193321,5.0551624],[0.8540447,5.8193321,5.0551624],[0.7342112,5.5556984,4.05655],[0.2395233,5.5556984,4.05655],[1.6727291,5.0044794,4.0888481],[0.9496512,5.4084468,4.064147],[1.0728847,5.6800089,5.100059],[1.9638414,5.1720209,5.0994902],[1.708429,5.0671163,4.068181],[0.9853511,5.4710841,4.0434804],[1.1085846,5.7426457,5.079392],[1.9995413,5.2346578,5.0788231],[1.705741,5.0969553,4.0813947],[1.0146099,5.4830751,4.057785],[1.1331977,5.7443995,5.0546436],[1.9859257,5.2582078,5.0540991],[-1.6727293,5.0044794,4.0888476],[-1.9638416,5.1720209,5.0994897],[-1.0728848,5.6800089,5.1000586],[-0.9496514,5.4084473,4.064147],[-1.6941493,5.0420618,4.0764475],[-1.9852614,5.2096033,5.0870895],[-1.0943048,5.7175913,5.0876584],[-0.9710713,5.4460292,4.0517464],[-1.6914613,5.0719008,4.0896611],[-1.9716458,5.2331533,5.0623655],[-1.1189178,5.7193451,5.0629101],[-1.0003301,5.4580207,4.0660515]],"bolts":28}, + "Hull.Sill": {"solid":[[1.05,5.9000001,5.1999998],[2.2,5.2199998,5.1999998],[1.02,5.8400002,5.3000002],[2.1400001,5.1799998,5.3000002],[2.0,4.9000001,5.1999998],[2.0,4.9000001,5.3000002],[-1.05,5.9000001,5.1999998],[-2.2,5.2199998,5.1999998],[-1.02,5.8400002,5.3000002],[-2.1400001,5.1799998,5.3000002],[-2.0,4.9000001,5.1999998],[-2.0,4.9000001,5.3000002]],"facets":12,"panels":[],"bolts":0}, + "Hull.Jaw": {"solid":[[1.2,5.3000002,3.97],[1.2,3.7,3.97],[1.0,5.1199999,3.3],[1.0,3.8499999,3.3],[-1.2,5.3000002,3.97],[-1.2,3.7,3.97],[-1.0,5.1199999,3.3],[-1.0,3.8499999,3.3]],"facets":6,"panels":[],"bolts":0}, + "Hull.Cheek.R": {"solid":[[4.0699725,4.0184684,6.4698162],[4.5260153,4.125421,5.25],[2.3800001,5.1999998,6.1999998],[2.3800001,5.5129309,5.25],[3.9938784,3.1328073,6.8332119],[4.0936742,0.9,6.9818964],[4.7517948,0.9,5.25],[2.3800001,2.2249999,7.3899999],[3.0849326,0.9,7.2845197],[2.3800001,1.6355822,7.4371529],[3.084933,0.9,5.25],[2.3800001,1.6355822,5.25]],"facets":8,"panels":[[4.0605597,2.097348,6.7920513],[4.1092281,1.0084592,6.8645611],[4.6863694,1.0084592,5.3457685],[4.6074672,2.1356313,5.3457685],[4.1025352,2.1002862,6.808002],[4.1512036,1.0113975,6.8805118],[4.7283449,1.0113975,5.3617191],[4.6494427,2.1385696,5.3617191],[4.1291742,2.0821021,6.7976732],[4.1760793,1.0326607,6.8675566],[4.7384973,1.0326607,5.3875098],[4.6624231,2.1194293,5.3875098],[4.0154209,3.1072907,6.7247982],[4.048501,2.3671649,6.7740841],[4.588614,2.4049726,5.345768],[4.4765992,4.0051847,5.345768],[4.0846686,3.9132679,6.3940973],[4.0853801,3.1121879,6.7513828],[4.1184602,2.372062,6.8006682],[4.6585732,2.4098697,5.3723526],[4.5465584,4.0100818,5.3723526],[4.1546278,3.918165,6.420682],[4.1113443,3.1090918,6.7400494],[4.1433125,2.3938506,6.7876778],[4.6687603,2.4306319,5.3981428],[4.5596213,3.9897637,5.3981428],[4.1793475,3.9005809,6.4152932],[2.4871092,4.9912777,6.2489614],[2.4871092,3.9125221,6.6804638],[3.9440475,3.8522353,6.5297465],[3.9538085,3.9658458,6.4831309],[2.4920921,5.0078874,6.2904863],[2.4920921,3.9291317,6.7219882],[3.9490304,3.868845,6.5712709],[3.9587915,3.9824557,6.5246553],[2.5141838,4.978662,6.3211989],[2.5141838,3.9542611,6.7309594],[3.9328942,3.895556,6.5841966],[3.9402881,3.9816122,6.5488873],[2.4871085,3.661833,6.7807398],[2.4871085,2.4007239,7.285183],[3.8869905,3.1881585,6.8022237],[3.9225841,3.6024342,6.6322427],[2.4954133,3.6895161,6.849947],[2.4954133,2.428407,7.3543901],[3.8952954,3.2158415,6.8714314],[3.9308889,3.6301172,6.7014499],[2.5175052,3.6775062,6.8737741],[2.5175049,2.4690814,7.3571434],[3.8784785,3.2346296,6.8876081],[3.9115732,3.6198206,6.7295604],[3.9776521,1.0081506,6.9871097],[3.9508991,1.6067107,6.9472508],[2.4796586,1.5705372,7.3915172],[2.4796588,1.6776093,7.3829517],[3.121223,1.0081505,7.2440386],[3.990545,1.0115887,7.030086],[3.9637921,1.6101487,6.9902272],[2.4925516,1.5739753,7.4344935],[2.4925516,1.6810473,7.4259276],[3.1341157,1.0115886,7.287015],[3.976222,1.0330583,7.053607],[3.9512725,1.5912702,7.0164351],[2.4791203,1.5550743,7.4609771],[2.4791203,1.7304838,7.4469442],[3.147486,1.0330582,7.302228],[3.9388695,1.8758466,6.9293289],[3.89083,2.9506743,6.8577552],[2.4796584,2.1568897,7.3446093],[2.4796584,1.839969,7.3699627],[3.9603574,1.8815767,7.0009561],[3.912318,2.9564044,6.9293823],[2.5011463,2.1626198,7.4162364],[2.5011463,1.8456992,7.4415898],[3.9460559,1.9025701,7.024509],[3.9003541,2.9250953,6.956418],[2.5260382,2.1520419,7.4305568],[2.5260382,1.8676562,7.4533076],[4.0081611,4.0742669,6.3467288],[4.3805432,4.1615996,5.3506866],[3.2888443,4.8674393,5.3506866],[3.1595957,4.6675353,6.2112494],[4.0474086,4.1349697,6.366724],[4.4197907,4.222302,5.3706822],[3.3280916,4.9281421,5.3706822],[3.1988432,4.7282381,6.2312446],[4.0485392,4.1642456,6.350646],[4.4057102,4.2480106,5.3952904],[3.352458,4.9289927,5.3952904],[3.2286329,4.7374768,6.2197423],[3.0621083,5.0140362,5.3506856],[2.4632707,5.4012156,5.3506856],[2.4632707,5.154366,6.1000748],[2.9381692,4.8223443,6.1758957],[3.0856566,5.050458,5.3626833],[2.486819,5.4376373,5.3626833],[2.486819,5.1907878,6.1120725],[2.9617176,4.8587661,6.1878929],[3.0764322,5.0730267,5.3872914],[2.514328,5.4364557,5.3872914],[2.514328,5.2016211,6.1002059],[2.9587035,4.8909397,6.1711535]],"bolts":34}, + "Hull.Cheek.L": {"solid":[[-4.0699725,4.0184684,6.4698162],[-4.5260153,4.125421,5.25],[-2.3800001,5.1999998,6.1999998],[-2.3800001,5.5129309,5.25],[-3.9938784,3.1328073,6.8332119],[-4.0936742,0.9,6.9818964],[-4.7517948,0.9,5.25],[-2.3800001,2.2249999,7.3899999],[-3.0849326,0.9,7.2845197],[-2.3800001,1.6355822,7.4371529],[-3.084933,0.9,5.25],[-2.3800001,1.6355822,5.25]],"facets":8,"panels":[[-4.0154204,3.1072907,6.7247982],[-4.0846686,3.9132679,6.3940978],[-4.4765992,4.0051847,5.3457685],[-4.5553617,2.8800015,5.3457685],[-4.0272317,2.8430324,6.7423954],[-4.0853796,3.1121879,6.7513828],[-4.1546278,3.918165,6.4206824],[-4.5465584,4.0100818,5.3723531],[-4.6253209,2.8848987,5.3723531],[-4.0971909,2.8479295,6.76898],[-4.1113443,3.1090918,6.7400494],[-4.1793475,3.9005809,6.4152937],[-4.5596213,3.9897637,5.3981438],[-4.6355081,2.9056606,5.3981438],[-4.1220431,2.8697181,6.7559896],[-4.5742154,2.6106603,5.3457689],[-4.6863694,1.0084593,5.3457689],[-4.1092281,1.0084593,6.8645616],[-4.0392909,2.5732152,6.7603631],[-4.6161909,2.6135986,5.3617196],[-4.7283449,1.0113976,5.3617196],[-4.1512036,1.0113976,6.8805122],[-4.0812664,2.5761535,6.7763138],[-4.6291714,2.5944583,5.3875103],[-4.7384973,1.0326608,5.3875103],[-4.1760798,1.0326608,6.8675566],[-4.1079054,2.5579693,6.7659855],[-3.9058976,3.4082141,6.7119331],[-3.886991,3.1881585,6.8022237],[-2.4871092,2.4007244,7.285183],[-2.4871092,3.4669223,6.8587041],[-3.9142027,3.4358971,6.7811403],[-3.8952961,3.2158415,6.8714314],[-2.495414,2.4284074,7.3543906],[-2.495414,3.4946053,6.9279113],[-3.894887,3.4256005,6.8092508],[-3.8784792,3.2346299,6.8876081],[-2.5175056,2.4690816,7.3571439],[-2.5175056,3.4825954,6.9517384],[-2.4871089,4.9912777,6.2489614],[-3.9538083,3.9658461,6.4831309],[-3.9273598,3.6580153,6.609437],[-2.4871089,3.7176116,6.7584281],[-2.4920919,5.0078878,6.2904859],[-3.9587913,3.9824557,6.5246553],[-3.9323428,3.6746249,6.6509614],[-2.4920919,3.7342215,6.7999525],[-2.5141835,4.9786625,6.3211989],[-3.9402878,3.9816124,6.5488873],[-3.9162068,3.7013359,6.6638875],[-2.5141835,3.7593505,6.8089242],[-2.4796581,2.0325902,7.3545527],[-2.4796581,2.1568892,7.3446088],[-3.89083,2.9506741,6.8577557],[-3.93027,2.0682566,6.9165163],[-2.4925508,2.0360284,7.3975286],[-2.4925508,2.1603274,7.3875852],[-3.9037228,2.9541123,6.900732],[-3.9431629,2.0716946,6.9594927],[-2.5174427,2.0579853,7.4092464],[-2.5174427,2.1497495,7.4019055],[-3.8917589,2.9228029,6.9277678],[-3.9288611,2.0926881,6.9830456],[-3.1212225,1.0081503,7.2440386],[-2.4796584,1.6776092,7.3829513],[-2.4796584,1.7631588,7.3761072],[-3.9422991,1.7991207,6.9344378],[-3.9776518,1.0081505,6.9871097],[-3.1427104,1.0138805,7.3156652],[-2.5011466,1.6833394,7.4545784],[-2.5011466,1.768889,7.4477344],[-3.9637873,1.8048508,7.0060649],[-3.9991398,1.0138806,7.0587363],[-3.1560807,1.0353501,7.3308787],[-2.5260382,1.6927865,7.4672966],[-2.5260382,1.7509302,7.4626455],[-3.9512677,1.7859722,7.0322728],[-3.9848168,1.0353502,7.0822577],[-2.4632707,5.4012156,5.3506866],[-3.020721,5.0407953,5.3506866],[-2.8977513,4.8506017,6.1694436],[-2.4632707,5.1543655,6.1000757],[-2.5025179,5.4619184,5.3706822],[-3.0599682,5.1014977,5.3706822],[-2.9369986,4.9113045,6.1894393],[-2.5025182,5.2150683,6.1200714],[-2.5300269,5.4607368,5.3952904],[-3.0507438,5.1240664,5.3952904],[-2.9339843,4.9434781,6.1726995],[-2.5300269,5.2259021,6.1082048],[-3.2474575,4.8941984,5.3506866],[-4.3805437,4.1615996,5.3506866],[-4.0081615,4.0742669,6.3467283],[-3.1191783,4.6957932,6.2047954],[-3.2710059,4.9306197,5.3626838],[-4.4040923,4.1980209,5.3626838],[-4.0317101,4.1106887,6.358726],[-3.1427269,4.7322149,6.2167931],[-3.295372,4.9314704,5.3872919],[-4.3900118,4.2237296,5.3872919],[-4.0328407,4.1399646,6.342648],[-3.1725166,4.7414536,6.2052908]],"bolts":34}, + "Hull.Skirt.R": {"solid":[[4.6230001,4.0,5.3000002],[4.8016,3.6199999,4.9000001],[5.1694999,1.35,4.3499999],[5.0300002,0.9,4.8000002],[4.3839998,0.9,6.5],[4.2950001,3.8,6.1999998],[4.3245077,3.9791055,5.186573],[4.5031075,3.5991056,4.7865729],[4.8710074,1.3291055,4.2365727],[4.7315078,0.8791055,4.686573],[4.0855074,0.8791055,6.3865728],[3.9965076,3.7791054,6.0865731]],"facets":8,"panels":[],"bolts":0}, + "Hull.Skirt.L": {"solid":[[-4.6230001,4.0,5.3000002],[-4.8016,3.6199999,4.9000001],[-5.1694999,1.35,4.3499999],[-5.0300002,0.9,4.8000002],[-4.3839998,0.9,6.5],[-4.2950001,3.8,6.1999998],[-4.3245077,3.9791055,5.186573],[-4.5031075,3.5991056,4.7865729],[-4.8710074,1.3291055,4.2365727],[-4.7315078,0.8791055,4.686573],[-4.0855074,0.8791055,6.3865728],[-3.9965076,3.7791054,6.0865731]],"facets":8,"panels":[],"bolts":0}, + "Hull.CheekLip.R": {"solid":[[2.45,5.4676719,4.8400002],[4.6892009,4.0199132,4.8400002],[2.45,5.4676719,4.9899998],[4.629499,4.0585136,4.9899998],[2.45,5.2771425,4.8400002],[4.7031698,3.8203516,4.8400002],[2.45,5.2771425,4.9899998],[4.6434679,3.858952,4.9899998]],"facets":6,"panels":[],"bolts":0}, + "Hull.CheekLip.L": {"solid":[[-2.45,5.4676719,4.8400002],[-4.6892009,4.0199132,4.8400002],[-2.45,5.4676719,4.9899998],[-4.629499,4.0585136,4.9899998],[-2.45,5.2771425,4.8400002],[-4.7031698,3.8203516,4.8400002],[-2.45,5.2771425,4.9899998],[-4.6434679,3.858952,4.9899998]],"facets":6,"panels":[],"bolts":0}, + "Hull.Quarter.R": {"solid":[[4.2910318,-2.9193861,6.8925695],[4.3936944,-1.4,7.0157642],[4.9976001,-1.4,5.506],[3.5958304,-4.3421259,6.9449539],[3.9363332,-4.6085348,5.8910241],[1.75,-4.8604336,7.409956],[1.75,-5.3931999,5.9851837],[2.5643883,-1.4,7.5279703],[1.75,-2.3254409,7.6634545],[2.5643883,-1.4,5.5060005],[1.75,-2.3254409,5.6170526]],"facets":9,"panels":[[2.6039631,-1.5075765,7.4852662],[1.8505968,-2.3636744,7.6105995],[1.8505968,-3.7839808,7.4685688],[3.7708514,-3.7307458,6.9362202],[4.181469,-2.8904121,6.9052806],[4.2749047,-1.5075765,7.0174022],[2.6160405,-1.5118898,7.5284004],[1.8626742,-2.3679876,7.6537333],[1.8626742,-3.7882941,7.5117025],[3.7829289,-3.7350593,6.9793544],[4.1935463,-2.8947253,6.9484148],[4.2869821,-1.5118899,7.0605364],[2.6295795,-1.5337148,7.543292],[1.8873084,-2.3772049,7.6667795],[1.8873082,-3.7697763,7.5275221],[3.7765129,-3.7174025,7.0037818],[4.1799693,-2.8917232,6.9733815],[4.2717276,-1.5337149,7.0834904],[1.8505965,-4.0526409,7.4417028],[1.8505965,-4.7160707,7.37536],[3.5181954,-4.2478104,6.9552579],[3.6377716,-4.0030956,6.9462481],[1.8707256,-4.0598297,7.5135922],[1.8707258,-4.7232594,7.4472499],[3.5383244,-4.2549992,7.0271478],[3.6579008,-4.0102844,7.0181379],[1.8953596,-4.0811133,7.5254316],[1.8953596,-4.6992774,7.4636159],[3.5305526,-4.2401166,7.0516772],[3.6317692,-4.0329757,7.0440507],[2.7647738,-4.5948009,7.0421376],[1.8471562,-4.8524671,7.273304],[1.8471562,-5.2996264,6.0774708],[2.8457143,-4.9412479,6.0344653],[2.7796867,-4.6345687,7.0570083],[1.862069,-4.8922348,7.2881742],[1.8620691,-5.3393941,6.0923409],[2.8606274,-4.9810157,6.049336],[2.7687323,-4.6642437,7.0491562],[1.8875668,-4.9116745,7.2711391],[1.8875669,-5.3432689,6.1169314],[2.8469315,-4.9989567,6.075614],[3.5113626,-4.385159,6.8540578],[3.0230417,-4.5222793,6.9770751],[3.0996346,-4.8501167,6.0235305],[3.7892847,-4.6026044,5.9938288],[3.5362175,-4.4514389,6.8788414],[3.0478966,-4.5885587,7.0018592],[3.1244895,-4.9163966,6.0483146],[3.8141394,-4.6688843,6.0186129],[3.5286927,-4.4801512,6.8701258],[3.0752041,-4.6074901,6.9843683],[3.1484115,-4.9208369,6.0729723],[3.7952363,-4.688694,6.0451155],[4.8567634,-1.7086165,5.6465893],[4.2893143,-2.930759,6.7566442],[4.0067,-4.2766261,5.9586406],[4.9274721,-1.7305669,5.6585679],[4.3600225,-2.9527094,6.7686234],[4.0774083,-4.2985768,5.9706192],[4.92415,-1.7936081,5.6878805],[4.3820004,-2.9616666,6.7477016],[4.1124616,-4.2452664,5.986618],[4.4087081,-1.5076799,6.8972273],[4.3302989,-2.6681259,6.8031359],[4.869947,-1.5076799,5.7441301],[4.4503107,-1.5118402,6.9138684],[4.371901,-2.672286,6.819777],[4.9115496,-1.5118402,5.7607713],[4.4748921,-1.5336035,6.9010568],[4.4008923,-2.6287878,6.8122573],[4.9101915,-1.5336035,5.8128085],[4.1558022,-3.2465746,6.7950749],[3.6602814,-4.2610569,6.831995],[3.9027374,-4.4507542,6.0815411],[4.2187653,-3.276315,6.8229346],[3.7232447,-4.2907972,6.8598547],[3.9657006,-4.4804945,6.1094007],[4.2140222,-3.3451762,6.8139858],[3.7548034,-4.285428,6.848104],[3.9794402,-4.4611835,6.1528049]],"bolts":27}, + "Hull.Quarter.L": {"solid":[[-4.2910318,-2.9193861,6.8925695],[-4.3936944,-1.4,7.0157642],[-4.9976001,-1.4,5.506],[-3.5958304,-4.3421259,6.9449539],[-3.9363332,-4.6085348,5.8910241],[-1.75,-4.8604336,7.409956],[-1.75,-5.3931999,5.9851837],[-2.5643883,-1.4,7.5279703],[-1.75,-2.3254409,7.6634545],[-2.5643883,-1.4,5.5060005],[-1.75,-2.3254409,5.6170526]],"facets":9,"panels":[[-1.8505965,-4.7160707,7.3753595],[-1.8505963,-4.0014849,7.4468179],[-3.6631114,-3.9512372,6.9443383],[-3.5181952,-4.2478104,6.9552579],[-1.8707256,-4.7232594,7.4472494],[-1.8707255,-4.0086741,7.5187078],[-3.6832407,-3.9584262,7.0162282],[-3.5383244,-4.2549992,7.0271473],[-1.8953596,-4.6992774,7.4636154],[-1.8953595,-4.0299578,7.5305471],[-3.6571088,-3.9811172,7.042141],[-3.5305526,-4.2401166,7.0516772],[-1.8505961,-3.7328248,7.4736838],[-1.8505962,-2.3636742,7.6105995],[-2.6039624,-1.5075763,7.4852662],[-4.2749043,-1.5075763,7.0174017],[-4.1814685,-2.8904119,6.9052796],[-3.7961907,-3.6788878,6.93431],[-1.8626735,-3.7371383,7.5168176],[-1.8626738,-2.3679876,7.6537333],[-2.61604,-1.5118898,7.5283999],[-4.2869816,-1.5118897,7.0605354],[-4.1935458,-2.8947253,6.9484134],[-3.8082683,-3.6832011,6.9774437],[-1.8873075,-3.7186203,7.5326371],[-1.8873078,-2.3772047,7.666779],[-2.6295791,-1.5337147,7.543292],[-4.2717271,-1.5337147,7.0834894],[-4.1799688,-2.8917229,6.9733806],[-3.8018522,-3.6655443,7.0018711],[-2.781431,-4.5901232,7.037941],[-3.5113628,-4.385159,6.8540564],[-3.7892847,-4.6026049,5.9938278],[-2.8620911,-4.9353704,6.0337601],[-2.8062859,-4.6564031,7.0627251],[-3.5362177,-4.4514389,6.8788404],[-3.8141396,-4.6688848,6.0186119],[-2.886946,-5.0016503,6.0585442],[-2.8335936,-4.6753345,7.0452337],[-3.528693,-4.4801512,6.8701243],[-3.7952366,-4.6886945,6.0451145],[-2.9108679,-5.0060902,6.0832024],[-1.847156,-5.2996264,6.0774708],[-1.847156,-4.8524671,7.273304],[-2.5231628,-4.6626449,7.103004],[-2.6081707,-5.0265012,6.0446959],[-1.8620689,-5.3393941,6.0923409],[-1.862069,-4.8922348,7.2881746],[-2.5380757,-4.7024126,7.1178746],[-2.6230836,-5.0662689,6.059566],[-1.8875667,-5.3432684,6.1169314],[-1.8875668,-4.9116745,7.2711396],[-2.5271213,-4.7320881,7.1100225],[-2.6093879,-5.0842099,6.0858445],[-4.006701,-4.2766266,5.9586406],[-4.2893152,-2.9307594,6.7566447],[-4.8567643,-1.7086169,5.6465893],[-4.0491261,-4.2897968,5.9658279],[-4.3317404,-2.9439294,6.7638316],[-4.8991895,-1.721787,5.6537766],[-4.0841789,-4.2364864,5.9818268],[-4.3537178,-2.9528866,6.7429104],[-4.8958673,-1.7848281,5.6830893],[-4.3302989,-2.6681259,6.8031359],[-4.4087081,-1.5076799,6.8972273],[-4.869947,-1.5076799,5.7441301],[-4.371901,-2.672286,6.819777],[-4.4503107,-1.5118402,6.9138684],[-4.9115496,-1.5118402,5.7607713],[-4.4008923,-2.6287878,6.8122573],[-4.4748921,-1.5336035,6.9010568],[-4.9101915,-1.5336035,5.8128085],[-3.6602814,-4.2610569,6.8319945],[-4.1558022,-3.2465746,6.7950749],[-3.9027376,-4.4507546,6.0815406],[-3.7232447,-4.2907972,6.8598542],[-4.2187657,-3.276315,6.8229346],[-3.9657006,-4.4804945,6.1094003],[-3.7548034,-4.2854285,6.8481035],[-4.2140226,-3.3451762,6.8139858],[-3.9794402,-4.461184,6.1528044]],"bolts":27}, + "Hull.FlankRoof.R": {"solid":[[2.8270271,0.85,7.4918909],[2.8270271,-1.3,7.4918909],[2.8,0.85,7.499999],[2.8,-1.3,7.499999],[2.9800003,0.85,6.8800001],[2.9800003,-1.3,6.8800001],[2.8,0.85,6.8800001],[2.8,-1.3,6.8800001]],"facets":6,"panels":[[2.9339185,0.7400001,6.9818645],[2.8343034,0.7400001,7.3803244],[2.8343034,-1.1899998,7.3803244],[2.9339185,-1.1899998,6.9818645],[3.0066793,0.7400001,7.0000548],[2.907064,0.7400001,7.3985143],[2.907064,-1.1899998,7.3985143],[3.0066793,-1.1899998,7.0000548],[3.0212314,0.7200001,7.0243082],[2.9313176,0.7200001,7.3839622],[2.9313176,-1.1699998,7.3839622],[3.0212314,-1.1699998,7.0243082]],"bolts":4}, + "Hull.FlankRoof.L": {"solid":[[-2.8270271,0.85,7.4918909],[-2.8270271,-1.3,7.4918909],[-2.8,0.85,7.499999],[-2.8,-1.3,7.499999],[-2.9800003,0.85,6.8800001],[-2.9800003,-1.3,6.8800001],[-2.8,0.85,6.8800001],[-2.8,-1.3,6.8800001]],"facets":6,"panels":[[-2.8343034,-1.1899998,7.3803244],[-2.8343034,0.7400001,7.3803244],[-2.9339185,0.7400001,6.9818645],[-2.9339185,-1.1899998,6.9818645],[-2.8779597,-1.1899998,7.3912382],[-2.8779597,0.7400001,7.3912382],[-2.9775751,0.7400001,6.9927788],[-2.9775751,-1.1899998,6.9927788],[-2.9022133,-1.1699998,7.3766861],[-2.9022133,0.7200001,7.3766861],[-2.9921272,0.7200001,7.0170321],[-2.9921272,-1.1699998,7.0170321]],"bolts":4}, + "Hull.FlankSill.R": {"solid":[[4.3656001,0.85,5.1199999],[4.3656001,-1.3,5.1199999],[4.3260002,0.85,5.4499998],[4.3260002,-1.3,5.4499998],[3.9000001,0.85,5.1199999],[3.9000001,-1.3,5.1199999],[3.9000001,0.85,5.4499998],[3.9000001,-1.3,5.4499998]],"facets":6,"panels":[],"bolts":0}, + "Hull.FlankSill.L": {"solid":[[-4.3656001,0.85,5.1199999],[-4.3656001,-1.3,5.1199999],[-4.3260002,0.85,5.4499998],[-4.3260002,-1.3,5.4499998],[-3.9000001,0.85,5.1199999],[-3.9000001,-1.3,5.1199999],[-3.9000001,0.85,5.4499998],[-3.9000001,-1.3,5.4499998]],"facets":6,"panels":[],"bolts":0}, + "Hull.Tail": {"solid":[[1.72,-2.75,7.5],[1.72,-5.0,7.3000002],[1.72,-2.75,7.1500001],[1.72,-5.0,7.0],[-1.72,-2.75,7.5],[-1.72,-5.0,7.3000002],[-1.72,-2.75,7.1500001],[-1.72,-5.0,7.0]],"facets":6,"panels":[[1.61,-4.8886614,7.2898178],[1.61,-2.8577971,7.4703388],[-0.0356075,-2.8577971,7.4703388],[-0.0356076,-4.8886614,7.2898178],[1.61,-4.8953018,7.3645234],[1.61,-2.8644376,7.5450439],[-0.0356075,-2.8644376,7.5450439],[-0.0356076,-4.8953018,7.3645234],[1.59,-4.877151,7.3862157],[1.59,-2.8861299,7.5631948],[-0.0156075,-2.8861299,7.5631948],[-0.0156076,-4.877151,7.3862157],[-0.3056076,-2.8577971,7.4703374],[-1.61,-2.8577971,7.4703374],[-1.61,-4.8886609,7.2898192],[-0.3056076,-4.8886609,7.2898192],[-0.3056076,-2.8617814,7.5151606],[-1.61,-2.8617814,7.5151606],[-1.61,-4.8926454,7.3346429],[-0.3056076,-4.8926454,7.3346429],[-0.3256076,-2.8834736,7.5333114],[-1.59,-2.8834736,7.5333114],[-1.59,-4.8744946,7.3563347],[-0.3256076,-4.8744946,7.3563347]],"bolts":8}, + "Hull.BellySide.R": {"solid":[[2.0999999,2.2,3.9000001],[2.0999999,-2.4000001,3.95],[2.45,2.0,4.0999999],[2.45,-2.2,4.1500001],[2.45,2.0,4.8499999],[2.45,-2.2,4.9000001],[2.25,2.2,5.0999999],[2.25,-2.4000001,5.1500001],[1.8,2.2,3.9000001],[1.8,-2.4000001,5.1500001]],"facets":15,"panels":[[2.4300001,-2.0900002,4.7886829],[2.4300001,-2.0900002,4.2586985],[2.4300001,-0.6636688,4.2417183],[2.4300001,-0.6573603,4.7716274],[2.5050001,-2.0900002,4.7886829],[2.5050001,-2.0900002,4.2586985],[2.5050001,-0.6636688,4.2417183],[2.5050001,-0.6573603,4.7716274],[2.5250001,-2.0700002,4.7684431],[2.5250001,-2.0700002,4.2784615],[2.5250001,-0.6834292,4.2619548],[2.5250001,-0.677597,4.7518668],[2.4300001,-0.3936881,4.2385039],[2.4300001,1.89,4.2113171],[2.4300001,1.89,4.7413015],[2.4300001,-0.3873795,4.7684135],[2.4750001,-0.3936881,4.2385039],[2.4750001,1.89,4.2113171],[2.4750001,1.89,4.7413015],[2.4750001,-0.3873795,4.7684135],[2.4950001,-0.3734515,4.2582645],[2.4950001,1.87,4.2315569],[2.4950001,1.87,4.7215385],[2.4950001,-0.367619,4.7481766],[2.2321301,1.8335732,5.0840106],[1.9212853,-2.2902241,5.1287899],[2.1400001,-2.2902241,5.1287899],[2.2321301,1.8343884,5.1590061],[1.9212853,-2.2894089,5.2037854],[2.1400001,-2.2894089,5.2037854],[2.2288792,1.7680224,5.179728],[1.9428494,-2.2691927,5.223567],[2.1204419,-2.2691927,5.223567]],"bolts":11}, + "Hull.BellySide.L": {"solid":[[-2.0999999,2.2,3.9000001],[-2.0999999,-2.4000001,3.95],[-2.45,2.0,4.0999999],[-2.45,-2.2,4.1500001],[-2.45,2.0,4.8499999],[-2.45,-2.2,4.9000001],[-2.25,2.2,5.0999999],[-2.25,-2.4000001,5.1500001],[-1.8,2.2,3.9000001],[-1.8,-2.4000001,5.1500001]],"facets":15,"panels":[[-2.4300001,-2.0900002,4.2586985],[-2.4300001,-2.0900002,4.7886829],[-2.4300001,0.1687398,4.7617931],[-2.4300001,0.1624316,4.2318835],[-2.5050001,-2.0900002,4.2586985],[-2.5050001,-2.0900002,4.7886829],[-2.5050001,0.1687398,4.7617931],[-2.5050001,0.1624316,4.2318835],[-2.5250001,-2.0700002,4.2784615],[-2.5250001,-2.0700002,4.7684431],[-2.5250001,0.1485032,4.7420325],[-2.5250001,0.1426711,4.2521205],[-2.4300001,0.4387209,4.7585793],[-2.4300001,1.89,4.7413015],[-2.4300001,1.89,4.2113171],[-2.4300001,0.4324124,4.2286692],[-2.4750001,0.4387209,4.7585793],[-2.4750001,1.89,4.7413015],[-2.4750001,1.89,4.2113171],[-2.4750001,0.4324124,4.2286692],[-2.4950001,0.4584814,4.7383423],[-2.4950001,1.87,4.7215385],[-2.4950001,1.87,4.2315569],[-2.4950001,0.4526491,4.2484298],[-2.2321301,1.8335732,5.0840106],[-2.1400001,-2.2902241,5.1287899],[-1.9212852,-2.2902241,5.1287899],[-2.2321301,1.8340623,5.1290078],[-2.1400001,-2.2897351,5.1737871],[-1.9212852,-2.2897351,5.1737871],[-2.2288792,1.7676963,5.1497297],[-2.1204419,-2.2695189,5.1935692],[-1.9428494,-2.2695189,5.1935692]],"bolts":11} + }} + ]} diff --git a/surfaces/blender/tests/fixtures/plates_paladin.json b/surfaces/blender/tests/fixtures/plates_paladin.json new file mode 100644 index 0000000..b1cd9c4 --- /dev/null +++ b/surfaces/blender/tests/fixtures/plates_paladin.json @@ -0,0 +1,1943 @@ +{"source": {"branch": "nibu/fable-paladin-3", "sha": "c35e57ee5aa9c52e589623fcc8abb19b909f09d4", "blender": "5.3.0"}, + "table": { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "Thigh.core", + "mat": "gunmetal", + "bevel": 0.02, + "sections": [ + [ + 0.4, + 0.9, + -0.3, + 0.5, + 0.12 + ], + [ + 0.05, + 1.2, + -0.34, + 0.64, + 0.18 + ], + [ + -1.45, + 1.2, + -0.34, + 0.64, + 0.18 + ], + [ + -1.8, + 0.95, + -0.3, + 0.5, + 0.14 + ] + ] + }, + { + "name": "Thigh.Shield", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + 0.02, + 0.9, + -0.5 + ], + "normal": [ + 0.06, + 1.0, + 0.05 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": [ + [ + -0.42, + 0.98 + ], + [ + 0.42, + 0.98 + ], + [ + 0.66, + 0.5 + ], + [ + 0.66, + -0.52 + ], + [ + 0.42, + -1.0 + ], + [ + -0.42, + -1.0 + ], + [ + -0.66, + -0.52 + ], + [ + -0.66, + 0.5 + ] + ], + "thick": 0.26, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.2, + "lifts": [ + 0.05, + 0.05 + ], + "inset": 0.075, + "gap": 0.045, + "split": 99.0, + "seed": 948708 + }, + "fits": [ + { + "kind": "mark", + "id": "tri", + "at": [ + 0.0, + -0.05 + ], + "height": 0.5 + } + ] + }, + { + "name": "Thigh.Block", + "mat": "olive_light", + "bevel": 0.022, + "slab": { + "at": [ + 0.02, + 1.0, + 0.12 + ], + "normal": [ + 0.06, + 1.0, + 0.05 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.56, + "h": 0.44, + "clip": 0.08 + }, + "thick": 0.16, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Thigh.Lame", + "mat": "olive_light", + "bevel": 0.022, + "slab": { + "at": [ + 0.02, + 0.985, + -1.17 + ], + "normal": [ + 0.06, + 1.0, + 0.02 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": [ + [ + -0.52, + 0.2 + ], + [ + 0.52, + 0.2 + ], + [ + 0.58, + 0.0 + ], + [ + 0.4, + -0.26 + ], + [ + -0.4, + -0.26 + ], + [ + -0.58, + 0.0 + ] + ], + "thick": 0.14, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Thigh.Outer", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + 0.86, + 0.0, + -0.45 + ], + "normal": [ + 1.0, + 0.08, + 0.04 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 0.0, + 1.0, + 0.0 + ], + "outline": [ + [ + -0.5, + 1.0 + ], + [ + 0.36, + 1.05 + ], + [ + 0.68, + 0.5 + ], + [ + 0.68, + -0.6 + ], + [ + 0.3, + -1.02 + ], + [ + -0.5, + -0.86 + ], + [ + -0.74, + -0.2 + ], + [ + -0.74, + 0.5 + ] + ], + "thick": 0.24, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.2, + "lifts": [ + 0.04, + 0.07 + ], + "inset": 0.075, + "gap": 0.045, + "split": 0.8, + "seed": 976538 + } + }, + { + "name": "Thigh.OuterStep", + "mat": "olive_light", + "bevel": 0.022, + "slab": { + "at": [ + 0.95, + -0.02, + -0.25 + ], + "normal": [ + 1.0, + 0.08, + 0.04 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 0.0, + 1.0, + 0.0 + ], + "outline": { + "w": 0.8, + "h": 0.9, + "clip": 0.2 + }, + "thick": 0.13, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Thigh.Inner", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + -0.82, + 0.05, + -0.75 + ], + "normal": [ + -1.0, + 0.1, + 0.0 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 0.0, + 1.0, + 0.0 + ], + "outline": [ + [ + -0.55, + 0.55 + ], + [ + 0.5, + 0.55 + ], + [ + 0.62, + 0.15 + ], + [ + 0.5, + -0.7 + ], + [ + -0.45, + -0.7 + ], + [ + -0.62, + -0.15 + ] + ], + "thick": 0.2, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.2, + "lifts": [ + 0.04, + 0.07 + ], + "inset": 0.075, + "gap": 0.045, + "split": 0.8, + "seed": 947561 + } + }, + { + "name": "Thigh.Rear", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + 0.0, + -0.98, + -0.25 + ], + "normal": [ + 0.0, + -1.0, + 0.05 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": [ + [ + -0.46, + 0.72 + ], + [ + 0.46, + 0.72 + ], + [ + 0.64, + 0.3 + ], + [ + 0.64, + -0.4 + ], + [ + 0.42, + -0.72 + ], + [ + -0.42, + -0.72 + ], + [ + -0.64, + -0.4 + ], + [ + -0.64, + 0.3 + ] + ], + "thick": 0.22, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.2, + "lifts": [ + 0.05, + 0.05 + ], + "inset": 0.075, + "gap": 0.045, + "split": 99.0, + "seed": 398253 + } + }, + { + "name": "Thigh.RearStep", + "mat": "olive_light", + "bevel": 0.022, + "slab": { + "at": [ + 0.0, + -1.06, + -0.3 + ], + "normal": [ + 0.0, + -1.0, + 0.05 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.7, + "h": 0.5, + "clip": 0.1 + }, + "thick": 0.12, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Thigh.CornerOut", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + 0.7, + 0.7, + -0.45 + ], + "normal": [ + 0.72, + 0.7, + 0.04 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.3, + "h": 1.5, + "clip": 0.08 + }, + "thick": 0.2, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Thigh.CornerIn", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + -0.67, + 0.7, + -0.6 + ], + "normal": [ + -0.72, + 0.7, + 0.03 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.26, + "h": 1.1, + "clip": 0.07 + }, + "thick": 0.18, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Thigh.Cap", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + 0.0, + 0.12, + 0.66 + ], + "normal": [ + 0.0, + 0.3, + 1.0 + ], + "up": [ + 0.0, + 1.0, + 0.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": [ + [ + -0.5, + -0.5 + ], + [ + 0.5, + -0.5 + ], + [ + 0.6, + 0.1 + ], + [ + 0.36, + 0.44 + ], + [ + -0.36, + 0.44 + ], + [ + -0.6, + 0.1 + ] + ], + "thick": 0.18, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.2, + "lifts": [ + 0.05, + 0.05 + ], + "inset": 0.075, + "gap": 0.045, + "split": 99.0, + "seed": 387260 + } + }, + { + "name": "Shin.core", + "mat": "gunmetal", + "bevel": 0.02, + "sections": [ + [ + -0.3, + 0.9, + -0.3, + 0.5, + 0.12 + ], + [ + -0.65, + 1.14, + -0.34, + 0.6, + 0.18 + ], + [ + -1.9, + 1.06, + -0.34, + 0.56, + 0.18 + ], + [ + -2.5, + 0.8, + -0.3, + 0.4, + 0.12 + ] + ] + }, + { + "name": "Shin.Knee", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + 0.0, + 1.0, + 0.02 + ], + "normal": [ + 0.0, + 1.0, + 0.22 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": [ + [ + -0.4, + 0.56 + ], + [ + 0.4, + 0.56 + ], + [ + 0.62, + 0.22 + ], + [ + 0.62, + -0.3 + ], + [ + 0.42, + -0.56 + ], + [ + -0.42, + -0.56 + ], + [ + -0.62, + -0.3 + ], + [ + -0.62, + 0.22 + ] + ], + "thick": 0.28, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.2, + "lifts": [ + 0.05, + 0.05 + ], + "inset": 0.075, + "gap": 0.045, + "split": 99.0, + "seed": 995246 + } + }, + { + "name": "Shin.KneeSide", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + 0.7, + 0.72, + 0.0 + ], + "normal": [ + 0.75, + 0.66, + 0.1 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.34, + "h": 0.9, + "clip": 0.1 + }, + "thick": 0.2, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Shin.KneeSideIn", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + -0.7, + 0.72, + 0.0 + ], + "normal": [ + -0.75, + 0.66, + 0.1 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.34, + "h": 0.9, + "clip": 0.1 + }, + "thick": 0.2, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Shin.Greave", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + 0.0, + 0.88, + -1.3 + ], + "normal": [ + 0.0, + 1.0, + -0.07 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": [ + [ + -0.5, + 0.72 + ], + [ + 0.5, + 0.72 + ], + [ + 0.66, + 0.4 + ], + [ + 0.6, + -0.5 + ], + [ + 0.36, + -0.95 + ], + [ + -0.36, + -0.95 + ], + [ + -0.6, + -0.5 + ], + [ + -0.66, + 0.4 + ] + ], + "thick": 0.28, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.2, + "lifts": [ + 0.04, + 0.07 + ], + "inset": 0.075, + "gap": 0.045, + "split": 0.8, + "seed": 564123 + } + }, + { + "name": "Shin.GreaveStep", + "mat": "olive_light", + "bevel": 0.022, + "slab": { + "at": [ + 0.0, + 0.97, + -1.2 + ], + "normal": [ + 0.0, + 1.0, + -0.07 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.62, + "h": 0.84, + "clip": 0.12 + }, + "thick": 0.15, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Shin.Outer", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + 0.82, + -0.2, + -1.05 + ], + "normal": [ + 1.0, + 0.04, + 0.0 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 0.0, + 1.0, + 0.0 + ], + "outline": [ + [ + -0.75, + 0.62 + ], + [ + 0.34, + 0.74 + ], + [ + 0.74, + 0.36 + ], + [ + 0.7, + -0.55 + ], + [ + 0.28, + -0.96 + ], + [ + -0.6, + -0.82 + ], + [ + -0.95, + -0.1 + ] + ], + "thick": 0.26, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.2, + "lifts": [ + 0.04, + 0.07 + ], + "inset": 0.075, + "gap": 0.045, + "split": 0.8, + "seed": 733553 + } + }, + { + "name": "Shin.OuterStep", + "mat": "olive_light", + "bevel": 0.022, + "slab": { + "at": [ + 0.92, + -0.2, + -1.0 + ], + "normal": [ + 1.0, + 0.04, + 0.0 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 0.0, + 1.0, + 0.0 + ], + "outline": [ + [ + -0.42, + 0.42 + ], + [ + 0.2, + 0.46 + ], + [ + 0.46, + 0.2 + ], + [ + 0.44, + -0.3 + ], + [ + 0.16, + -0.5 + ], + [ + -0.36, + -0.44 + ], + [ + -0.56, + -0.05 + ] + ], + "thick": 0.13, + "taper": 0.04, + "back": 1.0 + }, + "fits": [ + { + "kind": "mark", + "id": "tri", + "at": [ + -0.03, + -0.02 + ], + "height": 0.4 + } + ] + }, + { + "name": "Shin.Inner", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + -0.78, + -0.12, + -1.1 + ], + "normal": [ + -1.0, + 0.04, + 0.0 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 0.0, + 1.0, + 0.0 + ], + "outline": [ + [ + -0.7, + 0.55 + ], + [ + 0.3, + 0.66 + ], + [ + 0.66, + 0.3 + ], + [ + 0.62, + -0.5 + ], + [ + 0.25, + -0.86 + ], + [ + -0.55, + -0.74 + ], + [ + -0.85, + -0.1 + ] + ], + "thick": 0.22, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.2, + "lifts": [ + 0.05, + 0.05 + ], + "inset": 0.075, + "gap": 0.045, + "split": 99.0, + "seed": 299054 + } + }, + { + "name": "Shin.Calf", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + 0.0, + -1.12, + -0.95 + ], + "normal": [ + 0.0, + -1.0, + 0.1 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": [ + [ + -0.5, + 0.62 + ], + [ + 0.5, + 0.62 + ], + [ + 0.68, + 0.1 + ], + [ + 0.5, + -0.62 + ], + [ + -0.5, + -0.62 + ], + [ + -0.68, + 0.1 + ] + ], + "thick": 0.22, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.2, + "lifts": [ + 0.05, + 0.05 + ], + "inset": 0.075, + "gap": 0.045, + "split": 99.0, + "seed": 800359 + } + }, + { + "name": "Shin.CalfStep", + "mat": "olive_light", + "bevel": 0.022, + "slab": { + "at": [ + 0.0, + -1.2, + -1.05 + ], + "normal": [ + 0.0, + -1.0, + 0.1 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.72, + "h": 0.46, + "clip": 0.1 + }, + "thick": 0.12, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Shin.Ankle", + "mat": "olive_light", + "bevel": 0.022, + "slab": { + "at": [ + 0.0, + 0.66, + -2.42 + ], + "normal": [ + 0.0, + 1.0, + -0.2 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.8, + "h": 0.52, + "clip": 0.12 + }, + "thick": 0.2, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "khaki", + "min_area": 0.2, + "lifts": [ + 0.04, + 0.07 + ], + "inset": 0.075, + "gap": 0.045, + "split": 0.8, + "seed": 22775 + } + }, + { + "name": "Shin.AnkleSide", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + 0.6, + 0.1, + -2.35 + ], + "normal": [ + 1.0, + 0.1, + -0.1 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 0.0, + 1.0, + 0.0 + ], + "outline": { + "w": 0.7, + "h": 0.5, + "clip": 0.12 + }, + "thick": 0.16, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Pelvis.core", + "mat": "gunmetal", + "bevel": 0.02, + "points": [ + [ + 0.62, + 0.62, + 0.5 + ], + [ + 0.62, + -0.6, + 0.5 + ], + [ + 0.72, + 0.7, + -0.3 + ], + [ + 0.72, + -0.62, + -0.3 + ], + [ + 0.45, + 0.7, + 0.62 + ], + [ + 0.45, + -0.66, + 0.62 + ], + [ + 0.4, + 0.55, + -0.8 + ], + [ + 0.4, + -0.45, + -0.8 + ] + ], + "mirror": true + }, + { + "name": "Pelvis.Crown", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + 0.0, + 1.0, + 0.42 + ], + "normal": [ + 0.0, + 1.0, + 0.16 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": [ + [ + -0.32, + 0.3 + ], + [ + 0.32, + 0.3 + ], + [ + 0.48, + 0.04 + ], + [ + 0.3, + -0.3 + ], + [ + -0.3, + -0.3 + ], + [ + -0.48, + 0.04 + ] + ], + "thick": 0.3, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.2, + "lifts": [ + 0.05, + 0.05 + ], + "inset": 0.075, + "gap": 0.045, + "split": 99.0, + "seed": 345924 + } + }, + { + "name": "Pelvis.Cod", + "mat": "khaki", + "bevel": 0.022, + "slab": { + "at": [ + 0.0, + 1.06, + -0.62 + ], + "normal": [ + 0.0, + 1.0, + -0.1 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": [ + [ + -0.36, + 0.7 + ], + [ + 0.36, + 0.7 + ], + [ + 0.44, + 0.3 + ], + [ + 0.3, + -0.78 + ], + [ + -0.3, + -0.78 + ], + [ + -0.44, + 0.3 + ] + ], + "thick": 0.34, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.2, + "lifts": [ + 0.04, + 0.07 + ], + "inset": 0.075, + "gap": 0.045, + "split": 0.8, + "seed": 876596 + } + }, + { + "name": "Pelvis.CodStep", + "mat": "olive_light", + "bevel": 0.022, + "slab": { + "at": [ + 0.0, + 1.17, + -0.3 + ], + "normal": [ + 0.0, + 1.0, + -0.1 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.5, + "h": 0.42, + "clip": 0.1 + }, + "thick": 0.14, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Pelvis.CodLame", + "mat": "olive_light", + "bevel": 0.022, + "slab": { + "at": [ + 0.0, + 1.15, + -1.02 + ], + "normal": [ + 0.0, + 1.0, + -0.1 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.42, + "h": 0.4, + "clip": 0.08 + }, + "thick": 0.13, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Pelvis.Wing", + "mat": "khaki", + "bevel": 0.022, + "sides": "both", + "slab": { + "at": [ + 0.92, + 0.84, + 0.5 + ], + "normal": [ + 0.3, + 1.0, + 0.2 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": [ + [ + -0.46, + -0.02 + ], + [ + 0.44, + 0.36 + ], + [ + 0.54, + 0.1 + ], + [ + 0.44, + -0.26 + ], + [ + -0.46, + -0.36 + ] + ], + "thick": 0.22, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.2, + "lifts": [ + 0.04, + 0.07 + ], + "inset": 0.075, + "gap": 0.045, + "split": 0.8, + "seed": [ + 876672, + 589838 + ] + } + }, + { + "name": "Pelvis.HipGuard", + "mat": "olive_light", + "bevel": 0.022, + "sides": "both", + "slab": { + "at": [ + 0.62, + 0.92, + -0.05 + ], + "normal": [ + 0.2, + 1.0, + -0.05 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.34, + "h": 0.5, + "clip": 0.08 + }, + "thick": 0.16, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Pelvis.Seat", + "mat": "khaki", + "bevel": 0.022, + "sides": "both", + "slab": { + "at": [ + 0.56, + -0.86, + 0.02 + ], + "normal": [ + 0.22, + -1.0, + 0.1 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": [ + [ + -0.5, + 0.66 + ], + [ + 0.5, + 0.72 + ], + [ + 0.6, + -0.2 + ], + [ + 0.2, + -0.86 + ], + [ + -0.5, + -0.6 + ] + ], + "thick": 0.24, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.2, + "lifts": [ + 0.05, + 0.05 + ], + "inset": 0.075, + "gap": 0.045, + "split": 99.0, + "seed": [ + 1004746, + 453014 + ] + } + }, + { + "name": "Pelvis.SeatStep", + "mat": "olive_light", + "bevel": 0.022, + "sides": "both", + "slab": { + "at": [ + 0.6, + -0.95, + 0.1 + ], + "normal": [ + 0.22, + -1.0, + 0.1 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.56, + "h": 0.6, + "clip": 0.12 + }, + "thick": 0.12, + "taper": 0.04, + "back": 1.0 + } + }, + { + "name": "Pelvis.Tail", + "mat": "olive_light", + "bevel": 0.022, + "slab": { + "at": [ + 0.0, + -0.92, + -0.2 + ], + "normal": [ + 0.0, + -1.0, + -0.05 + ], + "up": [ + 0.0, + 0.0, + 1.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.36, + "h": 1.3, + "clip": 0.1 + }, + "thick": 0.22, + "taper": 0.04, + "back": 1.0 + }, + "clad": { + "mat": "khaki", + "min_area": 0.2, + "lifts": [ + 0.04, + 0.07 + ], + "inset": 0.075, + "gap": 0.045, + "split": 0.8, + "seed": 995407 + } + }, + { + "name": "Pelvis.Roof", + "mat": "khaki", + "bevel": 0.022, + "sides": "both", + "slab": { + "at": [ + 0.62, + 0.0, + 0.7 + ], + "normal": [ + 0.25, + 0.0, + 1.0 + ], + "up": [ + 0.0, + 1.0, + 0.0 + ], + "right": [ + 1.0, + 0.0, + 0.0 + ], + "outline": { + "w": 0.6, + "h": 1.1, + "clip": 0.14 + }, + "thick": 0.14, + "taper": 0.04, + "back": 1.0 + } + } + ] +}, + "cases": [ + {"side": 1, "truth": { + "Thigh.core": {"solid":[[-0.33,-0.3,0.4],[0.33,-0.3,0.4],[0.45,-0.18,0.4],[0.45,0.38,0.4],[0.33,0.5,0.4],[-0.33,0.5,0.4],[-0.45,0.38,0.4],[-0.45,-0.18,0.4],[-0.42,-0.34,0.05],[0.42,-0.34,0.05],[0.6,-0.16,0.05],[0.6,0.46,0.05],[0.42,0.64,0.05],[-0.42,0.64,0.05],[-0.6,0.46,0.05],[-0.6,-0.16,0.05],[-0.42,-0.34,-1.45],[0.42,-0.34,-1.45],[0.6,-0.16,-1.45],[0.6,0.46,-1.45],[0.42,0.64,-1.45],[-0.42,0.64,-1.45],[-0.6,0.46,-1.45],[-0.6,-0.16,-1.45],[-0.335,-0.3,-1.8],[0.335,-0.3,-1.8],[0.475,-0.16,-1.8],[0.475,0.36,-1.8],[0.335,0.5,-1.8],[-0.335,0.5,-1.8],[-0.475,0.36,-1.8],[-0.475,-0.16,-1.8]],"facets":26,"panels":[],"bolts":0}, + "Thigh.Shield": {"solid":[[-0.6003516,0.9127237,-0.0100526],[-0.5973628,0.9625379,-1.0099225],[-0.371703,0.9714425,-1.4588065],[0.4174352,0.9240942,-1.4588065],[0.6404113,0.8882715,-1.0099225],[0.6374224,0.8384573,-0.0100526],[0.4117627,0.8295527,0.4388314],[-0.3773755,0.8769009,0.4388314],[-0.6427007,0.874771,-0.0026155],[-0.6396555,0.9255249,-1.0213474],[-0.3986532,0.9350349,-1.5007508],[0.4398389,0.8847254,-1.5007508],[0.677975,0.8464671,-1.0213474],[0.6749298,0.7957132,-0.0026155],[0.4339275,0.7862031,0.4767878],[-0.4045646,0.8365127,0.4767878],[-0.6558607,0.6554389,-0.0135821],[-0.6528155,0.7061929,-1.0323141],[-0.4118131,0.7157029,-1.5117174],[0.426679,0.6653934,-1.5117174],[0.6648151,0.627135,-1.0323141],[0.6617699,0.5763811,-0.0135821],[0.4207676,0.566871,0.4658212],[-0.4177245,0.6171806,0.4658212]],"facets":18,"panels":[[0.5642967,0.8719431,-0.9932363],[0.3697456,0.9031991,-1.3848965],[-0.3268539,0.9449951,-1.3848965],[-0.5237467,0.9372256,-0.9932363],[-0.5266297,0.8891734,-0.0287326],[-0.3320786,0.8579174,0.3629277],[0.3645209,0.8161214,0.3629277],[0.5614136,0.8238909,-0.0287325],[0.5672876,0.9217913,-0.9907439],[0.3727365,0.9530473,-1.3824042],[-0.323863,0.9948433,-1.3824042],[-0.5207558,0.9870738,-0.9907439],[-0.5236388,0.9390216,-0.0262402],[-0.3290877,0.9077656,0.3654201],[0.3675118,0.8659696,0.3654201],[0.5644045,0.8737391,-0.0262401],[0.5485058,0.9426935,-0.9850315],[0.3615346,0.9727318,-1.3614321],[-0.3103879,1.0130471,-1.3614321],[-0.4996094,1.0055803,-0.9850315],[-0.5024643,0.957998,-0.0299587],[-0.3154931,0.9279597,0.346442],[0.3564294,0.8876444,0.346442],[0.5456509,0.8951111,-0.0299587]],"bolts":8}, + "Thigh.Block": {"solid":[[-0.2199377,1.0082324,0.243278],[-0.2192007,1.0205159,-0.003278],[-0.1625648,1.0199426,-0.0597762],[0.2036396,0.9979704,-0.0597762],[0.2599377,0.9917676,-0.003278],[0.2592007,0.9794841,0.243278],[0.2025648,0.9800573,0.2997762],[-0.1636396,1.0020295,0.2997762],[-0.262308,0.9699251,0.257832],[-0.2614721,0.9838576,-0.0218199],[-0.1813769,0.9830468,-0.1017204],[0.2179051,0.9590899,-0.1017204],[0.2975226,0.9503179,-0.0218199],[0.2966867,0.9363854,0.257832],[0.2165914,0.9371961,0.3377326],[-0.1826905,0.9611531,0.3377326],[-0.2694862,0.8502895,0.2518502],[-0.2686502,0.8642219,-0.0278017],[-0.188555,0.8634112,-0.1077022],[0.2107269,0.8394543,-0.1077022],[0.2903445,0.8306822,-0.0278017],[0.2895085,0.8167497,0.2518502],[0.2094133,0.8175604,0.3317508],[-0.1898686,0.8415174,0.3317508]],"facets":18,"panels":[],"bolts":0}, + "Thigh.Lame": {"solid":[[-0.5152019,1.0169734,-1.1630588],[-0.3580984,1.0120851,-1.3899561],[0.3986245,0.9666817,-1.3899561],[0.5551853,0.9527501,-1.1630588],[0.5091674,0.9524506,-1.0100318],[-0.46955,1.0111736,-1.0100318],[-0.561354,0.9798173,-1.1707984],[-0.3813663,0.9742171,-1.4307466],[0.4171976,0.9263031,-1.4307466],[0.5965636,0.9103422,-1.1707984],[0.5364322,0.909951,-0.9708382],[-0.5017008,0.972239,-0.9708382],[-0.5673421,0.8800166,-1.1727943],[-0.3873544,0.8744164,-1.4327425],[0.4112095,0.8265026,-1.4327425],[0.5905755,0.8105416,-1.1727943],[0.5304441,0.8101503,-0.9728342],[-0.5076889,0.8724384,-0.9728342]],"facets":14,"panels":[],"bolts":0}, + "Thigh.Outer": {"solid":[[0.8963261,-0.6993303,0.0405074],[0.9234846,-0.6971576,-0.6427998],[0.9302595,-0.4659773,-1.2745335],[0.8760005,0.2877677,-1.4255476],[0.8321795,0.6398191,-1.0341262],[0.7895345,0.6364074,0.0388219],[0.7930059,0.3335055,0.55784],[0.859628,-0.475686,0.5106725],[0.8593135,-0.7424191,0.0480094],[0.8871133,-0.7401951,-0.6514348],[0.8941858,-0.4988625,-1.3109107],[0.8367438,0.299098,-1.4707837],[0.7897608,0.6765533,-1.0511172],[0.7460753,0.6730585,0.0480094],[0.749751,0.3523302,0.5975726],[0.8203176,-0.504772,0.5476124],[0.6601087,-0.7583555,0.0400412],[0.6879086,-0.7561315,-0.659403],[0.694981,-0.5147989,-1.3188789],[0.6375391,0.2831616,-1.4787519],[0.590556,0.6606169,-1.0590854],[0.5468705,0.6571221,0.0400412],[0.5505463,0.3363939,0.5896044],[0.6211129,-0.5207084,0.5396442]],"facets":18,"panels":[[0.9001193,-0.6237868,-0.7074043],[0.8970585,-0.6240321,-0.6303937],[0.9032756,-0.4118871,-1.2101107],[0.8549845,0.2589536,-1.3445147],[0.8170925,0.5633724,-1.0060527],[0.8052226,0.5624229,-0.7074043],[0.969841,-0.6182091,-0.7046154],[0.9667802,-0.6184544,-0.6276049],[0.9729972,-0.4063094,-1.2073218],[0.9247062,0.2645313,-1.3417259],[0.8868142,0.5689502,-1.0032638],[0.8749442,0.5680006,-0.7046154],[0.9921507,-0.6364881,-0.7238027],[0.9850156,-0.6285996,-0.5612047],[0.9910342,-0.3898667,-1.1891332],[0.9443345,0.2588662,-1.3191079],[0.9080236,0.5505831,-0.9947683],[0.8972539,0.5497215,-0.7238027],[0.8711027,-0.6261086,0.0226564],[0.8923752,-0.6244068,-0.5125591],[0.7974783,0.5618034,-0.5125591],[0.7763985,0.560117,0.0178105],[0.7794868,0.2906393,0.4795566],[0.8387128,-0.4287195,0.4376253],[0.9109437,-0.6229213,0.02425],[0.9322161,-0.6212195,-0.5109655],[0.8373193,0.5649906,-0.5109655],[0.8162394,0.5633042,0.0194041],[0.8193278,0.2938266,0.4811502],[0.8785537,-0.4255322,0.439219],[0.92945,-0.601377,0.020499],[0.9497474,-0.5997531,-0.4901845],[0.8580404,0.5465844,-0.4901845],[0.8379691,0.5449787,0.0148104],[0.8409553,0.2844143,0.4612839],[0.898209,-0.4109892,0.420749]],"bolts":12}, + "Thigh.OuterStep": {"solid":[[0.9694378,-0.3795951,-0.0167539],[0.9879788,-0.3781119,-0.4832461],[0.9809105,-0.2015447,-0.6596745],[0.951655,0.1641499,-0.6596745],[0.9305622,0.3395951,-0.4832461],[0.9120212,0.3381118,-0.0167539],[0.9190895,0.1615447,0.1596745],[0.948345,-0.2041499,0.1596745],[0.9321286,-0.4227076,-0.0017921],[0.9519857,-0.4211191,-0.5013952],[0.9439794,-0.2211206,-0.7012363],[0.9120813,0.1776055,-0.7012363],[0.8881895,0.3763331,-0.5013952],[0.8683324,0.3747445,-0.0017921],[0.8763387,0.1747461,0.1980491],[0.9082368,-0.22398,0.1980491],[0.8424864,-0.429879,-0.0053778],[0.8623435,-0.4282905,-0.5049809],[0.8543373,-0.228292,-0.704822],[0.8224391,0.1704341,-0.704822],[0.7985473,0.3691617,-0.5049809],[0.7786903,0.3675731,-0.0053778],[0.7866965,0.1675747,0.1944634],[0.8185946,-0.2311514,0.1944634]],"facets":18,"panels":[],"bolts":0}, + "Thigh.Inner": {"solid":[[-0.8776518,-0.5265174,-0.8959235],[-0.861841,-0.3684096,-1.41],[-0.7737058,0.5129414,-1.41],[-0.7623708,0.6262924,-0.603093],[-0.7732095,0.5179051,-0.24],[-0.871125,-0.4612505,-0.24],[-0.8418908,-0.5709032,-0.9],[-0.8249752,-0.4017468,-1.45],[-0.7304466,0.5435384,-1.45],[-0.7185062,0.6629429,-0.6],[-0.7304466,0.5435384,-0.2],[-0.8349255,-0.5012506,-0.2],[-0.6826848,-0.5868238,-0.9],[-0.6657692,-0.4176674,-1.45],[-0.5712407,0.5276178,-1.45],[-0.5593002,0.6470223,-0.6],[-0.5712407,0.5276178,-0.2],[-0.6757196,-0.5171711,-0.2]],"facets":14,"panels":[[-0.850175,-0.4527469,-0.88828],[-0.8444706,-0.3957034,-0.315],[-0.8004089,0.0449137,-0.3149999],[-0.8004089,0.0449137,-1.3349999],[-0.8364358,-0.3153551,-1.3349999],[-0.9198276,-0.4457816,-0.88828],[-0.9141232,-0.3887382,-0.315],[-0.8700615,0.051879,-0.3149999],[-0.8700615,0.051879,-1.3349999],[-0.9060884,-0.3083898,-1.3349999],[-0.9377081,-0.4235888,-0.8862417],[-0.932223,-0.3687381,-0.335],[-0.8919523,0.0339683,-0.3349999],[-0.8919523,0.0339683,-1.3149999],[-0.9245213,-0.2917212,-1.3149999],[-0.7810057,0.238946,-0.315],[-0.7588613,0.4603896,-0.315],[-0.7500883,0.5481198,-0.6088924],[-0.7602883,0.4461192,-1.335],[-0.7810056,0.238946,-1.335],[-0.8208072,0.2429261,-0.315],[-0.7986628,0.4643697,-0.315],[-0.7898898,0.5521,-0.6088925],[-0.8000898,0.4500993,-1.335],[-0.8208071,0.2429261,-1.335],[-0.8387178,0.2648169,-0.335],[-0.8200442,0.451553,-0.335],[-0.8118221,0.5337747,-0.610439],[-0.8217194,0.4348008,-1.3150001],[-0.8387178,0.2648169,-1.3150001]],"bolts":10}, + "Thigh.Rear": {"solid":[[-0.6,-0.9654287,0.0414257],[-0.6,-0.9993547,-0.6370928],[-0.3989588,-1.0139576,-0.9291516],[0.3989588,-1.0139576,-0.9291516],[0.6,-0.9993547,-0.6370928],[0.6,-0.9654287,0.0414257],[0.4336241,-0.9460424,0.4291516],[-0.4336241,-0.9460424,0.4291516],[-0.64,-0.9250687,0.0476282],[-0.64,-0.960025,-0.6514985],[-0.42,-0.976005,-0.9710993],[0.42,-0.976005,-0.9710993],[0.64,-0.960025,-0.6514985],[0.64,-0.9250687,0.0476282],[0.46,-0.9040949,0.4671042],[-0.46,-0.9040949,0.4671042],[-0.64,-0.7452933,0.0386394],[-0.64,-0.7802496,-0.6604872],[-0.42,-0.7962296,-0.980088],[0.42,-0.7962296,-0.980088],[0.64,-0.7802496,-0.6604872],[0.64,-0.7452933,0.0386394],[0.46,-0.7243195,0.4581155],[-0.46,-0.7243195,0.4581155]],"facets":18,"panels":[[0.525,-0.9462224,0.0250518],[0.3841694,-0.9298127,0.3532465],[-0.3841694,-0.9298127,0.3532465],[-0.525,-0.9462224,0.0250518],[-0.525,-0.9782164,-0.6148264],[-0.3595065,-0.9902372,-0.8552439],[0.3595065,-0.9902372,-0.8552439],[0.525,-0.9782164,-0.6148264],[0.525,-0.99616,0.0275487],[0.3841694,-0.9797503,0.3557433],[-0.3841694,-0.9797503,0.3557433],[-0.525,-0.99616,0.0275487],[-0.525,-1.028154,-0.6123295],[-0.3595065,-1.0401748,-0.8527471],[0.3595065,-1.0401748,-0.8527471],[0.525,-1.028154,-0.6123295],[0.505,-1.0163401,0.0244474],[0.3709815,-1.0007241,0.3367671],[-0.3709815,-1.0007241,0.3367671],[-0.505,-1.0163401,0.0244474],[-0.505,-1.0478188,-0.6051267],[-0.3489859,-1.0591512,-0.8317733],[0.3489859,-1.0591512,-0.8317733],[0.505,-1.0478188,-0.6051267]],"bolts":8}, + "Thigh.RearStep": {"solid":[[-0.31,-1.0533367,-0.166735],[-0.31,-1.0666631,-0.433265],[-0.2334315,-1.0704868,-0.509738],[0.2334315,-1.0704868,-0.509738],[0.31,-1.0666631,-0.433265],[0.31,-1.0533367,-0.166735],[0.2334315,-1.0495131,-0.090262],[-0.2334315,-1.0495131,-0.090262],[-0.35,-1.0125592,-0.1521847],[-0.35,-1.0275404,-0.4518104],[-0.25,-1.0325342,-0.5516856],[0.25,-1.0325342,-0.5516856],[0.35,-1.0275404,-0.4518104],[0.35,-1.0125592,-0.1521847],[0.25,-1.0075654,-0.0523094],[-0.25,-1.0075654,-0.0523094],[-0.35,-0.932659,-0.1561797],[-0.35,-0.9476403,-0.4558054],[-0.25,-0.9526341,-0.5556806],[0.25,-0.9526341,-0.5556806],[0.35,-0.9476403,-0.4558054],[0.35,-0.932659,-0.1561797],[0.25,-0.9276652,-0.0563044],[-0.25,-0.9276652,-0.0563044]],"facets":18,"panels":[],"bolts":0}, + "Thigh.CornerOut": {"solid":[[0.6046741,0.7607402,0.2029137],[0.6419686,0.7969987,-1.1029136],[0.6830156,0.7580089,-1.1594374],[0.7575075,0.6813887,-1.1594374],[0.7953259,0.6392598,-1.1029136],[0.7580314,0.6030012,0.2029137],[0.7169843,0.6419911,0.2594374],[0.6424925,0.7186113,0.2594374],[0.5476611,0.7610992,0.217877],[0.5859013,0.7982771,-1.1210611],[0.6439505,0.7431371,-1.2009977],[0.7415414,0.6427579,-1.2009977],[0.7950248,0.5831786,-1.1210611],[0.7567846,0.5460007,0.217877],[0.6987353,0.6011407,0.2978136],[0.6011444,0.70152,0.2978136],[0.4330328,0.6496551,0.2115088],[0.471273,0.686833,-1.1274294],[0.5293223,0.631693,-1.207366],[0.6269132,0.5313138,-1.207366],[0.6803964,0.4717345,-1.1274294],[0.6421562,0.4345566,0.2115088],[0.584107,0.4896966,0.2914454],[0.4865161,0.5900759,0.2914454]],"facets":18,"panels":[],"bolts":0}, + "Thigh.CornerIn": {"solid":[[-0.7228147,0.6258237,-0.1367753],[-0.7426594,0.6451172,-1.0632248],[-0.7111945,0.6794759,-1.1097726],[-0.6506443,0.7417562,-1.1097726],[-0.6171853,0.7741762,-1.0632248],[-0.5973406,0.7548828,-0.1367753],[-0.6288055,0.7205241,-0.0902275],[-0.6893557,0.6582438,-0.0902275],[-0.7216761,0.5689284,-0.1214086],[-0.7422302,0.5889115,-1.0809804],[-0.6949335,0.6405582,-1.1509492],[-0.6112841,0.7265977,-1.1509492],[-0.5609899,0.7753302,-1.0809804],[-0.5404358,0.755347,-0.1214086],[-0.5877325,0.7037003,-0.0514398],[-0.6713819,0.6176609,-0.0514398],[-0.6213416,0.4713809,-0.1255892],[-0.6418957,0.4913641,-1.085161],[-0.594599,0.5430108,-1.1551298],[-0.5109496,0.6290503,-1.1551298],[-0.4606554,0.6777828,-1.085161],[-0.4401013,0.6577996,-0.1255892],[-0.487398,0.6061529,-0.0556204],[-0.5710474,0.5201135,-0.0556204]],"facets":18,"panels":[],"bolts":0}, + "Thigh.Cap": {"solid":[[-0.4661148,-0.3206001,0.7921801],[0.4661148,-0.3206001,0.7921801],[0.5578418,0.2065509,0.6340348],[0.3392738,0.5031305,0.5450609],[-0.3392738,0.5031305,0.5450609],[-0.5578418,0.2065509,0.6340348],[-0.4999999,-0.370407,0.765361],[0.4999999,-0.370407,0.765361],[0.6,0.2042887,0.5929522],[0.36,0.5299496,0.4952539],[-0.36,0.5299496,0.4952539],[-0.6,0.2042887,0.5929522],[-0.4999999,-0.4106357,0.6312653],[0.4999999,-0.4106357,0.6312653],[0.6,0.16406,0.4588565],[0.36,0.4897209,0.3611582],[-0.36,0.4897209,0.3611582],[-0.6,0.16406,0.4588565]],"facets":14,"panels":[[0.3004121,0.4255465,0.5474553],[-0.3004121,0.4255465,0.5474553],[-0.4787954,0.1834945,0.620071],[-0.4025803,-0.25451,0.7514725],[0.4025803,-0.25451,0.7514725],[0.4787954,0.1834945,0.620071],[0.3004121,0.4399139,0.5953466],[-0.3004121,0.4399139,0.5953466],[-0.4787954,0.1978619,0.6679623],[-0.4025803,-0.2401427,0.7993639],[0.4025803,-0.2401427,0.7993639],[0.4787954,0.1978619,0.6679623],[0.2900489,0.4265044,0.6202502],[-0.2900489,0.4265044,0.6202502],[-0.4577163,0.198993,0.6885036],[-0.3856378,-0.2152392,0.8127734],[0.3856378,-0.2152392,0.8127734],[0.4577163,0.198993,0.6885036]],"bolts":6}, + "Shin.core": {"solid":[[-0.33,-0.3,-0.3],[0.33,-0.3,-0.3],[0.45,-0.18,-0.3],[0.45,0.38,-0.3],[0.33,0.5,-0.3],[-0.33,0.5,-0.3],[-0.45,0.38,-0.3],[-0.45,-0.18,-0.3],[-0.39,-0.34,-0.65],[0.39,-0.34,-0.65],[0.57,-0.16,-0.65],[0.57,0.42,-0.65],[0.39,0.6,-0.65],[-0.39,0.6,-0.65],[-0.57,0.42,-0.65],[-0.57,-0.16,-0.65],[-0.35,-0.34,-1.9],[0.35,-0.34,-1.9],[0.53,-0.16,-1.9],[0.53,0.38,-1.9],[0.35,0.56,-1.9],[-0.35,0.56,-1.9],[-0.53,0.38,-1.9],[-0.53,-0.16,-1.9],[-0.28,-0.3,-2.5],[0.28,-0.3,-2.5],[0.4,-0.18,-2.5],[0.4,0.28,-2.5],[0.28,0.4,-2.5],[-0.28,0.4,-2.5],[-0.4,0.28,-2.5],[-0.4,-0.18,-2.5]],"facets":26,"panels":[],"bolts":0}, + "Shin.Knee": {"solid":[[-0.58,0.9552685,0.2233251],[-0.58,1.0615354,-0.2597062],[-0.4003039,1.1117281,-0.4878551],[0.4003039,1.1117281,-0.4878551],[0.58,1.0615354,-0.2597062],[0.58,0.9552685,0.2233251],[0.3782389,0.8882719,0.5278551],[-0.3782389,0.8882719,0.5278551],[-0.62,0.9136646,0.2262673],[-0.62,1.0253928,-0.2815878],[-0.42,1.0812569,-0.5355154],[0.42,1.0812569,-0.5355154],[0.62,1.0253928,-0.2815878],[0.62,0.9136646,0.2262673],[0.4,0.8406116,0.5583265],[-0.4,0.8406116,0.5583265],[-0.62,0.67927,0.1747005],[-0.62,0.790998,-0.3331546],[-0.42,0.8468621,-0.5870823],[0.42,0.8468621,-0.5870823],[0.62,0.790998,-0.3331546],[0.62,0.67927,0.1747005],[0.4,0.606217,0.5067596],[-0.4,0.606217,0.5067596]],"facets":18,"panels":[[0.3633738,1.0760806,-0.418904],[-0.3633738,1.0760806,-0.418904],[-0.505,1.0365214,-0.2390901],[-0.505,0.9404944,0.1973966],[-0.3374369,0.8848536,0.4503096],[0.3374369,0.8848536,0.4503096],[0.505,0.9404944,0.1973966],[0.505,1.0365214,-0.2390901],[0.3633738,1.1249127,-0.408161],[-0.3633738,1.1249127,-0.408161],[-0.505,1.0853537,-0.228347],[-0.505,0.9893267,0.2081397],[-0.3374369,0.9336858,0.4610527],[0.3374369,0.9336858,0.4610527],[0.505,0.9893267,0.2081397],[0.505,1.0853537,-0.228347],[0.3535258,1.1401484,-0.3843308],[-0.3535258,1.1401484,-0.3843308],[-0.485,1.103425,-0.2174062],[-0.485,1.0101286,0.2066686],[-0.3265564,0.957516,0.445817],[0.3265564,0.957516,0.445817],[0.485,1.0101286,0.2066686],[0.485,1.103425,-0.2174062]],"bolts":8}, + "Shin.KneeSide": {"solid":[[0.589188,0.7956541,0.3317735],[0.6390487,0.8395315,-0.3317735],[0.695357,0.7870885,-0.4079614],[0.7659536,0.706865,-0.4079614],[0.810812,0.644346,-0.3317735],[0.7609513,0.6004685,0.3317735],[0.704643,0.6529116,0.4079614],[0.6340464,0.733135,0.4079614],[0.5316448,0.7982987,0.3442758],[0.5839832,0.8443565,-0.3522436],[0.6575229,0.7758648,-0.4517464],[0.7500108,0.6707649,-0.4517464],[0.8085967,0.5891139,-0.3522436],[0.7562584,0.5430561,0.3442758],[0.6827186,0.6115477,0.4437786],[0.5902307,0.7166476,0.4437786],[0.4121279,0.6931238,0.3283402],[0.4644662,0.7391816,-0.3681792],[0.5380059,0.6706899,-0.467682],[0.6304939,0.56559,-0.467682],[0.6890798,0.483939,-0.3681792],[0.6367414,0.4378812,0.3283402],[0.5632017,0.5063728,0.427843],[0.4707137,0.6114727,0.427843]],"facets":18,"panels":[],"bolts":0}, + "Shin.KneeSideIn": {"solid":[[-0.7609513,0.6004685,0.3317735],[-0.810812,0.644346,-0.3317735],[-0.7659536,0.706865,-0.4079614],[-0.695357,0.7870885,-0.4079614],[-0.6390487,0.8395315,-0.3317735],[-0.589188,0.7956541,0.3317735],[-0.6340464,0.733135,0.4079614],[-0.704643,0.6529116,0.4079614],[-0.7562584,0.5430561,0.3442758],[-0.8085967,0.5891139,-0.3522436],[-0.7500108,0.6707649,-0.4517464],[-0.6575229,0.7758648,-0.4517464],[-0.5839832,0.8443565,-0.3522436],[-0.5316448,0.7982987,0.3442758],[-0.5902307,0.7166476,0.4437786],[-0.6827186,0.6115477,0.4437786],[-0.6367414,0.4378812,0.3283402],[-0.6890798,0.483939,-0.3681792],[-0.6304939,0.56559,-0.467682],[-0.5380059,0.6706899,-0.467682],[-0.4644662,0.7391816,-0.3681792],[-0.4121279,0.6931238,0.3283402],[-0.4707137,0.6114727,0.427843],[-0.5632017,0.5063728,0.427843]],"facets":18,"panels":[],"bolts":0}, + "Shin.Greave": {"solid":[[-0.6193662,0.9073608,-0.9091315],[-0.5606605,0.8458702,-1.7875686],[-0.336,0.8164555,-2.2077785],[0.336,0.8164555,-2.2077785],[0.5606605,0.8458702,-1.7875686],[0.6193662,0.9073608,-0.9091315],[0.4752786,0.9274838,-0.6216599],[-0.4752786,0.9274838,-0.6216599],[-0.66,0.8680293,-0.8981832],[-0.6,0.8051831,-1.7959863],[-0.36,0.77376,-2.2448878],[0.36,0.77376,-2.2448878],[0.6,0.8051831,-1.7959863],[0.66,0.8680293,-0.8981832],[0.5,0.8903747,-0.5789643],[-0.5,0.8903747,-0.5789643],[-0.66,0.6286151,-0.8814242],[-0.6,0.565769,-1.7792274],[-0.36,0.5343457,-2.2281287],[0.36,0.5343457,-2.2281287],[0.6,0.565769,-1.7792274],[0.66,0.6286151,-0.8814242],[0.5,0.6509604,-0.5622053],[-0.5,0.6509604,-0.5622053]],"facets":18,"panels":[[-0.1732338,0.8017416,-2.1315651],[-0.291,0.8017416,-2.1315651],[-0.4868988,0.8273906,-1.7651516],[-0.5431778,0.8863394,-0.9230259],[-0.4289261,0.9022955,-0.6950803],[-0.1732337,0.9022955,-0.6950803],[-0.1732338,0.8416439,-2.1343582],[-0.291,0.8416439,-2.1343582],[-0.4868988,0.8672929,-1.7679448],[-0.5431778,0.9262417,-0.9258191],[-0.4289261,0.9421979,-0.6978735],[-0.1732337,0.9421979,-0.6978735],[-0.1932338,0.8629917,-2.1158037],[-0.279,0.8629917,-2.1158037],[-0.467229,0.8876365,-1.7637359],[-0.5228609,0.9459075,-0.9312932],[-0.4165654,0.9607525,-0.7192212],[-0.1932337,0.9607525,-0.7192212],[0.4868988,0.8273906,-1.7651516],[0.291,0.8017416,-2.1315651],[0.0217662,0.8017416,-2.1315651],[0.0217663,0.9022955,-0.6950803],[0.4289261,0.9022955,-0.6950803],[0.5431778,0.8863394,-0.9230259],[0.4868988,0.8972197,-1.7700397],[0.291,0.8715707,-2.1364532],[0.0217662,0.8715707,-2.1364532],[0.0217663,0.9721246,-0.6999683],[0.4289261,0.9721247,-0.6999683],[0.5431778,0.9561685,-0.927914],[0.467229,0.9175633,-1.7658308],[0.279,0.8929185,-2.1178985],[0.0417663,0.8929185,-2.1178985],[0.0417663,0.9906793,-0.721316],[0.4165654,0.9906793,-0.721316],[0.5228609,0.9758343,-0.9333881]],"bolts":12}, + "Shin.GreaveStep": {"solid":[[-0.27,0.9897918,-0.9172604],[-0.27,0.9502082,-1.4827397],[-0.1734315,0.9434649,-1.5790725],[0.1734315,0.9434649,-1.5790725],[0.27,0.9502082,-1.4827397],[0.27,0.9897918,-0.9172604],[0.1734315,0.9965351,-0.8209276],[-0.1734315,0.9965351,-0.8209276],[-0.31,0.9510465,-0.8979391],[-0.31,0.9091489,-1.4964746],[-0.19,0.9007695,-1.6161816],[0.19,0.9007695,-1.6161816],[0.31,0.9091489,-1.4964746],[0.31,0.9510465,-0.8979391],[0.19,0.9594259,-0.7782321],[-0.19,0.9594259,-0.7782321],[-0.31,0.8413149,-0.890258],[-0.31,0.7994174,-1.4887935],[-0.19,0.7910379,-1.6085005],[0.19,0.7910379,-1.6085005],[0.31,0.7994174,-1.4887935],[0.31,0.8413149,-0.890258],[0.19,0.8496944,-0.7705509],[-0.19,0.8496944,-0.7705509]],"facets":18,"panels":[],"bolts":0}, + "Shin.Outer": {"solid":[[0.8562673,-1.1066836,-1.1461235],[0.8429071,-0.7726778,-1.8337708],[0.809351,0.0662256,-1.9673394],[0.7935917,0.4602057,-1.5824323],[0.7920528,0.4986797,-0.7064488],[0.8069738,0.1256552,-0.3517922],[0.8487253,-0.9181325,-0.4667965],[0.8180016,-1.1508397,-1.15],[0.8040128,-0.8011193,-1.8699999],[0.7688409,0.0781775,-2.01],[0.7520543,0.497842,-1.5999999],[0.7504556,0.53781,-0.6899999],[0.7664428,0.1381296,-0.3099999],[0.810008,-0.9509994,-0.4299999],[0.5981774,-1.1596327,-1.15],[0.5841886,-0.8099123,-1.8699999],[0.5490167,0.0693846,-2.01],[0.5322301,0.489049,-1.5999999],[0.5306314,0.529017,-0.6899999],[0.5466186,0.1293367,-0.3099999],[0.5901837,-0.9597924,-0.4299999]],"facets":16,"panels":[[0.7751235,0.4215133,-0.7372904],[0.7880453,0.0984686,-0.4301527],[0.8063356,-0.3587885,-0.4805332],[0.8003194,-0.2083839,-1.8478006],[0.7903833,0.0400187,-1.8873508],[0.7765504,0.3858406,-1.5494928],[0.8150916,0.423112,-0.7372904],[0.8280134,0.1000673,-0.4301527],[0.8463036,-0.3571897,-0.4805332],[0.8402874,-0.2067852,-1.8478006],[0.8303514,0.0416175,-1.8873509],[0.8165184,0.3874393,-1.549493],[0.8358902,0.4035468,-0.7455149],[0.8482788,0.0938301,-0.4510488],[0.8654056,-0.3343395,-0.4982244],[0.8595436,-0.1877901,-1.8304462],[0.8506064,0.0356415,-1.8660206],[0.8372872,0.3686212,-1.5407091],[0.8140826,-0.5524625,-0.5018721],[0.8263962,-0.8603038,-0.53579],[0.8330916,-1.027688,-1.1388552],[0.82091,-0.7231468,-1.765841],[0.8083001,-0.4078998,-1.8160341],[0.8840266,-0.5496647,-0.5018721],[0.8963403,-0.857506,-0.53579],[0.9030357,-1.0248903,-1.1388552],[0.890854,-0.7203491,-1.7658411],[0.8782442,-0.405102,-1.8160342],[0.9047178,-0.5665425,-0.5239406],[0.9156989,-0.8410726,-0.5541883],[0.9221686,-1.0028123,-1.136917],[0.9103012,-0.7061283,-1.7477266],[0.8991374,-0.4270333,-1.7921635]],"bolts":11}, + "Shin.OuterStep": {"solid":[[0.9406667,-0.7166683,-1.0460328],[0.933356,-0.5339003,-1.4027153],[0.9140334,-0.0508353,-1.4584981],[0.9039803,0.2004944,-1.2788334],[0.9032401,0.218997,-0.8159006],[0.9126254,-0.0156337,-0.5810822],[0.9355723,-0.5893077,-0.6181231],[0.9024141,-0.7611513,-1.05],[0.8944205,-0.5613111,-1.4400001],[0.8736371,-0.0417266,-1.5],[0.8624461,0.2380497,-1.3],[0.8616467,0.2580338,-0.8],[0.8720384,-0.0017585,-0.54],[0.8968186,-0.6212631,-0.58],[0.812486,-0.7647484,-1.05],[0.8044924,-0.5649082,-1.4400001],[0.783709,-0.0453237,-1.5],[0.772518,0.2344526,-1.3],[0.7717186,0.2544366,-0.8],[0.7821103,-0.0053556,-0.54],[0.8068905,-0.6248603,-0.58]],"facets":16,"panels":[],"bolts":0}, + "Shin.Inner": {"solid":[[-0.8122908,-0.9272723,-1.1955323],[-0.8008983,-0.6424584,-1.8036211],[-0.7705547,0.1161316,-1.9175006],[-0.7567852,0.4603711,-1.582297],[-0.7552532,0.4986687,-0.815732],[-0.7685975,0.1650628,-0.4818593],[-0.806675,-0.7868745,-0.5866562],[-0.7740048,-0.9709196,-1.2],[-0.7620144,-0.6711593,-1.84],[-0.73004,0.1282015,-1.96],[-0.7152518,0.4979059,-1.6],[-0.713653,0.537874,-0.8],[-0.7280415,0.1781616,-0.44],[-0.7680096,-0.8210394,-0.55],[-0.5941486,-0.9781139,-1.2],[-0.5821582,-0.6783535,-1.84],[-0.5501838,0.1210073,-1.96],[-0.5353956,0.4907117,-1.6],[-0.5337968,0.5306797,-0.8],[-0.5481853,0.1709673,-0.44],[-0.5881534,-0.8282337,-0.55]],"facets":16,"panels":[[-0.7397362,0.3861963,-1.549104],[-0.7515959,0.0897034,-1.8378143],[-0.7788817,-0.5924411,-1.7354107],[-0.7891533,-0.8492304,-1.1871556],[-0.7842486,-0.7266124,-0.6553865],[-0.7497159,0.1367056,-0.5603455],[-0.7383296,0.421362,-0.8452296],[-0.7896963,0.3881947,-1.5491039],[-0.801556,0.0917018,-1.8378142],[-0.8288417,-0.5904427,-1.7354107],[-0.8391134,-0.847232,-1.1871556],[-0.8342086,-0.724614,-0.6553865],[-0.7996759,0.138704,-0.5603455],[-0.7882897,0.4233604,-0.8452296],[-0.810463,0.3694274,-1.5402523],[-0.8218134,0.0856668,-1.8165646],[-0.8482838,-0.5760922,-1.7172213],[-0.8582564,-0.8254083,-1.1849217],[-0.8535413,-0.7075315,-0.6737146],[-0.8199539,0.1321546,-0.5812752],[-0.8090897,0.4037578,-0.8530955]],"bolts":7}, + "Shin.Calf": {"solid":[[-0.6383086,-1.1102328,-0.8523283],[-0.468769,-1.1777122,-1.5271215],[0.468769,-1.1777122,-1.5271215],[0.6383086,-1.1102328,-0.8523283],[0.4715175,-1.0622878,-0.3728784],[-0.4715175,-1.0622878,-0.3728784],[-0.68,-1.0702481,-0.8544765],[-0.5,-1.1418909,-1.5709033],[0.5,-1.1418909,-1.5709033],[0.68,-1.0702481,-0.8544765],[0.5,-1.0185062,-0.3370571],[-0.5,-1.0185062,-0.3370571],[-0.68,-0.8911414,-0.8723871],[-0.5,-0.9627842,-1.5888139],[0.5,-0.9627842,-1.5888139],[0.68,-0.8911414,-0.8723871],[0.5,-0.8393995,-0.3549677],[-0.5,-0.8393995,-0.3549677]],"facets":14,"panels":[[-0.4102107,-1.1503487,-1.4544837],[0.4102107,-1.1503487,-1.4544837],[0.5601374,-1.0906755,-0.8577533],[0.4181128,-1.0498497,-0.4494962],[-0.4181128,-1.0498497,-0.4494962],[-0.5601374,-1.0906755,-0.8577534],[-0.4102107,-1.2001004,-1.4495087],[0.4102107,-1.2001004,-1.4495087],[0.5601374,-1.1404274,-0.8527782],[0.4181128,-1.0996016,-0.444521],[-0.4181128,-1.0996016,-0.444521],[-0.5601374,-1.1404274,-0.8527782],[-0.3945952,-1.2180111,-1.4276178],[0.3945952,-1.2180111,-1.4276178],[0.5392917,-1.1604197,-0.8517041],[0.4038715,-1.1214925,-0.4624317],[-0.4038715,-1.1214925,-0.4624317],[-0.5392917,-1.1604197,-0.8517041]],"bolts":6}, + "Shin.CalfStep": {"solid":[[-0.32,-1.1887132,-0.9371314],[-0.32,-1.2112869,-1.1628685],[-0.2434314,-1.2189058,-1.2390571],[0.2434314,-1.2189058,-1.2390571],[0.32,-1.2112869,-1.1628685],[0.32,-1.1887132,-0.9371314],[0.2434314,-1.1810943,-0.8609428],[-0.2434314,-1.1810943,-0.8609428],[-0.36,-1.1472631,-0.9246253],[-0.36,-1.1731341,-1.1833349],[-0.26,-1.1830844,-1.2828387],[0.26,-1.1830844,-1.2828387],[0.36,-1.1731341,-1.1833349],[0.36,-1.1472631,-0.9246253],[0.26,-1.1373128,-0.8251215],[-0.26,-1.1373128,-0.8251215],[-0.36,-1.0676601,-0.9325855],[-0.36,-1.0935311,-1.1912953],[-0.26,-1.1034814,-1.290799],[0.26,-1.1034814,-1.290799],[0.36,-1.0935311,-1.1912953],[0.36,-1.0676601,-0.9325855],[0.26,-1.0577098,-0.8330818],[-0.26,-1.0577098,-0.8330818]],"facets":18,"panels":[],"bolts":0}, + "Shin.Ankle": {"solid":[[-0.36,0.6842069,-2.2989655],[-0.36,0.6357931,-2.5410347],[-0.2634315,0.6168545,-2.6357279],[0.2634315,0.6168545,-2.6357279],[0.36,0.6357931,-2.5410347],[0.36,0.6842069,-2.2989655],[0.2634315,0.7031456,-2.2042723],[-0.2634315,0.7031456,-2.2042723],[-0.4000001,0.6482331,-2.274874],[-0.4000001,0.5933205,-2.5494368],[-0.28,0.5697865,-2.6671064],[0.28,0.5697865,-2.6671064],[0.4000001,0.5933205,-2.5494368],[0.4000001,0.6482331,-2.274874],[0.28,0.671767,-2.1572044],[-0.28,0.671767,-2.1572044],[-0.4000001,0.4913402,-2.2434955],[-0.4000001,0.4364276,-2.5180583],[-0.28,0.4128937,-2.6357279],[0.28,0.4128937,-2.6357279],[0.4000001,0.4364276,-2.5180583],[0.4000001,0.4913402,-2.2434955],[0.28,0.5148741,-2.1258259],[-0.28,0.5148741,-2.1258259]],"facets":18,"panels":[[-0.285,0.6222742,-2.5066495],[-0.285,0.6585029,-2.3255057],[-0.2323655,0.6688253,-2.2738934],[0.2323655,0.6688253,-2.2738934],[0.2850001,0.6585029,-2.3255057],[0.285,0.6222742,-2.5066495],[0.2323654,0.6119516,-2.5582621],[-0.2323654,0.6119516,-2.5582621],[-0.285,0.6909148,-2.5203776],[-0.285,0.7271435,-2.3392339],[-0.2323655,0.737466,-2.2876215],[0.2323655,0.737466,-2.2876215],[0.2850001,0.7271435,-2.3392339],[0.285,0.6909148,-2.5203776],[0.2323654,0.6805923,-2.5719903],[-0.2323654,0.6805923,-2.5719903],[-0.265,0.7121511,-2.5161765],[-0.265,0.7451305,-2.3512797],[-0.2240812,0.7531553,-2.3111556],[0.2240812,0.7531553,-2.3111556],[0.265,0.7451305,-2.3512797],[0.265,0.7121511,-2.5161765],[0.2240812,0.7041262,-2.5563009],[-0.2240812,0.7041262,-2.5563009]],"bolts":8}, + "Shin.AnkleSide": {"solid":[[0.6420218,-0.207344,-2.2371259],[0.6196706,-0.2095791,-2.4628739],[0.6005474,-0.1144412,-2.5589681],[0.5580729,0.3103032,-2.5589681],[0.5579782,0.407344,-2.4628739],[0.5803295,0.4095791,-2.2371259],[0.5994527,0.3144412,-2.1410317],[0.6419272,-0.1103032,-2.1410317],[0.6080284,-0.2509428,-2.2166781],[0.5824124,-0.2535044,-2.4754004],[0.5586491,-0.1352822,-2.5948107],[0.5128774,0.3224349,-2.5948107],[0.5127598,0.4430216,-2.4754004],[0.5383759,0.4455832,-2.2166781],[0.5621391,0.327361,-2.0972679],[0.6079108,-0.130356,-2.0972679],[0.4892107,-0.2628246,-2.2047963],[0.4635947,-0.2653862,-2.4635186],[0.4398314,-0.147164,-2.5829289],[0.3940597,0.3105531,-2.5829289],[0.3939421,0.4311398,-2.4635186],[0.4195582,0.4337015,-2.2047963],[0.4433214,0.3154793,-2.085386],[0.4890931,-0.1422378,-2.085386]],"facets":18,"panels":[],"bolts":0}, + "Pelvis.core": {"solid":[[0.62,0.62,0.5],[0.62,-0.6,0.5],[0.72,0.7,-0.3],[0.72,-0.62,-0.3],[0.45,0.7,0.62],[0.45,-0.66,0.62],[0.4,0.55,-0.8],[0.4,-0.45,-0.8],[-0.62,0.62,0.5],[-0.62,-0.6,0.5],[-0.72,0.7,-0.3],[-0.72,-0.62,-0.3],[-0.45,0.7,0.62],[-0.45,-0.66,0.62],[-0.4,0.55,-0.8],[-0.4,-0.45,-0.8]],"facets":16,"panels":[],"bolts":0}, + "Pelvis.Crown": {"solid":[[-0.4339507,0.993916,0.4580249],[-0.2759168,1.0410775,0.1632654],[0.2759168,1.0410775,0.1632654],[0.4339507,0.993916,0.4580249],[0.2976482,0.9589224,0.6767346],[-0.2976482,0.9589224,0.6767346],[-0.48,0.9541827,0.453178],[-0.3,1.0078995,0.1174481],[0.3,1.0078995,0.1174481],[0.48,0.9541827,0.453178],[0.32,0.9131052,0.7099125],[-0.32,0.9131052,0.7099125],[-0.48,0.6974481,0.4121005],[-0.3,0.7511649,0.0763706],[0.3,0.7511649,0.0763706],[0.48,0.6974481,0.4121005],[0.32,0.6563706,0.668835],[-0.32,0.6563706,0.668835]],"facets":14,"panels":[[0.2307606,1.0094794,0.2341636],[-0.2307606,1.0094794,0.2341636],[-0.3476081,0.9746091,0.4521036],[-0.2557386,0.951023,0.5995167],[0.2557386,0.951023,0.5995167],[0.3476081,0.9746091,0.4521036],[0.2307606,1.0588515,0.2420631],[-0.2307606,1.0588515,0.2420631],[-0.3476081,1.0239811,0.4600031],[-0.2557386,1.0003949,0.6074162],[0.2557386,1.0003949,0.6074162],[0.3476081,1.0239811,0.4600031],[0.218719,1.0754405,0.2649717],[-0.218719,1.0754405,0.2649717],[-0.3245834,1.0438477,0.4624265],[-0.2445627,1.0233036,0.5908272],[0.2445627,1.0233036,0.5908272],[0.3245834,1.0438477,0.4624265]],"bolts":6}, + "Pelvis.Cod": {"solid":[[-0.3994854,1.089713,-0.3228698],[-0.2648505,0.9863672,-1.3563275],[0.2648505,0.9863672,-1.3563275],[0.3994854,1.089713,-0.3228698],[0.3272079,1.1256723,0.0367246],[-0.3272079,1.1256723,0.0367246],[-0.44,1.0500495,-0.3175087],[-0.3,0.9425856,-1.3921489],[0.3,0.9425856,-1.3921489],[0.44,1.0500495,-0.3175087],[0.36,1.089851,0.0805062],[-0.36,1.089851,0.0805062],[-0.44,0.7515384,-0.2876576],[-0.3,0.6440744,-1.3622978],[0.3,0.6440744,-1.3622978],[0.44,0.7515384,-0.2876576],[0.36,0.7913399,0.1103573],[-0.36,0.7913399,0.1103573]],"facets":14,"panels":[[0.3235205,1.0695533,-0.323469],[0.2698343,1.0283437,-0.7355647],[-0.2790578,1.0354236,-0.6647651],[-0.3235206,1.0695533,-0.323469],[-0.2657226,1.0983088,-0.0359131],[0.2657225,1.0983088,-0.0359132],[0.3235206,1.1093547,-0.3274492],[0.2698343,1.0681452,-0.7395448],[-0.2790578,1.0752251,-0.6687453],[-0.3235206,1.1093547,-0.3274492],[-0.2657226,1.1381103,-0.0398933],[0.2657225,1.1381103,-0.0398933],[0.3032633,1.1291864,-0.3301297],[0.2525714,1.0902753,-0.719241],[-0.2612047,1.0969024,-0.6529709],[-0.3032633,1.1291864,-0.3301297],[-0.2493265,1.156021,-0.0617841],[0.2493265,1.156021,-0.0617842],[0.2447663,1.0091016,-0.927987],[0.1989452,0.9739293,-1.2797097],[-0.1989452,0.9739293,-1.2797097],[-0.2531329,1.0155238,-0.8637649],[0.2447663,1.0787542,-0.9349523],[0.1989452,1.043582,-1.2866749],[-0.1989452,1.043582,-1.2866749],[-0.2531329,1.0851763,-0.8707301],[0.2223611,1.0969372,-0.9541196],[0.1813705,1.0654727,-1.2687643],[-0.1813705,1.0654727,-1.2687643],[-0.2299619,1.1027715,-0.8957762]],"bolts":10}, + "Pelvis.CodStep": {"solid":[[-0.21,1.1792967,-0.2070322],[-0.21,1.1607032,-0.3929678],[-0.1334315,1.1530843,-0.4691563],[0.1334315,1.1530843,-0.4691563],[0.21,1.1607032,-0.3929678],[0.21,1.1792967,-0.2070322],[0.1334315,1.1869156,-0.1308437],[-0.1334315,1.1869156,-0.1308437],[-0.25,1.1411439,-0.1865658],[-0.25,1.119253,-0.4054739],[-0.15,1.1093026,-0.5049777],[0.15,1.1093026,-0.5049777],[0.25,1.119253,-0.4054739],[0.25,1.1411439,-0.1865658],[0.15,1.1510943,-0.087062],[-0.15,1.1510943,-0.087062],[-0.25,1.0416402,-0.1766154],[-0.25,1.0197493,-0.3955236],[-0.15,1.0097989,-0.4950273],[0.15,1.0097989,-0.4950273],[0.25,1.0197493,-0.3955236],[0.25,1.0416402,-0.1766154],[0.15,1.0515906,-0.0771117],[-0.15,1.0515906,-0.0771117]],"facets":18,"panels":[],"bolts":0}, + "Pelvis.CodLame": {"solid":[[-0.17,1.1602918,-0.9170818],[-0.17,1.1397082,-1.1229181],[-0.1134315,1.1340793,-1.1792059],[0.1134315,1.1340793,-1.1792059],[0.17,1.1397082,-1.1229181],[0.17,1.1602918,-0.9170818],[0.1134315,1.1659206,-0.860794],[-0.1134315,1.1659206,-0.860794],[-0.21,1.122139,-0.8966154],[-0.21,1.098258,-1.1354243],[-0.13,1.0902977,-1.2150273],[0.13,1.0902977,-1.2150273],[0.21,1.098258,-1.1354243],[0.21,1.122139,-0.8966154],[0.13,1.1300993,-0.8170124],[-0.13,1.1300993,-0.8170124],[-0.21,1.0325856,-0.8876601],[-0.21,1.0087047,-1.1264689],[-0.13,1.0007443,-1.206072],[0.13,1.0007443,-1.206072],[0.21,1.0087047,-1.1264689],[0.21,1.0325856,-0.8876601],[0.13,1.0405459,-0.8080571],[-0.13,1.0405459,-0.8080571]],"facets":18,"panels":[],"bolts":0}, + "Pelvis.Wing.R": {"solid":[[0.5347595,1.0175078,0.1903216],[1.323531,0.7627897,0.2807549],[1.3916267,0.679267,0.5962243],[1.3032885,0.6646943,0.8015956],[0.5202285,0.9690713,0.4543006],[0.4875739,0.9994265,0.1389033],[1.3442112,0.7227925,0.2371175],[1.4205314,0.6291823,0.5906884],[1.3106923,0.6110626,0.8460452],[0.4691925,0.9381554,0.4728314],[0.436775,0.8300968,0.1050373],[1.2934123,0.5534627,0.2032515],[1.3697325,0.4598526,0.5568224],[1.2598934,0.4417329,0.8121792],[0.4183936,0.7688256,0.4389654]],"facets":12,"panels":[[1.3106201,0.6838076,0.5887305],[1.2579452,0.7484159,0.3447013],[0.5964219,0.9620417,0.2688571],[0.5891105,0.9376703,0.4016816],[1.2625957,0.6758852,0.7003791],[1.3303752,0.7496581,0.6019005],[1.2777003,0.8142664,0.3578714],[0.616177,1.0278922,0.2820272],[0.6088656,1.0035207,0.4148517],[1.2823509,0.7417357,0.7135491],[1.3159229,0.7747005,0.6046685],[1.2673602,0.834265,0.3796901],[0.6397699,1.0369328,0.3077363],[0.6343836,1.0189787,0.4055862],[1.2786489,0.7685515,0.6913244]],"bolts":5}, + "Pelvis.Wing.L": {"solid":[[-0.5347595,1.0175078,0.1903216],[-1.323531,0.7627897,0.2807549],[-1.3916267,0.679267,0.5962243],[-1.3032885,0.6646943,0.8015956],[-0.5202285,0.9690713,0.4543006],[-0.4875739,0.9994265,0.1389033],[-1.3442112,0.7227925,0.2371175],[-1.4205314,0.6291823,0.5906884],[-1.3106923,0.6110626,0.8460452],[-0.4691925,0.9381554,0.4728314],[-0.436775,0.8300968,0.1050373],[-1.2934123,0.5534627,0.2032515],[-1.3697325,0.4598526,0.5568224],[-1.2598934,0.4417329,0.8121792],[-0.4183936,0.7688256,0.4389654]],"facets":12,"panels":[[-1.2625957,0.6758852,0.700379],[-0.5891104,0.9376704,0.4016816],[-0.5964218,0.9620418,0.2688571],[-1.2579452,0.7484159,0.3447012],[-1.3106201,0.6838076,0.5887305],[-1.2823508,0.7417357,0.7135491],[-0.6088656,1.0035208,0.4148517],[-0.616177,1.0278922,0.2820272],[-1.2777003,0.8142664,0.3578713],[-1.3303752,0.7496581,0.6019005],[-1.2786489,0.7685515,0.6913244],[-0.6343836,1.0189787,0.4055862],[-0.6397698,1.0369328,0.3077363],[-1.2673602,0.834265,0.37969],[-1.315923,0.7747005,0.6046684]],"bolts":5}, + "Pelvis.HipGuard.R": {"solid":[[0.4939981,0.9528628,0.1032474],[0.491051,0.9381275,-0.2032474],[0.5459777,0.9243171,-0.2597481],[0.6899887,0.8955149,-0.2597481],[0.746002,0.8871372,-0.2032474],[0.7489491,0.9018726,0.1032474],[0.6940223,0.915683,0.1597481],[0.5500113,0.9444851,0.1597481],[0.4470987,0.9223269,0.1217549],[0.4438334,0.9060003,-0.2178373],[0.5215116,0.8864695,-0.2977413],[0.6980162,0.8511686,-0.2977413],[0.7772309,0.8393208,-0.2178373],[0.7804962,0.8556474,0.1217549],[0.702818,0.8751782,0.2016589],[0.5263134,0.9104791,0.2016589],[0.423593,0.8047984,0.1276313],[0.4203277,0.7884718,-0.2119608],[0.4980058,0.768941,-0.2918648],[0.6745104,0.7336401,-0.2918648],[0.7537252,0.7217923,-0.2119608],[0.7569904,0.7381189,0.1276313],[0.6793123,0.7576497,0.2075353],[0.5028077,0.7929506,0.2075353]],"facets":18,"panels":[],"bolts":0}, + "Pelvis.HipGuard.L": {"solid":[[-0.4939981,0.9528628,0.1032474],[-0.491051,0.9381275,-0.2032474],[-0.5459777,0.9243171,-0.2597481],[-0.6899887,0.8955149,-0.2597481],[-0.746002,0.8871372,-0.2032474],[-0.7489491,0.9018726,0.1032474],[-0.6940223,0.915683,0.1597481],[-0.5500113,0.9444851,0.1597481],[-0.4470987,0.9223269,0.1217549],[-0.4438334,0.9060003,-0.2178373],[-0.5215116,0.8864695,-0.2977413],[-0.6980162,0.8511686,-0.2977413],[-0.7772309,0.8393208,-0.2178373],[-0.7804962,0.8556474,0.1217549],[-0.702818,0.8751782,0.2016589],[-0.5263134,0.9104791,0.2016589],[-0.423593,0.8047984,0.1276313],[-0.4203277,0.7884718,-0.2119608],[-0.4980058,0.768941,-0.2918648],[-0.6745104,0.7336401,-0.2918648],[-0.7537252,0.7217923,-0.2119608],[-0.7569904,0.7381189,0.1276313],[-0.6793123,0.7576497,0.2075353],[-0.5028077,0.7929506,0.2075353]],"facets":18,"panels":[],"bolts":0}, + "Pelvis.Seat.R": {"solid":[[0.1226936,-1.0131552,-0.5494777],[0.7555954,-0.897684,-0.7871495],[1.1097059,-0.7580597,-0.1699502],[0.9993517,-0.6958846,0.6945797],[0.0977462,-0.8997577,0.6393812],[0.075655,-0.9855092,-0.5810469],[0.7647362,-0.8597882,-0.8398157],[1.14161,-0.7111885,-0.182941],[1.0247313,-0.6453375,0.7327026],[0.0493399,-0.8658952,0.6729866],[0.0328861,-0.7911053,-0.6004874],[0.7219673,-0.6653842,-0.8592561],[1.0988411,-0.5167845,-0.2023814],[0.9819624,-0.4509336,0.7132621],[0.006571,-0.6714912,0.6535462]],"facets":12,"panels":[[1.0295707,-0.7536014,-0.1548266],[0.9314498,-0.6983188,0.6138653],[0.1681929,-0.8709082,0.5671368],[0.190576,-0.9726495,-0.4995194],[0.7181413,-0.8763967,-0.6976346],[1.0402629,-0.8022023,-0.1499665],[0.9421421,-0.7469198,0.6187254],[0.1788851,-0.9195092,0.5719969],[0.2012682,-1.0212505,-0.4946593],[0.7288335,-0.9249977,-0.6927745],[1.0243109,-0.825638,-0.1434711],[0.9294523,-0.7721934,0.5996639],[0.2030882,-0.9364405,0.5551941],[0.2247875,-1.0350735,-0.4788747],[0.7242631,-0.9439455,-0.6664414]],"bolts":5}, + "Pelvis.Seat.L": {"solid":[[-0.1226936,-1.0131552,-0.5494777],[-0.7555954,-0.897684,-0.7871495],[-1.1097059,-0.7580597,-0.1699502],[-0.9993517,-0.6958846,0.6945797],[-0.0977462,-0.8997577,0.6393812],[-0.075655,-0.9855092,-0.5810469],[-0.7647362,-0.8597882,-0.8398157],[-1.14161,-0.7111885,-0.182941],[-1.0247313,-0.6453375,0.7327026],[-0.0493399,-0.8658952,0.6729866],[-0.0328861,-0.7911053,-0.6004874],[-0.7219673,-0.6653842,-0.8592561],[-1.0988411,-0.5167845,-0.2023814],[-0.9819624,-0.4509336,0.7132621],[-0.006571,-0.6714912,0.6535462]],"facets":12,"panels":[[-1.0295707,-0.7536014,-0.1548266],[-0.7181413,-0.8763967,-0.6976346],[-0.190576,-0.9726496,-0.4995195],[-0.1681929,-0.8709082,0.5671368],[-0.9314499,-0.6983188,0.6138653],[-1.0402629,-0.8022023,-0.1499665],[-0.7288336,-0.9249976,-0.6927745],[-0.2012682,-1.0212506,-0.4946594],[-0.1788851,-0.9195092,0.5719969],[-0.9421421,-0.7469198,0.6187254],[-1.0243108,-0.825638,-0.1434711],[-0.7242632,-0.9439455,-0.6664413],[-0.2247876,-1.0350735,-0.4788747],[-0.2030883,-0.9364405,0.5551941],[-0.9294524,-0.7721934,0.5996639]],"bolts":5}, + "Pelvis.SeatStep.R": {"solid":[[0.3621921,-0.9860519,0.2626576],[0.3690186,-1.0170816,-0.0626576],[0.4653486,-1.0055002,-0.1587689],[0.7455117,-0.9438643,-0.1587689],[0.837808,-0.913948,-0.0626576],[0.8309814,-0.8829183,0.2626576],[0.7346514,-0.8944998,0.3587689],[0.4544884,-0.9561356,0.3587689],[0.3142265,-0.9541928,0.2752596],[0.3217451,-0.9883682,-0.0830357],[0.4414486,-0.9739767,-0.2024675],[0.7539749,-0.9052209,-0.2024675],[0.8686661,-0.8680456,-0.0830357],[0.8611474,-0.8338702,0.2752596],[0.7414439,-0.8482618,0.3946913],[0.4289176,-0.9170176,0.3946913],[0.2971189,-0.8764312,0.2674834],[0.3046375,-0.9106066,-0.0908119],[0.4243411,-0.8962151,-0.2102437],[0.7368673,-0.8274593,-0.2102437],[0.8515585,-0.790284,-0.0908119],[0.8440399,-0.7561086,0.2674834],[0.7243363,-0.7705002,0.3869152],[0.4118101,-0.839256,0.3869152]],"facets":18,"panels":[],"bolts":0}, + "Pelvis.SeatStep.L": {"solid":[[-0.3621921,-0.9860519,0.2626576],[-0.3690186,-1.0170816,-0.0626576],[-0.4653486,-1.0055002,-0.1587689],[-0.7455117,-0.9438643,-0.1587689],[-0.837808,-0.913948,-0.0626576],[-0.8309814,-0.8829183,0.2626576],[-0.7346514,-0.8944998,0.3587689],[-0.4544884,-0.9561356,0.3587689],[-0.3142265,-0.9541928,0.2752596],[-0.3217451,-0.9883682,-0.0830357],[-0.4414486,-0.9739767,-0.2024675],[-0.7539749,-0.9052209,-0.2024675],[-0.8686661,-0.8680456,-0.0830357],[-0.8611474,-0.8338702,0.2752596],[-0.7414439,-0.8482618,0.3946913],[-0.4289176,-0.9170176,0.3946913],[-0.2971189,-0.8764312,0.2674834],[-0.3046375,-0.9106066,-0.0908119],[-0.4243411,-0.8962151,-0.2102437],[-0.7368673,-0.8274593,-0.2102437],[-0.8515585,-0.790284,-0.0908119],[-0.8440399,-0.7561086,0.2674834],[-0.7243363,-0.7705002,0.3869152],[-0.4118101,-0.839256,0.3869152]],"facets":18,"panels":[],"bolts":0}, + "Pelvis.Tail": {"solid":[[-0.14,-0.9466383,0.3327659],[-0.14,-0.8933617,-0.7327659],[-0.0634315,-0.889538,-0.8092389],[0.0634315,-0.889538,-0.8092389],[0.14,-0.8933617,-0.7327659],[0.14,-0.9466383,0.3327659],[0.0634315,-0.950462,0.4092389],[-0.0634315,-0.950462,0.4092389],[-0.18,-0.9075156,0.3513113],[-0.18,-0.8525842,-0.7473162],[-0.08,-0.8475905,-0.8471915],[0.08,-0.8475905,-0.8471915],[0.18,-0.8525842,-0.7473162],[0.18,-0.9075156,0.3513113],[0.08,-0.9125094,0.4511865],[-0.08,-0.9125094,0.4511865],[-0.18,-0.7277402,0.3603001],[-0.18,-0.6728088,-0.7383275],[-0.08,-0.6678151,-0.8382027],[0.08,-0.6678151,-0.8382027],[0.18,-0.6728088,-0.7383275],[0.18,-0.7277402,0.3603001],[0.08,-0.732734,0.4601753],[-0.08,-0.732734,0.4601753]],"facets":18,"panels":[[-0.0323655,-0.9267415,0.3353312],[-0.065,-0.9251118,0.3027374],[-0.065,-0.874938,-0.7007399],[-0.0323655,-0.8733082,-0.7333337],[0.0323655,-0.8733082,-0.7333337],[0.065,-0.874938,-0.7007399],[0.065,-0.9251118,0.3027374],[0.0323655,-0.9267415,0.3353312],[-0.0323655,-0.9666916,0.3333337],[-0.065,-0.9650619,0.3007399],[-0.065,-0.914888,-0.7027373],[-0.0323655,-0.9132584,-0.7353312],[0.0323655,-0.9132584,-0.7353312],[0.065,-0.914888,-0.7027373],[0.065,-0.9650619,0.3007399],[0.0323655,-0.9666916,0.3333337],[-0.0240812,-0.9856679,0.31236],[-0.045,-0.9846233,0.2914672],[-0.045,-0.9352768,-0.6954622],[-0.0240812,-0.9342322,-0.716355],[0.0240812,-0.9342322,-0.716355],[0.045,-0.9352768,-0.6954622],[0.045,-0.9846233,0.2914672],[0.0240812,-0.9856679,0.31236]],"bolts":8}, + "Pelvis.Roof.R": {"solid":[[0.3677629,0.3934315,0.7630593],[0.3677629,-0.3934315,0.7630593],[0.4808511,-0.51,0.7347872],[0.759149,-0.51,0.6652128],[0.8722371,-0.3934315,0.6369407],[0.8722371,0.3934315,0.6369407],[0.759149,0.51,0.6652128],[0.4808511,0.51,0.7347872],[0.3192558,0.41,0.733955],[0.3192558,-0.41,0.733955],[0.4550758,-0.55,0.7],[0.7655213,-0.55,0.6223885],[0.9013414,-0.41,0.5884336],[0.9013414,0.41,0.5884336],[0.7655213,0.55,0.6223885],[0.4550758,0.55,0.7],[0.2950023,0.41,0.6369407],[0.2950023,-0.41,0.6369407],[0.4308222,-0.55,0.6029857],[0.7412678,-0.55,0.5253743],[0.8770878,-0.41,0.4914193],[0.8770878,0.41,0.4914193],[0.7412678,0.55,0.5253743],[0.4308222,0.55,0.6029857]],"facets":18,"panels":[],"bolts":0}, + "Pelvis.Roof.L": {"solid":[[-0.3677629,0.3934315,0.7630593],[-0.3677629,-0.3934315,0.7630593],[-0.4808511,-0.51,0.7347872],[-0.759149,-0.51,0.6652128],[-0.8722371,-0.3934315,0.6369407],[-0.8722371,0.3934315,0.6369407],[-0.759149,0.51,0.6652128],[-0.4808511,0.51,0.7347872],[-0.3192558,0.41,0.733955],[-0.3192558,-0.41,0.733955],[-0.4550758,-0.55,0.7],[-0.7655213,-0.55,0.6223885],[-0.9013414,-0.41,0.5884336],[-0.9013414,0.41,0.5884336],[-0.7655213,0.55,0.6223885],[-0.4550758,0.55,0.7],[-0.2950023,0.41,0.6369407],[-0.2950023,-0.41,0.6369407],[-0.4308222,-0.55,0.6029857],[-0.7412678,-0.55,0.5253743],[-0.8770878,-0.41,0.4914193],[-0.8770878,0.41,0.4914193],[-0.7412678,0.55,0.5253743],[-0.4308222,0.55,0.6029857]],"facets":18,"panels":[],"bolts":0} + }}, + {"side": -1, "truth": { + "Thigh.core": {"solid":[[0.33,-0.3,0.4],[-0.33,-0.3,0.4],[-0.45,-0.18,0.4],[-0.45,0.38,0.4],[-0.33,0.5,0.4],[0.33,0.5,0.4],[0.45,0.38,0.4],[0.45,-0.18,0.4],[0.42,-0.34,0.05],[-0.42,-0.34,0.05],[-0.6,-0.16,0.05],[-0.6,0.46,0.05],[-0.42,0.64,0.05],[0.42,0.64,0.05],[0.6,0.46,0.05],[0.6,-0.16,0.05],[0.42,-0.34,-1.45],[-0.42,-0.34,-1.45],[-0.6,-0.16,-1.45],[-0.6,0.46,-1.45],[-0.42,0.64,-1.45],[0.42,0.64,-1.45],[0.6,0.46,-1.45],[0.6,-0.16,-1.45],[0.335,-0.3,-1.8],[-0.335,-0.3,-1.8],[-0.475,-0.16,-1.8],[-0.475,0.36,-1.8],[-0.335,0.5,-1.8],[0.335,0.5,-1.8],[0.475,0.36,-1.8],[0.475,-0.16,-1.8]],"facets":26,"panels":[],"bolts":0}, + "Thigh.Shield": {"solid":[[0.6003516,0.9127237,-0.0100526],[0.5973628,0.9625379,-1.0099225],[0.371703,0.9714425,-1.4588065],[-0.4174352,0.9240942,-1.4588065],[-0.6404113,0.8882715,-1.0099225],[-0.6374224,0.8384573,-0.0100526],[-0.4117627,0.8295527,0.4388314],[0.3773755,0.8769009,0.4388314],[0.6427007,0.874771,-0.0026155],[0.6396555,0.9255249,-1.0213474],[0.3986532,0.9350349,-1.5007508],[-0.4398389,0.8847254,-1.5007508],[-0.677975,0.8464671,-1.0213474],[-0.6749298,0.7957132,-0.0026155],[-0.4339275,0.7862031,0.4767878],[0.4045646,0.8365127,0.4767878],[0.6558607,0.6554389,-0.0135821],[0.6528155,0.7061929,-1.0323141],[0.4118131,0.7157029,-1.5117174],[-0.426679,0.6653934,-1.5117174],[-0.6648151,0.627135,-1.0323141],[-0.6617699,0.5763811,-0.0135821],[-0.4207676,0.566871,0.4658212],[0.4177245,0.6171806,0.4658212]],"facets":18,"panels":[[-0.3645209,0.8161214,0.3629277],[0.3320785,0.8579174,0.3629277],[0.5266297,0.8891734,-0.0287326],[0.5237466,0.9372256,-0.9932363],[0.3268539,0.9449951,-1.3848965],[-0.3697456,0.9031991,-1.3848965],[-0.5642967,0.8719431,-0.9932363],[-0.5614136,0.8238909,-0.0287326],[-0.3675118,0.8659696,0.3654201],[0.3290876,0.9077656,0.3654201],[0.5236388,0.9390216,-0.0262402],[0.5207557,0.9870738,-0.9907439],[0.323863,0.9948433,-1.3824042],[-0.3727365,0.9530473,-1.3824042],[-0.5672876,0.9217913,-0.9907439],[-0.5644045,0.8737391,-0.0262402],[-0.3564294,0.8876444,0.346442],[0.3154931,0.9279597,0.346442],[0.5024643,0.957998,-0.0299587],[0.4996094,1.0055803,-0.9850315],[0.3103879,1.0130471,-1.3614321],[-0.3615346,0.9727317,-1.3614321],[-0.5485058,0.9426934,-0.9850315],[-0.5456509,0.8951111,-0.0299587]],"bolts":8}, + "Thigh.Block": {"solid":[[0.2199377,1.0082324,0.243278],[0.2192007,1.0205159,-0.003278],[0.1625648,1.0199426,-0.0597762],[-0.2036396,0.9979704,-0.0597762],[-0.2599377,0.9917676,-0.003278],[-0.2592007,0.9794841,0.243278],[-0.2025648,0.9800573,0.2997762],[0.1636396,1.0020295,0.2997762],[0.262308,0.9699251,0.257832],[0.2614721,0.9838576,-0.0218199],[0.1813769,0.9830468,-0.1017204],[-0.2179051,0.9590899,-0.1017204],[-0.2975226,0.9503179,-0.0218199],[-0.2966867,0.9363854,0.257832],[-0.2165914,0.9371961,0.3377326],[0.1826905,0.9611531,0.3377326],[0.2694862,0.8502895,0.2518502],[0.2686502,0.8642219,-0.0278017],[0.188555,0.8634112,-0.1077022],[-0.2107269,0.8394543,-0.1077022],[-0.2903445,0.8306822,-0.0278017],[-0.2895085,0.8167497,0.2518502],[-0.2094133,0.8175604,0.3317508],[0.1898686,0.8415174,0.3317508]],"facets":18,"panels":[],"bolts":0}, + "Thigh.Lame": {"solid":[[0.5152019,1.0169734,-1.1630588],[0.3580984,1.0120851,-1.3899561],[-0.3986245,0.9666817,-1.3899561],[-0.5551853,0.9527501,-1.1630588],[-0.5091674,0.9524506,-1.0100318],[0.46955,1.0111736,-1.0100318],[0.561354,0.9798173,-1.1707984],[0.3813663,0.9742171,-1.4307466],[-0.4171976,0.9263031,-1.4307466],[-0.5965636,0.9103422,-1.1707984],[-0.5364322,0.909951,-0.9708382],[0.5017008,0.972239,-0.9708382],[0.5673421,0.8800166,-1.1727943],[0.3873544,0.8744164,-1.4327425],[-0.4112095,0.8265026,-1.4327425],[-0.5905755,0.8105416,-1.1727943],[-0.5304441,0.8101503,-0.9728342],[0.5076889,0.8724384,-0.9728342]],"facets":14,"panels":[],"bolts":0}, + "Thigh.Outer": {"solid":[[-0.8963261,-0.6993303,0.0405074],[-0.9234846,-0.6971576,-0.6427998],[-0.9302595,-0.4659773,-1.2745335],[-0.8760005,0.2877677,-1.4255476],[-0.8321795,0.6398191,-1.0341262],[-0.7895345,0.6364074,0.0388219],[-0.7930059,0.3335055,0.55784],[-0.859628,-0.475686,0.5106725],[-0.8593135,-0.7424191,0.0480094],[-0.8871133,-0.7401951,-0.6514348],[-0.8941858,-0.4988625,-1.3109107],[-0.8367438,0.299098,-1.4707837],[-0.7897608,0.6765533,-1.0511172],[-0.7460753,0.6730585,0.0480094],[-0.749751,0.3523302,0.5975726],[-0.8203176,-0.504772,0.5476124],[-0.6601087,-0.7583555,0.0400412],[-0.6879086,-0.7561315,-0.659403],[-0.694981,-0.5147989,-1.3188789],[-0.6375391,0.2831616,-1.4787519],[-0.590556,0.6606169,-1.0590854],[-0.5468705,0.6571221,0.0400412],[-0.5505463,0.3363939,0.5896044],[-0.6211129,-0.5207084,0.5396442]],"facets":18,"panels":[[-0.7794868,0.2906393,0.4795566],[-0.7763985,0.560117,0.0178105],[-0.7886124,0.5610941,-0.2894937],[-0.8835093,-0.6251161,-0.2894937],[-0.8711026,-0.6261086,0.0226564],[-0.8387128,-0.4287195,0.4376253],[-0.8492085,0.2962171,0.4823454],[-0.8461201,0.5656947,0.0205993],[-0.8583341,0.5666718,-0.2867048],[-0.9532309,-0.6195383,-0.2867049],[-0.9408243,-0.6205308,0.0254452],[-0.9084345,-0.4231417,0.4404142],[-0.870836,0.2868047,0.4624791],[-0.8678498,0.5473692,0.0160056],[-0.8790552,0.5482656,-0.2659239],[-0.9707623,-0.5980719,-0.2659239],[-0.9593307,-0.5989864,0.0216942],[-0.9280897,-0.4085987,0.4219443],[-0.7963567,0.5617135,-0.4843388],[-0.8170925,0.5633725,-1.0060527],[-0.8549845,0.2589536,-1.3445148],[-0.9032756,-0.4118871,-1.2101108],[-0.8970585,-0.624032,-0.6303939],[-0.8912535,-0.6244965,-0.4843389],[-0.8361976,0.5649008,-0.4827452],[-0.8569335,0.5665597,-1.004459],[-0.8948255,0.2621409,-1.3429213],[-0.9431165,-0.4086998,-1.2085171],[-0.9368995,-0.6208448,-0.6288003],[-0.9310944,-0.6213092,-0.4827453],[-0.8585073,0.5466217,-0.5019325],[-0.8781428,0.5481926,-0.9959635],[-0.9144538,0.2564758,-1.3203032],[-0.9611534,-0.3922571,-1.1903285],[-0.9550851,-0.5993261,-0.6244828],[-0.9502143,-0.5997157,-0.5019326]],"bolts":12}, + "Thigh.OuterStep": {"solid":[[-0.9694378,-0.3795951,-0.0167539],[-0.9879788,-0.3781119,-0.4832461],[-0.9809105,-0.2015447,-0.6596745],[-0.951655,0.1641499,-0.6596745],[-0.9305622,0.3395951,-0.4832461],[-0.9120212,0.3381118,-0.0167539],[-0.9190895,0.1615447,0.1596745],[-0.948345,-0.2041499,0.1596745],[-0.9321286,-0.4227076,-0.0017921],[-0.9519857,-0.4211191,-0.5013952],[-0.9439794,-0.2211206,-0.7012363],[-0.9120813,0.1776055,-0.7012363],[-0.8881895,0.3763331,-0.5013952],[-0.8683324,0.3747445,-0.0017921],[-0.8763387,0.1747461,0.1980491],[-0.9082368,-0.22398,0.1980491],[-0.8424864,-0.429879,-0.0053778],[-0.8623435,-0.4282905,-0.5049809],[-0.8543373,-0.228292,-0.704822],[-0.8224391,0.1704341,-0.704822],[-0.7985473,0.3691617,-0.5049809],[-0.7786903,0.3675731,-0.0053778],[-0.7866965,0.1675747,0.1944634],[-0.8185946,-0.2311514,0.1944634]],"facets":18,"panels":[],"bolts":0}, + "Thigh.Inner": {"solid":[[0.8776518,-0.5265174,-0.8959235],[0.861841,-0.3684096,-1.41],[0.7737058,0.5129414,-1.41],[0.7623708,0.6262924,-0.603093],[0.7732095,0.5179051,-0.24],[0.871125,-0.4612505,-0.24],[0.8418908,-0.5709032,-0.9],[0.8249752,-0.4017468,-1.45],[0.7304466,0.5435384,-1.45],[0.7185062,0.6629429,-0.6],[0.7304466,0.5435384,-0.2],[0.8349255,-0.5012506,-0.2],[0.6826848,-0.5868238,-0.9],[0.6657692,-0.4176674,-1.45],[0.5712407,0.5276178,-1.45],[0.5593002,0.6470223,-0.6],[0.5712407,0.5276178,-0.2],[0.6757196,-0.5171711,-0.2]],"facets":14,"panels":[[0.7588614,0.4603896,-0.315],[0.8041243,0.0077606,-0.315],[0.8041242,0.0077606,-1.335],[0.7602884,0.4461192,-1.335],[0.7500883,0.5481198,-0.6088924],[0.828514,0.4673549,-0.315],[0.8737769,0.0147259,-0.315],[0.8737769,0.0147259,-1.335],[0.829941,0.4530844,-1.335],[0.819741,0.5550851,-0.6088925],[0.8498954,0.4545382,-0.335],[0.8916876,0.0366167,-0.335],[0.8916875,0.0366167,-1.3150001],[0.8515706,0.437786,-1.3150001],[0.8416732,0.5367599,-0.610439],[0.8235274,-0.1862716,-0.3149999],[0.8444706,-0.3957034,-0.3149999],[0.8501749,-0.4527469,-0.88828],[0.8364357,-0.3153551,-1.3349999],[0.8235274,-0.1862716,-1.3349999],[0.8633289,-0.1822915,-0.3149999],[0.884272,-0.3917232,-0.3149999],[0.8899764,-0.4487667,-0.88828],[0.8762372,-0.3113749,-1.3349999],[0.8633289,-0.1822915,-1.3349999],[0.8852197,-0.2002021,-0.3349999],[0.9023718,-0.3717233,-0.3349999],[0.9078569,-0.4265738,-0.8862417],[0.8946701,-0.2947063,-1.3149999],[0.8852197,-0.2002021,-1.3149999]],"bolts":10}, + "Thigh.Rear": {"solid":[[0.6,-0.9654287,0.0414257],[0.6,-0.9993547,-0.6370928],[0.3989588,-1.0139576,-0.9291516],[-0.3989588,-1.0139576,-0.9291516],[-0.6,-0.9993547,-0.6370928],[-0.6,-0.9654287,0.0414257],[-0.4336241,-0.9460424,0.4291516],[0.4336241,-0.9460424,0.4291516],[0.64,-0.9250687,0.0476282],[0.64,-0.960025,-0.6514985],[0.42,-0.976005,-0.9710993],[-0.42,-0.976005,-0.9710993],[-0.64,-0.960025,-0.6514985],[-0.64,-0.9250687,0.0476282],[-0.46,-0.9040949,0.4671042],[0.46,-0.9040949,0.4671042],[0.64,-0.7452933,0.0386394],[0.64,-0.7802496,-0.6604872],[0.42,-0.7962296,-0.980088],[-0.42,-0.7962296,-0.980088],[-0.64,-0.7802496,-0.6604872],[-0.64,-0.7452933,0.0386394],[-0.46,-0.7243195,0.4581155],[0.46,-0.7243195,0.4581155]],"facets":18,"panels":[[0.525,-0.9462224,0.0250518],[0.3841694,-0.9298127,0.3532465],[-0.3841694,-0.9298127,0.3532465],[-0.525,-0.9462224,0.0250518],[-0.525,-0.9782164,-0.6148264],[-0.3595065,-0.9902372,-0.8552439],[0.3595065,-0.9902372,-0.8552439],[0.525,-0.9782164,-0.6148264],[0.525,-0.99616,0.0275487],[0.3841694,-0.9797503,0.3557433],[-0.3841694,-0.9797503,0.3557433],[-0.525,-0.99616,0.0275487],[-0.525,-1.028154,-0.6123295],[-0.3595065,-1.0401748,-0.8527471],[0.3595065,-1.0401748,-0.8527471],[0.525,-1.028154,-0.6123295],[0.505,-1.0163401,0.0244474],[0.3709815,-1.0007241,0.3367671],[-0.3709815,-1.0007241,0.3367671],[-0.505,-1.0163401,0.0244474],[-0.505,-1.0478188,-0.6051267],[-0.3489859,-1.0591512,-0.8317733],[0.3489859,-1.0591512,-0.8317733],[0.505,-1.0478188,-0.6051267]],"bolts":8}, + "Thigh.RearStep": {"solid":[[0.31,-1.0533367,-0.166735],[0.31,-1.0666631,-0.433265],[0.2334315,-1.0704868,-0.509738],[-0.2334315,-1.0704868,-0.509738],[-0.31,-1.0666631,-0.433265],[-0.31,-1.0533367,-0.166735],[-0.2334315,-1.0495131,-0.090262],[0.2334315,-1.0495131,-0.090262],[0.35,-1.0125592,-0.1521847],[0.35,-1.0275404,-0.4518104],[0.25,-1.0325342,-0.5516856],[-0.25,-1.0325342,-0.5516856],[-0.35,-1.0275404,-0.4518104],[-0.35,-1.0125592,-0.1521847],[-0.25,-1.0075654,-0.0523094],[0.25,-1.0075654,-0.0523094],[0.35,-0.932659,-0.1561797],[0.35,-0.9476403,-0.4558054],[0.25,-0.9526341,-0.5556806],[-0.25,-0.9526341,-0.5556806],[-0.35,-0.9476403,-0.4558054],[-0.35,-0.932659,-0.1561797],[-0.25,-0.9276652,-0.0563044],[0.25,-0.9276652,-0.0563044]],"facets":18,"panels":[],"bolts":0}, + "Thigh.CornerOut": {"solid":[[-0.6046741,0.7607402,0.2029137],[-0.6419686,0.7969987,-1.1029136],[-0.6830156,0.7580089,-1.1594374],[-0.7575075,0.6813887,-1.1594374],[-0.7953259,0.6392598,-1.1029136],[-0.7580314,0.6030012,0.2029137],[-0.7169843,0.6419911,0.2594374],[-0.6424925,0.7186113,0.2594374],[-0.5476611,0.7610992,0.217877],[-0.5859013,0.7982771,-1.1210611],[-0.6439505,0.7431371,-1.2009977],[-0.7415414,0.6427579,-1.2009977],[-0.7950248,0.5831786,-1.1210611],[-0.7567846,0.5460007,0.217877],[-0.6987353,0.6011407,0.2978136],[-0.6011444,0.70152,0.2978136],[-0.4330328,0.6496551,0.2115088],[-0.471273,0.686833,-1.1274294],[-0.5293223,0.631693,-1.207366],[-0.6269132,0.5313138,-1.207366],[-0.6803964,0.4717345,-1.1274294],[-0.6421562,0.4345566,0.2115088],[-0.584107,0.4896966,0.2914454],[-0.4865161,0.5900759,0.2914454]],"facets":18,"panels":[],"bolts":0}, + "Thigh.CornerIn": {"solid":[[0.7228147,0.6258237,-0.1367753],[0.7426594,0.6451172,-1.0632248],[0.7111945,0.6794759,-1.1097726],[0.6506443,0.7417562,-1.1097726],[0.6171853,0.7741762,-1.0632248],[0.5973406,0.7548828,-0.1367753],[0.6288055,0.7205241,-0.0902275],[0.6893557,0.6582438,-0.0902275],[0.7216761,0.5689284,-0.1214086],[0.7422302,0.5889115,-1.0809804],[0.6949335,0.6405582,-1.1509492],[0.6112841,0.7265977,-1.1509492],[0.5609899,0.7753302,-1.0809804],[0.5404358,0.755347,-0.1214086],[0.5877325,0.7037003,-0.0514398],[0.6713819,0.6176609,-0.0514398],[0.6213416,0.4713809,-0.1255892],[0.6418957,0.4913641,-1.085161],[0.594599,0.5430108,-1.1551298],[0.5109496,0.6290503,-1.1551298],[0.4606554,0.6777828,-1.085161],[0.4401013,0.6577996,-0.1255892],[0.487398,0.6061529,-0.0556204],[0.5710474,0.5201135,-0.0556204]],"facets":18,"panels":[],"bolts":0}, + "Thigh.Cap": {"solid":[[0.4661148,-0.3206001,0.7921801],[-0.4661148,-0.3206001,0.7921801],[-0.5578418,0.2065509,0.6340348],[-0.3392738,0.5031305,0.5450609],[0.3392738,0.5031305,0.5450609],[0.5578418,0.2065509,0.6340348],[0.4999999,-0.370407,0.765361],[-0.4999999,-0.370407,0.765361],[-0.6,0.2042887,0.5929522],[-0.36,0.5299496,0.4952539],[0.36,0.5299496,0.4952539],[0.6,0.2042887,0.5929522],[0.4999999,-0.4106357,0.6312653],[-0.4999999,-0.4106357,0.6312653],[-0.6,0.16406,0.4588565],[-0.36,0.4897209,0.3611582],[0.36,0.4897209,0.3611582],[0.6,0.16406,0.4588565]],"facets":14,"panels":[[0.3004121,0.4255465,0.5474553],[-0.3004121,0.4255465,0.5474553],[-0.4787954,0.1834945,0.620071],[-0.4025803,-0.25451,0.7514725],[0.4025803,-0.25451,0.7514725],[0.4787954,0.1834945,0.620071],[0.3004121,0.4399139,0.5953466],[-0.3004121,0.4399139,0.5953466],[-0.4787954,0.1978619,0.6679623],[-0.4025803,-0.2401427,0.7993639],[0.4025803,-0.2401427,0.7993639],[0.4787954,0.1978619,0.6679623],[0.2900489,0.4265044,0.6202502],[-0.2900489,0.4265044,0.6202502],[-0.4577163,0.198993,0.6885036],[-0.3856378,-0.2152392,0.8127734],[0.3856378,-0.2152392,0.8127734],[0.4577163,0.198993,0.6885036]],"bolts":6} + }} + ]} diff --git a/surfaces/blender/tests/fixtures/plates_raptor.json b/surfaces/blender/tests/fixtures/plates_raptor.json new file mode 100644 index 0000000..a8b19c0 --- /dev/null +++ b/surfaces/blender/tests/fixtures/plates_raptor.json @@ -0,0 +1,1336 @@ +{"source": {"branch": "nibu/fable-raptor-4", "sha": "0c271035b89cbf36b26977cc5a19c94e07199ae5", "blender": "5.3.0"}, + "table": { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "Torso.Jaw1", + "mat": "khaki", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.27, + 5.5, + 4.344352800343537 + ], + [ + 0.25, + 5.5, + 4.14792737789203 + ], + [ + 0.6025, + 4.75, + 4.437397172236504 + ], + [ + 0.6125, + 4.75, + 4.857397172236504 + ] + ], + "inside": [ + 0.0, + 5.125, + 4.5561471722365035 + ], + "lift": 0.1, + "thick": 0.14, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 9.0, + "seed": [ + 1, + 0 + ] + } + }, + { + "name": "Torso.Jaw2", + "mat": "olive_light", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.6131733333333336, + 4.72, + 4.885944978524653 + ], + [ + 0.6160000000000002, + 4.72, + 4.4478971722365035 + ], + [ + 0.88375, + 3.95, + 4.672185089974293 + ], + [ + 0.85025, + 3.95, + 5.162396244735779 + ] + ], + "inside": [ + 0.0, + 4.335, + 4.819518423307627 + ], + "lift": 0.13, + "thick": 0.16, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "khaki", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 0.9, + "seed": [ + 18, + 17 + ] + } + }, + { + "name": "Torso.Jaw3", + "mat": "khaki", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.8582000000000001, + 3.92, + 5.171231323471511 + ], + [ + 0.8920000000000001, + 3.92, + 4.680185089974293 + ], + [ + 1.041875, + 3.05, + 4.885938303341902 + ], + [ + 1.029375, + 3.25, + 5.265938303341902 + ] + ], + "inside": [ + 0.0, + 3.535, + 5.03285175664096 + ], + "lift": 0.1, + "thick": 0.14, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.035 + ], + "inset": 0.07, + "gap": 0.04, + "split": 99.0, + "seed": [ + 35, + 34 + ] + } + }, + { + "name": "Torso.JawLip1", + "mat": "gunmetal", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.27666666666666656, + 5.4, + 4.19167737789203 + ], + [ + 0.1577777777777777, + 5.4, + 4.03167737789203 + ], + [ + 0.45000000000000007, + 4.5, + 4.364897172236503 + ], + [ + 0.7150000000000001, + 4.5, + 4.5248971722365035 + ] + ], + "inside": [ + 0.0, + 4.95, + 4.617397172236504 + ], + "lift": 0.04, + "thick": 0.08, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + } + }, + { + "name": "Torso.JawLip2", + "mat": "khaki", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.7330000000000001, + 4.46, + 4.536185089974293 + ], + [ + 0.4620000000000001, + 4.46, + 4.3761850899742925 + ], + [ + 0.63, + 3.4, + 4.655938303341902 + ], + [ + 1.0025, + 3.4, + 4.815938303341902 + ] + ], + "inside": [ + 0.0, + 3.9299999999999997, + 4.927518423307626 + ], + "lift": 0.05, + "thick": 0.08, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 9.0, + "seed": [ + 69, + 68 + ] + } + }, + { + "name": "Torso.CollarU", + "mat": "olive_light", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.0636, + 3.5, + 6.0693942065828415 + ], + [ + 0.53, + 3.5, + 6.007794206582841 + ], + [ + 0.566, + 3.14, + 6.083710663170325 + ], + [ + 0.06863999999999999, + 3.08, + 6.155219361779141 + ] + ], + "inside": [ + 0.0, + 3.305, + 5.084938303341902 + ], + "lift": 0.17, + "thick": 0.16, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "khaki", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 9.0, + "seed": [ + 86, + 85 + ] + } + }, + { + "name": "Torso.CollarF", + "mat": "olive_light", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.53, + 3.5, + 6.007794206582841 + ], + [ + 1.00125, + 3.5, + 5.212185089974293 + ], + [ + 1.02375, + 3.3, + 5.255938303341902 + ], + [ + 0.566, + 3.14, + 6.083710663170325 + ] + ], + "inside": [ + 0.0, + 3.36, + 5.073938303341902 + ], + "lift": 0.16, + "thick": 0.16, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "khaki", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 9.0, + "seed": [ + 103, + 102 + ] + } + }, + { + "name": "Torso.Cheek", + "mat": "khaki", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.5910599999999999, + 3.08, + 6.0618721194416505 + ], + [ + 1.01152, + 3.24, + 5.29989720287198 + ], + [ + 1.0611000000000002, + 2.5, + 5.445415433520716 + ], + [ + 0.9396, + 2.32, + 5.664961644345172 + ], + [ + 0.6307200000000001, + 2.32, + 6.133612994552364 + ] + ], + "inside": [ + 0.0, + 2.692, + 5.207538303341902 + ], + "lift": 0.11, + "thick": 0.13, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "fits": [ + { + "kind": "mark", + "id": "27", + "at": [ + 0.006142872851341963, + 0.0045098247937858105 + ], + "height": 0.5 + } + ] + }, + { + "name": "Torso.CheekDeck", + "mat": "khaki", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.06911999999999999, + 3.04, + 6.1615584474346505 + ], + [ + 0.56448, + 3.04, + 6.1013584474346505 + ], + [ + 0.6076, + 2.0, + 6.175354661707495 + ], + [ + 0.0744, + 2.0, + 6.235554661707495 + ] + ], + "inside": [ + 0.0, + 2.52, + 5.241938303341902 + ], + "lift": 0.07, + "thick": 0.1, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 0.9, + "seed": [ + 137, + 136 + ] + } + }, + { + "name": "Torso.Gill", + "mat": "gunmetal", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.63168, + 2.28, + 6.135409293752973 + ], + [ + 1.06132, + 2.28, + 5.488082927942363 + ], + [ + 1.06038, + 1.98, + 5.5440385341450344 + ], + [ + 0.6378699999999999, + 1.98, + 6.148364408169792 + ] + ], + "inside": [ + 0.0, + 2.13, + 5.319938303341901 + ], + "lift": 0.05, + "thick": 0.09, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + } + }, + { + "name": "Torso.Shoulder", + "mat": "olive_light", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.63681, + 1.94, + 6.149855403487022 + ], + [ + 1.0762500000000002, + 1.94, + 5.524430162810625 + ], + [ + 0.9305714285714286, + 0.62, + 5.77571206803326 + ], + [ + 0.5378933333333333, + 0.42, + 6.1004641922008265 + ] + ], + "inside": [ + 0.0, + 1.23, + 5.472763496143958 + ], + "lift": 0.2, + "thick": 0.16, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "khaki", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 0.7, + "seed": [ + 171, + 170 + ] + } + }, + { + "name": "Torso.ShoulderDeck", + "mat": "khaki", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.07428, + 1.96, + 6.236924230634243 + ], + [ + 0.6066199999999999, + 1.96, + 6.176724230634243 + ], + [ + 0.51744, + 0.44, + 6.119364493385301 + ], + [ + 0.06336, + 0.44, + 6.179564493385301 + ] + ], + "inside": [ + 0.0, + 1.2, + 5.477763496143958 + ], + "lift": 0.09, + "thick": 0.1, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 0.6, + "seed": [ + 188, + 187 + ] + } + }, + { + "name": "Torso.Belt1", + "mat": "khaki", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 1.0571000000000002, + 3.0, + 5.299138303341902 + ], + [ + 1.04525, + 3.02, + 4.891938303341902 + ], + [ + 1.07, + 2.36, + 5.023938303341902 + ], + [ + 1.0796000000000001, + 2.36, + 5.427138303341902 + ] + ], + "inside": [ + 0.0, + 2.685, + 5.208938303341902 + ], + "lift": 0.07, + "thick": 0.11, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.035 + ], + "inset": 0.07, + "gap": 0.04, + "split": 99.0, + "seed": [ + 205, + 204 + ] + } + }, + { + "name": "Torso.Belt2", + "mat": "olive_light", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 1.0796000000000001, + 2.33, + 5.433138303341901 + ], + [ + 1.07, + 2.33, + 5.029938303341901 + ], + [ + 1.03875, + 1.5, + 5.1777634961439585 + ], + [ + 1.0483500000000001, + 1.5, + 5.5809634961439585 + ] + ], + "inside": [ + 0.0, + 1.915, + 5.358596829477292 + ], + "lift": 0.11, + "thick": 0.12, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "khaki", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 9.0, + "seed": [ + 222, + 221 + ] + } + }, + { + "name": "Torso.Belt3", + "mat": "khaki", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 1.046475, + 1.47, + 5.585963496143958 + ], + [ + 1.036875, + 1.47, + 5.182763496143958 + ], + [ + 0.9480000000000001, + 0.78, + 5.326616966580977 + ], + [ + 0.9301714285714286, + 0.62, + 5.759668263975169 + ] + ], + "inside": [ + 0.0, + 1.085, + 5.496930162810625 + ], + "lift": 0.08, + "thick": 0.11, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + } + }, + { + "name": "Torso.Lip1", + "mat": "gunmetal", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 1.0070000000000001, + 3.36, + 4.823938303341902 + ], + [ + 0.632, + 3.36, + 4.663938303341902 + ], + [ + 0.66, + 2.4, + 4.855938303341902 + ], + [ + 1.07, + 2.4, + 5.015938303341902 + ] + ], + "inside": [ + 0.0, + 2.88, + 5.169938303341902 + ], + "lift": 0.03, + "thick": 0.08, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + } + }, + { + "name": "Torso.Lip2", + "mat": "khaki", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 1.07, + 2.36, + 5.023938303341902 + ], + [ + 0.66, + 2.36, + 4.863938303341902 + ], + [ + 0.625, + 1.3, + 5.0510968294772915 + ], + [ + 1.02625, + 1.3, + 5.211096829477292 + ] + ], + "inside": [ + 0.0, + 1.83, + 5.372763496143959 + ], + "lift": 0.05, + "thick": 0.08, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 9.0, + "seed": [ + 273, + 272 + ] + } + }, + { + "name": "Torso.Lip3", + "mat": "gunmetal", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 1.02375, + 1.26, + 5.2177634961439585 + ], + [ + 0.623, + 1.26, + 5.057763496143958 + ], + [ + 0.56, + 0.5, + 5.250616966580976 + ], + [ + 0.9, + 0.5, + 5.410616966580976 + ] + ], + "inside": [ + 0.0, + 0.88, + 5.546616966580976 + ], + "lift": 0.03, + "thick": 0.08, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + } + }, + { + "name": "Torso.Hood1D", + "mat": "khaki", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.0624, + 0.4, + 6.169880489976104 + ], + [ + 0.52, + 0.4, + 6.108280489976104 + ], + [ + 0.364, + -0.66, + 6.250353133913001 + ], + [ + 0.04368, + -0.66, + 6.3119531339130015 + ] + ], + "inside": [ + 0.0, + -0.13, + 5.896217574199579 + ], + "lift": 0.14, + "thick": 0.11, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 9.0, + "seed": [ + 307, + 306 + ] + } + }, + { + "name": "Torso.Hood1F", + "mat": "khaki", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.5601485714285714, + 0.56, + 6.135829871438327 + ], + [ + 0.9411428571428572, + 0.74, + 5.338616966580977 + ], + [ + 0.6, + -0.1, + 5.633944846926852 + ], + [ + 0.488, + -0.66, + 5.797178285195826 + ], + [ + 0.36976, + -0.66, + 6.24185255718071 + ] + ], + "inside": [ + 0.0, + -0.024000000000000004, + 5.852853937835943 + ], + "lift": 0.13, + "thick": 0.12, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 0.5, + "seed": [ + 324, + 323 + ] + } + }, + { + "name": "Torso.Hood2D", + "mat": "olive_light", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.044399999999999995, + -0.6, + 6.311459761576258 + ], + [ + 0.37, + -0.6, + 6.249859761576258 + ], + [ + 0.32, + -1.5, + 6.226910880175944 + ], + [ + 0.0384, + -1.5, + 6.288510880175944 + ] + ], + "inside": [ + 0.0, + -1.05, + 6.070119461666414 + ], + "lift": 0.1, + "thick": 0.1, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "khaki", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 9.0, + "seed": [ + 341, + 340 + ] + } + }, + { + "name": "Torso.Hood2F", + "mat": "olive_light", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.37392, + -0.62, + 6.242114324404738 + ], + [ + 0.496, + -0.62, + 5.794825344019356 + ], + [ + 0.41, + -1.5, + 5.8465900499017085 + ], + [ + 0.3244, + -1.5, + 6.21998395024202 + ] + ], + "inside": [ + 0.0, + -1.06, + 6.070707696960532 + ], + "lift": 0.09, + "thick": 0.11, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + } + }, + { + "name": "Torso.Hood3D", + "mat": "khaki", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.03864, + -1.46, + 6.292862675791256 + ], + [ + 0.322, + -1.46, + 6.231262675791256 + ], + [ + 0.26, + -2.3, + 6.16377625008143 + ], + [ + 0.0312, + -2.3, + 6.22537625008143 + ] + ], + "inside": [ + 0.0, + -1.88, + 6.152707433134606 + ], + "lift": 0.06, + "thick": 0.09, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 9.0, + "seed": [ + 375, + 374 + ] + } + }, + { + "name": "Torso.Hood3F", + "mat": "khaki", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.32646000000000003, + -1.46, + 6.22419092354263 + ], + [ + 0.4135, + -1.46, + 5.844237108725237 + ], + [ + 0.32, + -2.3, + 5.992069135262265 + ], + [ + 0.2632, + -2.3, + 6.161355376401335 + ] + ], + "inside": [ + 0.0, + -1.88, + 6.152707433134606 + ], + "lift": 0.05, + "thick": 0.1, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + }, + "clad": { + "mat": "olive_light", + "min_area": 0.12, + "lifts": [ + 0.035, + 0.06 + ], + "inset": 0.07, + "gap": 0.04, + "split": 9.0, + "seed": [ + 392, + 391 + ] + } + }, + { + "name": "Torso.HoodLip", + "mat": "gunmetal", + "bevel": 0.012, + "sides": "both", + "slab": { + "corners": [ + [ + 0.85, + 0.4, + 5.4406169665809765 + ], + [ + 0.5366666666666667, + 0.4, + 5.280616966580976 + ], + [ + 0.24749999999999997, + -2.2, + 5.810792539517585 + ], + [ + 0.33124999999999993, + -2.2, + 5.970792539517585 + ] + ], + "inside": [ + 0.0, + -0.9000000000000001, + 6.061295932254649 + ], + "lift": 0.03, + "thick": 0.07, + "taper": 0.035, + "back": 0.94, + "gap": 0.025 + } + } + ] +}, + "cases": [ + {"side": 1, "truth": { + "Torso.Jaw1.R": {"solid":[[0.6781577,4.8458824,4.7452664],[0.668655,4.8445058,4.4767356],[0.3750727,5.4858899,4.2300553],[0.3787763,5.4840679,4.3069553],[0.6626044,4.800034,4.8098192],[0.6499786,4.7982044,4.4530377],[0.3264895,5.5049257,4.1812291],[0.3335624,5.5014462,4.3280835],[0.5565017,4.7785773,4.7914252],[0.5446335,4.7768579,4.4560513],[0.2405537,5.4411759,4.200551],[0.2472022,5.4379053,4.338594]],"facets":10,"panels":[],"bolts":0}, + "Torso.Jaw1.L": {"solid":[[-0.3787763,5.4840679,4.3069553],[-0.3750727,5.4858899,4.2300553],[-0.668655,4.8445058,4.4767356],[-0.6781577,4.8458824,4.7452664],[-0.3335624,5.5014462,4.3280835],[-0.3264895,5.5049257,4.1812291],[-0.6499786,4.7982044,4.4530377],[-0.6626044,4.800034,4.8098187],[-0.2472022,5.4379053,4.338594],[-0.2405537,5.4411759,4.200551],[-0.5446335,4.7768579,4.4560513],[-0.5565017,4.7785773,4.7914252]],"facets":10,"panels":[],"bolts":0}, + "Torso.Jaw2.R": {"solid":[[0.9634969,4.0501137,5.0842671],[0.9793593,4.0470967,4.7224078],[0.7621094,4.706634,4.5318127],[0.7502888,4.7032971,4.8479657],[0.9395706,4.0060921,5.1315699],[0.9587276,4.0024481,4.6945519],[0.7194206,4.7289476,4.4846058],[0.7049535,4.7248635,4.8715405],[0.8148237,3.9873223,5.106564],[0.8328313,3.9838972,4.6957669],[0.6078827,4.6668067,4.4984179],[0.5942836,4.6629677,4.8621368]],"facets":10,"panels":[[0.7623737,4.6329627,4.6227379],[0.755846,4.6311202,4.7973275],[0.9262363,4.1091132,4.9861736],[0.9355094,4.1073494,4.7746315],[0.7954733,4.644258,4.624095],[0.7889456,4.642415,4.7986841],[0.9593359,4.1204081,4.9875302],[0.968609,4.1186442,4.7759881],[0.8198669,4.6315074,4.6510701],[0.8148514,4.6300917,4.785213],[0.9730081,4.1455636,4.9605002],[0.9803985,4.1441579,4.7919059]],"bolts":4}, + "Torso.Jaw2.L": {"solid":[[-0.7502887,4.7032971,4.8479657],[-0.7621094,4.706634,4.5318127],[-0.9793593,4.0470967,4.7224078],[-0.9634969,4.0501137,5.0842671],[-0.7049535,4.7248635,4.8715405],[-0.7194206,4.7289476,4.4846058],[-0.9587276,4.0024481,4.6945519],[-0.9395706,4.0060921,5.1315699],[-0.5942836,4.6629682,4.8621368],[-0.6078827,4.6668067,4.4984179],[-0.8328313,3.9838972,4.6957669],[-0.8148237,3.9873223,5.106564]],"facets":10,"panels":[[-0.9262362,4.1091132,4.9861732],[-0.7558458,4.6311202,4.797327],[-0.7623736,4.6329632,4.6227379],[-0.9355093,4.1073499,4.774631],[-0.9829783,4.1284761,4.9884992],[-0.812588,4.6504831,4.7996531],[-0.8191157,4.6523261,4.6250639],[-0.9922515,4.1267123,4.776957],[-0.9966506,4.1536317,4.9614692],[-0.8384938,4.6381598,4.7861819],[-0.8435093,4.6395755,4.6520391],[-1.004041,4.152226,4.7928748]],"bolts":4}, + "Torso.Jaw3.R": {"solid":[[1.1034771,3.2995813,5.2017331],[1.1353582,3.1601076,4.9280725],[0.9894645,3.8798358,4.7565813],[0.984347,3.8839259,5.1203036],[1.0727185,3.273221,5.2393327],[1.1118007,3.1022437,4.9038582],[0.9487557,3.9065831,4.7122068],[0.9425905,3.9115105,5.1503859],[0.9666496,3.2685959,5.2238503],[1.0033869,3.107877,4.908504],[0.8501246,3.8639562,4.7283521],[0.8443294,3.868588,5.1402402]],"facets":10,"panels":[[0.9797079,3.8106408,5.0591025],[1.0768427,3.3341856,5.1254978],[1.0943214,3.2577195,4.9754639],[0.9827303,3.8082252,4.8442941],[1.0139892,3.8176858,5.0595059],[1.1111239,3.3412309,5.1259007],[1.1286026,3.2647648,4.9758673],[1.0170115,3.8152704,4.844697],[1.03785,3.8019233,5.042316],[1.1287004,3.3562937,5.1044154],[1.1420641,3.2978299,4.9897037],[1.0402737,3.7999861,4.8700538]],"bolts":4}, + "Torso.Jaw3.L": {"solid":[[-0.984347,3.8839259,5.1203036],[-0.9894645,3.8798358,4.7565813],[-1.1353582,3.1601076,4.9280725],[-1.1034771,3.2995813,5.2017331],[-0.9425905,3.9115105,5.1503859],[-0.9487557,3.9065831,4.7122068],[-1.1118007,3.1022437,4.9038582],[-1.0727185,3.273221,5.2393327],[-0.8443294,3.868588,5.1402402],[-0.8501246,3.8639562,4.7283521],[-1.0033869,3.107877,4.908504],[-0.9666496,3.2685959,5.2238503]],"facets":10,"panels":[[-1.0943214,3.2577195,4.9754634],[-1.0768428,3.3341856,5.1254973],[-0.979708,3.8106406,5.0591021],[-0.9827303,3.8082252,4.8442936],[-1.1286026,3.2647645,4.9758668],[-1.111124,3.3412306,5.1259003],[-1.0139892,3.8176858,5.0595055],[-1.0170116,3.8152702,4.8446965],[-1.1420641,3.2978299,4.9897032],[-1.1287004,3.3562937,5.1044149],[-1.03785,3.801923,5.0423155],[-1.0402738,3.7999861,4.8700533]],"bolts":4}, + "Torso.JawLip1.R": {"solid":[[0.6458802,4.5582738,4.4395108],[0.5161161,4.5574179,4.3403563],[0.2400006,5.3381481,4.0823326],[0.2889529,5.3373065,4.1198077],[0.6731222,4.5253091,4.5064259],[0.4764318,4.5240121,4.3561325],[0.1752755,5.375546,4.0747085],[0.2844312,5.3736696,4.1582718],[0.6295741,4.5529151,4.528182],[0.4446852,4.5516958,4.3869061],[0.1615982,5.352138,4.1223679],[0.2642045,5.3503742,4.2009172]],"facets":10,"panels":[],"bolts":0}, + "Torso.JawLip1.L": {"solid":[[-0.2889529,5.3373065,4.1198077],[-0.2400006,5.3381481,4.0823326],[-0.5161161,4.5574179,4.3403563],[-0.6458802,4.5582738,4.4395108],[-0.2844312,5.3736696,4.1582718],[-0.1752755,5.375546,4.0747085],[-0.4764318,4.5240121,4.3561325],[-0.6731222,4.5253091,4.5064259],[-0.2642045,5.3503742,4.2009172],[-0.1615982,5.352138,4.1223679],[-0.4446852,4.5516958,4.3869061],[-0.6295741,4.5529151,4.528182]],"facets":10,"panels":[],"bolts":0}, + "Torso.JawLip2.R": {"solid":[[0.9485517,3.4529181,4.7355824],[0.7014969,3.4510305,4.6154981],[0.5440177,4.3942752,4.3846078],[0.7175547,4.3920512,4.4695377],[0.9750648,3.4237115,4.7926283],[0.6596735,3.4213021,4.639328],[0.4905131,4.4345131,4.3913107],[0.7271858,4.4314795,4.5071402],[0.9398439,3.4604948,4.8200493],[0.6433761,3.4582298,4.6759472],[0.4843653,4.4106483,4.442811],[0.7068377,4.4077964,4.5516906]],"facets":10,"panels":[[0.6592853,4.3262753,4.4743786],[0.8565182,3.5244124,4.7015362],[0.7461367,3.5235691,4.6478839],[0.6120198,4.3268809,4.4512467],[0.6852901,4.3175545,4.4210148],[0.882523,3.5156915,4.6481724],[0.7721415,3.5148482,4.5945201],[0.6380246,4.3181601,4.3978829],[0.6797866,4.2950239,4.399528],[0.8673726,3.5323808,4.6155748],[0.7960405,3.5318358,4.5809031],[0.6685987,4.295167,4.3940525]],"bolts":4}, + "Torso.JawLip2.L": {"solid":[[-0.7175547,4.3920512,4.4695377],[-0.5440177,4.3942752,4.3846078],[-0.7014969,3.4510307,4.6154981],[-0.9485517,3.4529181,4.7355824],[-0.7271858,4.4314795,4.5071402],[-0.4905131,4.4345131,4.3913107],[-0.6596735,3.4213021,4.639328],[-0.9750648,3.4237115,4.7926283],[-0.7068377,4.4077964,4.5516906],[-0.4843653,4.4106483,4.442811],[-0.6433761,3.4582298,4.6759472],[-0.9398439,3.4604948,4.8200493]],"facets":10,"panels":[[-0.6592851,4.3262753,4.4743786],[-0.6120197,4.3268809,4.4512467],[-0.7461365,3.5235691,4.6478839],[-0.8565181,3.5244124,4.7015362],[-0.6852899,4.3175545,4.4210148],[-0.6380244,4.3181601,4.3978829],[-0.7721414,3.5148482,4.5945201],[-0.8825229,3.5156915,4.6481724],[-0.6797863,4.2950234,4.399528],[-0.6685985,4.295167,4.3940525],[-0.7960405,3.5318358,4.5809031],[-0.8673725,3.5323808,4.6155748]],"bolts":4}, + "Torso.CollarU.R": {"solid":[[0.1480696,3.1818228,6.300221],[0.5215798,3.2264247,6.2441702],[0.4968882,3.4767935,6.1938457],[0.1442731,3.4762638,6.2378926],[0.1096004,3.1358895,6.278759],[0.5551332,3.1890917,6.2119007],[0.5240929,3.5038362,6.1486363],[0.1048643,3.5032063,6.2010045],[0.1073099,3.1218333,6.1532855],[0.5261107,3.1718433,6.0904384],[0.4969327,3.4677031,6.0309701],[0.1028579,3.4671111,6.0801959]],"facets":10,"panels":[],"bolts":0}, + "Torso.CollarU.L": {"solid":[[-0.1442731,3.4762638,6.2378926],[-0.4968882,3.4767935,6.1938457],[-0.5215798,3.2264247,6.2441702],[-0.1480696,3.1818228,6.300221],[-0.1048643,3.5032063,6.2010045],[-0.5240929,3.5038362,6.1486363],[-0.5551332,3.1890917,6.2119007],[-0.1096004,3.1358895,6.278759],[-0.1028579,3.4671111,6.0801959],[-0.4969327,3.4677031,6.0309701],[-0.5261107,3.1718433,6.0904384],[-0.1073099,3.1218333,6.1532855]],"facets":10,"panels":[],"bolts":0}, + "Torso.CollarF.R": {"solid":[[0.72499,3.2426014,6.0970759],[1.1215882,3.3813784,5.3768516],[1.1122297,3.4722867,5.3575101],[0.701372,3.4719968,6.048275],[0.6817346,3.1941087,6.1187196],[1.1131568,3.3450711,5.3352547],[1.0972214,3.4998662,5.302321],[0.650287,3.4995508,6.0537405],[0.5885689,3.1813512,6.0310478],[0.9941058,3.3232558,5.294591],[0.9791265,3.4687634,5.2636328],[0.5590081,3.4684668,5.9699674]],"facets":10,"panels":[],"bolts":0}, + "Torso.CollarF.L": {"solid":[[-0.701372,3.4719968,6.048275],[-1.1122297,3.4722867,5.3575101],[-1.1215882,3.3813784,5.3768516],[-0.72499,3.2426014,6.0970759],[-0.650287,3.4995508,6.0537405],[-1.0972214,3.4998662,5.302321],[-1.1131568,3.3450711,5.3352547],[-0.6817346,3.1941087,6.1187196],[-0.5590081,3.4684668,5.9699674],[-0.9791265,3.4687634,5.2636328],[-0.9941058,3.3232558,5.294591],[-0.5885689,3.1813512,6.0310478]],"facets":10,"panels":[],"bolts":0}, + "Torso.Cheek.R": {"solid":[[0.7616042,2.3949468,6.1404848],[1.0143056,2.3933237,5.734005],[1.1105072,2.5457008,5.542192],[1.085451,3.1817539,5.4284258],[0.7093408,3.0426319,6.0677066],[0.7164118,2.3559163,6.155828],[0.9945078,2.3541298,5.7084999],[1.1004012,2.5218582,5.4973631],[1.0728861,3.2203295,5.3724322],[0.6590133,3.0672393,6.0758991],[0.6478956,2.3647487,6.0824809],[0.9093057,2.3630698,5.6619925],[1.0088454,2.5207343,5.4635239],[0.9829814,3.1772974,5.3460889],[0.593941,3.0333924,6.0073476]],"facets":12,"panels":[],"bolts":0}, + "Torso.Cheek.L": {"solid":[[-0.7093408,3.0426319,6.0677066],[-1.085451,3.1817539,5.4284258],[-1.1105072,2.5457008,5.542192],[-1.0143056,2.3933237,5.734005],[-0.7616042,2.3949468,6.1404848],[-0.6590133,3.0672393,6.0758991],[-1.0728861,3.2203295,5.3724322],[-1.1004012,2.5218582,5.4973631],[-0.9945078,2.3541298,5.7084999],[-0.7164119,2.3559163,6.155828],[-0.5939409,3.0333924,6.0073476],[-0.9829814,3.1772974,5.3460889],[-1.0088454,2.5207343,5.4635239],[-0.9093057,2.3630698,5.6619925],[-0.6478956,2.364749,6.0824809]],"facets":12,"panels":[],"bolts":0}, + "Torso.CheekDeck.R": {"solid":[[0.1419043,2.0650213,6.2945924],[0.5534907,2.0649021,6.2464862],[0.515558,2.9853468,6.1829267],[0.1370073,2.98522,6.2271891],[0.1032736,2.027564,6.266542],[0.5856587,2.0274243,6.2101612],[0.5448481,3.0177033,6.1417794],[0.0980052,3.0175533,6.1940269],[0.109527,2.0525076,6.19835],[0.562969,2.0523763,6.1453519],[0.5246071,2.9832382,6.0810733],[0.1045747,2.9830976,6.1301856]],"facets":10,"panels":[[0.4465562,2.9140482,6.1760697],[0.2045898,2.9139671,6.2043619],[0.208744,2.1333499,6.2615409],[0.4787329,2.1332717,6.2299848],[0.4506091,2.9166093,6.2107396],[0.2086427,2.9165282,6.2390318],[0.212797,2.135911,6.2962108],[0.4827859,2.1358328,6.2646546],[0.433872,2.8981199,6.2342525],[0.2309297,2.898052,6.2579818],[0.2348717,2.157315,6.3122396],[0.4644041,2.1572485,6.2854118]],"bolts":4}, + "Torso.CheekDeck.L": {"solid":[[-0.1370073,2.98522,6.2271891],[-0.515558,2.9853468,6.1829267],[-0.5534908,2.0649021,6.2464862],[-0.1419043,2.0650213,6.2945924],[-0.0980052,3.0175533,6.1940269],[-0.5448481,3.0177033,6.1417794],[-0.5856587,2.0274243,6.2101612],[-0.1032736,2.027564,6.266542],[-0.1045747,2.9830976,6.1301856],[-0.5246071,2.9832382,6.0810733],[-0.5629691,2.0523763,6.1453519],[-0.109527,2.0525076,6.19835]],"facets":10,"panels":[[-0.4465562,2.9140482,6.1760697],[-0.4787329,2.1332717,6.2299848],[-0.2087439,2.1333499,6.2615409],[-0.2045898,2.9139671,6.2043619],[-0.4535041,2.9184387,6.2355042],[-0.4856809,2.1376622,6.2894192],[-0.2156919,2.1377404,6.3209753],[-0.2115377,2.9183576,6.2637963],[-0.4367669,2.8999493,6.259017],[-0.4672992,2.1590779,6.3101764],[-0.2377666,2.1591444,6.3370037],[-0.2338247,2.8998814,6.2827458]],"bolts":4}, + "Torso.Gill.R": {"solid":[[0.7139895,2.0437119,6.1258149],[1.0652895,2.0431433,5.6095428],[1.0703707,2.2240007,5.5789557],[0.7057446,2.223469,6.1149549],[0.6670325,2.0063245,6.1372304],[1.0553687,2.0056958,5.5665302],[1.0624131,2.256434,5.5241241],[0.6555879,2.2558405,6.1221561],[0.6332603,2.0098648,6.0883889],[0.9982963,2.009274,5.5519304],[1.0049181,2.2449677,5.5120687],[0.6225024,2.24441,6.0742188]],"facets":10,"panels":[],"bolts":0}, + "Torso.Gill.L": {"solid":[[-0.7057446,2.223469,6.1149549],[-1.0703707,2.2240007,5.5789557],[-1.0652895,2.0431433,5.6095428],[-0.7139896,2.0437119,6.1258149],[-0.6555879,2.2558405,6.1221561],[-1.0624131,2.256434,5.5241241],[-1.0553687,2.0056958,5.5665302],[-0.6670325,2.0063245,6.1372304],[-0.6225024,2.24441,6.0742188],[-1.0049181,2.2449677,5.5120687],[-0.9982963,2.009274,5.5519304],[-0.6332603,2.0098648,6.0883889]],"facets":10,"panels":[],"bolts":0}, + "Torso.Shoulder.R": {"solid":[[0.766121,0.503258,6.2084999],[1.0149217,0.6597862,5.9122195],[1.2070429,1.8741268,5.7282615],[0.8078286,1.8753638,6.2140069],[0.7152762,0.4519182,6.2131157],[1.0066018,0.6351999,5.8661952],[1.208279,1.9099404,5.6730876],[0.7596377,1.9113306,6.2189732],[0.631173,0.5016816,6.120554],[0.905019,0.6739665,5.7944489],[1.0945956,1.8722225,5.6129274],[0.6728727,1.8735293,6.12606]],"facets":10,"panels":[[0.9620576,0.7113007,5.9471393],[1.1350672,1.8048418,5.7814813],[0.8347065,1.8057724,6.1469455],[0.7983067,0.6082799,6.1421394],[1.0083938,0.7097393,5.9852252],[1.1814033,1.8032804,5.8195667],[0.8810427,1.804211,6.1850314],[0.8446428,0.6067187,6.1802254],[1.013148,0.7237886,6.0115247],[1.180697,1.7828155,5.8510952],[0.9085804,1.7836586,6.1821938],[0.873697,0.6360558,6.177588]],"bolts":4}, + "Torso.Shoulder.L": {"solid":[[-0.8078286,1.8753638,6.2140069],[-1.2070429,1.8741268,5.7282615],[-1.0149217,0.6597862,5.9122195],[-0.766121,0.503258,6.2084999],[-0.7596377,1.9113306,6.2189732],[-1.208279,1.9099404,5.6730876],[-1.0066018,0.6351999,5.8661952],[-0.7152762,0.4519182,6.2131157],[-0.6728727,1.8735293,6.12606],[-1.0945956,1.8722225,5.6129274],[-0.905019,0.6739665,5.7944489],[-0.631173,0.5016816,6.120554]],"facets":10,"panels":[[-0.9620576,0.7113007,5.9471393],[-0.7983067,0.6082799,6.1421394],[-0.8347066,1.8057724,6.1469455],[-1.1350672,1.8048418,5.7814813],[-1.0083938,0.7097393,5.9852252],[-0.8446428,0.6067187,6.1802254],[-0.8810427,1.804211,6.1850314],[-1.1814033,1.8032804,5.8195667],[-1.013148,0.7237886,6.0115247],[-0.873697,0.6360558,6.177588],[-0.9085804,1.7836586,6.1821938],[-1.180697,1.7828155,5.8510952]],"bolts":4}, + "Torso.ShoulderDeck.R": {"solid":[[0.1338997,0.4963008,6.2615356],[0.4724211,0.4961444,6.2204647],[0.554043,1.8963948,6.2689981],[0.1444805,1.8962564,6.3186746],[0.094679,0.4627956,6.2296085],[0.5009658,0.4626078,6.180316],[0.5866662,1.9328259,6.2312741],[0.1057881,1.9326636,6.2896004],[0.100499,0.5095817,6.1653223],[0.4824086,0.5094053,6.1189871],[0.562967,1.8914104,6.1668882],[0.1109416,1.8912575,6.221715]],"facets":10,"panels":[[0.4045028,0.5669425,6.2114944],[0.4779677,1.8272576,6.2551775],[0.2110364,1.8271676,6.2875538],[0.2015125,0.5670362,6.2361221],[0.4117219,0.564459,6.2710066],[0.4851868,1.8247741,6.3146901],[0.2182556,1.824684,6.3470664],[0.2087317,0.5645527,6.2956343],[0.3954107,0.5836226,6.2939491],[0.466545,1.8039564,6.3362465],[0.2403655,1.80388,6.3636799],[0.2311435,0.5836985,6.3138785]],"bolts":4}, + "Torso.ShoulderDeck.L": {"solid":[[-0.1444805,1.8962564,6.3186746],[-0.5540429,1.8963948,6.2689981],[-0.4724211,0.4961443,6.2204647],[-0.1338998,0.4963008,6.2615356],[-0.1057881,1.9326636,6.2896004],[-0.5866662,1.9328259,6.2312741],[-0.5009658,0.4626078,6.180316],[-0.094679,0.4627956,6.2296085],[-0.1109416,1.8912575,6.221715],[-0.562967,1.8914104,6.1668882],[-0.4824086,0.5094053,6.1189871],[-0.100499,0.5095817,6.1653223]],"facets":10,"panels":[[-0.4045027,0.5669426,6.211494],[-0.2015124,0.5670363,6.2361217],[-0.2110364,1.8271676,6.2875533],[-0.4779676,1.8272578,6.255177],[-0.4087139,0.5654938,6.2462096],[-0.2057236,0.5655876,6.2708373],[-0.2152475,1.8257189,6.322269],[-0.4821788,1.825809,6.2898927],[-0.3924026,0.5846575,6.2691517],[-0.2281355,0.5847334,6.2890816],[-0.2373575,1.8049148,6.3388824],[-0.4635369,1.8049912,6.3114491]],"bolts":4}, + "Torso.Belt1.R": {"solid":[[1.146176,2.4221623,5.3521624],[1.1389598,2.4221458,5.071332],[1.1194549,2.9585156,4.964046],[1.1271794,2.9445682,5.2476935],[1.1133937,2.38609,5.3957429],[1.1043435,2.3860693,5.0435414],[1.0822154,2.9945703,4.9218278],[1.0919032,2.9770784,5.2775593],[1.0375291,2.4017417,5.3835039],[1.029022,2.4017222,5.0524349],[1.0082216,2.9737132,4.938024],[1.0173281,2.9572709,5.2724113]],"facets":10,"panels":[[1.104007,2.8835981,5.0507927],[1.1078055,2.8767397,5.1902728],[1.1218143,2.4914992,5.267312],[1.1182659,2.4914911,5.1292229],[1.1389785,2.88469,5.0498943],[1.1427768,2.8778317,5.189374],[1.1567856,2.4925911,5.2664132],[1.1532373,2.492583,5.1283245],[1.1602581,2.8640873,5.074019],[1.1629348,2.8592544,5.172308],[1.1755184,2.5132041,5.2415099],[1.1730181,2.5131984,5.1442046]],"bolts":4}, + "Torso.Belt1.L": {"solid":[[-1.1271794,2.9445682,5.2476935],[-1.1194549,2.9585156,4.964046],[-1.1389598,2.4221458,5.071332],[-1.146176,2.4221623,5.3521624],[-1.0919032,2.9770784,5.2775593],[-1.0822154,2.9945703,4.9218278],[-1.1043435,2.3860693,5.0435414],[-1.1133937,2.38609,5.3957429],[-1.0173281,2.9572709,5.2724113],[-1.0082216,2.9737132,4.938024],[-1.029022,2.4017222,5.0524349],[-1.0375291,2.4017417,5.3835039]],"facets":10,"panels":[[-1.1040069,2.8835983,5.0507936],[-1.1182657,2.4914913,5.1292238],[-1.1218141,2.4914994,5.2673125],[-1.1078054,2.8767397,5.1902738],[-1.1389784,2.8846903,5.0498953],[-1.1532372,2.4925833,5.128325],[-1.1567855,2.4925914,5.2664137],[-1.1427768,2.8778317,5.1893749],[-1.1602579,2.8640876,5.0740199],[-1.173018,2.5131986,5.1442051],[-1.1755183,2.5132043,5.2415104],[-1.1629347,2.8592544,5.1723089]],"bolts":4}, + "Torso.Belt2.R": {"solid":[[1.1590292,1.5553447,5.5067554],[1.15233,1.5553447,5.2253861],[1.1790659,2.2654498,5.0989141],[1.1857651,2.2654498,5.3802838],[1.1235993,1.5218399,5.5493498],[1.1152079,1.5218399,5.1969128],[1.144577,2.3018837,5.0579844],[1.1529684,2.3018837,5.4104218],[1.0393271,1.5487978,5.5366302],[1.0314392,1.5487978,5.2053394],[1.0590461,2.2820389,5.0747471],[1.0669341,2.2820389,5.4060378]],"facets":10,"panels":[[1.161463,2.1963477,5.3221474],[1.1399935,1.62612,5.4237065],[1.1366785,1.6261201,5.2844734],[1.1581479,2.1963477,5.1829138],[1.2213935,2.1938372,5.3207207],[1.199924,1.6236094,5.4222798],[1.196609,1.6236095,5.2830462],[1.2180784,2.1938372,5.1814871],[1.2401345,2.1730177,5.3034987],[1.2201698,1.642755,5.3979402],[1.2178216,1.6427552,5.2993169],[1.2377863,2.1730177,5.2048755]],"bolts":4}, + "Torso.Belt2.L": {"solid":[[-1.1857651,2.2654498,5.3802838],[-1.1790659,2.2654498,5.0989141],[-1.15233,1.5553447,5.2253861],[-1.1590292,1.5553447,5.5067554],[-1.1529684,2.3018837,5.4104218],[-1.144577,2.3018837,5.0579844],[-1.1152079,1.5218399,5.1969128],[-1.1235993,1.5218399,5.5493498],[-1.0669341,2.2820389,5.4060383],[-1.0590461,2.2820389,5.0747471],[-1.0314392,1.5487978,5.2053394],[-1.0393271,1.5487978,5.5366302]],"facets":10,"panels":[[-1.1366785,1.62612,5.2844734],[-1.1399935,1.62612,5.4237065],[-1.161463,2.1963477,5.3221474],[-1.1581479,2.1963477,5.1829138],[-1.1716379,1.6246555,5.2836409],[-1.174953,1.6246555,5.422874],[-1.1964225,2.1948833,5.3213153],[-1.1931074,2.1948833,5.1820812],[-1.1928506,1.6438012,5.2999115],[-1.1951988,1.6438012,5.3985343],[-1.2151635,2.1740639,5.3040934],[-1.2128153,2.1740639,5.2054701]],"bolts":4}, + "Torso.Belt3.R": {"solid":[[1.0221877,0.7020862,5.6781473],[1.0325204,0.81351,5.3773651],[1.1108152,1.3995476,5.2550621],[1.1154573,1.3998268,5.5356541],[0.9808402,0.6525131,5.7254996],[0.9938226,0.7925092,5.3475885],[1.0801847,1.4389318,5.2126832],[1.0860105,1.4392823,5.5648246],[0.9098068,0.6883913,5.7109475],[0.9220102,0.8199875,5.355711],[1.0031906,1.4276248,5.2289],[1.0086669,1.4279542,5.5599132]],"facets":10,"panels":[],"bolts":0}, + "Torso.Belt3.L": {"solid":[[-1.1154573,1.3998268,5.5356541],[-1.1108152,1.3995476,5.2550621],[-1.0325204,0.81351,5.3773651],[-1.0221877,0.7020862,5.6781473],[-1.0860105,1.4392823,5.5648246],[-1.0801847,1.4389318,5.2126832],[-0.9938226,0.7925092,5.3475885],[-0.9808403,0.6525132,5.7254992],[-1.0086669,1.4279542,5.5599132],[-1.0031906,1.4276248,5.2289],[-0.9220102,0.8199875,5.355711],[-0.9098068,0.6883913,5.7109475]],"facets":10,"panels":[],"bolts":0}, + "Torso.Lip1.R": {"solid":[[1.0201858,2.4545801,4.9563909],[0.7262938,2.4538357,4.8369279],[0.6996334,3.2962456,4.6738377],[0.9670646,3.2954555,4.7828097],[1.0420594,2.4259324,5.0087824],[0.6817942,2.4250197,4.8623395],[0.6529431,3.3366497,4.6858482],[0.9845879,3.33567,4.8209863],[1.0132276,2.4606547,5.0400338],[0.6745782,2.4597969,4.9023776],[0.6474582,3.3167291,4.7364755],[0.9592044,3.3158081,4.8635054]],"facets":10,"panels":[],"bolts":0}, + "Torso.Lip1.L": {"solid":[[-0.9670646,3.2954555,4.7828097],[-0.6996334,3.2962456,4.6738377],[-0.7262938,2.4538357,4.8369279],[-1.0201858,2.4545801,4.9563909],[-0.9845879,3.33567,4.8209863],[-0.652943,3.3366497,4.6858482],[-0.6817942,2.4250197,4.8623395],[-1.0420594,2.4259324,5.0087824],[-0.9592044,3.3158081,4.8635054],[-0.6474582,3.3167291,4.7364755],[-0.6745782,2.4597969,4.9023776],[-1.0132276,2.4606547,5.0400338]],"facets":10,"panels":[],"bolts":0}, + "Torso.Lip2.R": {"solid":[[0.9911727,1.3502163,5.1321969],[0.7006019,1.3504183,5.0175533],[0.7322098,2.2920723,4.8499608],[1.0295374,2.2922714,4.9671926],[1.0096952,1.3218635,5.1831384],[0.6542254,1.3221107,5.0428891],[0.6881451,2.3326383,4.8630385],[1.0508684,2.3328812,5.0060549],[0.9839019,1.360075,5.2147918],[0.6497603,1.3603073,5.0829573],[0.6816448,2.3102033,4.9138975],[1.0226047,2.3104317,5.0483332]],"facets":10,"panels":[[0.9216167,1.4226836,5.1127429],[0.7608439,1.4227954,5.0493107],[0.7878281,2.226702,4.9062343],[0.9543645,2.2268133,4.9718971],[0.9342599,1.416554,5.080687],[0.7734872,1.4166658,5.0172548],[0.8004714,2.2205722,4.8741784],[0.9670078,2.2206838,4.9398413],[0.9236757,1.4327556,5.0515776],[0.799988,1.4328415,5.0027776],[0.8256512,2.1973917,4.8667054],[0.9548187,2.1974781,4.917634]],"bolts":4}, + "Torso.Lip2.L": {"solid":[[-1.0295374,2.2922711,4.9671926],[-0.7322098,2.2920723,4.8499608],[-0.7006019,1.3504183,5.0175533],[-0.9911727,1.3502163,5.1321969],[-1.0508684,2.3328812,5.0060549],[-0.6881451,2.3326383,4.8630385],[-0.6542254,1.3221107,5.0428891],[-1.0096952,1.3218635,5.1831384],[-1.0226047,2.3104315,5.0483332],[-0.6816448,2.3102033,4.9138975],[-0.6497603,1.3603073,5.0829573],[-0.9839019,1.360075,5.2147918]],"facets":10,"panels":[[-0.9216166,1.4226835,5.1127429],[-0.9543644,2.2268131,4.9718971],[-0.7878281,2.2267017,4.9062343],[-0.7608438,1.4227953,5.0493107],[-0.9432907,1.4121755,5.0577903],[-0.9760386,2.2163053,4.916944],[-0.8095022,2.2161939,4.8512812],[-0.7825179,1.4122874,4.9943581],[-0.9327064,1.4283772,5.0286808],[-0.9638494,2.1930995,4.8947372],[-0.834682,2.1930132,4.8438082],[-0.8090188,1.4284631,4.9798803]],"bolts":4}, + "Torso.Lip3.R": {"solid":[[0.8676552,0.5484633,5.3409948],[0.629285,0.5507765,5.2378912],[0.6864839,1.1930634,5.0655351],[0.9688227,1.1951368,5.1861811],[0.8812362,0.5239664,5.3939147],[0.5808482,0.5268815,5.2639861],[0.6439989,1.2360016,5.0736952],[0.9930302,1.2385647,5.2228398],[0.8577532,0.5576117,5.4243941],[0.5753885,0.5603519,5.3022614],[0.6347501,1.2269248,5.1233878],[0.9628395,1.2293341,5.2635837]],"facets":10,"panels":[],"bolts":0}, + "Torso.Lip3.L": {"solid":[[-0.9688227,1.1951368,5.1861811],[-0.6864839,1.1930634,5.0655351],[-0.629285,0.5507765,5.2378912],[-0.8676552,0.5484633,5.3409948],[-0.9930302,1.2385647,5.2228398],[-0.6439989,1.2360016,5.0736952],[-0.5808482,0.5268815,5.2639861],[-0.8812362,0.5239664,5.3939147],[-0.9628395,1.2293341,5.2635837],[-0.6347501,1.2269248,5.1233878],[-0.5753885,0.5603519,5.3022614],[-0.8577532,0.5576117,5.4243941]],"facets":10,"panels":[],"bolts":0}, + "Torso.Hood1D.R": {"solid":[[0.12437,-0.5841965,6.4268317],[0.3345847,-0.5832529,6.3944097],[0.4716979,0.3567483,6.2592425],[0.1423651,0.3574846,6.3097682],[0.0838059,-0.6232779,6.4021449],[0.3593167,-0.6220412,6.3596516],[0.5065353,0.3872391,6.2145228],[0.1031336,0.388141,6.276412],[0.0832575,-0.6018638,6.3232055],[0.3422377,-0.6007013,6.2832618],[0.4806232,0.3480221,6.1468406],[0.1014256,0.3488699,6.2050166]],"facets":10,"panels":[[0.3884488,0.2850463,6.2603598],[0.2072538,0.2854514,6.2881584],[0.1919241,-0.5167541,6.3878837],[0.2715463,-0.5163967,6.3756032],[0.3974983,0.2921931,6.3192415],[0.2163033,0.2925983,6.3470402],[0.2009735,-0.5096073,6.4467649],[0.2805958,-0.5092499,6.4344845],[0.3775912,0.2747698,6.3447957],[0.2387213,0.2750803,6.3661008],[0.224153,-0.4872751,6.4608717],[0.2664632,-0.4870851,6.4543462]],"bolts":4}, + "Torso.Hood1D.L": {"solid":[[-0.1423651,0.3574846,6.3097682],[-0.4716979,0.3567483,6.2592425],[-0.3345847,-0.5832529,6.3944097],[-0.12437,-0.5841965,6.4268317],[-0.1031336,0.388141,6.276412],[-0.5065353,0.3872391,6.2145228],[-0.3593167,-0.6220412,6.3596516],[-0.0838059,-0.6232779,6.4021449],[-0.1014256,0.3488699,6.2050166],[-0.4806232,0.3480221,6.1468406],[-0.3422377,-0.6007013,6.2832618],[-0.0832575,-0.6018638,6.3232055]],"facets":10,"panels":[[-0.1919241,-0.516754,6.3878837],[-0.2072538,0.2854515,6.2881584],[-0.3884487,0.2850464,6.2603598],[-0.2715462,-0.5163966,6.3756032],[-0.1972029,-0.512585,6.4222312],[-0.2125326,0.2896205,6.322506],[-0.3937276,0.2892154,6.2947073],[-0.2768251,-0.5122277,6.4099507],[-0.2203824,-0.4902529,6.4363379],[-0.2349506,0.2721025,6.341567],[-0.3738205,0.2717921,6.3202615],[-0.2626925,-0.490063,6.4298124]],"bolts":4}, + "Torso.Hood1F.R": {"solid":[[0.4889922,-0.6167604,6.2126741],[0.6078163,-0.6218183,5.8866138],[0.9811482,0.6417188,5.4644799],[0.7089781,0.487129,6.133101],[0.4376203,-0.6451254,6.2363691],[0.5786441,-0.6511283,5.8493915],[0.9770675,0.6957217,5.3981285],[0.6700795,0.5213558,6.1522841],[0.3732574,-0.5951188,6.1853604],[0.5058198,-0.6007615,5.8216019],[0.8803378,0.6652775,5.3974147],[0.5917692,0.5013735,6.1063209]],"facets":11,"panels":[[0.6432545,0.1313842,6.0858674],[0.5083398,-0.5456179,6.1346684],[0.5838301,-0.5488312,5.9275188],[0.7427546,-0.0109527,5.7478194],[0.6988522,0.1217758,6.1062775],[0.5639374,-0.5552263,6.1550784],[0.6394277,-0.5584396,5.9479289],[0.7983524,-0.0205611,5.76823],[0.7187667,0.0906101,6.0961523],[0.5932928,-0.5390178,6.1415386],[0.6564021,-0.5417041,5.9683633],[0.8062518,-0.0345391,5.7989254],[0.7033786,0.4330879,6.0641189],[0.6795222,0.3133766,6.0727487],[0.7913266,0.1534384,5.6928978],[0.9083525,0.5495109,5.5605745],[0.7358106,0.427483,6.076025],[0.7119542,0.3077717,6.0846543],[0.8237587,0.1478335,5.7048035],[0.9407845,0.543906,5.5724802],[0.7580383,0.4079248,6.065063],[0.7399283,0.3170487,6.0716138],[0.8424519,0.1703869,5.7232943],[0.9438132,0.513443,5.6086831]],"bolts":8}, + "Torso.Hood1F.L": {"solid":[[-0.7089781,0.487129,6.133101],[-0.9811482,0.6417188,5.4644799],[-0.6078163,-0.6218184,5.8866138],[-0.4889922,-0.6167604,6.2126741],[-0.6700795,0.5213558,6.1522841],[-0.9770675,0.6957217,5.3981285],[-0.5786441,-0.6511284,5.8493915],[-0.4376203,-0.6451254,6.2363691],[-0.5917692,0.5013735,6.1063209],[-0.8803378,0.6652775,5.3974147],[-0.5058198,-0.6007615,5.8216019],[-0.3732574,-0.5951188,6.1853604]],"facets":11,"panels":[[-0.7033787,0.4330879,6.0641189],[-0.9083524,0.5495109,5.5605745],[-0.7575487,0.0391177,5.7310915],[-0.654301,0.1868157,6.0818715],[-0.7589764,0.4234796,6.0845289],[-0.9639502,0.5399025,5.5809851],[-0.8131465,0.0295093,5.751502],[-0.7098987,0.1772073,6.1022816],[-0.7812041,0.4039214,6.0735674],[-0.9669788,0.5094395,5.617188],[-0.8318397,0.0520627,5.7699924],[-0.7378727,0.1864843,6.089241],[-0.7089766,-0.1252735,5.7860131],[-0.5838298,-0.5488313,5.9275193],[-0.5083395,-0.5456179,6.1346688],[-0.6180329,0.0048233,6.0949907],[-0.7414086,-0.1308784,5.7979188],[-0.6162618,-0.5544362,5.939425],[-0.5407715,-0.5512229,6.146575],[-0.6504649,-0.0007816,6.1068964],[-0.7493081,-0.1448564,5.8286147],[-0.6332361,-0.5377007,5.9598594],[-0.5701269,-0.5350143,6.1330347],[-0.6703794,-0.0319473,6.0967712]],"bolts":8}, + "Torso.Hood2D.R": {"solid":[[0.1169894,-1.4431006,6.374145],[0.2846297,-1.4431865,6.3402987],[0.3272185,-0.6630456,6.3564939],[0.1229361,-0.6631249,6.3977323],[0.0754922,-1.4769762,6.3457222],[0.3101459,-1.4770966,6.2983465],[0.3565559,-0.6269588,6.3159947],[0.0819721,-0.6270654,6.3714247],[0.0704687,-1.4494553,6.2812676],[0.2910432,-1.4495684,6.2367344],[0.3346686,-0.6504388,6.2533236],[0.0765598,-0.650539,6.3054276]],"facets":10,"panels":[],"bolts":0}, + "Torso.Hood2D.L": {"solid":[[-0.1229361,-0.6631249,6.3977323],[-0.3272185,-0.6630456,6.3564939],[-0.2846297,-1.4431865,6.3402987],[-0.1169894,-1.4431006,6.374145],[-0.0819721,-0.6270654,6.3714247],[-0.3565559,-0.6269588,6.3159947],[-0.3101459,-1.4770966,6.2983465],[-0.0754922,-1.4769762,6.3457222],[-0.0765598,-0.650539,6.3054276],[-0.3346686,-0.6504388,6.2533236],[-0.2910432,-1.4495684,6.2367344],[-0.0704687,-1.4494553,6.2812676]],"facets":10,"panels":[],"bolts":0}, + "Torso.Hood2F.R": {"solid":[[0.4256355,-1.4462472,6.1845303],[0.4919126,-1.4467067,5.924593],[0.5590963,-0.6859823,5.8780618],[0.4755452,-0.6863772,6.2054691],[0.3808642,-1.4786416,6.2088552],[0.4636741,-1.4792155,5.8840771],[0.5370334,-0.6485647,5.8332686],[0.4353537,-0.6490453,6.2317157],[0.3127733,-1.4484841,6.1801996],[0.3906146,-1.4490235,5.874908],[0.4595724,-0.6682117,5.827148],[0.3639935,-0.6686635,6.2016883]],"facets":10,"panels":[],"bolts":0}, + "Torso.Hood2F.L": {"solid":[[-0.4755452,-0.6863772,6.2054691],[-0.5590963,-0.6859823,5.8780618],[-0.4919126,-1.4467067,5.924593],[-0.4256355,-1.4462472,6.1845303],[-0.4353537,-0.6490453,6.2317157],[-0.5370334,-0.6485647,5.8332686],[-0.4636741,-1.4792155,5.8840771],[-0.3808642,-1.4786416,6.2088552],[-0.3639935,-0.6686635,6.2016883],[-0.4595724,-0.6682117,5.827148],[-0.3906146,-1.4490235,5.874908],[-0.3127733,-1.4484841,6.1801996]],"facets":10,"panels":[],"bolts":0}, + "Torso.Hood3D.R": {"solid":[[0.1032437,-2.2453222,6.2714987],[0.2205016,-2.2456303,6.2435641],[0.2724218,-1.5248752,6.2962074],[0.1108723,-1.5251584,6.33463],[0.0607521,-2.277041,6.2426353],[0.244008,-2.2775223,6.1989779],[0.3009622,-1.4868872,6.2567248],[0.0691178,-1.4872937,6.3118663],[0.0545442,-2.2485428,6.1899295],[0.2268047,-2.2489953,6.1488914],[0.2803416,-1.5057983,6.2031736],[0.0624079,-1.5061804,6.2550068]],"facets":10,"panels":[],"bolts":0}, + "Torso.Hood3D.L": {"solid":[[-0.1108722,-1.5251584,6.33463],[-0.2724218,-1.5248752,6.2962074],[-0.2205016,-2.2456303,6.2435641],[-0.1032437,-2.2453222,6.2714987],[-0.0691178,-1.4872937,6.3118663],[-0.3009622,-1.4868872,6.2567248],[-0.244008,-2.2775223,6.1989779],[-0.0607521,-2.277041,6.2426353],[-0.0624079,-1.5061804,6.2550068],[-0.2803416,-1.5057983,6.2031736],[-0.2268047,-2.2489953,6.1488914],[-0.0545442,-2.2485428,6.1899295]],"facets":10,"panels":[],"bolts":0}, + "Torso.Hood3F.R": {"solid":[[0.3368095,-2.2442985,6.1210251],[0.3540591,-2.2438414,6.0513573],[0.4430484,-1.5238899,5.9266953],[0.3822896,-1.5235535,6.1727257],[0.2923129,-2.2766652,6.144166],[0.3244511,-2.2758133,6.0143657],[0.4220367,-1.4863158,5.8776622],[0.3422129,-1.4858738,6.2008915],[0.2325801,-2.2478509,6.1235294],[0.2627901,-2.24705,6.0015173],[0.3545205,-1.5049223,5.8730159],[0.2794862,-1.5045068,6.1768513]],"facets":10,"panels":[],"bolts":0}, + "Torso.Hood3F.L": {"solid":[[-0.3822896,-1.5235535,6.1727257],[-0.4430485,-1.5238899,5.9266953],[-0.3540591,-2.2438414,6.0513573],[-0.3368095,-2.2442985,6.1210251],[-0.3422129,-1.4858738,6.2008915],[-0.4220367,-1.4863158,5.8776622],[-0.3244511,-2.2758133,6.0143661],[-0.2923129,-2.2766652,6.144166],[-0.2794861,-1.5045068,6.1768513],[-0.3545205,-1.5049223,5.8730159],[-0.2627901,-2.24705,6.0015173],[-0.2325801,-2.2478509,6.1235294]],"facets":10,"panels":[],"bolts":0}, + "Torso.HoodLip.R": {"solid":[[0.3319675,-2.1517057,5.8672805],[0.2972293,-2.1460621,5.8425512],[0.6060616,0.3312727,5.2865472],[0.7946815,0.3373919,5.4095373],[0.3353004,-2.1816168,5.9219961],[0.2456244,-2.1670485,5.8581576],[0.5622626,0.3729025,5.2881007],[0.8116803,0.380994,5.4507341],[0.3257884,-2.0959625,5.932734],[0.241493,-2.0822682,5.872726],[0.5391329,0.3052856,5.3368726],[0.7735855,0.3128915,5.4897475]],"facets":10,"panels":[],"bolts":0}, + "Torso.HoodLip.L": {"solid":[[-0.7946815,0.3373919,5.4095373],[-0.6060616,0.3312727,5.2865472],[-0.2972293,-2.1460621,5.8425512],[-0.3319675,-2.1517057,5.8672805],[-0.8116803,0.380994,5.4507341],[-0.5622626,0.3729025,5.2881007],[-0.2456244,-2.1670485,5.8581576],[-0.3353004,-2.1816168,5.9219961],[-0.7735855,0.3128915,5.4897475],[-0.5391329,0.3052856,5.3368726],[-0.241493,-2.0822682,5.872726],[-0.3257884,-2.0959625,5.932734]],"facets":10,"panels":[],"bolts":0} + }} + ]} diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 49d85e2..98feaca 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -2267,7 +2267,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", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json", "ram.py", "route.py"]) + self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json", "plate.py", "ram.py", "route.py"]) for pattern in self.PACKAGE: for name, text in self.sources().items(): if pattern is self.PACKAGE[2] and name == "__init__.py": @@ -2279,6 +2279,9 @@ class OwnershipTests(unittest.TestCase): self.assertIn('modifier.solver = "MANIFOLD"', source.split("class BROKKR_KITBASH_OT_ribs(")[1].split("class BROKKR_KITBASH_OT_")[0]) self.assertIn('"COLLECTION", "EXACT", True', source.split("def operation_collection(")[1].split("\n\n\n")[0]) self.assertIsNone(re.search(self.CORE, self.sources()["core.py"], re.M)) + # plate.py is core's kind: no Blender, no experiment module, and no random source but a seeded one + self.assertIsNone(re.search(self.CORE, self.sources()["plate.py"], re.M)) + self.assertIsNone(re.search(r"Random\(\)|^\s*(import|from)\s+(massing|mechlib|surface|mathutils)", self.sources()["plate.py"], re.M)) schemas = [p for p in (SURFACE.parents[1] / "schemas").rglob("*") if p.is_file()] self.assertTrue(schemas) for path in schemas: diff --git a/surfaces/blender/tests/test_plate.py b/surfaces/blender/tests/test_plate.py new file mode 100644 index 0000000..890da4b --- /dev/null +++ b/surfaces/blender/tests/test_plate.py @@ -0,0 +1,484 @@ +"""Hard plate tests. No Blender: brokkr_kitbash/plate.py against solids with known corners and against the three mech +tracks' own builders (fixtures/plates_*.json: each a table and the truth its branch's builder made in Blender 5.3). + +Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) + +The truth is float32 (mathutils and Blender meshes) and plate.py is float64; KNOWN lists every fixture plate where +that, a corner the branch's builder lost, or a tie Blender's mesh order decided keeps the two apart, with what is +asserted of it instead. +""" +from __future__ import annotations + +import copy +import importlib +import inspect +import json +import math +import sys +import types +import unittest +from pathlib import Path + +SURFACE = Path(__file__).resolve().parents[1] +FIXTURES = Path(__file__).resolve().parent / "fixtures" + +try: + import numpy as np +except ImportError: # pragma: no cover + np = None + +if np is not None: + package = types.ModuleType("brokkr_kitbash_plates") # the package's own __init__ wants bpy + package.__path__ = [str(SURFACE / "brokkr_kitbash")] + sys.modules["brokkr_kitbash_plates"] = package + plate = importlib.import_module("brokkr_kitbash_plates.plate") + +BOX = [{"at": [1, 0, 0], "normal": [1, 0, 0]}, {"at": [-1, 0, 0], "normal": [-1, 0, 0]}, {"at": [0, 1, 0], "normal": [0, 1, 0]}, + {"at": [0, -1, 0], "normal": [0, -1, 0]}, {"at": [0, 0, 1], "normal": [0, 0, 1]}, {"through": [[0, 0, -1], [1, 0, -1], [0, 1, -1]], "out": [0, 0, -1]}] +CLAD = {"mat": "olive_light", "min_area": 0.2, "lifts": [0.04, 0.07], "inset": 0.075, "gap": 0.045, "split": 0.8, "seed": 5} +SLAB = {"at": [0.5, 1.0, 0.0], "normal": [0.06, 1, 0.05], "outline": {"w": 0.8, "h": 1.2, "clip": 0.1}, "thick": 0.2} + + +def doc(*rows): + return {"schema": "brokkr.plates.v0", "plates": [copy.deepcopy(r) for r in rows]} + + +def row(name="p", **more): + out = {"name": name, "mat": "olive"} + out.update(copy.deepcopy(more)) + if not any(k in out for k in ("faces", "slab", "sections", "points")): + out["faces"] = copy.deepcopy(BOX) + return out + + +def volume(mesh): + V, faces = mesh + return sum(float(np.dot(V[f[0]], np.cross(V[f[i]], V[f[i + 1]]))) for f in faces for i in range(1, len(f) - 1)) / 6 + + +def apart(a, b): + """How far two point sets stand from each other: the farthest any point of one is from the other's nearest.""" + a, b = np.asarray(a, dtype=float).reshape(-1, 3), np.asarray(b, dtype=float).reshape(-1, 3) + if not len(a) or not len(b): + return 0.0 if len(a) == len(b) else math.inf + d = np.linalg.norm(a[:, None, :] - b[None, :, :], axis=2) + return float(max(d.min(axis=1).max(), d.min(axis=0).max())) + + +@unittest.skipIf(np is None, "numpy is not installed") +class CheckTests(unittest.TestCase): + def refused(self, document, path): + with self.assertRaises(plate.PlateError) as caught: + plate.check(document) + self.assertIn(path, str(caught.exception)) + + def test_defaults_are_written_in_and_check_takes_its_own_answer(self): + table = plate.check(doc(row(slab=SLAB, clad=CLAD))) + slab = table["plates"][0]["slab"] + self.assertEqual((slab["taper"], slab["back"], slab["gap"], slab["up"]), (0.04, 1.0, 0.0, [0.0, 0.0, 1.0])) + self.assertEqual((table["plates"][0]["sides"], table["plates"][0]["mirror"], table["plates"][0]["clad"]["facets"], table["plates"][0]["clad"]["bolt_r"]), ("one", False, "outer", 0.028)) + self.assertEqual(plate.check(table), table) + + def test_schema(self): + self.refused({"schema": "brokkr.plates.v1", "plates": [row()]}, "document.schema") + + def test_unknown_key(self): + self.refused(doc(row(colour="red")), "plates[0].colour") + self.refused(doc(row(slab=dict(SLAB, depth=1))), "plates[0].slab.depth") + self.refused(doc(row(slab=SLAB, clad=dict(CLAD, lift=0.1))), "plates[0].clad.lift") + self.refused(dict(doc(row()), units="m"), "document.units") + + def test_no_solid_form_and_two(self): + bare = {"name": "p", "mat": "olive"} + self.refused(doc(bare), "plates[0]: wants exactly one solid form") + self.refused(doc(row(points=[[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], faces=BOX)), "plates[0]: wants exactly one solid form") + + def test_duplicate_name(self): + self.refused(doc(row("a"), row("a")), "plates[1].name") + self.refused(doc(row("a", sides="both"), row("a.L")), "plates[1].name") + + def test_name(self): + self.refused(doc(row("a b")), "plates[0].name") + self.refused(doc(row("a" * 49)), "plates[0].name") + + def test_non_finite_number(self): + self.refused(doc(row(slab=dict(SLAB, at=[0, math.nan, 0]))), "plates[0].slab.at[1]") + self.refused(doc(row(points=[[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, math.inf]])), "plates[0].points[3][2]") + self.refused(doc(row(slab=dict(SLAB, thick=True))), "plates[0].slab.thick") + + def test_outline_under_three_points(self): + self.refused(doc(row(slab=dict(SLAB, outline=[[0, 0], [1, 0]]))), "plates[0].slab.outline") + + def test_outline_of_sixty_five_points(self): + ring = [[math.cos(2 * math.pi * k / 65), math.sin(2 * math.pi * k / 65)] for k in range(65)] + self.refused(doc(row(slab=dict(SLAB, outline=ring))), "plates[0].slab.outline") + plate.check(doc(row(slab=dict(SLAB, outline=ring[:64])))) + + def test_outline_crossing_itself(self): + self.refused(doc(row(slab=dict(SLAB, outline=[[0, 0], [2, 2], [2, 0], [0, 1]]))), "plates[0].slab.outline: the outline crosses itself") + + def test_outline_of_zero_area(self): + self.refused(doc(row(slab=dict(SLAB, outline=[[0, 0], [1, 0], [2, 0]]))), "plates[0].slab.outline: the outline has zero area") + + def test_slab_ranges(self): + for key, low, high in (("thick", 0.0005, 2.5), ("taper", -0.01, 0.6), ("back", 0.05, 1.6), ("gap", -0.01, 0.6)): + for value in (low, high): + self.refused(doc(row(slab=dict(SLAB, **{key: value}))), f"plates[0].slab.{key}") + + def test_taper_half_the_least_width(self): + self.refused(doc(row(slab=dict(SLAB, outline=[[0, 0], [1, 0], [1, 0.2], [0, 0.2]], taper=0.1))), "plates[0].slab.taper") + plate.check(doc(row(slab=dict(SLAB, outline=[[0, 0], [1, 0], [1, 0.2], [0, 0.2]], taper=0.09)))) + + def test_corners_off_their_plane(self): + slab = {"corners": [[0, 0, 0], [1, 0, 0], [1, 1, 0.5], [0, 1, 0]], "inside": [0.5, 0.5, -1], "thick": 0.1} + self.refused(doc(row(slab=slab)), "plates[0].slab.corners") + plate.check(doc(row(slab=dict(slab, corners=[[0, 0, 0], [1, 0, 0], [1, 1, 0.1], [0, 1, 0]])))) + + def test_faces_that_bound_nothing(self): + self.refused(doc(row(faces=BOX[:4])), "plates[0].faces") + self.refused(doc(row(faces=BOX[:5] + [{"at": [0, 0, 2], "normal": [0, 0, -1]}])), "plates[0].faces") + open_box = BOX[:5] + [{"at": [0, 0, -5000], "normal": [0, 0, -1]}] + self.refused(doc(row(faces=open_box)), "plates[0].faces") + + def test_coplanar_points(self): + self.refused(doc(row(points=[[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0.3, 0.2, 0]])), "plates[0]: the points lie in one plane") + + def test_seed_pair_on_a_one_sided_row(self): + self.refused(doc(row(slab=SLAB, clad=dict(CLAD, seed=[1, 2]))), "plates[0].clad.seed") + plate.check(doc(row(slab=SLAB, sides="both", clad=dict(CLAD, seed=[1, 2])))) + + def test_no_default_seed(self): + self.refused(doc(row(slab=SLAB, clad={k: v for k, v in CLAD.items() if k != "seed"})), "plates[0].clad.seed") + self.refused(doc(row(slab=SLAB, clad=dict(CLAD, seed=1.5))), "plates[0].clad.seed") + + def test_up_along_the_normal(self): + self.refused(doc(row(slab=dict(SLAB, normal=[0, 0, 1]))), "plates[0].slab.normal") + plate.check(doc(row(slab=dict(SLAB, normal=[0, 0, 1], up=[0, 1, 0])))) + + def test_unknown_fit_kind(self): + with self.assertRaises(plate.PlateError) as caught: + plate.check(doc(row(slab=SLAB, fits=[{"kind": "bolts", "at": [0, 0]}]))) + self.assertIn("plates[0].fits[0].kind", str(caught.exception)) + self.assertIn("mark, hose_port", str(caught.exception)) + + def test_duplicate_anchor_name(self): + fits = [{"kind": "mark", "id": "a", "at": [0, 0], "height": 0.3}, {"kind": "hose_port", "name": "a", "at": [0.1, 0]}] + self.refused(doc(row(slab=SLAB, fits=fits)), "plates[0].fits[1]") + + def test_fit_without_a_face(self): + self.refused(doc(row(fits=[{"kind": "hose_port", "name": "a", "at": [0, 0]}])), "plates[0].fits[0]") + self.refused(doc(row(slab=SLAB, face={"at": [0, 0, 0], "normal": [0, 1, 0]})), "plates[0].face") + + def test_outer_wants_a_face(self): + self.refused(doc(row(clad=dict(CLAD, facets="outer"))), "plates[0].clad.facets") + self.refused(doc(row(clad=CLAD)), "plates[0].clad.facets") + + def test_rows(self): + self.refused({"schema": "brokkr.plates.v0", "plates": [row(f"p{k}") for k in range(257)]}, "plates: wants 1 to 256") + self.refused({"schema": "brokkr.plates.v0", "plates": []}, "plates: wants 1 to 256") + + def test_side(self): + with self.assertRaises(plate.PlateError): + plate.build(doc(row()), 0) + + +@unittest.skipIf(np is None, "numpy is not installed") +class SolidTests(unittest.TestCase): + def test_a_cube_from_six_faces(self): + made = plate.build(doc(row()))[0] + self.assertEqual(made["report"], {"corners": 8, "facets": 6, "panels": 0, "bolts": 0}) + self.assertEqual(sorted(map(tuple, np.round(made["solid"][0]).astype(int).tolist())), sorted((x, y, z) for x in (-1, 1) for y in (-1, 1) for z in (-1, 1))) + self.assertAlmostEqual(volume(made["solid"]), 8.0, places=12) + + def test_a_slab_has_a_flat_outer_face_and_its_taper_ring(self): + made = plate.build(doc(row(slab=dict(SLAB, back=0.9))))[0] + V, faces = made["solid"] + n = np.array(SLAB["normal"]) / np.linalg.norm(SLAB["normal"]) + depth = np.round((V - np.array(SLAB["at"])) @ n, 9) + self.assertEqual(sorted(set(depth.tolist())), [-0.2, -0.04, 0.0]) + self.assertEqual([int((depth == d).sum()) for d in (0.0, -0.04, -0.2)], [8, 8, 8]) + outer = [f for f, facet in zip(faces, made["facets"]) if facet["normal"] @ n > 0.999] + self.assertEqual(len(outer), 1) + self.assertEqual(len(outer[0]), 8) + self.assertAlmostEqual(made["facets"][faces.index(outer[0])]["area"], (0.8 - 0.08) * (1.2 - 0.08) - 2 * (0.1 - 0.04 * (2 - math.sqrt(2))) ** 2, places=9) + ring, rear = V[depth == -0.04], V[depth == -0.2] + middle = ring.mean(axis=0) - n * 0.16 + self.assertLess(apart(rear, middle + (ring - n * 0.16 - middle) * 0.9), 1e-12) + + def test_an_outline_as_a_clipped_rectangle_is_its_eight_points(self): + ring = [[-0.3, 0.6], [0.3, 0.6], [0.4, 0.5], [0.4, -0.5], [0.3, -0.6], [-0.3, -0.6], [-0.4, -0.5], [-0.4, 0.5]] + a, b = plate.build(doc(row(slab=SLAB)))[0], plate.build(doc(row(slab=dict(SLAB, outline=ring[::-1]))))[0] + self.assertLess(apart(a["solid"][0], b["solid"][0]), 1e-12) + self.assertEqual(len(plate.build(doc(row(slab=dict(SLAB, outline={"w": 0.8, "h": 1.2, "clip": 0}))))[0]["solid"][0]), 12) + + def test_a_gap_draws_the_outline_in(self): + wide, drawn = (plate.build(doc(row(slab=dict(SLAB, outline=[[0, 0], [1, 0], [1, 1], [0, 1]], taper=0.0, gap=g))))[0] for g in (0.0, 0.1)) + self.assertAlmostEqual(wide["facets"][0]["area"], 1.0, places=12) + self.assertAlmostEqual(drawn["facets"][0]["area"], 0.64, places=12) + + def test_a_corners_slab_stands_its_lift_off_coplanar_corners(self): + corners = [[1, 0, 0], [0, 1, 0], [0, 1, 1], [1, 0, 1]] # all on x + y = 1 + made = plate.build(doc(row(slab={"corners": corners, "names": ["a", "b", "c", "d"], "inside": [0, 0, 0.5], "lift": 0.06, "thick": 0.1, "taper": 0.03})))[0] + n = np.array([1.0, 1.0, 0.0]) / math.sqrt(2) + off = np.round(made["solid"][0] @ n - 1 / math.sqrt(2), 12) + self.assertEqual(sorted(set(off.tolist())), [-0.04, 0.03, 0.06]) + flipped = plate.build(doc(row(slab={"corners": corners, "inside": [2, 2, 0.5], "thick": 0.1, "taper": 0.03})))[0] + self.assertEqual(sorted(set(np.round(flipped["solid"][0] @ -n + 1 / math.sqrt(2), 12).tolist())), [-0.04, 0.03, 0.06]) + + def test_sections(self): + made = plate.build(doc(row(sections=[[0.4, 0.9, -0.3, 0.5, 0.12], [-1.8, 0.95, -0.3, 0.5, 0.14]])))[0] + self.assertEqual(made["report"]["corners"], 16) + self.assertEqual(made["report"]["facets"], 10) + self.assertEqual(sorted(set(np.round(made["solid"][0][:, 2], 12).tolist())), [-1.8, 0.4]) + + def test_mirror_is_one_solid_across_the_centre(self): + half = [[0.5, 0, 0], [0.5, 1, 0], [0.5, 0, 1], [0.5, 1, 1], [0, 0, 0], [0, 1, 0], [0, 0, 1], [0, 1, 1]] + made = plate.build(doc(row(points=half, mirror=True)))[0] + self.assertEqual(made["report"]["corners"], 8) + self.assertAlmostEqual(volume(made["solid"]), 1.0, places=12) + self.assertEqual(sorted(set(made["solid"][0][:, 0].tolist())), [-0.5, 0.5]) + + def test_side_minus_one_is_the_mirror_and_both_sides_are_named(self): + right, left = plate.build(doc(row(slab=SLAB, sides="both"))) + self.assertEqual((right["name"], right["side"], left["name"], left["side"]), ("p.R", 1, "p.L", -1)) + self.assertLess(apart(right["solid"][0] * (-1, 1, 1), left["solid"][0]), 1e-12) + self.assertAlmostEqual(volume(left["solid"]), volume(right["solid"]), places=12) + self.assertEqual([e["name"] for e in plate.build(doc(row(slab=SLAB, sides="both")), -1)], ["p.L", "p.R"]) + self.assertLess(apart(plate.build(doc(row(slab=SLAB)), -1)[0]["solid"][0], left["solid"][0]), 1e-12) + + +@unittest.skipIf(np is None, "numpy is not installed") +class HullTests(unittest.TestCase): + def roof(self, degrees): + """A box whose top is two facets meeting on a ridge, their normals `degrees` apart.""" + h = math.tan(math.radians(degrees / 2)) + return [[x, y, 0] for x in (-1, 1) for y in (-1, 1)] + [[x, y, 1] for x in (-1, 1) for y in (-1, 1)] + [[0, -1, 1 + h], [0, 1, 1 + h]] + + def test_facets_are_flat_closed_and_face_out(self): + for case in (row(), row(slab=SLAB), row(sections=[[0.4, 0.9, -0.3, 0.5, 0.12], [-1.8, 0.95, -0.3, 0.5, 0.14]])): + made = plate.build(doc(case))[0] + V, faces = made["solid"] + edges = {} + for face, facet in zip(faces, made["facets"]): + self.assertLess(float(np.abs((V[face] - V[face[0]]) @ facet["normal"]).max()), 1e-9) + self.assertGreater(float((facet["centre"] - V.mean(axis=0)) @ facet["normal"]), 0) + for a, b in zip(face, face[1:] + face[:1]): + edges[(a, b)] = edges.get((a, b), 0) + 1 + self.assertTrue(all(count == 1 and edges.get((b, a)) == 1 for (a, b), count in edges.items())) + self.assertGreater(volume(made["solid"]), 0) + + def test_facets_within_half_a_degree_are_one(self): + V, faces, facets = plate.hull(self.roof(0.4)) + self.assertEqual((len(V), len(faces)), (8, 6)) # the ridge's ends turn 0.4 degrees on the gables: dropped + + def test_facets_over_half_a_degree_stay_two(self): + V, faces, facets = plate.hull(self.roof(0.6)) + self.assertEqual((len(V), len(faces)), (10, 7)) + + def test_a_vertex_on_a_straight_run_is_dropped(self): + V, faces, facets = plate.hull(self.roof(0.3)) + self.assertEqual(sorted(len(f) for f in faces), [4] * 6) + + def test_points_inside_and_on_edges_are_no_corners(self): + cube = [[x, y, z] for x in (0, 1) for y in (0, 1) for z in (0, 1)] + V, faces, facets = plate.hull(cube + [[0.5, 0.5, 0.5], [0.5, 0, 0], [0.5, 0.5, 0], [1, 1, 1]]) + self.assertEqual((len(V), len(faces)), (8, 6)) + + def test_order_is_area_then_the_greater_centre(self): + V, faces, facets = plate.hull([[x, y, z] for x in (-1, 1) for y in (-2, 2) for z in (-3, 3)]) + self.assertEqual([round(f["area"]) for f in facets], [24, 24, 12, 12, 8, 8]) + self.assertEqual([f["normal"].round().astype(int).tolist() for f in facets], [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]]) + self.assertTrue(all(tuple(V[face[0]]) == min(tuple(V[k]) for k in face) for face in faces)) + + +@unittest.skipIf(np is None, "numpy is not installed") +class CladTests(unittest.TestCase): + def test_same_seed_same_bytes(self): + table = doc(row("a", slab=SLAB, clad=CLAD), row("b", clad=dict(CLAD, facets="all", seed=9))) + one, two = plate.build(table), plate.build(copy.deepcopy(table)) + for a, b in zip(one, two): + for key in ("solid", "panels", "bolts"): + self.assertEqual(a[key][0].tobytes(), b[key][0].tobytes()) + self.assertEqual(a[key][1], b[key][1]) + self.assertEqual(json.dumps(a["anchors"]), json.dumps(b["anchors"])) + + def test_seed_plus_one_changes_that_plate_and_no_other(self): + table = doc(row("a", clad=dict(CLAD, facets="all", seed=9)), row("b", clad=dict(CLAD, facets="all", seed=9))) + base = plate.build(table) + table["plates"][0]["clad"]["seed"] = 10 + moved = plate.build(table) + self.assertNotEqual(base[0]["panels"][0].tobytes(), moved[0]["panels"][0].tobytes()) + self.assertEqual(base[1]["panels"][0].tobytes(), moved[1]["panels"][0].tobytes()) + self.assertEqual(base[0]["panels"][0].tobytes(), base[1]["panels"][0].tobytes()) + + def test_a_seed_pair_is_right_then_left(self): + pair = plate.build(doc(row(sides="both", clad=dict(CLAD, facets="all", seed=[9, 10])))) + nine, ten = (plate.build(doc(row(clad=dict(CLAD, facets="all", seed=s))), side)[0] for s, side in ((9, 1), (10, -1))) + self.assertEqual(pair[0]["panels"][0].tobytes(), nine["panels"][0].tobytes()) + self.assertEqual(pair[1]["panels"][0].tobytes(), ten["panels"][0].tobytes()) + self.assertNotEqual(pair[1]["panels"][0].tobytes(), plate.build(doc(row(clad=dict(CLAD, facets="all", seed=9))), -1)[0]["panels"][0].tobytes()) + + def test_a_split_facet_takes_two_panels_and_a_whole_one_a_panel(self): + made = plate.build(doc(row(clad=dict(CLAD, facets=[{"n": [0, 0, 1], "cos": 0.9}], split=2.2))))[0] + self.assertEqual(made["report"], {"corners": 8, "facets": 6, "panels": 2, "bolts": 8}) + self.assertEqual((len(made["panels"][0]), len(made["bolts"][0])), (24, 96)) + self.assertGreater(volume(made["panels"]), 0) + self.assertAlmostEqual(volume(made["bolts"]), 8 * 1.5 * math.sqrt(3) * 0.028 ** 2 * 0.6 * 0.028, places=12) + tops = sorted(set(np.round(made["panels"][0][:, 2] - 1, 9).tolist())) + self.assertEqual(tops, [-0.02, 0.02, 0.04, 0.05, 0.07]) # sunk 0.02; rims at lift less 0.02; lifts 0.04 and 0.07 + whole = plate.build(doc(row(clad=dict(CLAD, facets=[{"n": [0, 0, 1], "cos": 0.9}], split=4.0))))[0] + self.assertEqual(whole["report"]["panels"], 1) + + def test_outer_is_the_face_and_not_its_neighbour(self): + lean = math.radians(18) # the neighbour's normal is cos 0.951 on the face's + faces = BOX[:4] + [{"at": [0, 0, 1], "normal": [0, 0, 1]}, {"at": [0, 0, -1], "normal": [0, 0, -1]}, {"at": [0.2, 0, 1], "normal": [math.sin(lean), 0, math.cos(lean)]}] + made = plate.build(doc(row(faces=faces, face={"at": [0, 0, 1], "normal": [0, 0, 1], "up": [0, 1, 0]}, clad=dict(CLAD, facets="outer", min_area=0.5, split=99))))[0] + big = [f for f in made["facets"] if f["normal"][2] > 0.9] + self.assertEqual(len(big), 2) + self.assertTrue(all(f["area"] > 0.5 for f in big)) + self.assertEqual(made["report"]["panels"], 1) + + def test_selectors_and_the_floor(self): + count = lambda **clad: plate.build(doc(row(clad=dict(CLAD, split=99, **clad))))[0]["report"]["panels"] # noqa: E731 + self.assertEqual(count(facets="all"), 6) + self.assertEqual(count(facets="all", floor=-0.35), 5) + self.assertEqual(count(facets=[{"n": [0, 0, 1], "cos": 0.6}]), 1) + self.assertEqual(count(facets=[{"radial": [0, 0, 1], "min_r": 0.5, "cos": 0.25}]), 4) + self.assertEqual(count(facets=[{"radial": [0, 0, 1], "min_r": 1.5, "cos": 0.25}]), 0) + self.assertEqual(count(facets=[{"n": [0, 0, 1], "cos": 0.6}, {"radial": [0, 0, 1], "min_r": 0.5, "cos": 0.25}]), 5) + self.assertEqual(count(facets="all", min_area=4.5), 0) + + def test_a_selector_is_mirrored_with_the_side(self): + table = doc(row(clad=dict(CLAD, split=99, facets=[{"n": [1, 0, 0], "cos": 0.9}]))) + right, left = plate.build(table, 1)[0], plate.build(table, -1)[0] + self.assertGreater(float(right["panels"][0][:, 0].min()), 0.9) + self.assertLess(float(left["panels"][0][:, 0].max()), -0.9) + + def test_a_tied_longest_edge_goes_to_the_greater_middle(self): + made = plate.build(doc(row(points=[[x, y, z] for x in (-2, 2) for y in (-1, 1) for z in (0, 1)], clad=dict(CLAD, split=1.0, facets=[{"n": [0, 0, 1], "cos": 0.9}]))))[0] + self.assertEqual(plate._longest([np.array(p, dtype=float) for p in ([-2, -1, 1], [2, -1, 1], [2, 1, 1], [-2, 1, 1])]), 2) + self.assertEqual(made["report"]["panels"], 2) + + +@unittest.skipIf(np is None, "numpy is not installed") +class AnchorTests(unittest.TestCase): + FITS = [{"kind": "mark", "id": "07", "at": [0.1, -0.05], "height": 0.42}, {"kind": "hose_port", "name": "feed", "at": [-0.2, 0.3], "lift": 0.01}] + + def test_frames_stand_on_the_face(self): + mark, port = plate.build(doc(row(slab=dict(SLAB, right=[1, 0, 0]), fits=self.FITS)))[0]["anchors"] + a, b, n = plate.plane_basis(SLAB["normal"], (0, 0, 1), (1, 0, 0)) + self.assertGreater(a[0], 0) + m, p = np.array(mark["matrix"]), np.array(port["matrix"]) + self.assertEqual((mark["kind"], mark["name"], mark["height"], mark["mirrored"]), ("mark", "07", 0.42, False)) + self.assertEqual((port["kind"], port["name"], port["mirrored"], "height" in port), ("hose_port", "feed", False, False)) + self.assertLess(float(np.abs(m[:3, 3] - (np.array(SLAB["at"]) + a * 0.1 - b * 0.05)).max()), 1e-12) + self.assertLess(float(np.abs(p[:3, 3] - (np.array(SLAB["at"]) - a * 0.2 + b * 0.3 + n * 0.01)).max()), 1e-12) + for frame in (m, p): + self.assertLess(float(np.abs(frame[:3, 2] - n).max()), 1e-12) + self.assertAlmostEqual(float(np.linalg.det(frame[:3, :3])), 1.0, places=12) + upright = np.array([0.0, 0.0, 1.0]) - n * n[2] # a mark's y is the table's +z off the normal + self.assertLess(float(np.abs(m[:3, 1] - upright / np.linalg.norm(upright)).max()), 1e-12) + self.assertGreater(float(m[2, 1]), 0.99) + self.assertLess(float(np.abs(p[:3, 1] - b).max()), 1e-12) # a port's y is the face's up + + def test_right_handed_at_side_minus_one(self): + table = doc(row(slab=dict(SLAB, right=[1, 0, 0]), fits=self.FITS)) + for right, left in zip(plate.build(table, 1)[0]["anchors"], plate.build(table, -1)[0]["anchors"]): + r, m = np.array(right["matrix"]), np.array(left["matrix"]) + self.assertTrue(left["mirrored"]) + self.assertAlmostEqual(float(np.linalg.det(m[:3, :3])), 1.0, places=12) + self.assertLess(float(np.abs(m[:3, 3] - r[:3, 3] * (-1, 1, 1)).max()), 1e-12) + self.assertLess(float(np.abs(m[:3, 2] - r[:3, 2] * (-1, 1, 1)).max()), 1e-12) + self.assertLess(float(np.abs(m[:3, 1] - r[:3, 1] * (-1, 1, 1)).max()), 1e-12) + + def test_anchors_stand_on_the_clad_face(self): + bare = plate.build(doc(row(slab=SLAB, fits=self.FITS)))[0]["anchors"][0] + clad = plate.build(doc(row(slab=SLAB, fits=self.FITS, clad=dict(CLAD, lifts=[0.05, 0.05], split=99))))[0]["anchors"][0] + n = np.array(SLAB["normal"]) / np.linalg.norm(SLAB["normal"]) + self.assertLess(float(np.abs(np.array(clad["matrix"])[:3, 3] - np.array(bare["matrix"])[:3, 3] - n * 0.05).max()), 1e-12) + + def test_a_face_on_a_row_that_is_no_slab(self): + made = plate.build(doc(row(face={"at": [0, 1, 0], "normal": [0, 1, 0]}, fits=[self.FITS[1]])))[0] + self.assertLess(float(np.abs(np.array(made["anchors"][0]["matrix"])[:3, 3] - np.array([0.2, 1.01, 0.3])).max()), 1e-12) + + +@unittest.skipIf(np is None, "numpy is not installed") +class DeterminismTests(unittest.TestCase): + def test_the_table_and_the_side_are_the_only_inputs(self): + self.assertEqual(list(inspect.signature(plate.build).parameters), ["table", "side"]) + self.assertEqual(list(inspect.signature(plate.check).parameters), ["document"]) + + def test_build_leaves_the_table_as_given(self): + table = doc(row(slab=SLAB, clad=CLAD)) + kept = copy.deepcopy(table) + plate.build(table) + self.assertEqual(table, kept) + + +# Fixture plates the truth cannot be met on, each with what is asserted instead (cut hard-plate-core's report has the readings): +# float32 the branch solved the plate in float32 (mathutils); it stands up to 2e-6 m (solid) or 3e-5 m (panels) from the float64 solid +# corner the branch's massing.corners lost a true corner to its float32 inside test: its solid lacks one corner plate.py has +# tie two edges of the split facet are equally long and the branch's choice followed Blender's loop order, which differs +# between the two sides of this row; plate.py's rule (the greater middle) meets the other side's truth +KNOWN = {("bastion", "Hull.Cheek.R"): "float32", ("bastion", "Hull.Cheek.L"): "float32", ("bastion", "Hull.BellySide.L"): "float32", + ("bastion", "Hull.Quarter.R"): "corner", ("bastion", "Hull.Quarter.L"): "corner", ("bastion", "Hull.BellySide.R"): "tie", + ("raptor", "Torso.Jaw1.L"): "float32", ("raptor", "Torso.Cheek.R"): "float32", ("raptor", "Torso.Cheek.L"): "float32", + ("raptor", "Torso.Belt3.R"): "float32", ("raptor", "Torso.Belt3.L"): "float32"} +SOLID, PANELS = 1e-6, 1e-5 # the cut's tolerances, metres +FLOAT32 = (4e-6, 4e-5) # for a KNOWN float32 plate: a few float32 steps at 8 m, and the same through an inset + + +@unittest.skipIf(np is None, "numpy is not installed") +class ParityTests(unittest.TestCase): + """plate.build against each branch's own builder: solid vertices as a set, facet count, panel vertices as a set, + bolt count. Kills: the miter clamp 0.3 -> 0.5; the cut's share (0.36, 0.64) -> (0.3, 0.7); the lift-order coin + removed; a slab's gap ignored (raptor). The outer test 0.97 -> 0.9 is CladTests' (no fixture facet stands + between the two).""" + + def parity(self, mech, plates): + fixture = json.loads((FIXTURES / f"plates_{mech}.json").read_text(encoding="utf-8")) + seen = 0 + for case in fixture["cases"]: + built = {e["name"]: e for e in plate.build(fixture["table"], case["side"])} + for name, truth in case["truth"].items(): + made, known = built[name], KNOWN.get((mech, name)) + seen += 1 + with self.subTest(plate=name, side=case["side"]): + solid, panels = apart(made["solid"][0], truth["solid"]), apart(made["panels"][0], truth["panels"]) + if known == "corner": + V, T = made["solid"][0], np.array(truth["solid"]) + d = np.linalg.norm(V[:, None, :] - T[None, :, :], axis=2) + self.assertLess(float(d.min(axis=0).max()), FLOAT32[0]) # every corner of the branch's is one of these + self.assertEqual(int((d.min(axis=1) > 1e-3).sum()), 1) # and one more, which the faces do bound + continue + self.assertEqual(made["report"]["facets"], truth["facets"]) + self.assertEqual(made["report"]["bolts"], truth["bolts"]) + self.assertEqual(len(made["panels"][0]), len(truth["panels"])) + self.assertLessEqual(solid, FLOAT32[0] if known == "float32" else SOLID) + if known == "tie": + self.assertGreater(panels, 0.1) + else: + self.assertLessEqual(panels, FLOAT32[1] if known == "float32" else PANELS) + self.assertEqual(seen, plates) + + def test_bastion(self): + self.parity("bastion", 23) + + def test_paladin(self): + self.parity("paladin", 53) + + def test_raptor(self): + self.parity("raptor", 50) + + def test_the_lost_corner_is_a_corner(self): + table = plate.check(json.loads((FIXTURES / "plates_bastion.json").read_text(encoding="utf-8"))["table"]) + quarter = next(r for r in table["plates"] if r["name"] == "Hull.Quarter") + points, _ = plate._row_points(quarter, "plates") + planes = [(np.array(f["normal"]) / np.linalg.norm(f["normal"]), np.array(f["at"])) for f in quarter["faces"]] + slack = np.array([[float(n @ (p - at)) for n, at in planes] for p in points]) + self.assertTrue((slack < 1e-9).all()) # every corner is inside every face + self.assertTrue(((np.abs(slack) < 1e-9).sum(axis=1) >= 3).all()) # and on three of them + + +if __name__ == "__main__": + unittest.main() From 3acd7faddbe60062a00b093ba119b4e8d3361614 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 14:32:46 +0100 Subject: [PATCH 207/223] docs/kitbash.md: Hard plates; plate fixtures one row a line The section states the brokkr.plates.v0 table (rows, solid forms, clad, anchors, sides), the hull and facet rules, what build returns, the refusals, and how the three mech fixtures are held, with the eleven plates the branches' float32 builders keep apart. The fixtures are rewritten one table row a line; their content is unchanged. Cut hard-plate-core. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/kitbash.md | 152 ++ .../tests/fixtures/plates_bastion.json | 1315 +---------- .../tests/fixtures/plates_paladin.json | 1921 +---------------- .../blender/tests/fixtures/plates_raptor.json | 1308 +---------- 4 files changed, 234 insertions(+), 4462 deletions(-) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 7a8470d..8589e55 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -833,6 +833,158 @@ evaluate, but deleting the copy costs the same whole evaluation (1.44 to 1.54 s included, and the hole cut's temporary objects must be deleted too. So a hull with twenty cutters pays their evaluation once for every `ribs` call; iterate planes on the cage before it is cut, or with its Booleans off. +## Hard plates + +`brokkr_kitbash/plate.py` owns a hard armour plate's geometry: a convex faceted solid, every facet flat, with +raised detail panels, a bolt inside each panel corner, and the frames of what stands on it. It is numpy and the +standard library, as `core.py` and `route.py` are, and it is a library so far: `plate.check(document)` and +`plate.build(table, side=1)`. No action calls it yet and nothing here makes a Blender object. A plate the concept +draws curved is a shell (Making a shell); the two do not call each other. + +A plate table is a data document: + +```json +{"schema": "brokkr.plates.v0", "plates": [ + {"name": "Thigh.Shield", "mat": "khaki", "bevel": 0.022, + "slab": {"at": [0.02, 0.9, -0.5], "normal": [0.06, 1, 0.05], "up": [0, 0, 1], "right": [1, 0, 0], + "outline": [[-0.42, 0.98], [0.42, 0.98], [0.66, 0.5], [0.66, -0.52], [0.42, -1.0], [-0.42, -1.0], [-0.66, -0.52], [-0.66, 0.5]], + "thick": 0.26, "taper": 0.04}, + "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.05, 0.05], "inset": 0.075, "gap": 0.045, "split": 99.0, "seed": 948708}, + "fits": [{"kind": "mark", "id": "tri", "at": [0.0, -0.05], "height": 0.5}]} +]} +``` + +Coordinates are metres in the table's own frame. The module never sees a host or a world: whoever stands the +plates somewhere owns that matrix. The table alone decides the result. A table holds 1 to 256 rows. + +### A row + +| key | value | +| --- | --- | +| `name` | 1 to 48 of `a-z A-Z 0-9 _ .`, unique among the plates built | +| `mat` | a material name, 1 to 63 characters; the caller resolves it | +| `bevel` | 0 to 0.1 (default 0): the width of the chamfer the caller's Bevel gives every edge; carried, not built | +| `sides` | `"one"` (default) or `"both"`: built at `side` and at `-side`, named `.R` at side +1 and `.L` at -1 | +| `mirror` | `true`: the solid is the hull of its points and their x-mirrors, one solid across x = 0 | +| one solid form | `faces`, `slab`, `sections` or `points` (below) | +| `clad` | `null` or the detail plating (below) | +| `face` | `{at, normal, up, right}`: the face anchors stand on, for a row that is not a slab | +| `fits` | anchors (below) | + +`mirror` and `sides` are independent. Side -1 negates x of every point before the hull is built, so facets, +panels and anchors are those of the mirrored solid as built. + +### Solid forms + +Each form gives points; the plate is their convex hull. + +- `faces`: 4 to 32 half-spaces, each `{at, normal}` (kept where `n . p <= n . at`) or + `{through: [a, b, c], out}` (the plane through three points, outward toward `out`). The corners are every three + faces' meeting point that lies inside all the others within 1e-6 m. Refused with fewer than four corners or a + corner 1000 m or more away. +- `slab`: `{at, normal, up, right, outline, thick, taper, back, gap}`. The outline is drawn on the plane through + `at` facing `normal`, in (a, b): b is `up` projected into the plane, a is b cross normal, turned toward `right` + where one is given. `outline` is 3 to 64 `[a, b]` points in either winding, or `{w, h, clip}`: a w by h + rectangle with its corners cut by `clip`. The outline is drawn in by `gap` (default 0) on every edge; the outer + face is that ring moved in by `taper` (default 0.04); the ring itself stands `taper` behind the face; the back + ring stands `thick` behind, scaled by `back` (default 1) about the ring's middle (the mean of its points). +- `slab` by corners: `{corners, names, inside, lift, thick, taper, back, gap, up}`. `corners` is 3 to 64 points; + the outer face is their least-squares plane, outward away from `inside`, standing `lift` (default 0.06) off + it; the outline is the corners in that plane's frame (`core.surface_frame` at centre + normal x lift). `names` + is optional, one distinct name per corner, so a plate blocked by `brokkr_reference.block_plate` can become a + row. Corners that stand off their plane by more than 0.05 of their extent (the greatest distance between two + of them) are refused: that is not a plate. +- `sections`: 2 to 16 `[z, w, y0, y1, c]`, each a rectangle w across x from y0 to y1 at height z with its corners + cut c: a housing down a limb. +- `points`: 4 to 64 `[x, y, z]`. + +Where each came from on the three mech tracks: `faces` is bastion's carapace (`massing.corners`), `slab` paladin's +limb armour (`massing.slab_points`) with raptor's `gap`, the corners slab raptor's hull plates +(`raptor_body.wedge_plate`), `sections` paladin's and raptor's limb housings, `points` all three. + +### The hull and its facets + +The module builds the hull itself. A facet is every plane through three points that has all points on its inner +side, taken once for the set of points on it and ordered by angle about their middle. Then two rules, both at +0.5 degrees: adjacent facets whose normals are closer than that are one facet, and a vertex left with two edges +that turn less than that is dropped. + +Facets are ordered by area, largest first; areas within 1e-9 m2 tie and go to the greater centre by x, then y, +then z (the centre is the mean of the facet's vertices). The order is computed on the solid as built in the table +frame, never from where the plate stands or from a mesh's order, and it decides which facet draws from the seed +first. + +### Clad + +`clad` raises a panel on each chosen facet: + +| key | value | +| --- | --- | +| `mat` | the panels' material | +| `facets` | `"outer"` (a slab's default): facets whose normal on the face's normal is over 0.97. `"all"`. Or 1 to 8 selectors, any of which chooses: `{n, cos}` (normal on `n` over `cos`) or `{radial: axis, min_r, cos}` (the facet's centre stands over `min_r` from the axis through the origin, and its normal on the outward radial is over `cos`). A selector's direction is mirrored with the side. | +| `floor` | optional: facets whose normal's z is below it are left bare | +| `min_area` | facets under it are left bare | +| `lifts` | `[l0, l1]`: how proud panels stand | +| `inset` | how far a panel stands in from its facet's edges | +| `gap` | the seam between the two panels of a split facet | +| `split` | a facet over this area is cut in two | +| `seed` | an integer, or `[right, left]` on a row with `sides: "both"`. There is no default. | +| `bolt_r` | a bolt's corner radius (default 0.028) | + +One `random.Random(seed)` draws, in facet order. A chosen facet over `split` is cut across its longest edge at a +share drawn from 0.36 to 0.64 of that edge, the two parts `gap` apart; edges within 1e-9 m of the longest tie and +go to the edge whose middle is greater by x, y, z. Then every chosen facet draws once: under 0.5 the parts take +`l0, l1`, otherwise `l1, l0`. A panel is its part moved in by `inset` (a sharp corner moves at most inset / 0.3), +refused under a quarter of the part's area or under 0.02 m2; it is a prism from 0.02 below the facet to its lift +above, its far rim chamfered 0.02. A hexagonal bolt of radius `bolt_r` stands inside each panel corner, 3.2 +`bolt_r` in. + +### Anchors + +A fit is a frame on the face, at `[a, b]` in the face's (a, b), standing on the face's top: the face, plus +`lifts[0]` where a panel stands on it. Two kinds: + +- `{kind: "mark", id, at, height}`: z is the face's normal and y the table's +z projected off it, so a numeral + stands upright whatever the plate's lean. +- `{kind: "hose_port", name, at, lift}`: z out of the face, y the face's up, `lift` (default 0) further out. + +`build` returns each as `{kind, name, matrix, mirrored}` (and `height` for a mark). At side -1 the position, normal +and up are mirrored and the frame is made right-handed again (x = y cross z); `mirrored` says so. What stands on +an anchor is its owner's business; the fittings the mech tracks draw on a face (bolt rows, slots, vents, ports, +handles, eyes, louvres, steps) are not fits of this table yet, and any other kind is refused. + +### What build returns + +One entry per plate built, in the table's order: `name`, `row` (its index), `mat`, `bevel`, `side`, +`solid: (V, faces)`, `facets` (each face's `normal`, `area`, `centre`), `panels: (V, faces)`, `bolts: (V, faces)`, +`anchors`, and `report: {corners, facets, panels, bolts}`. `V` is an (N, 3) float64 array; faces are lists of +vertex indices wound outward. `check` returns the table with every default written in. Both are pure functions. + +Building the three mech fixtures takes 0.5 to 0.9 s each (23 to 50 plates, medians of 5 on Starfire, Python +3.13); the hull tries every plane through three points, so a slab with a 64-point outline takes 1.5 s alone. + +### Refusals + +Every refusal is a `PlateError` (a `ValueError`) that names the path, as `plates[3].slab.outline[2]` or +`plates[0].clad.seed`: a schema that is not `brokkr.plates.v0`; an unknown key anywhere; a row with no solid form +or two; a name built twice; a number that is not finite; an outline under 3 points or over 64, one that crosses +itself, repeats a point or has zero area; `thick`, `taper`, `back` or `gap` outside 0.001 to 2, 0 to 0.5, 0.1 to +1.5 and 0 to 0.5; a `taper` of half the outline's least width or more; corners that are not a plate; faces that +bound nothing; points in one plane; a pair of seeds on a one-sided row, or no seed; an `up` along the normal; a +fit on a row with no face; an unknown fit kind; two anchors of one name in a row. + +### Against the mech tracks' builders + +`tests/fixtures/plates_bastion.json`, `plates_paladin.json` and `plates_raptor.json` each hold a table converted +from a mech branch's own numbers and the solids, panels and bolt counts that branch's builder made in Blender +5.3; `tests/test_plate.py` holds `build` to them (solid vertices within 1e-6 m, panel vertices within 1e-5 m, +facet and bolt counts equal). The branches' builders work in float32 and leave two choices to Blender's mesh +order, so eleven of the 126 fixture plates are held to something else, each named in the test's `KNOWN`: +eight stand 1 to 2 micrometres (solid) or 29 micrometres (panels) from the float64 result; bastion's two +quarter pods lack a corner their faces do bound (the branch's inside test lost it to float32), so its solid is +smaller than the table's; and one of bastion's two belly-side plates splits its panel from the other of two +equally long edges. + ## Hoses between sockets `brokkr_kitbash.hose` routes a bundle of hoses from one socket to another around everything in the scene: diff --git a/surfaces/blender/tests/fixtures/plates_bastion.json b/surfaces/blender/tests/fixtures/plates_bastion.json index 703fc91..0ff6adc 100644 --- a/surfaces/blender/tests/fixtures/plates_bastion.json +++ b/surfaces/blender/tests/fixtures/plates_bastion.json @@ -1,1302 +1,21 @@ {"source": {"branch": "nibu/fable-bastion-2", "sha": "eeda8bf2defd411bebc2fd438d8934ba46e88614", "blender": "5.3.0"}, - "table": { - "schema": "brokkr.plates.v0", - "plates": [ - { - "name": "Core.upper", - "mat": "gunmetal", - "bevel": 0.0, - "mirror": true, - "points": [ - [ - 0.0, - 5.3, - 5.3 - ], - [ - 2.2, - 5.0, - 5.3 - ], - [ - 4.3, - 3.6, - 5.3 - ], - [ - 4.5, - 0.9, - 5.2 - ], - [ - 4.5, - -1.4, - 5.4 - ], - [ - 4.3, - -2.8, - 5.6 - ], - [ - 3.6, - -4.4, - 5.8 - ], - [ - 2.2, - -5.0, - 5.9 - ], - [ - 0.0, - -5.0, - 5.9 - ], - [ - 0.0, - 3.4, - 6.8 - ], - [ - 2.2, - 3.4, - 6.8 - ], - [ - 4.0, - 3.0, - 6.6 - ], - [ - 4.2, - 0.9, - 6.8 - ], - [ - 4.2, - -1.4, - 6.8 - ], - [ - 3.9, - -2.8, - 6.8 - ], - [ - 3.2, - -4.2, - 6.8 - ], - [ - 0.0, - -4.6, - 6.9 - ], - [ - 2.6, - 2.6, - 7.3 - ], - [ - 2.6, - -2.6, - 7.3 - ], - [ - 0.0, - 3.4, - 7.0 - ] - ] - }, - { - "name": "Core.belly", - "mat": "gunmetal", - "bevel": 0.03, - "mirror": true, - "points": [ - [ - 2.3, - 4.7, - 5.3 - ], - [ - 2.3, - -4.9, - 5.9 - ], - [ - 1.7, - 4.0, - 3.6 - ], - [ - 1.8, - 2.2, - 3.3 - ], - [ - 1.8, - -2.6, - 3.35 - ], - [ - 1.5, - -4.6, - 4.0 - ], - [ - 1.2, - 4.9, - 3.7 - ] - ] - }, - { - "name": "Core.cheek_tray", - "mat": "gunmetal", - "bevel": 0.0, - "sides": "both", - "faces": [ - { - "at": [ - 2.2479736988984707, - 5.264865987629634, - 5.0 - ], - "normal": [ - 0.5429510753626048, - 0.839764329894162, - 0.0 - ] - }, - { - "at": [ - 1.6941636020286137, - 4.40830637113759, - 5.0 - ], - "normal": [ - -0.5429510753626048, - -0.839764329894162, - 0.0 - ] - }, - { - "at": [ - 0.0, - 0.0, - 4.9 - ], - "normal": [ - 0.0, - 0.0, - -1.0 - ] - }, - { - "at": [ - 0.0, - 0.0, - 5.3 - ], - "normal": [ - 0.0, - 0.0, - 1.0 - ] - }, - { - "at": [ - 2.5, - 0.0, - 0.0 - ], - "normal": [ - -1.0, - 0.0, - 0.0 - ] - }, - { - "at": [ - 4.750163376895761, - 0.8804114363827034, - 4.6936620832203895 - ], - "normal": [ - 1.0, - 0.07, - 0.38 - ] - } - ] - }, - { - "name": "Hull.Brow", - "mat": "olive", - "bevel": 0.04, - "mirror": true, - "points": [ - [ - 0.0, - 6.3, - 5.58 - ], - [ - 1.05, - 6.25, - 5.72 - ], - [ - 2.0, - 5.72, - 5.76 - ], - [ - 2.28, - 4.95, - 5.8 - ], - [ - 0.0, - 6.14, - 6.12 - ], - [ - 1.0, - 6.1, - 6.14 - ], - [ - 1.92, - 5.6, - 6.16 - ], - [ - 2.2, - 4.95, - 6.2 - ], - [ - 0.0, - 3.25, - 7.0 - ], - [ - 2.05, - 3.25, - 7.0 - ], - [ - 0.0, - 3.25, - 6.2 - ], - [ - 2.28, - 3.25, - 6.2 - ] - ], - "clad": { - "mat": "olive_light", - "facets": [ - { - "n": [ - 0, - 0, - 1 - ], - "cos": 0.6 - }, - { - "radial": [ - 0, - 0, - 1 - ], - "min_r": 1.0, - "cos": 0.25 - } - ], - "floor": -0.35, - "min_area": 0.9, - "lifts": [ - 0.045, - 0.075 - ], - "inset": 0.11, - "gap": 0.05, - "split": 2.2, - "seed": 2 - } - }, - { - "name": "Hull.Chin", - "mat": "olive", - "bevel": 0.04, - "mirror": true, - "points": [ - [ - 0.0, - 5.78, - 5.2 - ], - [ - 1.0, - 5.78, - 5.2 - ], - [ - 2.1, - 5.15, - 5.2 - ], - [ - 2.3, - 4.3, - 5.2 - ], - [ - 0.0, - 5.45, - 3.95 - ], - [ - 0.85, - 5.45, - 3.95 - ], - [ - 1.75, - 4.95, - 3.98 - ], - [ - 1.95, - 4.3, - 4.0 - ], - [ - 2.3, - 3.5, - 5.2 - ], - [ - 1.95, - 3.5, - 3.95 - ] - ], - "clad": { - "mat": "olive_light", - "facets": [ - { - "n": [ - 0, - 0, - 1 - ], - "cos": 0.6 - }, - { - "radial": [ - 0, - 0, - 1 - ], - "min_r": 1.0, - "cos": 0.25 - } - ], - "floor": -0.35, - "min_area": 0.9, - "lifts": [ - 0.045, - 0.075 - ], - "inset": 0.11, - "gap": 0.05, - "split": 2.2, - "seed": 7 - } - }, - { - "name": "Hull.Sill", - "mat": "olive_light", - "bevel": 0.02, - "mirror": true, - "points": [ - [ - 0.0, - 5.9, - 5.2 - ], - [ - 1.05, - 5.9, - 5.2 - ], - [ - 2.2, - 5.22, - 5.2 - ], - [ - 0.0, - 5.84, - 5.3 - ], - [ - 1.02, - 5.84, - 5.3 - ], - [ - 2.14, - 5.18, - 5.3 - ], - [ - 0.0, - 5.3, - 5.2 - ], - [ - 2.0, - 4.9, - 5.2 - ], - [ - 0.0, - 5.3, - 5.3 - ], - [ - 2.0, - 4.9, - 5.3 - ] - ] - }, - { - "name": "Hull.Jaw", - "mat": "olive_light", - "bevel": 0.03, - "mirror": true, - "points": [ - [ - 1.2, - 5.3, - 3.97 - ], - [ - 1.2, - 3.7, - 3.97 - ], - [ - 1.0, - 5.12, - 3.3 - ], - [ - 1.0, - 3.85, - 3.3 - ] - ] - }, - { - "name": "Hull.Cheek", - "mat": "olive", - "bevel": 0.04, - "sides": "both", - "faces": [ - { - "through": [ - [ - 2.4, - 5.5, - 5.25 - ], - [ - 4.72, - 4.0, - 5.25 - ], - [ - 2.38, - 5.2, - 6.2 - ] - ], - "out": [ - 0.5, - 1.0, - 0.2 - ] - }, - { - "at": [ - 4.93672112563192, - 0.8934704787942345, - 4.76455402774013 - ], - "normal": [ - 1.0, - 0.07, - 0.38 - ] - }, - { - "at": [ - 4.2, - 0.9, - 6.95 - ], - "normal": [ - 0.3, - 0.08, - 1.0 - ] - }, - { - "at": [ - 2.38, - 5.2, - 6.2 - ], - "normal": [ - 0.12, - 0.4, - 1.0 - ] - }, - { - "at": [ - 0.0, - 0.0, - 5.25 - ], - "normal": [ - 0.0, - 0.0, - -1.0 - ] - }, - { - "at": [ - 0.0, - 0.9, - 0.0 - ], - "normal": [ - 0.0, - -1.0, - 0.0 - ] - }, - { - "at": [ - 2.38, - 0.0, - 0.0 - ], - "normal": [ - -1.0, - 0.0, - 0.0 - ] - }, - { - "at": [ - 2.057666384578959, - 1.9719302852215022, - 0.0 - ], - "normal": [ - -0.7219882051154242, - -0.6919053632356148, - -0.0 - ] - } - ], - "clad": { - "mat": "olive_light", - "facets": [ - { - "n": [ - 0, - 0, - 1 - ], - "cos": 0.6 - }, - { - "radial": [ - 0, - 0, - 1 - ], - "min_r": 1.0, - "cos": 0.25 - } - ], - "floor": -0.35, - "min_area": 0.9, - "lifts": [ - 0.045, - 0.075 - ], - "inset": 0.11, - "gap": 0.05, - "split": 2.2, - "seed": [ - 4, - 3 - ] - } - }, - { - "name": "Hull.Skirt", - "mat": "olive", - "bevel": 0.035, - "sides": "both", - "points": [ - [ - 4.622999999999999, - 4.0, - 5.3 - ], - [ - 4.8016, - 3.62, - 4.9 - ], - [ - 5.1695, - 1.35, - 4.35 - ], - [ - 5.03, - 0.9, - 4.8 - ], - [ - 4.384, - 0.9, - 6.5 - ], - [ - 4.295, - 3.8, - 6.2 - ], - [ - 4.324507602022145, - 3.97910553214155, - 5.186572888768415 - ], - [ - 4.503107602022145, - 3.59910553214155, - 4.786572888768416 - ], - [ - 4.8710076020221456, - 1.3291055321415504, - 4.236572888768415 - ], - [ - 4.731507602022146, - 0.8791055321415502, - 4.686572888768415 - ], - [ - 4.085507602022146, - 0.8791055321415502, - 6.3865728887684154 - ], - [ - 3.9965076020221453, - 3.77910553214155, - 6.086572888768416 - ] - ] - }, - { - "name": "Hull.CheekLip", - "mat": "olive_light", - "bevel": 0.02, - "sides": "both", - "faces": [ - { - "at": [ - 2.4, - 5.5, - 5.0 - ], - "normal": [ - 0.5429510753626048, - 0.839764329894162, - 0.0 - ] - }, - { - "at": [ - 2.313127827941983, - 5.365637707216934, - 5.0 - ], - "normal": [ - -0.5429510753626048, - -0.839764329894162, - 0.0 - ] - }, - { - "at": [ - 0.0, - 0.0, - 4.84 - ], - "normal": [ - 0.0, - 0.0, - -1.0 - ] - }, - { - "at": [ - 0.0, - 0.0, - 4.99 - ], - "normal": [ - 0.0, - 0.0, - 1.0 - ] - }, - { - "at": [ - 2.45, - 0.0, - 0.0 - ], - "normal": [ - -1.0, - 0.0, - 0.0 - ] - }, - { - "at": [ - 4.93672112563192, - 0.8934704787942345, - 4.76455402774013 - ], - "normal": [ - 1.0, - 0.07, - 0.38 - ] - } - ] - }, - { - "name": "Hull.Quarter", - "mat": "olive", - "bevel": 0.04, - "sides": "both", - "faces": [ - { - "at": [ - 5.0, - -1.4, - 5.5 - ], - "normal": [ - 1.0, - -0.1, - 0.4 - ] - }, - { - "at": [ - 4.45, - -3.7, - 5.7 - ], - "normal": [ - 0.904, - -0.427, - 0.4 - ] - }, - { - "at": [ - 3.2, - -4.9, - 5.85 - ], - "normal": [ - 0.351, - -0.936, - 0.35 - ] - }, - { - "at": [ - 4.2, - -2.6, - 6.95 - ], - "normal": [ - 0.28, - -0.1, - 1.0 - ] - }, - { - "at": [ - 0.0, - -1.35, - 5.5 - ], - "normal": [ - 0.0, - -0.12, - -1.0 - ] - }, - { - "at": [ - 0.0, - -1.4, - 0.0 - ], - "normal": [ - 0.0, - 1.0, - 0.0 - ] - }, - { - "at": [ - 1.75, - 0.0, - 0.0 - ], - "normal": [ - -1.0, - 0.0, - 0.0 - ] - }, - { - "at": [ - 2.139533523229853, - -1.8827895004422703, - 0.0 - ], - "normal": [ - -0.7507135169227553, - 0.6606278948920247, - -0.0 - ] - } - ], - "clad": { - "mat": "olive_light", - "facets": [ - { - "n": [ - 0, - 0, - 1 - ], - "cos": 0.6 - }, - { - "radial": [ - 0, - 0, - 1 - ], - "min_r": 1.0, - "cos": 0.25 - } - ], - "floor": -0.35, - "min_area": 0.9, - "lifts": [ - 0.045, - 0.075 - ], - "inset": 0.11, - "gap": 0.05, - "split": 2.2, - "seed": [ - 15, - 14 - ] - } - }, - { - "name": "Hull.FlankRoof", - "mat": "olive_light", - "bevel": 0.03, - "sides": "both", - "faces": [ - { - "at": [ - 4.3, - 0.0, - 7.05 - ], - "normal": [ - 0.3, - 0.0, - 1.0 - ] - }, - { - "at": [ - 4.7, - 0.0, - 0.0 - ], - "normal": [ - 1.0, - 0.0, - 0.25 - ] - }, - { - "at": [ - 0.0, - 0.0, - 6.88 - ], - "normal": [ - 0.0, - 0.0, - -1.0 - ] - }, - { - "at": [ - 0.0, - 0.85, - 0.0 - ], - "normal": [ - 0.0, - 1.0, - 0.0 - ] - }, - { - "at": [ - 0.0, - -1.3, - 0.0 - ], - "normal": [ - 0.0, - -1.0, - 0.0 - ] - }, - { - "at": [ - 2.8, - 0.0, - 0.0 - ], - "normal": [ - -1.0, - 0.0, - 0.0 - ] - } - ], - "clad": { - "mat": "olive", - "facets": [ - { - "n": [ - 0, - 0, - 1 - ], - "cos": 0.6 - }, - { - "radial": [ - 0, - 0, - 1 - ], - "min_r": 1.0, - "cos": 0.25 - } - ], - "floor": -0.35, - "min_area": 0.9, - "lifts": [ - 0.045, - 0.075 - ], - "inset": 0.11, - "gap": 0.05, - "split": 2.2, - "seed": [ - 10, - 9 - ] - } - }, - { - "name": "Hull.FlankSill", - "mat": "olive", - "bevel": 0.03, - "sides": "both", - "faces": [ - { - "at": [ - 4.98, - 0.0, - 0.0 - ], - "normal": [ - 1.0, - 0.0, - 0.12 - ] - }, - { - "at": [ - 3.9, - 0.0, - 0.0 - ], - "normal": [ - -1.0, - 0.0, - 0.0 - ] - }, - { - "at": [ - 0.0, - 0.0, - 5.12 - ], - "normal": [ - 0.0, - 0.0, - -1.0 - ] - }, - { - "at": [ - 0.0, - 0.0, - 5.45 - ], - "normal": [ - 0.0, - 0.0, - 1.0 - ] - }, - { - "at": [ - 0.0, - 0.85, - 0.0 - ], - "normal": [ - 0.0, - 1.0, - 0.0 - ] - }, - { - "at": [ - 0.0, - -1.3, - 0.0 - ], - "normal": [ - 0.0, - -1.0, - 0.0 - ] - } - ] - }, - { - "name": "Hull.Tail", - "mat": "olive_light", - "bevel": 0.03, - "mirror": true, - "points": [ - [ - 1.72, - -2.75, - 7.5 - ], - [ - 1.72, - -5.0, - 7.3 - ], - [ - 1.72, - -2.75, - 7.15 - ], - [ - 1.72, - -5.0, - 7.0 - ] - ], - "clad": { - "mat": "olive", - "facets": [ - { - "n": [ - 0, - 0, - 1 - ], - "cos": 0.6 - }, - { - "radial": [ - 0, - 0, - 1 - ], - "min_r": 1.0, - "cos": 0.25 - } - ], - "floor": -0.35, - "min_area": 0.9, - "lifts": [ - 0.045, - 0.075 - ], - "inset": 0.11, - "gap": 0.05, - "split": 2.2, - "seed": 19 - } - }, - { - "name": "Hull.BellySide", - "mat": "olive_light", - "bevel": 0.03, - "sides": "both", - "points": [ - [ - 2.1, - 2.2, - 3.9 - ], - [ - 2.1, - -2.4, - 3.95 - ], - [ - 2.45, - 2.0, - 4.1 - ], - [ - 2.45, - -2.2, - 4.15 - ], - [ - 2.45, - 2.0, - 4.85 - ], - [ - 2.45, - -2.2, - 4.9 - ], - [ - 2.25, - 2.2, - 5.1 - ], - [ - 2.25, - -2.4, - 5.15 - ], - [ - 1.8, - 2.2, - 3.9 - ], - [ - 1.8, - -2.4, - 5.15 - ] - ], - "clad": { - "mat": "olive", - "facets": [ - { - "n": [ - 0, - 0, - 1 - ], - "cos": 0.6 - }, - { - "radial": [ - 0, - 0, - 1 - ], - "min_r": 1.0, - "cos": 0.25 - } - ], - "floor": -0.35, - "min_area": 0.9, - "lifts": [ - 0.045, - 0.075 - ], - "inset": 0.11, - "gap": 0.05, - "split": 2.2, - "seed": [ - 1, - 0 - ] - } - } - ] -}, + "table": {"schema": "brokkr.plates.v0", "plates": [ + {"name": "Core.upper", "mat": "gunmetal", "bevel": 0.0, "mirror": true, "points": [[0.0, 5.3, 5.3], [2.2, 5.0, 5.3], [4.3, 3.6, 5.3], [4.5, 0.9, 5.2], [4.5, -1.4, 5.4], [4.3, -2.8, 5.6], [3.6, -4.4, 5.8], [2.2, -5.0, 5.9], [0.0, -5.0, 5.9], [0.0, 3.4, 6.8], [2.2, 3.4, 6.8], [4.0, 3.0, 6.6], [4.2, 0.9, 6.8], [4.2, -1.4, 6.8], [3.9, -2.8, 6.8], [3.2, -4.2, 6.8], [0.0, -4.6, 6.9], [2.6, 2.6, 7.3], [2.6, -2.6, 7.3], [0.0, 3.4, 7.0]]}, + {"name": "Core.belly", "mat": "gunmetal", "bevel": 0.03, "mirror": true, "points": [[2.3, 4.7, 5.3], [2.3, -4.9, 5.9], [1.7, 4.0, 3.6], [1.8, 2.2, 3.3], [1.8, -2.6, 3.35], [1.5, -4.6, 4.0], [1.2, 4.9, 3.7]]}, + {"name": "Core.cheek_tray", "mat": "gunmetal", "bevel": 0.0, "sides": "both", "faces": [{"at": [2.2479736988984707, 5.264865987629634, 5.0], "normal": [0.5429510753626048, 0.839764329894162, 0.0]}, {"at": [1.6941636020286137, 4.40830637113759, 5.0], "normal": [-0.5429510753626048, -0.839764329894162, 0.0]}, {"at": [0.0, 0.0, 4.9], "normal": [0.0, 0.0, -1.0]}, {"at": [0.0, 0.0, 5.3], "normal": [0.0, 0.0, 1.0]}, {"at": [2.5, 0.0, 0.0], "normal": [-1.0, 0.0, 0.0]}, {"at": [4.750163376895761, 0.8804114363827034, 4.6936620832203895], "normal": [1.0, 0.07, 0.38]}]}, + {"name": "Hull.Brow", "mat": "olive", "bevel": 0.04, "mirror": true, "points": [[0.0, 6.3, 5.58], [1.05, 6.25, 5.72], [2.0, 5.72, 5.76], [2.28, 4.95, 5.8], [0.0, 6.14, 6.12], [1.0, 6.1, 6.14], [1.92, 5.6, 6.16], [2.2, 4.95, 6.2], [0.0, 3.25, 7.0], [2.05, 3.25, 7.0], [0.0, 3.25, 6.2], [2.28, 3.25, 6.2]], "clad": {"mat": "olive_light", "facets": [{"n": [0, 0, 1], "cos": 0.6}, {"radial": [0, 0, 1], "min_r": 1.0, "cos": 0.25}], "floor": -0.35, "min_area": 0.9, "lifts": [0.045, 0.075], "inset": 0.11, "gap": 0.05, "split": 2.2, "seed": 2}}, + {"name": "Hull.Chin", "mat": "olive", "bevel": 0.04, "mirror": true, "points": [[0.0, 5.78, 5.2], [1.0, 5.78, 5.2], [2.1, 5.15, 5.2], [2.3, 4.3, 5.2], [0.0, 5.45, 3.95], [0.85, 5.45, 3.95], [1.75, 4.95, 3.98], [1.95, 4.3, 4.0], [2.3, 3.5, 5.2], [1.95, 3.5, 3.95]], "clad": {"mat": "olive_light", "facets": [{"n": [0, 0, 1], "cos": 0.6}, {"radial": [0, 0, 1], "min_r": 1.0, "cos": 0.25}], "floor": -0.35, "min_area": 0.9, "lifts": [0.045, 0.075], "inset": 0.11, "gap": 0.05, "split": 2.2, "seed": 7}}, + {"name": "Hull.Sill", "mat": "olive_light", "bevel": 0.02, "mirror": true, "points": [[0.0, 5.9, 5.2], [1.05, 5.9, 5.2], [2.2, 5.22, 5.2], [0.0, 5.84, 5.3], [1.02, 5.84, 5.3], [2.14, 5.18, 5.3], [0.0, 5.3, 5.2], [2.0, 4.9, 5.2], [0.0, 5.3, 5.3], [2.0, 4.9, 5.3]]}, + {"name": "Hull.Jaw", "mat": "olive_light", "bevel": 0.03, "mirror": true, "points": [[1.2, 5.3, 3.97], [1.2, 3.7, 3.97], [1.0, 5.12, 3.3], [1.0, 3.85, 3.3]]}, + {"name": "Hull.Cheek", "mat": "olive", "bevel": 0.04, "sides": "both", "faces": [{"through": [[2.4, 5.5, 5.25], [4.72, 4.0, 5.25], [2.38, 5.2, 6.2]], "out": [0.5, 1.0, 0.2]}, {"at": [4.93672112563192, 0.8934704787942345, 4.76455402774013], "normal": [1.0, 0.07, 0.38]}, {"at": [4.2, 0.9, 6.95], "normal": [0.3, 0.08, 1.0]}, {"at": [2.38, 5.2, 6.2], "normal": [0.12, 0.4, 1.0]}, {"at": [0.0, 0.0, 5.25], "normal": [0.0, 0.0, -1.0]}, {"at": [0.0, 0.9, 0.0], "normal": [0.0, -1.0, 0.0]}, {"at": [2.38, 0.0, 0.0], "normal": [-1.0, 0.0, 0.0]}, {"at": [2.057666384578959, 1.9719302852215022, 0.0], "normal": [-0.7219882051154242, -0.6919053632356148, -0.0]}], "clad": {"mat": "olive_light", "facets": [{"n": [0, 0, 1], "cos": 0.6}, {"radial": [0, 0, 1], "min_r": 1.0, "cos": 0.25}], "floor": -0.35, "min_area": 0.9, "lifts": [0.045, 0.075], "inset": 0.11, "gap": 0.05, "split": 2.2, "seed": [4, 3]}}, + {"name": "Hull.Skirt", "mat": "olive", "bevel": 0.035, "sides": "both", "points": [[4.622999999999999, 4.0, 5.3], [4.8016, 3.62, 4.9], [5.1695, 1.35, 4.35], [5.03, 0.9, 4.8], [4.384, 0.9, 6.5], [4.295, 3.8, 6.2], [4.324507602022145, 3.97910553214155, 5.186572888768415], [4.503107602022145, 3.59910553214155, 4.786572888768416], [4.8710076020221456, 1.3291055321415504, 4.236572888768415], [4.731507602022146, 0.8791055321415502, 4.686572888768415], [4.085507602022146, 0.8791055321415502, 6.3865728887684154], [3.9965076020221453, 3.77910553214155, 6.086572888768416]]}, + {"name": "Hull.CheekLip", "mat": "olive_light", "bevel": 0.02, "sides": "both", "faces": [{"at": [2.4, 5.5, 5.0], "normal": [0.5429510753626048, 0.839764329894162, 0.0]}, {"at": [2.313127827941983, 5.365637707216934, 5.0], "normal": [-0.5429510753626048, -0.839764329894162, 0.0]}, {"at": [0.0, 0.0, 4.84], "normal": [0.0, 0.0, -1.0]}, {"at": [0.0, 0.0, 4.99], "normal": [0.0, 0.0, 1.0]}, {"at": [2.45, 0.0, 0.0], "normal": [-1.0, 0.0, 0.0]}, {"at": [4.93672112563192, 0.8934704787942345, 4.76455402774013], "normal": [1.0, 0.07, 0.38]}]}, + {"name": "Hull.Quarter", "mat": "olive", "bevel": 0.04, "sides": "both", "faces": [{"at": [5.0, -1.4, 5.5], "normal": [1.0, -0.1, 0.4]}, {"at": [4.45, -3.7, 5.7], "normal": [0.904, -0.427, 0.4]}, {"at": [3.2, -4.9, 5.85], "normal": [0.351, -0.936, 0.35]}, {"at": [4.2, -2.6, 6.95], "normal": [0.28, -0.1, 1.0]}, {"at": [0.0, -1.35, 5.5], "normal": [0.0, -0.12, -1.0]}, {"at": [0.0, -1.4, 0.0], "normal": [0.0, 1.0, 0.0]}, {"at": [1.75, 0.0, 0.0], "normal": [-1.0, 0.0, 0.0]}, {"at": [2.139533523229853, -1.8827895004422703, 0.0], "normal": [-0.7507135169227553, 0.6606278948920247, -0.0]}], "clad": {"mat": "olive_light", "facets": [{"n": [0, 0, 1], "cos": 0.6}, {"radial": [0, 0, 1], "min_r": 1.0, "cos": 0.25}], "floor": -0.35, "min_area": 0.9, "lifts": [0.045, 0.075], "inset": 0.11, "gap": 0.05, "split": 2.2, "seed": [15, 14]}}, + {"name": "Hull.FlankRoof", "mat": "olive_light", "bevel": 0.03, "sides": "both", "faces": [{"at": [4.3, 0.0, 7.05], "normal": [0.3, 0.0, 1.0]}, {"at": [4.7, 0.0, 0.0], "normal": [1.0, 0.0, 0.25]}, {"at": [0.0, 0.0, 6.88], "normal": [0.0, 0.0, -1.0]}, {"at": [0.0, 0.85, 0.0], "normal": [0.0, 1.0, 0.0]}, {"at": [0.0, -1.3, 0.0], "normal": [0.0, -1.0, 0.0]}, {"at": [2.8, 0.0, 0.0], "normal": [-1.0, 0.0, 0.0]}], "clad": {"mat": "olive", "facets": [{"n": [0, 0, 1], "cos": 0.6}, {"radial": [0, 0, 1], "min_r": 1.0, "cos": 0.25}], "floor": -0.35, "min_area": 0.9, "lifts": [0.045, 0.075], "inset": 0.11, "gap": 0.05, "split": 2.2, "seed": [10, 9]}}, + {"name": "Hull.FlankSill", "mat": "olive", "bevel": 0.03, "sides": "both", "faces": [{"at": [4.98, 0.0, 0.0], "normal": [1.0, 0.0, 0.12]}, {"at": [3.9, 0.0, 0.0], "normal": [-1.0, 0.0, 0.0]}, {"at": [0.0, 0.0, 5.12], "normal": [0.0, 0.0, -1.0]}, {"at": [0.0, 0.0, 5.45], "normal": [0.0, 0.0, 1.0]}, {"at": [0.0, 0.85, 0.0], "normal": [0.0, 1.0, 0.0]}, {"at": [0.0, -1.3, 0.0], "normal": [0.0, -1.0, 0.0]}]}, + {"name": "Hull.Tail", "mat": "olive_light", "bevel": 0.03, "mirror": true, "points": [[1.72, -2.75, 7.5], [1.72, -5.0, 7.3], [1.72, -2.75, 7.15], [1.72, -5.0, 7.0]], "clad": {"mat": "olive", "facets": [{"n": [0, 0, 1], "cos": 0.6}, {"radial": [0, 0, 1], "min_r": 1.0, "cos": 0.25}], "floor": -0.35, "min_area": 0.9, "lifts": [0.045, 0.075], "inset": 0.11, "gap": 0.05, "split": 2.2, "seed": 19}}, + {"name": "Hull.BellySide", "mat": "olive_light", "bevel": 0.03, "sides": "both", "points": [[2.1, 2.2, 3.9], [2.1, -2.4, 3.95], [2.45, 2.0, 4.1], [2.45, -2.2, 4.15], [2.45, 2.0, 4.85], [2.45, -2.2, 4.9], [2.25, 2.2, 5.1], [2.25, -2.4, 5.15], [1.8, 2.2, 3.9], [1.8, -2.4, 5.15]], "clad": {"mat": "olive", "facets": [{"n": [0, 0, 1], "cos": 0.6}, {"radial": [0, 0, 1], "min_r": 1.0, "cos": 0.25}], "floor": -0.35, "min_area": 0.9, "lifts": [0.045, 0.075], "inset": 0.11, "gap": 0.05, "split": 2.2, "seed": [1, 0]}} + ]}, "cases": [ {"side": 1, "truth": { "Core.upper": {"solid":[[0.0,5.3000002,5.3000002],[2.2,5.0,5.3000002],[4.3000002,3.5999999,5.3000002],[4.5,0.9,5.1999998],[4.5,-1.4,5.4000001],[4.3000002,-2.8,5.5999999],[3.5999999,-4.4000001,5.8000002],[2.2,-5.0,5.9000001],[2.2,3.4000001,6.8000002],[4.0,3.0,6.5999999],[4.1999998,0.9,6.8000002],[4.1999998,-1.4,6.8000002],[3.9000001,-2.8,6.8000002],[3.2,-4.1999998,6.8000002],[0.0,-4.5999999,6.9000001],[2.5999999,2.5999999,7.3000002],[2.5999999,-2.5999999,7.3000002],[0.0,3.4000001,7.0],[-2.2,5.0,5.3000002],[-4.3000002,3.5999999,5.3000002],[-4.5,0.9,5.1999998],[-4.5,-1.4,5.4000001],[-4.3000002,-2.8,5.5999999],[-3.5999999,-4.4000001,5.8000002],[-2.2,-5.0,5.9000001],[-2.2,3.4000001,6.8000002],[-4.0,3.0,6.5999999],[-4.1999998,0.9,6.8000002],[-4.1999998,-1.4,6.8000002],[-3.9000001,-2.8,6.8000002],[-3.2,-4.1999998,6.8000002],[-2.5999999,2.5999999,7.3000002],[-2.5999999,-2.5999999,7.3000002]],"facets":54,"panels":[],"bolts":0}, diff --git a/surfaces/blender/tests/fixtures/plates_paladin.json b/surfaces/blender/tests/fixtures/plates_paladin.json index b1cd9c4..791c2eb 100644 --- a/surfaces/blender/tests/fixtures/plates_paladin.json +++ b/surfaces/blender/tests/fixtures/plates_paladin.json @@ -1,1887 +1,42 @@ {"source": {"branch": "nibu/fable-paladin-3", "sha": "c35e57ee5aa9c52e589623fcc8abb19b909f09d4", "blender": "5.3.0"}, - "table": { - "schema": "brokkr.plates.v0", - "plates": [ - { - "name": "Thigh.core", - "mat": "gunmetal", - "bevel": 0.02, - "sections": [ - [ - 0.4, - 0.9, - -0.3, - 0.5, - 0.12 - ], - [ - 0.05, - 1.2, - -0.34, - 0.64, - 0.18 - ], - [ - -1.45, - 1.2, - -0.34, - 0.64, - 0.18 - ], - [ - -1.8, - 0.95, - -0.3, - 0.5, - 0.14 - ] - ] - }, - { - "name": "Thigh.Shield", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - 0.02, - 0.9, - -0.5 - ], - "normal": [ - 0.06, - 1.0, - 0.05 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": [ - [ - -0.42, - 0.98 - ], - [ - 0.42, - 0.98 - ], - [ - 0.66, - 0.5 - ], - [ - 0.66, - -0.52 - ], - [ - 0.42, - -1.0 - ], - [ - -0.42, - -1.0 - ], - [ - -0.66, - -0.52 - ], - [ - -0.66, - 0.5 - ] - ], - "thick": 0.26, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.2, - "lifts": [ - 0.05, - 0.05 - ], - "inset": 0.075, - "gap": 0.045, - "split": 99.0, - "seed": 948708 - }, - "fits": [ - { - "kind": "mark", - "id": "tri", - "at": [ - 0.0, - -0.05 - ], - "height": 0.5 - } - ] - }, - { - "name": "Thigh.Block", - "mat": "olive_light", - "bevel": 0.022, - "slab": { - "at": [ - 0.02, - 1.0, - 0.12 - ], - "normal": [ - 0.06, - 1.0, - 0.05 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.56, - "h": 0.44, - "clip": 0.08 - }, - "thick": 0.16, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Thigh.Lame", - "mat": "olive_light", - "bevel": 0.022, - "slab": { - "at": [ - 0.02, - 0.985, - -1.17 - ], - "normal": [ - 0.06, - 1.0, - 0.02 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": [ - [ - -0.52, - 0.2 - ], - [ - 0.52, - 0.2 - ], - [ - 0.58, - 0.0 - ], - [ - 0.4, - -0.26 - ], - [ - -0.4, - -0.26 - ], - [ - -0.58, - 0.0 - ] - ], - "thick": 0.14, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Thigh.Outer", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - 0.86, - 0.0, - -0.45 - ], - "normal": [ - 1.0, - 0.08, - 0.04 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 0.0, - 1.0, - 0.0 - ], - "outline": [ - [ - -0.5, - 1.0 - ], - [ - 0.36, - 1.05 - ], - [ - 0.68, - 0.5 - ], - [ - 0.68, - -0.6 - ], - [ - 0.3, - -1.02 - ], - [ - -0.5, - -0.86 - ], - [ - -0.74, - -0.2 - ], - [ - -0.74, - 0.5 - ] - ], - "thick": 0.24, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.2, - "lifts": [ - 0.04, - 0.07 - ], - "inset": 0.075, - "gap": 0.045, - "split": 0.8, - "seed": 976538 - } - }, - { - "name": "Thigh.OuterStep", - "mat": "olive_light", - "bevel": 0.022, - "slab": { - "at": [ - 0.95, - -0.02, - -0.25 - ], - "normal": [ - 1.0, - 0.08, - 0.04 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 0.0, - 1.0, - 0.0 - ], - "outline": { - "w": 0.8, - "h": 0.9, - "clip": 0.2 - }, - "thick": 0.13, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Thigh.Inner", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - -0.82, - 0.05, - -0.75 - ], - "normal": [ - -1.0, - 0.1, - 0.0 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 0.0, - 1.0, - 0.0 - ], - "outline": [ - [ - -0.55, - 0.55 - ], - [ - 0.5, - 0.55 - ], - [ - 0.62, - 0.15 - ], - [ - 0.5, - -0.7 - ], - [ - -0.45, - -0.7 - ], - [ - -0.62, - -0.15 - ] - ], - "thick": 0.2, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.2, - "lifts": [ - 0.04, - 0.07 - ], - "inset": 0.075, - "gap": 0.045, - "split": 0.8, - "seed": 947561 - } - }, - { - "name": "Thigh.Rear", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - 0.0, - -0.98, - -0.25 - ], - "normal": [ - 0.0, - -1.0, - 0.05 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": [ - [ - -0.46, - 0.72 - ], - [ - 0.46, - 0.72 - ], - [ - 0.64, - 0.3 - ], - [ - 0.64, - -0.4 - ], - [ - 0.42, - -0.72 - ], - [ - -0.42, - -0.72 - ], - [ - -0.64, - -0.4 - ], - [ - -0.64, - 0.3 - ] - ], - "thick": 0.22, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.2, - "lifts": [ - 0.05, - 0.05 - ], - "inset": 0.075, - "gap": 0.045, - "split": 99.0, - "seed": 398253 - } - }, - { - "name": "Thigh.RearStep", - "mat": "olive_light", - "bevel": 0.022, - "slab": { - "at": [ - 0.0, - -1.06, - -0.3 - ], - "normal": [ - 0.0, - -1.0, - 0.05 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.7, - "h": 0.5, - "clip": 0.1 - }, - "thick": 0.12, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Thigh.CornerOut", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - 0.7, - 0.7, - -0.45 - ], - "normal": [ - 0.72, - 0.7, - 0.04 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.3, - "h": 1.5, - "clip": 0.08 - }, - "thick": 0.2, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Thigh.CornerIn", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - -0.67, - 0.7, - -0.6 - ], - "normal": [ - -0.72, - 0.7, - 0.03 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.26, - "h": 1.1, - "clip": 0.07 - }, - "thick": 0.18, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Thigh.Cap", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - 0.0, - 0.12, - 0.66 - ], - "normal": [ - 0.0, - 0.3, - 1.0 - ], - "up": [ - 0.0, - 1.0, - 0.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": [ - [ - -0.5, - -0.5 - ], - [ - 0.5, - -0.5 - ], - [ - 0.6, - 0.1 - ], - [ - 0.36, - 0.44 - ], - [ - -0.36, - 0.44 - ], - [ - -0.6, - 0.1 - ] - ], - "thick": 0.18, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.2, - "lifts": [ - 0.05, - 0.05 - ], - "inset": 0.075, - "gap": 0.045, - "split": 99.0, - "seed": 387260 - } - }, - { - "name": "Shin.core", - "mat": "gunmetal", - "bevel": 0.02, - "sections": [ - [ - -0.3, - 0.9, - -0.3, - 0.5, - 0.12 - ], - [ - -0.65, - 1.14, - -0.34, - 0.6, - 0.18 - ], - [ - -1.9, - 1.06, - -0.34, - 0.56, - 0.18 - ], - [ - -2.5, - 0.8, - -0.3, - 0.4, - 0.12 - ] - ] - }, - { - "name": "Shin.Knee", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - 0.0, - 1.0, - 0.02 - ], - "normal": [ - 0.0, - 1.0, - 0.22 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": [ - [ - -0.4, - 0.56 - ], - [ - 0.4, - 0.56 - ], - [ - 0.62, - 0.22 - ], - [ - 0.62, - -0.3 - ], - [ - 0.42, - -0.56 - ], - [ - -0.42, - -0.56 - ], - [ - -0.62, - -0.3 - ], - [ - -0.62, - 0.22 - ] - ], - "thick": 0.28, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.2, - "lifts": [ - 0.05, - 0.05 - ], - "inset": 0.075, - "gap": 0.045, - "split": 99.0, - "seed": 995246 - } - }, - { - "name": "Shin.KneeSide", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - 0.7, - 0.72, - 0.0 - ], - "normal": [ - 0.75, - 0.66, - 0.1 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.34, - "h": 0.9, - "clip": 0.1 - }, - "thick": 0.2, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Shin.KneeSideIn", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - -0.7, - 0.72, - 0.0 - ], - "normal": [ - -0.75, - 0.66, - 0.1 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.34, - "h": 0.9, - "clip": 0.1 - }, - "thick": 0.2, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Shin.Greave", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - 0.0, - 0.88, - -1.3 - ], - "normal": [ - 0.0, - 1.0, - -0.07 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": [ - [ - -0.5, - 0.72 - ], - [ - 0.5, - 0.72 - ], - [ - 0.66, - 0.4 - ], - [ - 0.6, - -0.5 - ], - [ - 0.36, - -0.95 - ], - [ - -0.36, - -0.95 - ], - [ - -0.6, - -0.5 - ], - [ - -0.66, - 0.4 - ] - ], - "thick": 0.28, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.2, - "lifts": [ - 0.04, - 0.07 - ], - "inset": 0.075, - "gap": 0.045, - "split": 0.8, - "seed": 564123 - } - }, - { - "name": "Shin.GreaveStep", - "mat": "olive_light", - "bevel": 0.022, - "slab": { - "at": [ - 0.0, - 0.97, - -1.2 - ], - "normal": [ - 0.0, - 1.0, - -0.07 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.62, - "h": 0.84, - "clip": 0.12 - }, - "thick": 0.15, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Shin.Outer", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - 0.82, - -0.2, - -1.05 - ], - "normal": [ - 1.0, - 0.04, - 0.0 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 0.0, - 1.0, - 0.0 - ], - "outline": [ - [ - -0.75, - 0.62 - ], - [ - 0.34, - 0.74 - ], - [ - 0.74, - 0.36 - ], - [ - 0.7, - -0.55 - ], - [ - 0.28, - -0.96 - ], - [ - -0.6, - -0.82 - ], - [ - -0.95, - -0.1 - ] - ], - "thick": 0.26, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.2, - "lifts": [ - 0.04, - 0.07 - ], - "inset": 0.075, - "gap": 0.045, - "split": 0.8, - "seed": 733553 - } - }, - { - "name": "Shin.OuterStep", - "mat": "olive_light", - "bevel": 0.022, - "slab": { - "at": [ - 0.92, - -0.2, - -1.0 - ], - "normal": [ - 1.0, - 0.04, - 0.0 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 0.0, - 1.0, - 0.0 - ], - "outline": [ - [ - -0.42, - 0.42 - ], - [ - 0.2, - 0.46 - ], - [ - 0.46, - 0.2 - ], - [ - 0.44, - -0.3 - ], - [ - 0.16, - -0.5 - ], - [ - -0.36, - -0.44 - ], - [ - -0.56, - -0.05 - ] - ], - "thick": 0.13, - "taper": 0.04, - "back": 1.0 - }, - "fits": [ - { - "kind": "mark", - "id": "tri", - "at": [ - -0.03, - -0.02 - ], - "height": 0.4 - } - ] - }, - { - "name": "Shin.Inner", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - -0.78, - -0.12, - -1.1 - ], - "normal": [ - -1.0, - 0.04, - 0.0 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 0.0, - 1.0, - 0.0 - ], - "outline": [ - [ - -0.7, - 0.55 - ], - [ - 0.3, - 0.66 - ], - [ - 0.66, - 0.3 - ], - [ - 0.62, - -0.5 - ], - [ - 0.25, - -0.86 - ], - [ - -0.55, - -0.74 - ], - [ - -0.85, - -0.1 - ] - ], - "thick": 0.22, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.2, - "lifts": [ - 0.05, - 0.05 - ], - "inset": 0.075, - "gap": 0.045, - "split": 99.0, - "seed": 299054 - } - }, - { - "name": "Shin.Calf", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - 0.0, - -1.12, - -0.95 - ], - "normal": [ - 0.0, - -1.0, - 0.1 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": [ - [ - -0.5, - 0.62 - ], - [ - 0.5, - 0.62 - ], - [ - 0.68, - 0.1 - ], - [ - 0.5, - -0.62 - ], - [ - -0.5, - -0.62 - ], - [ - -0.68, - 0.1 - ] - ], - "thick": 0.22, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.2, - "lifts": [ - 0.05, - 0.05 - ], - "inset": 0.075, - "gap": 0.045, - "split": 99.0, - "seed": 800359 - } - }, - { - "name": "Shin.CalfStep", - "mat": "olive_light", - "bevel": 0.022, - "slab": { - "at": [ - 0.0, - -1.2, - -1.05 - ], - "normal": [ - 0.0, - -1.0, - 0.1 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.72, - "h": 0.46, - "clip": 0.1 - }, - "thick": 0.12, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Shin.Ankle", - "mat": "olive_light", - "bevel": 0.022, - "slab": { - "at": [ - 0.0, - 0.66, - -2.42 - ], - "normal": [ - 0.0, - 1.0, - -0.2 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.8, - "h": 0.52, - "clip": 0.12 - }, - "thick": 0.2, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "khaki", - "min_area": 0.2, - "lifts": [ - 0.04, - 0.07 - ], - "inset": 0.075, - "gap": 0.045, - "split": 0.8, - "seed": 22775 - } - }, - { - "name": "Shin.AnkleSide", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - 0.6, - 0.1, - -2.35 - ], - "normal": [ - 1.0, - 0.1, - -0.1 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 0.0, - 1.0, - 0.0 - ], - "outline": { - "w": 0.7, - "h": 0.5, - "clip": 0.12 - }, - "thick": 0.16, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Pelvis.core", - "mat": "gunmetal", - "bevel": 0.02, - "points": [ - [ - 0.62, - 0.62, - 0.5 - ], - [ - 0.62, - -0.6, - 0.5 - ], - [ - 0.72, - 0.7, - -0.3 - ], - [ - 0.72, - -0.62, - -0.3 - ], - [ - 0.45, - 0.7, - 0.62 - ], - [ - 0.45, - -0.66, - 0.62 - ], - [ - 0.4, - 0.55, - -0.8 - ], - [ - 0.4, - -0.45, - -0.8 - ] - ], - "mirror": true - }, - { - "name": "Pelvis.Crown", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - 0.0, - 1.0, - 0.42 - ], - "normal": [ - 0.0, - 1.0, - 0.16 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": [ - [ - -0.32, - 0.3 - ], - [ - 0.32, - 0.3 - ], - [ - 0.48, - 0.04 - ], - [ - 0.3, - -0.3 - ], - [ - -0.3, - -0.3 - ], - [ - -0.48, - 0.04 - ] - ], - "thick": 0.3, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.2, - "lifts": [ - 0.05, - 0.05 - ], - "inset": 0.075, - "gap": 0.045, - "split": 99.0, - "seed": 345924 - } - }, - { - "name": "Pelvis.Cod", - "mat": "khaki", - "bevel": 0.022, - "slab": { - "at": [ - 0.0, - 1.06, - -0.62 - ], - "normal": [ - 0.0, - 1.0, - -0.1 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": [ - [ - -0.36, - 0.7 - ], - [ - 0.36, - 0.7 - ], - [ - 0.44, - 0.3 - ], - [ - 0.3, - -0.78 - ], - [ - -0.3, - -0.78 - ], - [ - -0.44, - 0.3 - ] - ], - "thick": 0.34, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.2, - "lifts": [ - 0.04, - 0.07 - ], - "inset": 0.075, - "gap": 0.045, - "split": 0.8, - "seed": 876596 - } - }, - { - "name": "Pelvis.CodStep", - "mat": "olive_light", - "bevel": 0.022, - "slab": { - "at": [ - 0.0, - 1.17, - -0.3 - ], - "normal": [ - 0.0, - 1.0, - -0.1 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.5, - "h": 0.42, - "clip": 0.1 - }, - "thick": 0.14, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Pelvis.CodLame", - "mat": "olive_light", - "bevel": 0.022, - "slab": { - "at": [ - 0.0, - 1.15, - -1.02 - ], - "normal": [ - 0.0, - 1.0, - -0.1 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.42, - "h": 0.4, - "clip": 0.08 - }, - "thick": 0.13, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Pelvis.Wing", - "mat": "khaki", - "bevel": 0.022, - "sides": "both", - "slab": { - "at": [ - 0.92, - 0.84, - 0.5 - ], - "normal": [ - 0.3, - 1.0, - 0.2 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": [ - [ - -0.46, - -0.02 - ], - [ - 0.44, - 0.36 - ], - [ - 0.54, - 0.1 - ], - [ - 0.44, - -0.26 - ], - [ - -0.46, - -0.36 - ] - ], - "thick": 0.22, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.2, - "lifts": [ - 0.04, - 0.07 - ], - "inset": 0.075, - "gap": 0.045, - "split": 0.8, - "seed": [ - 876672, - 589838 - ] - } - }, - { - "name": "Pelvis.HipGuard", - "mat": "olive_light", - "bevel": 0.022, - "sides": "both", - "slab": { - "at": [ - 0.62, - 0.92, - -0.05 - ], - "normal": [ - 0.2, - 1.0, - -0.05 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.34, - "h": 0.5, - "clip": 0.08 - }, - "thick": 0.16, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Pelvis.Seat", - "mat": "khaki", - "bevel": 0.022, - "sides": "both", - "slab": { - "at": [ - 0.56, - -0.86, - 0.02 - ], - "normal": [ - 0.22, - -1.0, - 0.1 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": [ - [ - -0.5, - 0.66 - ], - [ - 0.5, - 0.72 - ], - [ - 0.6, - -0.2 - ], - [ - 0.2, - -0.86 - ], - [ - -0.5, - -0.6 - ] - ], - "thick": 0.24, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.2, - "lifts": [ - 0.05, - 0.05 - ], - "inset": 0.075, - "gap": 0.045, - "split": 99.0, - "seed": [ - 1004746, - 453014 - ] - } - }, - { - "name": "Pelvis.SeatStep", - "mat": "olive_light", - "bevel": 0.022, - "sides": "both", - "slab": { - "at": [ - 0.6, - -0.95, - 0.1 - ], - "normal": [ - 0.22, - -1.0, - 0.1 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.56, - "h": 0.6, - "clip": 0.12 - }, - "thick": 0.12, - "taper": 0.04, - "back": 1.0 - } - }, - { - "name": "Pelvis.Tail", - "mat": "olive_light", - "bevel": 0.022, - "slab": { - "at": [ - 0.0, - -0.92, - -0.2 - ], - "normal": [ - 0.0, - -1.0, - -0.05 - ], - "up": [ - 0.0, - 0.0, - 1.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.36, - "h": 1.3, - "clip": 0.1 - }, - "thick": 0.22, - "taper": 0.04, - "back": 1.0 - }, - "clad": { - "mat": "khaki", - "min_area": 0.2, - "lifts": [ - 0.04, - 0.07 - ], - "inset": 0.075, - "gap": 0.045, - "split": 0.8, - "seed": 995407 - } - }, - { - "name": "Pelvis.Roof", - "mat": "khaki", - "bevel": 0.022, - "sides": "both", - "slab": { - "at": [ - 0.62, - 0.0, - 0.7 - ], - "normal": [ - 0.25, - 0.0, - 1.0 - ], - "up": [ - 0.0, - 1.0, - 0.0 - ], - "right": [ - 1.0, - 0.0, - 0.0 - ], - "outline": { - "w": 0.6, - "h": 1.1, - "clip": 0.14 - }, - "thick": 0.14, - "taper": 0.04, - "back": 1.0 - } - } - ] -}, + "table": {"schema": "brokkr.plates.v0", "plates": [ + {"name": "Thigh.core", "mat": "gunmetal", "bevel": 0.02, "sections": [[0.4, 0.9, -0.3, 0.5, 0.12], [0.05, 1.2, -0.34, 0.64, 0.18], [-1.45, 1.2, -0.34, 0.64, 0.18], [-1.8, 0.95, -0.3, 0.5, 0.14]]}, + {"name": "Thigh.Shield", "mat": "khaki", "bevel": 0.022, "slab": {"at": [0.02, 0.9, -0.5], "normal": [0.06, 1.0, 0.05], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": [[-0.42, 0.98], [0.42, 0.98], [0.66, 0.5], [0.66, -0.52], [0.42, -1.0], [-0.42, -1.0], [-0.66, -0.52], [-0.66, 0.5]], "thick": 0.26, "taper": 0.04, "back": 1.0}, "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.05, 0.05], "inset": 0.075, "gap": 0.045, "split": 99.0, "seed": 948708}, "fits": [{"kind": "mark", "id": "tri", "at": [0.0, -0.05], "height": 0.5}]}, + {"name": "Thigh.Block", "mat": "olive_light", "bevel": 0.022, "slab": {"at": [0.02, 1.0, 0.12], "normal": [0.06, 1.0, 0.05], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.56, "h": 0.44, "clip": 0.08}, "thick": 0.16, "taper": 0.04, "back": 1.0}}, + {"name": "Thigh.Lame", "mat": "olive_light", "bevel": 0.022, "slab": {"at": [0.02, 0.985, -1.17], "normal": [0.06, 1.0, 0.02], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": [[-0.52, 0.2], [0.52, 0.2], [0.58, 0.0], [0.4, -0.26], [-0.4, -0.26], [-0.58, 0.0]], "thick": 0.14, "taper": 0.04, "back": 1.0}}, + {"name": "Thigh.Outer", "mat": "khaki", "bevel": 0.022, "slab": {"at": [0.86, 0.0, -0.45], "normal": [1.0, 0.08, 0.04], "up": [0.0, 0.0, 1.0], "right": [0.0, 1.0, 0.0], "outline": [[-0.5, 1.0], [0.36, 1.05], [0.68, 0.5], [0.68, -0.6], [0.3, -1.02], [-0.5, -0.86], [-0.74, -0.2], [-0.74, 0.5]], "thick": 0.24, "taper": 0.04, "back": 1.0}, "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.04, 0.07], "inset": 0.075, "gap": 0.045, "split": 0.8, "seed": 976538}}, + {"name": "Thigh.OuterStep", "mat": "olive_light", "bevel": 0.022, "slab": {"at": [0.95, -0.02, -0.25], "normal": [1.0, 0.08, 0.04], "up": [0.0, 0.0, 1.0], "right": [0.0, 1.0, 0.0], "outline": {"w": 0.8, "h": 0.9, "clip": 0.2}, "thick": 0.13, "taper": 0.04, "back": 1.0}}, + {"name": "Thigh.Inner", "mat": "khaki", "bevel": 0.022, "slab": {"at": [-0.82, 0.05, -0.75], "normal": [-1.0, 0.1, 0.0], "up": [0.0, 0.0, 1.0], "right": [0.0, 1.0, 0.0], "outline": [[-0.55, 0.55], [0.5, 0.55], [0.62, 0.15], [0.5, -0.7], [-0.45, -0.7], [-0.62, -0.15]], "thick": 0.2, "taper": 0.04, "back": 1.0}, "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.04, 0.07], "inset": 0.075, "gap": 0.045, "split": 0.8, "seed": 947561}}, + {"name": "Thigh.Rear", "mat": "khaki", "bevel": 0.022, "slab": {"at": [0.0, -0.98, -0.25], "normal": [0.0, -1.0, 0.05], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": [[-0.46, 0.72], [0.46, 0.72], [0.64, 0.3], [0.64, -0.4], [0.42, -0.72], [-0.42, -0.72], [-0.64, -0.4], [-0.64, 0.3]], "thick": 0.22, "taper": 0.04, "back": 1.0}, "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.05, 0.05], "inset": 0.075, "gap": 0.045, "split": 99.0, "seed": 398253}}, + {"name": "Thigh.RearStep", "mat": "olive_light", "bevel": 0.022, "slab": {"at": [0.0, -1.06, -0.3], "normal": [0.0, -1.0, 0.05], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.7, "h": 0.5, "clip": 0.1}, "thick": 0.12, "taper": 0.04, "back": 1.0}}, + {"name": "Thigh.CornerOut", "mat": "khaki", "bevel": 0.022, "slab": {"at": [0.7, 0.7, -0.45], "normal": [0.72, 0.7, 0.04], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.3, "h": 1.5, "clip": 0.08}, "thick": 0.2, "taper": 0.04, "back": 1.0}}, + {"name": "Thigh.CornerIn", "mat": "khaki", "bevel": 0.022, "slab": {"at": [-0.67, 0.7, -0.6], "normal": [-0.72, 0.7, 0.03], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.26, "h": 1.1, "clip": 0.07}, "thick": 0.18, "taper": 0.04, "back": 1.0}}, + {"name": "Thigh.Cap", "mat": "khaki", "bevel": 0.022, "slab": {"at": [0.0, 0.12, 0.66], "normal": [0.0, 0.3, 1.0], "up": [0.0, 1.0, 0.0], "right": [1.0, 0.0, 0.0], "outline": [[-0.5, -0.5], [0.5, -0.5], [0.6, 0.1], [0.36, 0.44], [-0.36, 0.44], [-0.6, 0.1]], "thick": 0.18, "taper": 0.04, "back": 1.0}, "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.05, 0.05], "inset": 0.075, "gap": 0.045, "split": 99.0, "seed": 387260}}, + {"name": "Shin.core", "mat": "gunmetal", "bevel": 0.02, "sections": [[-0.3, 0.9, -0.3, 0.5, 0.12], [-0.65, 1.14, -0.34, 0.6, 0.18], [-1.9, 1.06, -0.34, 0.56, 0.18], [-2.5, 0.8, -0.3, 0.4, 0.12]]}, + {"name": "Shin.Knee", "mat": "khaki", "bevel": 0.022, "slab": {"at": [0.0, 1.0, 0.02], "normal": [0.0, 1.0, 0.22], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": [[-0.4, 0.56], [0.4, 0.56], [0.62, 0.22], [0.62, -0.3], [0.42, -0.56], [-0.42, -0.56], [-0.62, -0.3], [-0.62, 0.22]], "thick": 0.28, "taper": 0.04, "back": 1.0}, "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.05, 0.05], "inset": 0.075, "gap": 0.045, "split": 99.0, "seed": 995246}}, + {"name": "Shin.KneeSide", "mat": "khaki", "bevel": 0.022, "slab": {"at": [0.7, 0.72, 0.0], "normal": [0.75, 0.66, 0.1], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.34, "h": 0.9, "clip": 0.1}, "thick": 0.2, "taper": 0.04, "back": 1.0}}, + {"name": "Shin.KneeSideIn", "mat": "khaki", "bevel": 0.022, "slab": {"at": [-0.7, 0.72, 0.0], "normal": [-0.75, 0.66, 0.1], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.34, "h": 0.9, "clip": 0.1}, "thick": 0.2, "taper": 0.04, "back": 1.0}}, + {"name": "Shin.Greave", "mat": "khaki", "bevel": 0.022, "slab": {"at": [0.0, 0.88, -1.3], "normal": [0.0, 1.0, -0.07], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": [[-0.5, 0.72], [0.5, 0.72], [0.66, 0.4], [0.6, -0.5], [0.36, -0.95], [-0.36, -0.95], [-0.6, -0.5], [-0.66, 0.4]], "thick": 0.28, "taper": 0.04, "back": 1.0}, "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.04, 0.07], "inset": 0.075, "gap": 0.045, "split": 0.8, "seed": 564123}}, + {"name": "Shin.GreaveStep", "mat": "olive_light", "bevel": 0.022, "slab": {"at": [0.0, 0.97, -1.2], "normal": [0.0, 1.0, -0.07], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.62, "h": 0.84, "clip": 0.12}, "thick": 0.15, "taper": 0.04, "back": 1.0}}, + {"name": "Shin.Outer", "mat": "khaki", "bevel": 0.022, "slab": {"at": [0.82, -0.2, -1.05], "normal": [1.0, 0.04, 0.0], "up": [0.0, 0.0, 1.0], "right": [0.0, 1.0, 0.0], "outline": [[-0.75, 0.62], [0.34, 0.74], [0.74, 0.36], [0.7, -0.55], [0.28, -0.96], [-0.6, -0.82], [-0.95, -0.1]], "thick": 0.26, "taper": 0.04, "back": 1.0}, "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.04, 0.07], "inset": 0.075, "gap": 0.045, "split": 0.8, "seed": 733553}}, + {"name": "Shin.OuterStep", "mat": "olive_light", "bevel": 0.022, "slab": {"at": [0.92, -0.2, -1.0], "normal": [1.0, 0.04, 0.0], "up": [0.0, 0.0, 1.0], "right": [0.0, 1.0, 0.0], "outline": [[-0.42, 0.42], [0.2, 0.46], [0.46, 0.2], [0.44, -0.3], [0.16, -0.5], [-0.36, -0.44], [-0.56, -0.05]], "thick": 0.13, "taper": 0.04, "back": 1.0}, "fits": [{"kind": "mark", "id": "tri", "at": [-0.03, -0.02], "height": 0.4}]}, + {"name": "Shin.Inner", "mat": "khaki", "bevel": 0.022, "slab": {"at": [-0.78, -0.12, -1.1], "normal": [-1.0, 0.04, 0.0], "up": [0.0, 0.0, 1.0], "right": [0.0, 1.0, 0.0], "outline": [[-0.7, 0.55], [0.3, 0.66], [0.66, 0.3], [0.62, -0.5], [0.25, -0.86], [-0.55, -0.74], [-0.85, -0.1]], "thick": 0.22, "taper": 0.04, "back": 1.0}, "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.05, 0.05], "inset": 0.075, "gap": 0.045, "split": 99.0, "seed": 299054}}, + {"name": "Shin.Calf", "mat": "khaki", "bevel": 0.022, "slab": {"at": [0.0, -1.12, -0.95], "normal": [0.0, -1.0, 0.1], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": [[-0.5, 0.62], [0.5, 0.62], [0.68, 0.1], [0.5, -0.62], [-0.5, -0.62], [-0.68, 0.1]], "thick": 0.22, "taper": 0.04, "back": 1.0}, "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.05, 0.05], "inset": 0.075, "gap": 0.045, "split": 99.0, "seed": 800359}}, + {"name": "Shin.CalfStep", "mat": "olive_light", "bevel": 0.022, "slab": {"at": [0.0, -1.2, -1.05], "normal": [0.0, -1.0, 0.1], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.72, "h": 0.46, "clip": 0.1}, "thick": 0.12, "taper": 0.04, "back": 1.0}}, + {"name": "Shin.Ankle", "mat": "olive_light", "bevel": 0.022, "slab": {"at": [0.0, 0.66, -2.42], "normal": [0.0, 1.0, -0.2], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.8, "h": 0.52, "clip": 0.12}, "thick": 0.2, "taper": 0.04, "back": 1.0}, "clad": {"mat": "khaki", "min_area": 0.2, "lifts": [0.04, 0.07], "inset": 0.075, "gap": 0.045, "split": 0.8, "seed": 22775}}, + {"name": "Shin.AnkleSide", "mat": "khaki", "bevel": 0.022, "slab": {"at": [0.6, 0.1, -2.35], "normal": [1.0, 0.1, -0.1], "up": [0.0, 0.0, 1.0], "right": [0.0, 1.0, 0.0], "outline": {"w": 0.7, "h": 0.5, "clip": 0.12}, "thick": 0.16, "taper": 0.04, "back": 1.0}}, + {"name": "Pelvis.core", "mat": "gunmetal", "bevel": 0.02, "points": [[0.62, 0.62, 0.5], [0.62, -0.6, 0.5], [0.72, 0.7, -0.3], [0.72, -0.62, -0.3], [0.45, 0.7, 0.62], [0.45, -0.66, 0.62], [0.4, 0.55, -0.8], [0.4, -0.45, -0.8]], "mirror": true}, + {"name": "Pelvis.Crown", "mat": "khaki", "bevel": 0.022, "slab": {"at": [0.0, 1.0, 0.42], "normal": [0.0, 1.0, 0.16], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": [[-0.32, 0.3], [0.32, 0.3], [0.48, 0.04], [0.3, -0.3], [-0.3, -0.3], [-0.48, 0.04]], "thick": 0.3, "taper": 0.04, "back": 1.0}, "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.05, 0.05], "inset": 0.075, "gap": 0.045, "split": 99.0, "seed": 345924}}, + {"name": "Pelvis.Cod", "mat": "khaki", "bevel": 0.022, "slab": {"at": [0.0, 1.06, -0.62], "normal": [0.0, 1.0, -0.1], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": [[-0.36, 0.7], [0.36, 0.7], [0.44, 0.3], [0.3, -0.78], [-0.3, -0.78], [-0.44, 0.3]], "thick": 0.34, "taper": 0.04, "back": 1.0}, "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.04, 0.07], "inset": 0.075, "gap": 0.045, "split": 0.8, "seed": 876596}}, + {"name": "Pelvis.CodStep", "mat": "olive_light", "bevel": 0.022, "slab": {"at": [0.0, 1.17, -0.3], "normal": [0.0, 1.0, -0.1], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.5, "h": 0.42, "clip": 0.1}, "thick": 0.14, "taper": 0.04, "back": 1.0}}, + {"name": "Pelvis.CodLame", "mat": "olive_light", "bevel": 0.022, "slab": {"at": [0.0, 1.15, -1.02], "normal": [0.0, 1.0, -0.1], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.42, "h": 0.4, "clip": 0.08}, "thick": 0.13, "taper": 0.04, "back": 1.0}}, + {"name": "Pelvis.Wing", "mat": "khaki", "bevel": 0.022, "sides": "both", "slab": {"at": [0.92, 0.84, 0.5], "normal": [0.3, 1.0, 0.2], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": [[-0.46, -0.02], [0.44, 0.36], [0.54, 0.1], [0.44, -0.26], [-0.46, -0.36]], "thick": 0.22, "taper": 0.04, "back": 1.0}, "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.04, 0.07], "inset": 0.075, "gap": 0.045, "split": 0.8, "seed": [876672, 589838]}}, + {"name": "Pelvis.HipGuard", "mat": "olive_light", "bevel": 0.022, "sides": "both", "slab": {"at": [0.62, 0.92, -0.05], "normal": [0.2, 1.0, -0.05], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.34, "h": 0.5, "clip": 0.08}, "thick": 0.16, "taper": 0.04, "back": 1.0}}, + {"name": "Pelvis.Seat", "mat": "khaki", "bevel": 0.022, "sides": "both", "slab": {"at": [0.56, -0.86, 0.02], "normal": [0.22, -1.0, 0.1], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": [[-0.5, 0.66], [0.5, 0.72], [0.6, -0.2], [0.2, -0.86], [-0.5, -0.6]], "thick": 0.24, "taper": 0.04, "back": 1.0}, "clad": {"mat": "olive_light", "min_area": 0.2, "lifts": [0.05, 0.05], "inset": 0.075, "gap": 0.045, "split": 99.0, "seed": [1004746, 453014]}}, + {"name": "Pelvis.SeatStep", "mat": "olive_light", "bevel": 0.022, "sides": "both", "slab": {"at": [0.6, -0.95, 0.1], "normal": [0.22, -1.0, 0.1], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.56, "h": 0.6, "clip": 0.12}, "thick": 0.12, "taper": 0.04, "back": 1.0}}, + {"name": "Pelvis.Tail", "mat": "olive_light", "bevel": 0.022, "slab": {"at": [0.0, -0.92, -0.2], "normal": [0.0, -1.0, -0.05], "up": [0.0, 0.0, 1.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.36, "h": 1.3, "clip": 0.1}, "thick": 0.22, "taper": 0.04, "back": 1.0}, "clad": {"mat": "khaki", "min_area": 0.2, "lifts": [0.04, 0.07], "inset": 0.075, "gap": 0.045, "split": 0.8, "seed": 995407}}, + {"name": "Pelvis.Roof", "mat": "khaki", "bevel": 0.022, "sides": "both", "slab": {"at": [0.62, 0.0, 0.7], "normal": [0.25, 0.0, 1.0], "up": [0.0, 1.0, 0.0], "right": [1.0, 0.0, 0.0], "outline": {"w": 0.6, "h": 1.1, "clip": 0.14}, "thick": 0.14, "taper": 0.04, "back": 1.0}} + ]}, "cases": [ {"side": 1, "truth": { "Thigh.core": {"solid":[[-0.33,-0.3,0.4],[0.33,-0.3,0.4],[0.45,-0.18,0.4],[0.45,0.38,0.4],[0.33,0.5,0.4],[-0.33,0.5,0.4],[-0.45,0.38,0.4],[-0.45,-0.18,0.4],[-0.42,-0.34,0.05],[0.42,-0.34,0.05],[0.6,-0.16,0.05],[0.6,0.46,0.05],[0.42,0.64,0.05],[-0.42,0.64,0.05],[-0.6,0.46,0.05],[-0.6,-0.16,0.05],[-0.42,-0.34,-1.45],[0.42,-0.34,-1.45],[0.6,-0.16,-1.45],[0.6,0.46,-1.45],[0.42,0.64,-1.45],[-0.42,0.64,-1.45],[-0.6,0.46,-1.45],[-0.6,-0.16,-1.45],[-0.335,-0.3,-1.8],[0.335,-0.3,-1.8],[0.475,-0.16,-1.8],[0.475,0.36,-1.8],[0.335,0.5,-1.8],[-0.335,0.5,-1.8],[-0.475,0.36,-1.8],[-0.475,-0.16,-1.8]],"facets":26,"panels":[],"bolts":0}, diff --git a/surfaces/blender/tests/fixtures/plates_raptor.json b/surfaces/blender/tests/fixtures/plates_raptor.json index a8b19c0..b85d1c2 100644 --- a/surfaces/blender/tests/fixtures/plates_raptor.json +++ b/surfaces/blender/tests/fixtures/plates_raptor.json @@ -1,1285 +1,31 @@ {"source": {"branch": "nibu/fable-raptor-4", "sha": "0c271035b89cbf36b26977cc5a19c94e07199ae5", "blender": "5.3.0"}, - "table": { - "schema": "brokkr.plates.v0", - "plates": [ - { - "name": "Torso.Jaw1", - "mat": "khaki", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.27, - 5.5, - 4.344352800343537 - ], - [ - 0.25, - 5.5, - 4.14792737789203 - ], - [ - 0.6025, - 4.75, - 4.437397172236504 - ], - [ - 0.6125, - 4.75, - 4.857397172236504 - ] - ], - "inside": [ - 0.0, - 5.125, - 4.5561471722365035 - ], - "lift": 0.1, - "thick": 0.14, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 9.0, - "seed": [ - 1, - 0 - ] - } - }, - { - "name": "Torso.Jaw2", - "mat": "olive_light", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.6131733333333336, - 4.72, - 4.885944978524653 - ], - [ - 0.6160000000000002, - 4.72, - 4.4478971722365035 - ], - [ - 0.88375, - 3.95, - 4.672185089974293 - ], - [ - 0.85025, - 3.95, - 5.162396244735779 - ] - ], - "inside": [ - 0.0, - 4.335, - 4.819518423307627 - ], - "lift": 0.13, - "thick": 0.16, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "khaki", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 0.9, - "seed": [ - 18, - 17 - ] - } - }, - { - "name": "Torso.Jaw3", - "mat": "khaki", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.8582000000000001, - 3.92, - 5.171231323471511 - ], - [ - 0.8920000000000001, - 3.92, - 4.680185089974293 - ], - [ - 1.041875, - 3.05, - 4.885938303341902 - ], - [ - 1.029375, - 3.25, - 5.265938303341902 - ] - ], - "inside": [ - 0.0, - 3.535, - 5.03285175664096 - ], - "lift": 0.1, - "thick": 0.14, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.035 - ], - "inset": 0.07, - "gap": 0.04, - "split": 99.0, - "seed": [ - 35, - 34 - ] - } - }, - { - "name": "Torso.JawLip1", - "mat": "gunmetal", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.27666666666666656, - 5.4, - 4.19167737789203 - ], - [ - 0.1577777777777777, - 5.4, - 4.03167737789203 - ], - [ - 0.45000000000000007, - 4.5, - 4.364897172236503 - ], - [ - 0.7150000000000001, - 4.5, - 4.5248971722365035 - ] - ], - "inside": [ - 0.0, - 4.95, - 4.617397172236504 - ], - "lift": 0.04, - "thick": 0.08, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - } - }, - { - "name": "Torso.JawLip2", - "mat": "khaki", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.7330000000000001, - 4.46, - 4.536185089974293 - ], - [ - 0.4620000000000001, - 4.46, - 4.3761850899742925 - ], - [ - 0.63, - 3.4, - 4.655938303341902 - ], - [ - 1.0025, - 3.4, - 4.815938303341902 - ] - ], - "inside": [ - 0.0, - 3.9299999999999997, - 4.927518423307626 - ], - "lift": 0.05, - "thick": 0.08, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 9.0, - "seed": [ - 69, - 68 - ] - } - }, - { - "name": "Torso.CollarU", - "mat": "olive_light", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.0636, - 3.5, - 6.0693942065828415 - ], - [ - 0.53, - 3.5, - 6.007794206582841 - ], - [ - 0.566, - 3.14, - 6.083710663170325 - ], - [ - 0.06863999999999999, - 3.08, - 6.155219361779141 - ] - ], - "inside": [ - 0.0, - 3.305, - 5.084938303341902 - ], - "lift": 0.17, - "thick": 0.16, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "khaki", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 9.0, - "seed": [ - 86, - 85 - ] - } - }, - { - "name": "Torso.CollarF", - "mat": "olive_light", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.53, - 3.5, - 6.007794206582841 - ], - [ - 1.00125, - 3.5, - 5.212185089974293 - ], - [ - 1.02375, - 3.3, - 5.255938303341902 - ], - [ - 0.566, - 3.14, - 6.083710663170325 - ] - ], - "inside": [ - 0.0, - 3.36, - 5.073938303341902 - ], - "lift": 0.16, - "thick": 0.16, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "khaki", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 9.0, - "seed": [ - 103, - 102 - ] - } - }, - { - "name": "Torso.Cheek", - "mat": "khaki", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.5910599999999999, - 3.08, - 6.0618721194416505 - ], - [ - 1.01152, - 3.24, - 5.29989720287198 - ], - [ - 1.0611000000000002, - 2.5, - 5.445415433520716 - ], - [ - 0.9396, - 2.32, - 5.664961644345172 - ], - [ - 0.6307200000000001, - 2.32, - 6.133612994552364 - ] - ], - "inside": [ - 0.0, - 2.692, - 5.207538303341902 - ], - "lift": 0.11, - "thick": 0.13, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "fits": [ - { - "kind": "mark", - "id": "27", - "at": [ - 0.006142872851341963, - 0.0045098247937858105 - ], - "height": 0.5 - } - ] - }, - { - "name": "Torso.CheekDeck", - "mat": "khaki", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.06911999999999999, - 3.04, - 6.1615584474346505 - ], - [ - 0.56448, - 3.04, - 6.1013584474346505 - ], - [ - 0.6076, - 2.0, - 6.175354661707495 - ], - [ - 0.0744, - 2.0, - 6.235554661707495 - ] - ], - "inside": [ - 0.0, - 2.52, - 5.241938303341902 - ], - "lift": 0.07, - "thick": 0.1, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 0.9, - "seed": [ - 137, - 136 - ] - } - }, - { - "name": "Torso.Gill", - "mat": "gunmetal", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.63168, - 2.28, - 6.135409293752973 - ], - [ - 1.06132, - 2.28, - 5.488082927942363 - ], - [ - 1.06038, - 1.98, - 5.5440385341450344 - ], - [ - 0.6378699999999999, - 1.98, - 6.148364408169792 - ] - ], - "inside": [ - 0.0, - 2.13, - 5.319938303341901 - ], - "lift": 0.05, - "thick": 0.09, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - } - }, - { - "name": "Torso.Shoulder", - "mat": "olive_light", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.63681, - 1.94, - 6.149855403487022 - ], - [ - 1.0762500000000002, - 1.94, - 5.524430162810625 - ], - [ - 0.9305714285714286, - 0.62, - 5.77571206803326 - ], - [ - 0.5378933333333333, - 0.42, - 6.1004641922008265 - ] - ], - "inside": [ - 0.0, - 1.23, - 5.472763496143958 - ], - "lift": 0.2, - "thick": 0.16, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "khaki", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 0.7, - "seed": [ - 171, - 170 - ] - } - }, - { - "name": "Torso.ShoulderDeck", - "mat": "khaki", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.07428, - 1.96, - 6.236924230634243 - ], - [ - 0.6066199999999999, - 1.96, - 6.176724230634243 - ], - [ - 0.51744, - 0.44, - 6.119364493385301 - ], - [ - 0.06336, - 0.44, - 6.179564493385301 - ] - ], - "inside": [ - 0.0, - 1.2, - 5.477763496143958 - ], - "lift": 0.09, - "thick": 0.1, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 0.6, - "seed": [ - 188, - 187 - ] - } - }, - { - "name": "Torso.Belt1", - "mat": "khaki", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 1.0571000000000002, - 3.0, - 5.299138303341902 - ], - [ - 1.04525, - 3.02, - 4.891938303341902 - ], - [ - 1.07, - 2.36, - 5.023938303341902 - ], - [ - 1.0796000000000001, - 2.36, - 5.427138303341902 - ] - ], - "inside": [ - 0.0, - 2.685, - 5.208938303341902 - ], - "lift": 0.07, - "thick": 0.11, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.035 - ], - "inset": 0.07, - "gap": 0.04, - "split": 99.0, - "seed": [ - 205, - 204 - ] - } - }, - { - "name": "Torso.Belt2", - "mat": "olive_light", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 1.0796000000000001, - 2.33, - 5.433138303341901 - ], - [ - 1.07, - 2.33, - 5.029938303341901 - ], - [ - 1.03875, - 1.5, - 5.1777634961439585 - ], - [ - 1.0483500000000001, - 1.5, - 5.5809634961439585 - ] - ], - "inside": [ - 0.0, - 1.915, - 5.358596829477292 - ], - "lift": 0.11, - "thick": 0.12, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "khaki", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 9.0, - "seed": [ - 222, - 221 - ] - } - }, - { - "name": "Torso.Belt3", - "mat": "khaki", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 1.046475, - 1.47, - 5.585963496143958 - ], - [ - 1.036875, - 1.47, - 5.182763496143958 - ], - [ - 0.9480000000000001, - 0.78, - 5.326616966580977 - ], - [ - 0.9301714285714286, - 0.62, - 5.759668263975169 - ] - ], - "inside": [ - 0.0, - 1.085, - 5.496930162810625 - ], - "lift": 0.08, - "thick": 0.11, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - } - }, - { - "name": "Torso.Lip1", - "mat": "gunmetal", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 1.0070000000000001, - 3.36, - 4.823938303341902 - ], - [ - 0.632, - 3.36, - 4.663938303341902 - ], - [ - 0.66, - 2.4, - 4.855938303341902 - ], - [ - 1.07, - 2.4, - 5.015938303341902 - ] - ], - "inside": [ - 0.0, - 2.88, - 5.169938303341902 - ], - "lift": 0.03, - "thick": 0.08, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - } - }, - { - "name": "Torso.Lip2", - "mat": "khaki", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 1.07, - 2.36, - 5.023938303341902 - ], - [ - 0.66, - 2.36, - 4.863938303341902 - ], - [ - 0.625, - 1.3, - 5.0510968294772915 - ], - [ - 1.02625, - 1.3, - 5.211096829477292 - ] - ], - "inside": [ - 0.0, - 1.83, - 5.372763496143959 - ], - "lift": 0.05, - "thick": 0.08, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 9.0, - "seed": [ - 273, - 272 - ] - } - }, - { - "name": "Torso.Lip3", - "mat": "gunmetal", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 1.02375, - 1.26, - 5.2177634961439585 - ], - [ - 0.623, - 1.26, - 5.057763496143958 - ], - [ - 0.56, - 0.5, - 5.250616966580976 - ], - [ - 0.9, - 0.5, - 5.410616966580976 - ] - ], - "inside": [ - 0.0, - 0.88, - 5.546616966580976 - ], - "lift": 0.03, - "thick": 0.08, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - } - }, - { - "name": "Torso.Hood1D", - "mat": "khaki", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.0624, - 0.4, - 6.169880489976104 - ], - [ - 0.52, - 0.4, - 6.108280489976104 - ], - [ - 0.364, - -0.66, - 6.250353133913001 - ], - [ - 0.04368, - -0.66, - 6.3119531339130015 - ] - ], - "inside": [ - 0.0, - -0.13, - 5.896217574199579 - ], - "lift": 0.14, - "thick": 0.11, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 9.0, - "seed": [ - 307, - 306 - ] - } - }, - { - "name": "Torso.Hood1F", - "mat": "khaki", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.5601485714285714, - 0.56, - 6.135829871438327 - ], - [ - 0.9411428571428572, - 0.74, - 5.338616966580977 - ], - [ - 0.6, - -0.1, - 5.633944846926852 - ], - [ - 0.488, - -0.66, - 5.797178285195826 - ], - [ - 0.36976, - -0.66, - 6.24185255718071 - ] - ], - "inside": [ - 0.0, - -0.024000000000000004, - 5.852853937835943 - ], - "lift": 0.13, - "thick": 0.12, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 0.5, - "seed": [ - 324, - 323 - ] - } - }, - { - "name": "Torso.Hood2D", - "mat": "olive_light", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.044399999999999995, - -0.6, - 6.311459761576258 - ], - [ - 0.37, - -0.6, - 6.249859761576258 - ], - [ - 0.32, - -1.5, - 6.226910880175944 - ], - [ - 0.0384, - -1.5, - 6.288510880175944 - ] - ], - "inside": [ - 0.0, - -1.05, - 6.070119461666414 - ], - "lift": 0.1, - "thick": 0.1, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "khaki", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 9.0, - "seed": [ - 341, - 340 - ] - } - }, - { - "name": "Torso.Hood2F", - "mat": "olive_light", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.37392, - -0.62, - 6.242114324404738 - ], - [ - 0.496, - -0.62, - 5.794825344019356 - ], - [ - 0.41, - -1.5, - 5.8465900499017085 - ], - [ - 0.3244, - -1.5, - 6.21998395024202 - ] - ], - "inside": [ - 0.0, - -1.06, - 6.070707696960532 - ], - "lift": 0.09, - "thick": 0.11, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - } - }, - { - "name": "Torso.Hood3D", - "mat": "khaki", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.03864, - -1.46, - 6.292862675791256 - ], - [ - 0.322, - -1.46, - 6.231262675791256 - ], - [ - 0.26, - -2.3, - 6.16377625008143 - ], - [ - 0.0312, - -2.3, - 6.22537625008143 - ] - ], - "inside": [ - 0.0, - -1.88, - 6.152707433134606 - ], - "lift": 0.06, - "thick": 0.09, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 9.0, - "seed": [ - 375, - 374 - ] - } - }, - { - "name": "Torso.Hood3F", - "mat": "khaki", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.32646000000000003, - -1.46, - 6.22419092354263 - ], - [ - 0.4135, - -1.46, - 5.844237108725237 - ], - [ - 0.32, - -2.3, - 5.992069135262265 - ], - [ - 0.2632, - -2.3, - 6.161355376401335 - ] - ], - "inside": [ - 0.0, - -1.88, - 6.152707433134606 - ], - "lift": 0.05, - "thick": 0.1, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - }, - "clad": { - "mat": "olive_light", - "min_area": 0.12, - "lifts": [ - 0.035, - 0.06 - ], - "inset": 0.07, - "gap": 0.04, - "split": 9.0, - "seed": [ - 392, - 391 - ] - } - }, - { - "name": "Torso.HoodLip", - "mat": "gunmetal", - "bevel": 0.012, - "sides": "both", - "slab": { - "corners": [ - [ - 0.85, - 0.4, - 5.4406169665809765 - ], - [ - 0.5366666666666667, - 0.4, - 5.280616966580976 - ], - [ - 0.24749999999999997, - -2.2, - 5.810792539517585 - ], - [ - 0.33124999999999993, - -2.2, - 5.970792539517585 - ] - ], - "inside": [ - 0.0, - -0.9000000000000001, - 6.061295932254649 - ], - "lift": 0.03, - "thick": 0.07, - "taper": 0.035, - "back": 0.94, - "gap": 0.025 - } - } - ] -}, + "table": {"schema": "brokkr.plates.v0", "plates": [ + {"name": "Torso.Jaw1", "mat": "khaki", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.27, 5.5, 4.344352800343537], [0.25, 5.5, 4.14792737789203], [0.6025, 4.75, 4.437397172236504], [0.6125, 4.75, 4.857397172236504]], "inside": [0.0, 5.125, 4.5561471722365035], "lift": 0.1, "thick": 0.14, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "olive_light", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 9.0, "seed": [1, 0]}}, + {"name": "Torso.Jaw2", "mat": "olive_light", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.6131733333333336, 4.72, 4.885944978524653], [0.6160000000000002, 4.72, 4.4478971722365035], [0.88375, 3.95, 4.672185089974293], [0.85025, 3.95, 5.162396244735779]], "inside": [0.0, 4.335, 4.819518423307627], "lift": 0.13, "thick": 0.16, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "khaki", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 0.9, "seed": [18, 17]}}, + {"name": "Torso.Jaw3", "mat": "khaki", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.8582000000000001, 3.92, 5.171231323471511], [0.8920000000000001, 3.92, 4.680185089974293], [1.041875, 3.05, 4.885938303341902], [1.029375, 3.25, 5.265938303341902]], "inside": [0.0, 3.535, 5.03285175664096], "lift": 0.1, "thick": 0.14, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "olive_light", "min_area": 0.12, "lifts": [0.035, 0.035], "inset": 0.07, "gap": 0.04, "split": 99.0, "seed": [35, 34]}}, + {"name": "Torso.JawLip1", "mat": "gunmetal", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.27666666666666656, 5.4, 4.19167737789203], [0.1577777777777777, 5.4, 4.03167737789203], [0.45000000000000007, 4.5, 4.364897172236503], [0.7150000000000001, 4.5, 4.5248971722365035]], "inside": [0.0, 4.95, 4.617397172236504], "lift": 0.04, "thick": 0.08, "taper": 0.035, "back": 0.94, "gap": 0.025}}, + {"name": "Torso.JawLip2", "mat": "khaki", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.7330000000000001, 4.46, 4.536185089974293], [0.4620000000000001, 4.46, 4.3761850899742925], [0.63, 3.4, 4.655938303341902], [1.0025, 3.4, 4.815938303341902]], "inside": [0.0, 3.9299999999999997, 4.927518423307626], "lift": 0.05, "thick": 0.08, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "olive_light", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 9.0, "seed": [69, 68]}}, + {"name": "Torso.CollarU", "mat": "olive_light", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.0636, 3.5, 6.0693942065828415], [0.53, 3.5, 6.007794206582841], [0.566, 3.14, 6.083710663170325], [0.06863999999999999, 3.08, 6.155219361779141]], "inside": [0.0, 3.305, 5.084938303341902], "lift": 0.17, "thick": 0.16, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "khaki", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 9.0, "seed": [86, 85]}}, + {"name": "Torso.CollarF", "mat": "olive_light", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.53, 3.5, 6.007794206582841], [1.00125, 3.5, 5.212185089974293], [1.02375, 3.3, 5.255938303341902], [0.566, 3.14, 6.083710663170325]], "inside": [0.0, 3.36, 5.073938303341902], "lift": 0.16, "thick": 0.16, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "khaki", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 9.0, "seed": [103, 102]}}, + {"name": "Torso.Cheek", "mat": "khaki", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.5910599999999999, 3.08, 6.0618721194416505], [1.01152, 3.24, 5.29989720287198], [1.0611000000000002, 2.5, 5.445415433520716], [0.9396, 2.32, 5.664961644345172], [0.6307200000000001, 2.32, 6.133612994552364]], "inside": [0.0, 2.692, 5.207538303341902], "lift": 0.11, "thick": 0.13, "taper": 0.035, "back": 0.94, "gap": 0.025}, "fits": [{"kind": "mark", "id": "27", "at": [0.006142872851341963, 0.0045098247937858105], "height": 0.5}]}, + {"name": "Torso.CheekDeck", "mat": "khaki", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.06911999999999999, 3.04, 6.1615584474346505], [0.56448, 3.04, 6.1013584474346505], [0.6076, 2.0, 6.175354661707495], [0.0744, 2.0, 6.235554661707495]], "inside": [0.0, 2.52, 5.241938303341902], "lift": 0.07, "thick": 0.1, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "olive_light", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 0.9, "seed": [137, 136]}}, + {"name": "Torso.Gill", "mat": "gunmetal", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.63168, 2.28, 6.135409293752973], [1.06132, 2.28, 5.488082927942363], [1.06038, 1.98, 5.5440385341450344], [0.6378699999999999, 1.98, 6.148364408169792]], "inside": [0.0, 2.13, 5.319938303341901], "lift": 0.05, "thick": 0.09, "taper": 0.035, "back": 0.94, "gap": 0.025}}, + {"name": "Torso.Shoulder", "mat": "olive_light", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.63681, 1.94, 6.149855403487022], [1.0762500000000002, 1.94, 5.524430162810625], [0.9305714285714286, 0.62, 5.77571206803326], [0.5378933333333333, 0.42, 6.1004641922008265]], "inside": [0.0, 1.23, 5.472763496143958], "lift": 0.2, "thick": 0.16, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "khaki", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 0.7, "seed": [171, 170]}}, + {"name": "Torso.ShoulderDeck", "mat": "khaki", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.07428, 1.96, 6.236924230634243], [0.6066199999999999, 1.96, 6.176724230634243], [0.51744, 0.44, 6.119364493385301], [0.06336, 0.44, 6.179564493385301]], "inside": [0.0, 1.2, 5.477763496143958], "lift": 0.09, "thick": 0.1, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "olive_light", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 0.6, "seed": [188, 187]}}, + {"name": "Torso.Belt1", "mat": "khaki", "bevel": 0.012, "sides": "both", "slab": {"corners": [[1.0571000000000002, 3.0, 5.299138303341902], [1.04525, 3.02, 4.891938303341902], [1.07, 2.36, 5.023938303341902], [1.0796000000000001, 2.36, 5.427138303341902]], "inside": [0.0, 2.685, 5.208938303341902], "lift": 0.07, "thick": 0.11, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "olive_light", "min_area": 0.12, "lifts": [0.035, 0.035], "inset": 0.07, "gap": 0.04, "split": 99.0, "seed": [205, 204]}}, + {"name": "Torso.Belt2", "mat": "olive_light", "bevel": 0.012, "sides": "both", "slab": {"corners": [[1.0796000000000001, 2.33, 5.433138303341901], [1.07, 2.33, 5.029938303341901], [1.03875, 1.5, 5.1777634961439585], [1.0483500000000001, 1.5, 5.5809634961439585]], "inside": [0.0, 1.915, 5.358596829477292], "lift": 0.11, "thick": 0.12, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "khaki", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 9.0, "seed": [222, 221]}}, + {"name": "Torso.Belt3", "mat": "khaki", "bevel": 0.012, "sides": "both", "slab": {"corners": [[1.046475, 1.47, 5.585963496143958], [1.036875, 1.47, 5.182763496143958], [0.9480000000000001, 0.78, 5.326616966580977], [0.9301714285714286, 0.62, 5.759668263975169]], "inside": [0.0, 1.085, 5.496930162810625], "lift": 0.08, "thick": 0.11, "taper": 0.035, "back": 0.94, "gap": 0.025}}, + {"name": "Torso.Lip1", "mat": "gunmetal", "bevel": 0.012, "sides": "both", "slab": {"corners": [[1.0070000000000001, 3.36, 4.823938303341902], [0.632, 3.36, 4.663938303341902], [0.66, 2.4, 4.855938303341902], [1.07, 2.4, 5.015938303341902]], "inside": [0.0, 2.88, 5.169938303341902], "lift": 0.03, "thick": 0.08, "taper": 0.035, "back": 0.94, "gap": 0.025}}, + {"name": "Torso.Lip2", "mat": "khaki", "bevel": 0.012, "sides": "both", "slab": {"corners": [[1.07, 2.36, 5.023938303341902], [0.66, 2.36, 4.863938303341902], [0.625, 1.3, 5.0510968294772915], [1.02625, 1.3, 5.211096829477292]], "inside": [0.0, 1.83, 5.372763496143959], "lift": 0.05, "thick": 0.08, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "olive_light", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 9.0, "seed": [273, 272]}}, + {"name": "Torso.Lip3", "mat": "gunmetal", "bevel": 0.012, "sides": "both", "slab": {"corners": [[1.02375, 1.26, 5.2177634961439585], [0.623, 1.26, 5.057763496143958], [0.56, 0.5, 5.250616966580976], [0.9, 0.5, 5.410616966580976]], "inside": [0.0, 0.88, 5.546616966580976], "lift": 0.03, "thick": 0.08, "taper": 0.035, "back": 0.94, "gap": 0.025}}, + {"name": "Torso.Hood1D", "mat": "khaki", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.0624, 0.4, 6.169880489976104], [0.52, 0.4, 6.108280489976104], [0.364, -0.66, 6.250353133913001], [0.04368, -0.66, 6.3119531339130015]], "inside": [0.0, -0.13, 5.896217574199579], "lift": 0.14, "thick": 0.11, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "olive_light", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 9.0, "seed": [307, 306]}}, + {"name": "Torso.Hood1F", "mat": "khaki", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.5601485714285714, 0.56, 6.135829871438327], [0.9411428571428572, 0.74, 5.338616966580977], [0.6, -0.1, 5.633944846926852], [0.488, -0.66, 5.797178285195826], [0.36976, -0.66, 6.24185255718071]], "inside": [0.0, -0.024000000000000004, 5.852853937835943], "lift": 0.13, "thick": 0.12, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "olive_light", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 0.5, "seed": [324, 323]}}, + {"name": "Torso.Hood2D", "mat": "olive_light", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.044399999999999995, -0.6, 6.311459761576258], [0.37, -0.6, 6.249859761576258], [0.32, -1.5, 6.226910880175944], [0.0384, -1.5, 6.288510880175944]], "inside": [0.0, -1.05, 6.070119461666414], "lift": 0.1, "thick": 0.1, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "khaki", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 9.0, "seed": [341, 340]}}, + {"name": "Torso.Hood2F", "mat": "olive_light", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.37392, -0.62, 6.242114324404738], [0.496, -0.62, 5.794825344019356], [0.41, -1.5, 5.8465900499017085], [0.3244, -1.5, 6.21998395024202]], "inside": [0.0, -1.06, 6.070707696960532], "lift": 0.09, "thick": 0.11, "taper": 0.035, "back": 0.94, "gap": 0.025}}, + {"name": "Torso.Hood3D", "mat": "khaki", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.03864, -1.46, 6.292862675791256], [0.322, -1.46, 6.231262675791256], [0.26, -2.3, 6.16377625008143], [0.0312, -2.3, 6.22537625008143]], "inside": [0.0, -1.88, 6.152707433134606], "lift": 0.06, "thick": 0.09, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "olive_light", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 9.0, "seed": [375, 374]}}, + {"name": "Torso.Hood3F", "mat": "khaki", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.32646000000000003, -1.46, 6.22419092354263], [0.4135, -1.46, 5.844237108725237], [0.32, -2.3, 5.992069135262265], [0.2632, -2.3, 6.161355376401335]], "inside": [0.0, -1.88, 6.152707433134606], "lift": 0.05, "thick": 0.1, "taper": 0.035, "back": 0.94, "gap": 0.025}, "clad": {"mat": "olive_light", "min_area": 0.12, "lifts": [0.035, 0.06], "inset": 0.07, "gap": 0.04, "split": 9.0, "seed": [392, 391]}}, + {"name": "Torso.HoodLip", "mat": "gunmetal", "bevel": 0.012, "sides": "both", "slab": {"corners": [[0.85, 0.4, 5.4406169665809765], [0.5366666666666667, 0.4, 5.280616966580976], [0.24749999999999997, -2.2, 5.810792539517585], [0.33124999999999993, -2.2, 5.970792539517585]], "inside": [0.0, -0.9000000000000001, 6.061295932254649], "lift": 0.03, "thick": 0.07, "taper": 0.035, "back": 0.94, "gap": 0.025}} + ]}, "cases": [ {"side": 1, "truth": { "Torso.Jaw1.R": {"solid":[[0.6781577,4.8458824,4.7452664],[0.668655,4.8445058,4.4767356],[0.3750727,5.4858899,4.2300553],[0.3787763,5.4840679,4.3069553],[0.6626044,4.800034,4.8098192],[0.6499786,4.7982044,4.4530377],[0.3264895,5.5049257,4.1812291],[0.3335624,5.5014462,4.3280835],[0.5565017,4.7785773,4.7914252],[0.5446335,4.7768579,4.4560513],[0.2405537,5.4411759,4.200551],[0.2472022,5.4379053,4.338594]],"facets":10,"panels":[],"bolts":0}, From 08896d85652ccb0232ab499b5aae8b862983b623 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 15:07:25 +0100 Subject: [PATCH 208/223] brokkr_kitbash: set_params and setObjectParent ask the one-driver rule before they write; a joints row says held write_checks is the writer's own checks and the one-driver rule in one call: write_connections asks it before it writes, and set_params asks it before it rebuilds a mesh or rewrites kit_params, so its refusal leaves the scene as it stood (finding set-params-writes-before-the-guard). Brokkr's setObjectParent asks each enabled add-on that defines brokkr_parent_refusal(object, parent) before it writes a parent; brokkr_kitbash answers one_driver over the scene as the new parent would leave it (finding bridge-reparent-bypasses-the-guard). A brokkr.joints row carries held: true when its limits are of one value (finding held-pin-row-is-undistinguished). Co-Authored-By: Claude Fable 5.2 --- .../blender/brokkr_bridge/blender_target.py | 6 ++ surfaces/blender/brokkr_kitbash/__init__.py | 65 ++++++++++++++----- surfaces/blender/brokkr_kitbash/core.py | 4 +- .../blender/tests/live/kitbash_follows.py | 24 ++++++- .../tests/live/kitbash_follows.result.json | 29 ++++++++- .../tests/live/kitbash_pose.result.json | 6 ++ surfaces/blender/tests/test_kitbash.py | 21 ++++-- 7 files changed, 125 insertions(+), 30 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 6e23e8c..5d90bc4 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -47,6 +47,7 @@ HOST_SNAPSHOT_SCHEMA = "brokkr.blender.host_snapshot.v0" HOST_ACTIONS_FILE = "brokkr_actions.json" HOST_RESULT_LIMIT = 16000 # characters of a host operator's result copied into a receipt KIT_RESERVED = "kit_" # brokkr_kitbash owns every custom property so named: kit_owned is the one test, setObjectCustomProperty refuses them and importGltf drops them +PARENT_REFUSAL = "brokkr_parent_refusal" # a function(object, parent or None) -> why not, or None, that an enabled add-on may define: setObjectParent asks each before it writes (brokkr_kitbash: its one-driver rule) KIT_FROZEN = "kit_frozen" # brokkr_kitbash's frozen state (its FROZEN): read here only, to refuse an export that would apply a stack twice COMMAND_INTENT_SCHEMA = "brokkr.blender.command_intent.v0" COMMAND_RECEIPT_SCHEMA = "brokkr.blender.command_receipt.v0" @@ -934,6 +935,11 @@ class BrokkrBlenderTarget: if ancestor.name == obj.name: raise sa.ActionRefused(f"{obj.name!r} cannot be parented to itself or to one of its own children.") ancestor = getattr(ancestor, "parent", None) + for module in self.bpy.context.preferences.addons.keys(): # an enabled add-on that owns a rule over parents is asked before the write + refusal = getattr(sys.modules.get(module), PARENT_REFUSAL, None) + reason = refusal(obj, parent) if callable(refusal) else None + if reason: + raise sa.ActionRefused(reason) obj.parent = parent return self._receipt(command, "accepted", "Blender object parent updated.", obj.name) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index b4c008f..1d04944 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -222,29 +222,33 @@ def dof(parent, parent_socket: dict): return core.load_kit(str(parent.get(KIT, "")))["socketTypes"][parent_socket["type"]].get("dof") -def connection_kind(obj, kits=None) -> tuple: +STANDS = object() # connection_kind's and joint_record's `parent` when it is the one the child has + + +def connection_kind(obj, kits=None, parent=STANDS) -> tuple: """(DOF kind, parent socket type) of the connection a child states, from the parent's kit by the socket's name alone (a socket's type is the same at every params), or (None, None) when it cannot be read: no parent, a parent that is no kit part, a socket the part does not have. `kits` is kit_part_of's: one call's read of each - kit file.""" + kit file. `parent` is the parent the child is about to be given (parent_refusal), read in place of its own.""" try: - name, kits = str(obj.parent.get(KIT, "")), {} if kits is None else kits + parent = obj.parent if parent is STANDS else parent + name, kits = str(parent.get(KIT, "")), {} if kits is None else kits if name not in kits: kits[name] = core.load_kit(name) kit = kits[name] - socket_type = next(s["type"] for s in core.part(kit, str(obj.parent[PART]))["sockets"] if s["name"] == obj.get(PARENT_SOCKET)) + socket_type = next(s["type"] for s in core.part(kit, str(parent[PART]))["sockets"] if s["name"] == obj.get(PARENT_SOCKET)) return kit["socketTypes"][socket_type].get("dof"), socket_type except (AttributeError, KeyError, StopIteration, core.KitError): return None, None -def joint_record(obj, kits=None) -> dict: +def joint_record(obj, kits=None, parent=STANDS) -> dict: """The joint record a child's connection states, {limits: (lo, hi) or None, mechanism, compliance, follows}: degrees of its roll on a revolute joint, metres of its slide on a prismatic one; follows is None or {driver (the object, None once it is gone, as closure's other part), kind 'ratio' | 'loop', k, offset}. Every report, the joints report, the poses and hose read it here. A value written by hand that write_connections would not have written reads None: one that is not of its shape, and one record_refusal refuses for this connection's DOF kind (a compliance on a - revolute joint), so no report emits it and the next write clears it.""" + revolute joint), so no report emits it and the next write clears it. `parent` is connection_kind's.""" lo, hi, label, spring, follows = obj.get(LIMIT_MIN), obj.get(LIMIT_MAX), obj.get(MECHANISM), None, None with contextlib.suppress(ValueError, TypeError): spring = json.loads(obj.get(COMPLIANCE, "null")) @@ -259,7 +263,7 @@ def joint_record(obj, kits=None) -> dict: "follows": {"driver": driver if isinstance(driver, bpy.types.Object) and driver.users_collection else None, "kind": follows["kind"], "k": float(follows["k"]) if ratio else None, "offset": float(follows["offset"]) if ratio else None} if ratio or follows == {"kind": "loop"} else None} - kind, socket_type = connection_kind(obj, kits) + kind, socket_type = connection_kind(obj, kits, parent) for field in ("limits", "mechanism", "compliance", "follows"): # limits first: a compliance is read beside the limits that stand alone = {**dict.fromkeys(record), "limits": record["limits"] if field == "compliance" else None, field: record[field]} if record[field] is not None and record_refusal(kind, socket_type, alone) is not None: @@ -390,16 +394,24 @@ def connection_checks(entries) -> list: return checked +def write_checks(entries) -> list: + """Every check a write of `entries` must pass, and what it writes (connection_checks): each entry's own, then + the one-driver rule over the scene as the entries would leave it (one_driver). write_connections asks before + it writes; set_params asks before it rebuilds a mesh, so each refusal leaves the scene as it stood.""" + checked = connection_checks(entries) + one_driver({child: (parent, kind, record) for child, parent, _, _, _, _, _, kind, record in checked}) + return checked + + def write_connections(entries) -> None: """State connections and seat them, all or none: each child's parent, its derived matrix_basis, its three properties and its joint record, kit_follows and its driver pointer with it. Every entry is checked - (connection_checks) before any is written, so one refusal leaves every part as it stood. attach, set_params, + (write_checks) before any is written, so one refusal leaves every part as it stood. attach, set_params, roll, aim, reach, slide, joint and follow write a connection here and nowhere else, so what a joint record may - be, and that a follower's value is written with its driver's, is decided here. So is the one-driver rule: the - scene as these entries would leave it is read by one_driver before any is written, whatever the action.""" - checked = connection_checks(entries) - one_driver({child: (parent, kind, record) for child, parent, _, _, _, _, _, kind, record in checked}) - for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in checked: + be, and that a follower's value is written with its driver's, is decided here. So is the one-driver rule: + write_checks reads the scene as these entries would leave it (one_driver) before any is written, whatever the + action.""" + for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in write_checks(entries): child.parent = parent seat(child, core.mate(*sockets, roll, slide)) child[SOCKET], child[PARENT_SOCKET], child[ROLL] = socket, parent_socket, roll @@ -441,9 +453,11 @@ def one_driver(stating: dict) -> None: follows nothing and has travel, is a second driver: a pose of it would open the loop, so the write is refused naming the loop's driver and each other one. A joint both ends hang from moves them together and is not counted. A loop whose driver is gone or states no DOF connection is derived by nothing and is not read; it is - read again by the attach that gives the driver a connection. write_connections and detach ask here before - they write, so no action (attach, detach, clearing a follower, limits widened or cleared, any pose, a new - follow) leaves a loop with two drivers, and a scene edited by hand into one is refused its next write.""" + read again by the attach that gives the driver a connection. write_checks (every write of a connection, + and set_params before it rebuilds a mesh), detach and parent_refusal (Brokkr's setObjectParent) ask here + before they write, so no action (attach, detach, clearing a follower, limits widened or cleared, any pose, a + new follow, set_params, a new parent) leaves a loop with two drivers, and a scene edited by hand into one is + refused its next write.""" known, kits = {}, {} # each part's joint and each kit file are read once def parent(o): @@ -484,6 +498,20 @@ def one_driver(stating: dict) -> None: f"limits of one value. Give it that first, or clear the loop (brokkr_kitbash.follow on {closing.name!r} with record null); nothing changed.") +def brokkr_parent_refusal(obj, parent) -> str | None: + """Why an object may not be given `parent` (None clears it), or None when it may: the one-driver rule over the + scene as it would stand, the object's stated connection read on its new parent. Brokkr's setObjectParent asks + every enabled add-on that defines this name before it writes a parent, so a new parent that would give a + stated loop a second driver is refused there and then. Nothing else is asked: a parent that only leaves a + connection not holding is drift, and reports show it.""" + kind = connection_kind(obj, None, parent)[0] if SOCKET in obj else None + try: + one_driver({obj: (parent, kind, joint_record(obj, None, parent) if kind is not None else None)}) + except (Refused, core.KitError) as error: + return str(error) + return None + + def loop_pair(obj, stating=None): """(the parent follower, the closing follower) of the loop a loop follower is one of, or None when it has no partner. The closing follower states the closure and its parent is the other: both follow one driver as a @@ -987,7 +1015,8 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): """Change params of a placed kit part and rebuild its mesh in place: its modifiers and material slots stay, each shape keeps its faces' material, the Bevel width follows, and its connection and those of the parts attached to it are seated again on the moved sockets, through write_connections (a value outside its joint's - limits or a stray slide, written by hand, is refused before anything changes); a closure is never seated and a + limits or a stray slide, written by hand, and a scene that holds a loop with a second driver, are refused + before anything changes); a closure is never seated and a follower never derived again, only reported""" bl_idname = "brokkr_kitbash.set_params" bl_label = "Set Kit Part Params" @@ -1015,7 +1044,7 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): for child in attached(obj): child_part, child_built = built_part(child) entries.append((child, obj, mated(obj, part, built, child, child_part, child_built, link(child)), link(child), None)) - connection_checks(entries) + write_checks(entries) # every refusal write_connections has, the one-driver rule with them, before the mesh is rebuilt try: old = core.build(part, stored) except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index b1ddab5..92ed5eb 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1674,7 +1674,8 @@ def joint_rows(root_world, entries) -> tuple[list, int]: parent's 4x4 world, DOF kind or None for rigid, value, joint record, driven: what the report says drives it, or None). A row is a revolute or prismatic connection; its parent is the nearest one above it (a rigid connection belongs to the joint above it), its axis and origin the parent socket's z and origin in the frame of root_world, - and min and max what the limits leave of the value either way.""" + min and max what the limits leave of the value either way, and held whether the limits are of one value: a + joint with no travel, which is no degree of freedom (the one-driver rule's held pin).""" frame, nearest, rows, rigid = np.linalg.inv(np.asarray(root_world, dtype=np.float64)), {}, [], 0 for name, parent, part_name, socket, parent_world, kind, value, record, driven in entries: if kind is None: @@ -1685,6 +1686,7 @@ def joint_rows(root_world, entries) -> tuple[list, int]: rows.append({"id": name, "parent": nearest.get(parent), "part": part_name, "socket": f"{parent}:{socket['name']}", "kind": kind, "axis": [round(float(v), 6) for v in at[:3, 2]], "origin": [round(float(v), 6) for v in at[:3, 3]], "value": round(value, 6), "limits": limits, "min": limits and round(record["limits"][0] - value, 6), "max": limits and round(record["limits"][1] - value, 6), + "held": limits is not None and record["limits"][0] == record["limits"][1], "mechanism": record["mechanism"], "compliance": record["compliance"], "driven": driven}) nearest[name] = name return rows, rigid diff --git a/surfaces/blender/tests/live/kitbash_follows.py b/surfaces/blender/tests/live/kitbash_follows.py index 7b2cb9e..7d04ea1 100644 --- a/surfaces/blender/tests/live/kitbash_follows.py +++ b/surfaces/blender/tests/live/kitbash_follows.py @@ -472,13 +472,19 @@ try: refused("a pose of the driver after the lug's limits were widened by hand: the writer reads the rule before it writes", "brokkr_kitbash.slide", {"object_name": "T_Rod", "slide": 0.1}, "depend on more than one driver: 'T_Rod' and 'T_Lug' (it follows nothing and its joint has travel") refused("and a pose of the lug itself", "brokkr_kitbash.roll", {"object_name": "T_Lug", "roll": 95.0}, "depend on more than one driver: 'T_Rod' and 'T_Lug'") + shape = lambda: {name: np.array([v.co[:] for v in bpy.data.objects[name].data.vertices]).tobytes() for name in ("Idle", "Tip")} # noqa: E731 + was, tip_was = shape(), connection("Tip") + refused("set_params of an unrelated part in a scene that holds a second driver (finding set-params-writes-before-the-guard): the rule is read before the mesh is rebuilt", + "brokkr_kitbash.set_params", {"object_name": "Idle", "params": "length=0.6"}, + "the two ends of the loop 'T_Lower' closes, 'T_Barrel' (the base) and 'T_Lug' (closed on), depend on more than one driver: 'T_Rod' and 'T_Lug' (it follows nothing and its joint has travel", "nothing changed") + check("and nothing moved: the part's vertices and its child's connection read as before the refusal", shape() == was and connection("Tip") == tip_was and tip_was["holds"] is True, [tip_was, connection("Tip")]) t_lug["kit_min"], t_lug["kit_max"] = 90.0, 90.0 receipt, report = send("brokkr_kitbash.slide", object_name="T_Rod", slide=0.11) check("with the lug held again the driver is posed", receipt["status"] == "accepted" and report["closures"][0]["holds"] is True, receipt["message"]) receipt, joints = send("brokkr_kitbash.joints", object_name="T_Barrel") - check("the torque link has one degree of freedom: the rod's slide is its one row with travel that nothing drives, the lug has none, the arms are driven, and no row is unlimited", - receipt["status"] == "accepted" and [(row["id"], row["kind"], row["driven"] and row["driven"]["by"], row["min"], row["max"]) for row in joints["joints"]] == [ - ("T_Rod", "prismatic", None, -0.11, 0.19), ("T_Lug", "revolute", None, 0.0, 0.0), ("T_Upper", "revolute", "T_Rod", None, None), ("T_Lower", "revolute", "T_Rod", None, None)] + check("the torque link has one degree of freedom: the rod's slide is its one row with travel that nothing drives, the lug is its one held row, the arms are driven, and no row is unlimited", + receipt["status"] == "accepted" and [(row["id"], row["kind"], row["driven"] and row["driven"]["by"], row["min"], row["max"], row["held"]) for row in joints["joints"]] == [ + ("T_Rod", "prismatic", None, -0.11, 0.19, False), ("T_Lug", "revolute", None, 0.0, 0.0, True), ("T_Upper", "revolute", "T_Rod", None, None, False), ("T_Lower", "revolute", "T_Rod", None, None, False)] and joints["unlimited"] == [] and reading("closed", apart(t_lower, "end_b", t_lug, "end_b")) < CLOSED, [receipt["message"], joints]) place("T_Mount", "strut", W, far @ far @ far @ far @ turn) hinged = attach("T_Barrel", "base", "T_Mount", "end_a", 25.0) @@ -493,6 +499,18 @@ try: {"object_name": "T_Lug"}, "the two ends of the loop 'T_Lower' closes, 'T_Barrel' (the base) and 'T_Lug' (closed on), depend on more than one driver: 'T_Rod' and 'T_Barrel' (it follows nothing and its joint has travel") + refused("setObjectParent clearing the lug's parent (finding bridge-reparent-bypasses-the-guard): Brokkr's own row asks the same rule before it writes a parent", "setObjectParent", + {"targetObjectName": "T_Lug", "parentObjectName": ""}, + "the two ends of the loop 'T_Lower' closes, 'T_Barrel' (the base) and 'T_Lug' (closed on), depend on more than one driver: 'T_Rod' and 'T_Barrel' (it follows nothing and its joint has travel", "nothing changed") + refused("setObjectParent of a root onto a part on a free pin: with the four-bar's base under Idle, the rocker the ram closes on depends on Idle's roll", "setObjectParent", + {"targetObjectName": "Base", "parentObjectName": "Idle"}, + "the two ends of the loop 'A_Rod' closes, 'Pad' (the base) and 'Rocker' (closed on), depend on more than one driver: 'Crank' and 'Idle' (it follows nothing and its joint has travel", "nothing changed") + receipt, _ = send("setObjectParent", targetObjectName="Loose", parentObjectName="Idle") + under = bpy.data.objects["Loose"].parent + receipt2, _ = send("setObjectParent", targetObjectName="Loose", parentObjectName="") + check("setObjectParent of a part no loop depends on is written as before, and cleared again", receipt["status"] == "accepted" and under == bpy.data.objects["Idle"] + and receipt2["status"] == "accepted" and bpy.data.objects["Loose"].parent is None, [receipt["message"], receipt2["message"]]) + # --- joints, version 2 ---------------------------------------------------------------------------------------------------------- receipt, joints = send("brokkr_kitbash.joints", object_name="Ground") table = {row["id"]: row for row in (joints or {}).get("joints", [])} diff --git a/surfaces/blender/tests/live/kitbash_follows.result.json b/surfaces/blender/tests/live/kitbash_follows.result.json index a8434ac..7ffc432 100644 --- a/surfaces/blender/tests/live/kitbash_follows.result.json +++ b/surfaces/blender/tests/live/kitbash_follows.result.json @@ -321,13 +321,23 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: set_params of an unrelated part in a scene that holds a second driver (finding set-params-writes-before-the-guard): the rule is read before the mesh is rebuilt", + "ok": true, + "detail": null + }, + { + "name": "and nothing moved: the part's vertices and its child's connection read as before the refusal", + "ok": true, + "detail": null + }, { "name": "with the lug held again the driver is posed", "ok": true, "detail": null }, { - "name": "the torque link has one degree of freedom: the rod's slide is its one row with travel that nothing drives, the lug has none, the arms are driven, and no row is unlimited", + "name": "the torque link has one degree of freedom: the rod's slide is its one row with travel that nothing drives, the lug is its one held row, the arms are driven, and no row is unlimited", "ok": true, "detail": null }, @@ -341,6 +351,21 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: setObjectParent clearing the lug's parent (finding bridge-reparent-bypasses-the-guard): Brokkr's own row asks the same rule before it writes a parent", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: setObjectParent of a root onto a part on a free pin: with the four-bar's base under Idle, the rocker the ram closes on depends on Idle's roll", + "ok": true, + "detail": null + }, + { + "name": "setObjectParent of a part no loop depends on is written as before, and cleared again", + "ok": true, + "detail": null + }, { "name": "joints is version 2: a driven row names what drives it (F6), and unlimited lists the rows that are not driven and state no limits", "ok": true, @@ -434,7 +459,7 @@ "ram solved at 45": 0.0, "ram solved at 60": 0.0, "ratio": 0.0, - "rows in the first receipt": 33.0, + "rows in the first receipt": 32.0, "slid": 1e-07, "solved": 3.3e-05 }, diff --git a/surfaces/blender/tests/live/kitbash_pose.result.json b/surfaces/blender/tests/live/kitbash_pose.result.json index 3091443..50ea94b 100644 --- a/surfaces/blender/tests/live/kitbash_pose.result.json +++ b/surfaces/blender/tests/live/kitbash_pose.result.json @@ -528,6 +528,7 @@ ], "min": -3.000003, "max": 72.999997, + "held": false, "mechanism": "knee", "compliance": null, "driven": null @@ -552,6 +553,7 @@ "limits": null, "min": null, "max": null, + "held": false, "mechanism": null, "compliance": null, "driven": null @@ -579,6 +581,7 @@ ], "min": -0.12, "max": 0.18, + "held": false, "mechanism": "shock", "compliance": { "damping_ratio": 0.7, @@ -609,6 +612,7 @@ ], "min": -75.0, "max": 35.0, + "held": false, "mechanism": "ankle", "compliance": null, "driven": null @@ -633,6 +637,7 @@ "limits": null, "min": null, "max": null, + "held": false, "mechanism": null, "compliance": null, "driven": null @@ -657,6 +662,7 @@ "limits": null, "min": null, "max": null, + "held": false, "mechanism": null, "compliance": null, "driven": null diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index fe1cfeb..02aa454 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1617,6 +1617,9 @@ class JointRecordTests(unittest.TestCase): [("Barrel", None, "revolute", "Root:end_b"), ("Rod", "Barrel", "prismatic", "Plate:bore")]) self.assertEqual((rows[0]["value"], rows[0]["limits"], rows[0]["min"], rows[0]["max"], rows[0]["mechanism"], rows[0]["driven"]), (30.0, [-20.0, 60.0], -50.0, 30.0, "elbow", None)) self.assertEqual((rows[1]["value"], rows[1]["limits"], rows[1]["min"], rows[1]["max"], rows[1]["driven"]["by"]), (0.125, None, None, None, "Barrel")) + self.assertEqual([row["held"] for row in rows], [False, False]) + (held,), _ = core.joint_rows(root, [("Lug", "Root", "strut", socket(strut, "end_b"), root, "revolute", 90.0, {**free, "limits": (90.0, 90.0)}, None)]) + self.assertEqual((held["limits"], held["min"], held["max"], held["held"]), ([90.0, 90.0], 0.0, 0.0, True)) # limits of one value: no travel, and the row says so pin = socket(strut, "end_b")["matrix"] self.assertEqual((rows[0]["axis"], rows[0]["origin"]), ([round(float(v), 6) for v in pin[:3, 2]], [round(float(v), 6) for v in pin[:3, 3]])) # in the root's frame: the socket as the part has it bore = core.mate(socket(strut, "end_b"), socket(barrel, "base"), 30.0) @ socket(barrel, "bore")["matrix"] @@ -2530,20 +2533,26 @@ class OwnershipTests(unittest.TestCase): self.assertIsNone(re.search(r"seat\(seated|driver_add\(|constraints\.new\(", source)) self.assertEqual(source.count("seat("), 5) # its def, write_connections, and a cutter's, a ribs' and a hose's own frames body = source.split("class BROKKR_KITBASH_OT_set_params(")[1].split("class BROKKR_KITBASH_OT_")[0] - self.assertLess(body.index("connection_checks(entries)"), body.index("clear_geometry()")) + self.assertLess(body.index("write_checks(entries)"), body.index("clear_geometry()")) # the writer's own checks, the one-driver rule with them (live: 'set_params of an unrelated part in a scene that holds a second driver') + self.assertLess(body.index("write_checks(entries)"), body.index("obj[PARAMS] =")) self.assertLess(body.index("clear_geometry()"), body.index("write_connections(entries)")) self.assertEqual(source.count("core.close_loop("), 1) self.assertIn("core.close_loop(", source.split("\ndef driven(")[1].split("\n\n\n")[0]) self.assertEqual(source.count("write_connections(["), 2) # write_connection, and follow clearing a statement # every entry is checked before one is written (mutant J5, a refusal raised after the writes; F5 is its live twin): the writer's loop runs over the # checks' whole answer and raises nothing itself, and the checks write nothing - self.assertIn(" checked = connection_checks(entries)\n one_driver({child: (parent, kind, record) for child, parent, _, _, _, _, _, kind, record in checked})\n" - " for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in checked:\n child.parent = parent\n", writer) + self.assertIn(" for child, parent, sockets, socket, parent_socket, roll, slide, kind, record in write_checks(entries):\n child.parent = parent\n", writer) + asked = source.split("\ndef write_checks(")[1].split("\n\n\n")[0] + self.assertIn(" checked = connection_checks(entries)\n one_driver({child: (parent, kind, record) for child, parent, _, _, _, _, _, kind, record in checked})\n return checked", asked) self.assertNotIn("raise ", writer) - # the one-driver rule has one owner, asked by the one writer and by detach before either writes, and it writes nothing: no action states its own - # copy (live: an attach, a clear, widened limits, a pose and a detach after the loop is stated are each refused) + # the one-driver rule has one owner, asked by write_checks (the one writer, and set_params before its mesh), by detach and by + # brokkr_parent_refusal (Brokkr's setObjectParent) before any writes, and it writes nothing: no action states its own copy (live: an attach, a + # clear, widened limits, a pose, a set_params, a detach and a new parent after the loop is stated are each refused) rule = source.split("\ndef one_driver(")[1].split("\n\n\n")[0] - self.assertEqual((source.count("one_driver("), source.count("depend on more than one driver")), (3, 1)) + self.assertEqual((source.count("one_driver("), source.count("depend on more than one driver")), (4, 1)) + asker = source.split("\ndef brokkr_parent_refusal(")[1].split("\n\n\n")[0] + self.assertIn("one_driver({obj: (parent, kind,", asker) + self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|\w+\[\w+\]\s*=(?!=)|\bdel ", asker + asked)) self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|\w+\[[A-Z_]+\]\s*=(?!=)|\bdel ", rule)) detach = source.split("class BROKKR_KITBASH_OT_detach(")[1].split("class BROKKR_KITBASH_OT_")[0] self.assertLess(detach.index("one_driver("), detach.index("obj.parent = None")) From a25cec6f2777d535361cd9819db48aff02094227 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 15:07:25 +0100 Subject: [PATCH 209/223] docs/kitbash.md, install.md, action table: who asks the one-driver rule, a ram's limits and its dead centre, held The rule is read before every write, by set_params before its mesh and by setObjectParent; a ram whose limits reach its closed length is refused by the conditioning bound; a held row is in neither unlimited nor rigid (finding docs-state-the-old-rule). Co-Authored-By: Claude Fable 5.2 --- .../brokkr_kitbash/brokkr_actions.json | 2 +- surfaces/blender/docs/install.md | 4 ++- surfaces/blender/docs/kitbash.md | 35 +++++++++++-------- 3 files changed, 25 insertions(+), 16 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index e83a183..8a2f11c 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -360,7 +360,7 @@ }, { "name": "brokkr_kitbash.joints", - "doc": "The joints of the tree of kit parts attached under a root part, as {schema: brokkr.joints, version: 2, root, frame, rigid, unlimited, next, joints}. A row per revolute or prismatic connection, depth first with children by name, so a joint's parent row comes before it; a root that itself states a revolute or prismatic connection has its own row first, parent null: id (the child object), parent (the id of the nearest joint above, or null: rigid connections fold into it and are counted in rigid), part, socket ('Object:socket', the parent socket), kind, axis and origin (that socket's z and origin in the root object's frame: Blender axes, +Z up, metres), value (the roll in degrees or the slide in metres now), limits ([lo, hi] or null), min and max (the limits less the value: the travel either way from this pose), mechanism, compliance and driven (null, or {by: the driver's id, kind: ratio | loop, k, offset}: the value is derived from the driver's, so a rig makes a driven bone and not a DOF). kind is revolute or prismatic: Aetheria's ShipJoint calls them rotate and slide, one to one. unlimited lists the ids of the rows this report carries that are not driven and state no limits: an exporter that needs limits refuses by this one field of each report. Axis, origin and order are derived at each report from the kits and the parent tree; nothing stores them. Rows a receipt cannot carry are counted in jointsOmitted, and next is then the id of the last row carried (else null): call again with after set to it for the rows that follow and their unlimited ids; a report is never over a receipt and always carries a row. after refuses an id that is no row's. Refuses a connection that cannot be read. Evaluates no modifier.", + "doc": "The joints of the tree of kit parts attached under a root part, as {schema: brokkr.joints, version: 2, root, frame, rigid, unlimited, next, joints}. A row per revolute or prismatic connection, depth first with children by name, so a joint's parent row comes before it; a root that itself states a revolute or prismatic connection has its own row first, parent null: id (the child object), parent (the id of the nearest joint above, or null: rigid connections fold into it and are counted in rigid), part, socket ('Object:socket', the parent socket), kind, axis and origin (that socket's z and origin in the root object's frame: Blender axes, +Z up, metres), value (the roll in degrees or the slide in metres now), limits ([lo, hi] or null), min and max (the limits less the value: the travel either way from this pose), held (true when the limits are of one value: the joint has no travel, as a torque link's lug held at [90, 90], so a rig makes a fixed bone and not a DOF; such a row is in neither unlimited nor rigid), mechanism, compliance and driven (null, or {by: the driver's id, kind: ratio | loop, k, offset}: the value is derived from the driver's, so a rig makes a driven bone and not a DOF). kind is revolute or prismatic: Aetheria's ShipJoint calls them rotate and slide, one to one. unlimited lists the ids of the rows this report carries that are not driven and state no limits: an exporter that needs limits refuses by this one field of each report. Axis, origin and order are derived at each report from the kits and the parent tree; nothing stores them. Rows a receipt cannot carry are counted in jointsOmitted, and next is then the id of the last row carried (else null): call again with after set to it for the rows that follow and their unlimited ids; a report is never over a receipt and always carries a row. after refuses an id that is no row's. Refuses a connection that cannot be read. Evaluates no modifier.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 40362d6..c6c67fa 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -182,7 +182,9 @@ Behaviour the table does not say, per action: - `createObject`: a `MESH` is a cube of `size`. `lightType`, `emptyDisplayType` and `meshType` apply only to their own `objectType`. -- `setObjectParent`: an empty or absent `parentObjectName` clears the parent. +- `setObjectParent`: an empty or absent `parentObjectName` clears the parent. Before it writes, each enabled + add-on that defines `brokkr_parent_refusal(object, parent)` is asked, and a reason it answers refuses the + intent with nothing changed (`brokkr_kitbash` answers its one-driver rule, `docs/kitbash.md`). - `importGltf`: `filepath`, `.gltf` or `.glb`, relative to the add-on preference `Import Directory` (absolute paths, `..` and symlinks that resolve outside it are refused). Empty `Import Directory` disables the action. Needs Blender's glTF add-on. diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 34263e8..33dfb1f 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -223,12 +223,13 @@ driver is the only input the two ends depend on: every revolute or prismatic joi two ends share (or the root, when they share none) is the driver, follows it, or is held by limits of one value. A joint there that follows another driver, or that follows nothing and has travel, is a second driver: a pose of it would open the loop, and nothing here solves a loop for two drivers. The rule is read over every loop in the scene -before each write, as the scene would stand after it (`one_driver`, asked by the one writer of connections and by -`detach`), so it holds after the loop is stated as it does when `follow` states it. Each of these is refused with +before each write, as the scene would stand after it (`one_driver`, asked by the one writer of connections, by +`set_params` before it rebuilds a mesh, by `detach` and by Brokkr's `setObjectParent`), so it holds after the loop +is stated as it does when `follow` states it. Each of these is refused with nothing changed, naming the loop's driver and each other one: `attach` of an end's root on a pin or a slide, `detach` of a part between an end and the part both ends hang from, `follow` with null on a follower between the -ends, `joint` widening or clearing limits that held a pin there, and any pose once such a joint was written by -hand. To change a mechanism between a loop's ends, give the new joint its one driver or its one value first, or +ends, `joint` widening or clearing limits that held a pin there, `setObjectParent` giving or clearing a parent +between the ends, and any pose or `set_params` once such a joint was written by hand. To change a mechanism between a loop's ends, give the new joint its one driver or its one value first, or clear the loop and state it again. A loop whose driver is detached is derived by nothing and is not read; the attach that gives the driver a connection again reads it. A torque link is the case for limits of one value: a real torque link exists to stop the rod rolling in its barrel, so its lug has no travel, and a strut pinned to @@ -253,13 +254,15 @@ at 0 and the reading is the ram's lever over its closed lever: a ram drawn in to accepted and one at 0.047 refused. The sign of the Jacobian's determinant about the pin is the assembly branch (an elbow bent one way or the other, a rod's end on one side of its barrel's pin or the other), and a Newton step that lands on the other sign from its seed is refused as past the dead centre, so no pose answers the other branch. -A ram with limits never comes near either: its slide leaves its limits first. +A ram whose limits keep its slide clear of minus its closed length never comes near either: its slide leaves its +limits first. One whose limits reach that far is refused by the bound above before it leaves them. What followers give up: a loop of three or more unknowns, or one out of a plane, is not solved (follow-up `kit-follows-wider-loops`); a follower does not drive another; `set_params` never derives a follower again, so a -loop it opens reads `holds: false` until its driver is posed; and the one-driver rule is checked when a loop is -stated, so a part attached, detached, cleared of its statement or given wider limits afterwards between a loop's -ends can still open it, and reads the same way. A connection's row in a report carries `follows: {driver, kind, k, offset, holds, reason}`: +loop it opens reads `holds: false` until its driver is posed; and a scene that holds a loop +with a second driver (a limit widened by hand, a parent set in Blender's own interface, a saved file) is refused +every write of a connection, a `set_params` and a `setObjectParent`, related to the loop or not, until the joint +is held again, follows the driver, or the loop is cleared. A connection's row in a report carries `follows: {driver, kind, k, offset, holds, reason}`: `holds` is false, with a reason, when the value stands off the ratio, the loop's closure does not hold, or the driver is gone or states no revolute or prismatic connection. Detaching a driver leaves its followers' statements; detaching a loop follower clears its partner's. No Blender driver or constraint is made: a follower's @@ -280,14 +283,15 @@ nothing: "rigid": 2, "unlimited": ["Barrel"], "next": null, "joints": [ {"id": "Strut", "parent": null, "part": "strut", "socket": "Mount:pivot", "kind": "revolute", "axis": [0.0, 1.0, 0.0], "origin": [0.436, 0.0, 0.85368], "value": -113.019997, "limits": [-116.02, -40.02], - "min": -3.000003, "max": 72.999997, "mechanism": "knee", "compliance": null, "driven": null}, + "min": -3.000003, "max": 72.999997, "mechanism": "knee", "compliance": null, "held": false, "driven": null}, {"id": "Cap", "parent": "Strut", "part": "strut", "socket": "Strut:end_a_back", "kind": "revolute", "axis": [0.0, -1.0, 0.0], "origin": [0.436, -0.09, 0.85368], "value": -56.509999, "limits": null, - "min": null, "max": null, "mechanism": null, "compliance": null, + "min": null, "max": null, "mechanism": null, "compliance": null, "held": false, "driven": {"by": "Strut", "kind": "ratio", "k": 0.5, "offset": 0.0}}, {"id": "Rod", "parent": "Barrel", "part": "ram_rod", "socket": "Barrel:bore", "kind": "prismatic", "axis": [0.97429, 0.0, 0.225296], "origin": [1.072572, 0.124, 1.312762], "value": 0.12, "limits": [0.0, 0.3], - "min": -0.12, "max": 0.18, "mechanism": "shock", "compliance": {"damping_ratio": 0.7, "hertz": 4.0}, "driven": null}]} + "min": -0.12, "max": 0.18, "mechanism": "shock", "compliance": {"damping_ratio": 0.7, "hertz": 4.0}, + "held": false, "driven": null}]} ``` A row per revolute or prismatic connection under the root, depth first with children by name, so a row's parent @@ -295,7 +299,9 @@ comes before it; a root that itself states a revolute or prismatic connection ha null, so a report of a sub-tree carries the joint the sub-tree hangs by. `parent` is the nearest joint above, not the object the part hangs from: rigid connections fold into it and are counted in `rigid`. `axis` and `origin` are the parent socket's z and origin in the root object's frame. `min` and `max` are the limits less the value, the travel either way from the pose the report was taken at, -which is the shape of Aetheria's `ShipJoint` (`Min` and `Max` about rest). `driven` is null, or what the row follows +which is the shape of Aetheria's `ShipJoint` (`Min` and `Max` about rest). `held` is true when the limits are of +one value: the joint has no travel (a torque link's lug held at `[90, 90]`), its `min` and `max` are 0, and a rig +makes a fixed bone for it and not a degree of freedom; a held row is in neither `unlimited` nor `rigid`. `driven` is null, or what the row follows (`by` the driver's id, `kind`, `k`, `offset`): a driven row's value is derived, so a rig makes a driven bone for it and not a degree of freedom. `unlimited` lists the ids of the rows this report carries that are not driven and state no limits, so an exporter that needs limits on every degree of freedom refuses by reading one field of each @@ -422,7 +428,8 @@ that breaks one (a `pipe_r` that no longer matches the flange it is bolted to) i connection. **Drift.** `setObjectTransform` and `setObjectParent` are Brokkr's own rows and can move or re-parent an attached -child. Reports show it: a part's `connection` is `null`, or +child; `setObjectParent` refuses only a parent that would give a stated loop a second driver ("Followers"). +Reports show it: a part's `connection` is `null`, or ```json {"parent": "Tee", "socket": "mount", "parentSocket": "c", "roll": 37.0, "residual": 2.1e-07, "holds": true} @@ -1348,7 +1355,7 @@ under such load (five runs), and reading a 336-face part takes 27 to 37 ms. | `brokkr_kitbash.reach` | `object_name`, `socket` (one of the part's), `height` (metres, -1000 to 1000), `direction_x`, `direction_y`, `direction_z` (world; default 0, 0, 1) | Solves the roll that brings the socket's origin to `height` along the direction, the nearer of the two, and turns the part to it. Refuses a height out of reach, naming the range. Reports the part, `reached: {roll, residual}` and `closures`. | | `brokkr_kitbash.joint` | `object_name`, `record` (a JSON object of any of `limits`: `[lo, hi]` or null; `mechanism`: a label or null; `compliance`: `{hertz, damping_ratio}` or null) | States the joint record of an attached part's connection; a key left out keeps what is stated and null clears it. A follower keeps its derived value, and a driver's followers are derived again. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits over a turn or past 360, prismatic limits past 10 m, and compliance on a revolute joint or without limits. Reports the part and `closures` as `roll` does | | `brokkr_kitbash.slide` | `object_name`, `slide` (metres, -10 to 10) | Slides an attached part along its parent socket's normal on a prismatic connection, where it hangs, and every follower of it with it. Refuses a revolute or rigid connection naming its socket type, a slide outside the joint's limits, and a follower. Reports the part and `closures` as `roll` does | -| `brokkr_kitbash.joints` | `object_name` (the root, a kit part), `after` (default empty: an id, the `next` of the report before) | Reports the joints of the tree attached under the root as `brokkr.joints` version 2: a row per revolute or prismatic connection, parents first and the root's own first when it states one, with `id`, `parent`, `part`, `socket`, `kind`, `axis`, `origin`, `value`, `limits`, `min`, `max`, `mechanism`, `compliance` and `driven`, in the root's frame, and `unlimited` and `next` beside them ("Joint records"). With `after`, the rows after that id. Changes nothing and evaluates no modifier. | +| `brokkr_kitbash.joints` | `object_name` (the root, a kit part), `after` (default empty: an id, the `next` of the report before) | Reports the joints of the tree attached under the root as `brokkr.joints` version 2: a row per revolute or prismatic connection, parents first and the root's own first when it states one, with `id`, `parent`, `part`, `socket`, `kind`, `axis`, `origin`, `value`, `limits`, `min`, `max`, `held`, `mechanism`, `compliance` and `driven`, in the root's frame, and `unlimited` and `next` beside them ("Joint records"). With `after`, the rows after that id. Changes nothing and evaluates no modifier. | | `brokkr_kitbash.follow` | `object_name` (the follower; for a loop, the part that states the closure), `record` (JSON: `{driver, kind: "ratio", k, offset}`, `{driver, kind: "loop"}` or null) | States that the part's joint follows the driver's, by a ratio or by keeping its closure closed with its parent's joint, and moves it there at once; null clears the statement, and a loop partner's with it ("Followers"). Refuses a rigid connection, a driver that is the follower, below it or itself a follower, a follower that already follows or drives another, a ratio whose driver states no limits, and a loop without a closure that holds, with both ends or neither moving with the driver, whose ends depend on another driver or on a joint posed by hand, that is not planar or that stands at a dead centre. Reports the part, `followers` and `closures`. | | `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. | | `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added; `booleansOmitted` counts rows a receipt had no room for) and `evaluated`. | From 2d4943804caf34f6f4743e6c6fae381b6ea1a0e7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 15:19:56 +0100 Subject: [PATCH 210/223] brokkr_kitbash.plate: a two-sided row with one seed is a mirrored pair; KNOWN's corner and tie plates held to repaired truths; one hash on two platforms (cut hard-plate-core, Soul s1) plate.build draws a two-sided row with one seed (or no clad) once, at side +1, and its .L is the mirror of its .R. A one-sided row at side -1 and a two-sided row with a pair of seeds are drawn on the mirrored solid as before, as the mech branches' builders do (paladin's left thigh). _longest's docstring says greatest. tests: Hull.Quarter.R/.L and Hull.BellySide.R are held, solid, facets, panels and bolts, to plates_bastion.json's "repaired": the branch's builder at eeda8bf in Blender 5.3 with massing.corners' inside test at 1e-5 m, and with massing.clad cutting from the other of the two tied edges. The panels whose outline crosses itself are named (Hull.Cheek.R's render difference is one of them, by where Blender starts its loop). The three fixtures build to one sha256 at 1e-9 m on Starfire and on Yggdrasil. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/plate.py | 45 ++++-- surfaces/blender/docs/kitbash.md | 34 ++++- .../tests/fixtures/plates_bastion.json | 7 +- surfaces/blender/tests/test_plate.py | 135 +++++++++++++++--- 4 files changed, 177 insertions(+), 44 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/plate.py b/surfaces/blender/brokkr_kitbash/plate.py index 5ad4b4d..5417cad 100644 --- a/surfaces/blender/brokkr_kitbash/plate.py +++ b/surfaces/blender/brokkr_kitbash/plate.py @@ -708,7 +708,7 @@ def panel(panels: _Mesh, bolts: _Mesh, polygon: list[np.ndarray], out: np.ndarra def _longest(pts: list[np.ndarray]) -> int: """The index of a polygon's longest edge; edges within TIE of it tie, and the tie goes to the edge whose middle - is least by x, y, z.""" + is greatest by x, y, z.""" lengths = [float(np.linalg.norm(pts[(k + 1) % len(pts)] - pts[k])) for k in range(len(pts))] top = max(lengths) return max((k for k in range(len(pts)) if top - lengths[k] <= TIE), key=lambda k: _lexical((pts[k] + pts[(k + 1) % len(pts)]) / 2)) @@ -764,11 +764,20 @@ def clad_layout(V: np.ndarray, faces, facets, clad: dict, seed: int, face_n, sid # --- build ------------------------------------------------------------------------------------------------------------ +def _across(mesh): + """A mesh (V, faces) mirrored across x = 0, its faces wound outward still and starting where they did.""" + V, faces = mesh + return V * (-1.0, 1.0, 1.0), [face[:1] + face[:0:-1] for face in faces] + + def build(table: Any, side: int = 1) -> list[dict]: """One entry per plate built, in the table's order: a row with sides "both" is built at `side`, then at -side. - Side -1 negates x of every point before the hull, so facets, panels and anchors are those of the mirrored solid - as built; a clad selector's direction is mirrored with it. Names end .R at side +1 and .L at -1 on a two-sided - row. Each entry: {name, row (its index in the table), mat, bevel, side, solid: (V, faces), facets, panels: (V, faces), bolts: (V, faces), + Names end .R at side +1 and .L at -1 on a two-sided row. A two-sided row with one seed (or no clad) is drawn + once, at side +1, and its .L is the mirror of its .R: the same facets in the same order, the same cuts and + lifts. Anywhere else (a one-sided row at side -1, a two-sided row with a pair of seeds) side -1 negates x of + every point before the hull, and facets, ties and draws are those of the mirrored solid as built, which is not + the mirror of side +1's panels; a clad selector's direction is mirrored with it. Each entry: {name, row (its + index in the table), mat, bevel, side, solid: (V, faces), facets, panels: (V, faces), bolts: (V, faces), anchors: [{kind, name, matrix, mirrored, height?}], report: {corners, facets, panels, bolts}}.""" if side not in (1, -1): raise PlateError(f"side: {side!r} is not 1 or -1") @@ -777,16 +786,26 @@ def build(table: Any, side: int = 1) -> list[dict]: for i, row in enumerate(table["plates"]): path = f"plates[{i}]" points, face = _row_points(row, path) + clad = row["clad"] + pair = clad is not None and not isinstance(clad["seed"], int) + drawn: dict[int, tuple] = {} for s in ((side, -side) if row["sides"] == "both" else (side,)): flip = np.array([float(s), 1.0, 1.0]) - V, faces, facets = hull(_mirrored(points * flip, row["mirror"]), path) face_n = None if face is None else face[3] * flip - clad, top = row["clad"], 0.0 - panels = bolts = (np.zeros((0, 3)), []) - made = 0 - if clad is not None: - seed = clad["seed"] if isinstance(clad["seed"], int) else clad["seed"][0 if s > 0 else 1] - panels, bolts, made, top = clad_layout(V, faces, facets, clad, seed, face_n, s) + where = 1 if row["sides"] == "both" and not pair else s # the side this plate is drawn at + if where not in drawn: + turn = np.array([float(where), 1.0, 1.0]) + V, faces, facets = hull(_mirrored(points * turn, row["mirror"]), path) + panels = bolts = (np.zeros((0, 3)), []) + made, top = 0, 0.0 + if clad is not None: + seed = clad["seed"][0 if where > 0 else 1] if pair else clad["seed"] + panels, bolts, made, top = clad_layout(V, faces, facets, clad, seed, None if face is None else face[3] * turn, where) + drawn[where] = ((V, faces), facets, panels, bolts, made, top) + solid, facets, panels, bolts, made, top = drawn[where] + if where != s: + solid, panels, bolts = _across(solid), _across(panels), _across(bolts) + facets = [{"normal": f["normal"] * flip, "area": f["area"], "centre": f["centre"] * flip} for f in facets] anchors = [] for j, fit in enumerate(row["fits"]): origin, a, b, n = face @@ -797,6 +816,6 @@ def build(table: Any, side: int = 1) -> list[dict]: anchor["height"] = fit["height"] anchors.append(anchor) built.append({"name": row["name"] + ((".R" if s > 0 else ".L") if row["sides"] == "both" else ""), "row": i, "mat": row["mat"], "bevel": row["bevel"], "side": s, - "solid": (V, faces), "facets": facets, "panels": panels, "bolts": bolts, "anchors": anchors, - "report": {"corners": len(V), "facets": len(faces), "panels": made, "bolts": len(bolts[0]) // 12}}) + "solid": solid, "facets": facets, "panels": panels, "bolts": bolts, "anchors": anchors, + "report": {"corners": len(solid[0]), "facets": len(solid[1]), "panels": made, "bolts": len(bolts[0]) // 12}}) return built diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 8589e55..ae8eb2e 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -871,8 +871,15 @@ plates somewhere owns that matrix. The table alone decides the result. A table h | `face` | `{at, normal, up, right}`: the face anchors stand on, for a row that is not a slab | | `fits` | anchors (below) | -`mirror` and `sides` are independent. Side -1 negates x of every point before the hull is built, so facets, -panels and anchors are those of the mirrored solid as built. +`mirror` and `sides` are independent. A two-sided row with one seed, or with no clad, is drawn once, at side +1, +and its `.L` is the mirror of its `.R`: the same facets in the same order, the same cuts and lifts, every face +wound the other way from the vertex it started at. Everywhere else, which is a one-sided row built at side -1 and +a two-sided row with a pair of seeds, side -1 negates x of every point before the hull is built, and facets, ties +and draws are those of the mirrored solid as built. That is not the mirror of side +1's panels even under the +same seed: a cut is measured along its edge in the facet's winding, which a mirror reverses, and a tie goes to the +greater x of the mirrored solid. The mech tracks' builders work this way (paladin's left thigh is its right +thigh's table at side -1 with the same seeds, and its split panels are cut at the other share), and the fixtures +hold `build` to them. ### Solid forms @@ -928,7 +935,7 @@ first. | `inset` | how far a panel stands in from its facet's edges | | `gap` | the seam between the two panels of a split facet | | `split` | a facet over this area is cut in two | -| `seed` | an integer, or `[right, left]` on a row with `sides: "both"`. There is no default. | +| `seed` | an integer, or `[right, left]` on a row with `sides: "both"`. There is no default. One integer on a two-sided row makes a mirrored pair; a pair of seeds draws each side on its own solid, also where the two are equal. | | `bolt_r` | a bolt's corner radius (default 0.028) | One `random.Random(seed)` draws, in facet order. A chosen facet over `split` is cut across its longest edge at a @@ -939,6 +946,12 @@ refused under a quarter of the part's area or under 0.02 m2; it is a prism from above, its far rim chamfered 0.02. A hexagonal bolt of radius `bolt_r` stands inside each panel corner, 3.2 `bolt_r` in. +The inset moves each corner along its own miter and does not look at its neighbours, so where it passes the two +ends of a short edge over each other the panel's outline crosses itself. `build` makes that panel as it stands; +Blender fills a face that crosses itself by where its loop starts, so the same vertices can render differently +from another builder's mesh. Two of the 104 fixture panels do it (bastion's `Hull.Cheek.R` and paladin's +`Thigh.Outer`), and the test names them. + ### Anchors A fit is a frame on the face, at `[a, b]` in the face's (a, b), standing on the face's top: the face, plus @@ -980,10 +993,17 @@ from a mech branch's own numbers and the solids, panels and bolt counts that bra 5.3; `tests/test_plate.py` holds `build` to them (solid vertices within 1e-6 m, panel vertices within 1e-5 m, facet and bolt counts equal). The branches' builders work in float32 and leave two choices to Blender's mesh order, so eleven of the 126 fixture plates are held to something else, each named in the test's `KNOWN`: -eight stand 1 to 2 micrometres (solid) or 29 micrometres (panels) from the float64 result; bastion's two -quarter pods lack a corner their faces do bound (the branch's inside test lost it to float32), so its solid is -smaller than the table's; and one of bastion's two belly-side plates splits its panel from the other of two -equally long edges. +eight stand 1 to 2 micrometres (solid) or 29 micrometres (panels) from the float64 result and are held at 4 and +40; bastion's two quarter pods lack a corner their faces do bound (the branch's inside test lost it to float32), +so the branch's solid is smaller than the table's and its panels are another solid's; and one of bastion's two +belly-side plates splits its panel from the other of two equally long edges. Those three are held, solid, facets, +panels and bolts, to `repaired` in `plates_bastion.json`: the branch's own builder run in Blender 5.3 with the +inside test at 1e-5 m, and with its clad cutting from the other tied edge. + +The same test builds the three fixtures to one sha256 of every coordinate rounded to 1e-9 m and every face, +pinned from Starfire (Windows 11, numpy 2.5.4) and Yggdrasil (Debian 13, numpy 2.2.4 on the system LAPACK). The +two hosts' coordinates differ by up to 2.7e-15 m, so the bytes of `build`'s arrays are equal between runs on one +host and not between hosts. ## Hoses between sockets diff --git a/surfaces/blender/tests/fixtures/plates_bastion.json b/surfaces/blender/tests/fixtures/plates_bastion.json index 0ff6adc..f57150a 100644 --- a/surfaces/blender/tests/fixtures/plates_bastion.json +++ b/surfaces/blender/tests/fixtures/plates_bastion.json @@ -42,4 +42,9 @@ "Hull.BellySide.R": {"solid":[[2.0999999,2.2,3.9000001],[2.0999999,-2.4000001,3.95],[2.45,2.0,4.0999999],[2.45,-2.2,4.1500001],[2.45,2.0,4.8499999],[2.45,-2.2,4.9000001],[2.25,2.2,5.0999999],[2.25,-2.4000001,5.1500001],[1.8,2.2,3.9000001],[1.8,-2.4000001,5.1500001]],"facets":15,"panels":[[2.4300001,-2.0900002,4.7886829],[2.4300001,-2.0900002,4.2586985],[2.4300001,-0.6636688,4.2417183],[2.4300001,-0.6573603,4.7716274],[2.5050001,-2.0900002,4.7886829],[2.5050001,-2.0900002,4.2586985],[2.5050001,-0.6636688,4.2417183],[2.5050001,-0.6573603,4.7716274],[2.5250001,-2.0700002,4.7684431],[2.5250001,-2.0700002,4.2784615],[2.5250001,-0.6834292,4.2619548],[2.5250001,-0.677597,4.7518668],[2.4300001,-0.3936881,4.2385039],[2.4300001,1.89,4.2113171],[2.4300001,1.89,4.7413015],[2.4300001,-0.3873795,4.7684135],[2.4750001,-0.3936881,4.2385039],[2.4750001,1.89,4.2113171],[2.4750001,1.89,4.7413015],[2.4750001,-0.3873795,4.7684135],[2.4950001,-0.3734515,4.2582645],[2.4950001,1.87,4.2315569],[2.4950001,1.87,4.7215385],[2.4950001,-0.367619,4.7481766],[2.2321301,1.8335732,5.0840106],[1.9212853,-2.2902241,5.1287899],[2.1400001,-2.2902241,5.1287899],[2.2321301,1.8343884,5.1590061],[1.9212853,-2.2894089,5.2037854],[2.1400001,-2.2894089,5.2037854],[2.2288792,1.7680224,5.179728],[1.9428494,-2.2691927,5.223567],[2.1204419,-2.2691927,5.223567]],"bolts":11}, "Hull.BellySide.L": {"solid":[[-2.0999999,2.2,3.9000001],[-2.0999999,-2.4000001,3.95],[-2.45,2.0,4.0999999],[-2.45,-2.2,4.1500001],[-2.45,2.0,4.8499999],[-2.45,-2.2,4.9000001],[-2.25,2.2,5.0999999],[-2.25,-2.4000001,5.1500001],[-1.8,2.2,3.9000001],[-1.8,-2.4000001,5.1500001]],"facets":15,"panels":[[-2.4300001,-2.0900002,4.2586985],[-2.4300001,-2.0900002,4.7886829],[-2.4300001,0.1687398,4.7617931],[-2.4300001,0.1624316,4.2318835],[-2.5050001,-2.0900002,4.2586985],[-2.5050001,-2.0900002,4.7886829],[-2.5050001,0.1687398,4.7617931],[-2.5050001,0.1624316,4.2318835],[-2.5250001,-2.0700002,4.2784615],[-2.5250001,-2.0700002,4.7684431],[-2.5250001,0.1485032,4.7420325],[-2.5250001,0.1426711,4.2521205],[-2.4300001,0.4387209,4.7585793],[-2.4300001,1.89,4.7413015],[-2.4300001,1.89,4.2113171],[-2.4300001,0.4324124,4.2286692],[-2.4750001,0.4387209,4.7585793],[-2.4750001,1.89,4.7413015],[-2.4750001,1.89,4.2113171],[-2.4750001,0.4324124,4.2286692],[-2.4950001,0.4584814,4.7383423],[-2.4950001,1.87,4.7215385],[-2.4950001,1.87,4.2315569],[-2.4950001,0.4526491,4.2484298],[-2.2321301,1.8335732,5.0840106],[-2.1400001,-2.2902241,5.1287899],[-1.9212852,-2.2902241,5.1287899],[-2.2321301,1.8340623,5.1290078],[-2.1400001,-2.2897351,5.1737871],[-1.9212852,-2.2897351,5.1737871],[-2.2288792,1.7676963,5.1497297],[-2.1204419,-2.2695189,5.1935692],[-1.9428494,-2.2695189,5.1935692]],"bolts":11} }} - ]} + ], + "repaired": {"how": {"corner": "the branch's builder with massing.corners' inside test at 1e-5 m in place of 1e-6: the corner float32 lost is kept", "tie": "the branch's massing.clad cutting from the other of the split facet's two equally long edges"}, "truth": { + "Hull.Quarter.R": {"solid":[[4.2910318,-2.9193861,6.8925695],[4.7526722,-3.0549133,5.7045879],[4.3936944,-1.4,7.0157642],[4.9976001,-1.4,5.506],[3.5958304,-4.3421259,6.9449539],[3.9363332,-4.6085348,5.8910241],[1.75,-4.8604336,7.409956],[1.75,-5.3931999,5.9851837],[2.5643883,-1.4,7.5279703],[1.75,-2.3254409,7.6634545],[2.5643883,-1.4,5.5060005],[1.75,-2.3254409,5.6170526]],"facets":8,"panels":[[2.6039631,-1.5075765,7.4852662],[1.8505968,-2.3636744,7.6105995],[1.8505968,-3.7839808,7.4685688],[3.7708514,-3.7307458,6.9362202],[4.181469,-2.8904121,6.9052806],[4.2749047,-1.5075765,7.0174022],[2.6160405,-1.5118898,7.5284004],[1.8626742,-2.3679876,7.6537333],[1.8626742,-3.7882941,7.5117025],[3.7829289,-3.7350593,6.9793544],[4.1935463,-2.8947253,6.9484148],[4.2869821,-1.5118899,7.0605364],[2.6295795,-1.5337148,7.543292],[1.8873084,-2.3772049,7.6667795],[1.8873082,-3.7697763,7.5275221],[3.7765129,-3.7174025,7.0037818],[4.1799693,-2.8917232,6.9733815],[4.2717276,-1.5337149,7.0834904],[1.8505965,-4.0526409,7.4417028],[1.8505965,-4.7160707,7.37536],[3.5181954,-4.2478104,6.9552579],[3.6377716,-4.0030956,6.9462481],[1.8707256,-4.0598297,7.5135922],[1.8707258,-4.7232594,7.4472499],[3.5383244,-4.2549992,7.0271478],[3.6579008,-4.0102844,7.0181379],[1.8953596,-4.0811133,7.5254316],[1.8953596,-4.6992774,7.4636159],[3.5305526,-4.2401166,7.0516772],[3.6317692,-4.0329757,7.0440507],[2.7647738,-4.5948009,7.0421376],[1.8471562,-4.8524671,7.273304],[1.8471562,-5.2996264,6.0774708],[2.8457143,-4.9412479,6.0344653],[2.7796867,-4.6345687,7.0570083],[1.862069,-4.8922348,7.2881742],[1.8620691,-5.3393941,6.0923409],[2.8606274,-4.9810157,6.049336],[2.7687323,-4.6642437,7.0491562],[1.8875668,-4.9116745,7.2711391],[1.8875669,-5.3432689,6.1169314],[2.8469315,-4.9989567,6.075614],[3.5113626,-4.385159,6.8540578],[3.0230417,-4.5222793,6.9770751],[3.0996346,-4.8501167,6.0235305],[3.7892847,-4.6026044,5.9938288],[3.5362175,-4.4514389,6.8788414],[3.0478966,-4.5885587,7.0018592],[3.1244895,-4.9163966,6.0483146],[3.8141394,-4.6688843,6.0186129],[3.5286927,-4.4801512,6.8701258],[3.0752041,-4.6074901,6.9843683],[3.1484115,-4.9208369,6.0729723],[3.7952363,-4.688694,6.0451155],[4.3817148,-1.9071758,6.8648353],[4.3201332,-2.8185694,6.7909379],[4.710516,-2.9331768,5.7863297],[4.8316121,-2.1149623,5.6881447],[4.4233174,-1.9113361,6.8814764],[4.3617358,-2.8227296,6.8075786],[4.7521186,-2.9373369,5.8029709],[4.8732147,-2.1191227,5.7047858],[4.4476438,-1.9368703,6.8683591],[4.3888788,-2.8065846,6.7978411],[4.7663054,-2.9173882,5.8265738],[4.8817496,-2.1373634,5.7329712],[4.9214897,-1.5076798,5.6152711],[4.4087076,-1.5076798,6.8972268],[4.400281,-1.6323925,6.887115],[4.8708658,-1.8497338,5.6563177],[4.9908276,-1.5146136,5.6430063],[4.478045,-1.5146136,6.924962],[4.4696183,-1.6393265,6.9148502],[4.9402032,-1.8566676,5.6840525],[4.9988408,-1.536377,5.6716146],[4.5026264,-1.5363771,6.9121504],[4.4966955,-1.6241521,6.9050336],[4.9545536,-1.8356153,5.7075229],[4.2655559,-3.0223532,6.786387],[3.6602807,-4.2610564,6.8319945],[3.9375505,-4.4779921,5.9737864],[4.6440229,-3.1334624,5.8124413],[4.3285189,-3.0520933,6.8142467],[3.723244,-4.2907968,6.8598547],[4.0005136,-4.5077324,6.001646],[4.706986,-3.1632028,5.840301],[4.34373,-3.0801873,6.8037205],[3.7548051,-4.28543,6.8480964],[4.0205779,-4.4933701,6.0254736],[4.7070746,-3.186857,5.868691]],"bolts":30}, + "Hull.Quarter.L": {"solid":[[-4.2910318,-2.9193861,6.8925695],[-4.7526722,-3.0549133,5.7045879],[-4.3936944,-1.4,7.0157642],[-4.9976001,-1.4,5.506],[-3.5958304,-4.3421259,6.9449539],[-3.9363332,-4.6085348,5.8910241],[-1.75,-4.8604336,7.409956],[-1.75,-5.3931999,5.9851837],[-2.5643883,-1.4,7.5279703],[-1.75,-2.3254409,7.6634545],[-2.5643883,-1.4,5.5060005],[-1.75,-2.3254409,5.6170526]],"facets":8,"panels":[[-1.8505965,-4.7160707,7.3753595],[-1.8505963,-4.0014849,7.4468179],[-3.6631114,-3.9512372,6.9443383],[-3.5181952,-4.2478104,6.9552579],[-1.8707256,-4.7232594,7.4472494],[-1.8707255,-4.0086741,7.5187078],[-3.6832407,-3.9584262,7.0162282],[-3.5383244,-4.2549992,7.0271473],[-1.8953596,-4.6992774,7.4636154],[-1.8953595,-4.0299578,7.5305471],[-3.6571088,-3.9811172,7.042141],[-3.5305526,-4.2401166,7.0516772],[-1.8505961,-3.7328248,7.4736838],[-1.8505962,-2.3636742,7.6105995],[-2.6039624,-1.5075763,7.4852662],[-4.2749043,-1.5075763,7.0174017],[-4.1814685,-2.8904119,6.9052796],[-3.7961907,-3.6788878,6.93431],[-1.8626735,-3.7371383,7.5168176],[-1.8626738,-2.3679876,7.6537333],[-2.61604,-1.5118898,7.5283999],[-4.2869816,-1.5118897,7.0605354],[-4.1935458,-2.8947253,6.9484134],[-3.8082683,-3.6832011,6.9774437],[-1.8873075,-3.7186203,7.5326371],[-1.8873078,-2.3772047,7.666779],[-2.6295791,-1.5337147,7.543292],[-4.2717271,-1.5337147,7.0834894],[-4.1799688,-2.8917229,6.9733806],[-3.8018522,-3.6655443,7.0018711],[-3.5113626,-4.385159,6.8540568],[-3.7892847,-4.6026049,5.9938283],[-2.8620911,-4.9353704,6.0337601],[-2.7814307,-4.5901232,7.0379415],[-3.5362175,-4.4514389,6.8788409],[-3.8141396,-4.6688843,6.0186124],[-2.8869457,-5.0016503,6.0585442],[-2.8062856,-4.6564031,7.0627251],[-3.5286927,-4.4801512,6.8701248],[-3.7952363,-4.6886945,6.0451145],[-2.9108679,-5.0060902,6.0832024],[-2.8335931,-4.6753345,7.0452342],[-2.6081707,-5.0265012,6.0446959],[-1.8471559,-5.2996264,6.0774708],[-1.8471559,-4.8524671,7.273304],[-2.5231626,-4.6626449,7.103004],[-2.6230836,-5.0662689,6.059566],[-1.8620688,-5.3393941,6.0923409],[-1.8620689,-4.8922348,7.2881746],[-2.5380757,-4.7024126,7.1178746],[-2.6093876,-5.0842099,6.0858445],[-1.8875666,-5.3432684,6.1169314],[-1.8875667,-4.9116745,7.2711396],[-2.5271213,-4.7320881,7.1100225],[-4.3919301,-1.7559885,6.8770943],[-4.4087081,-1.5076798,6.8972273],[-4.9214902,-1.5076798,5.615272],[-4.85321,-1.969032,5.6706338],[-4.4335327,-1.7601488,6.8937349],[-4.4503107,-1.5118401,6.9138684],[-4.9630928,-1.5118401,5.6319127],[-4.8948126,-1.9731923,5.6872749],[-4.4606104,-1.7449744,6.8839188],[-4.4748921,-1.5336035,6.9010572],[-4.9711065,-1.5336035,5.660521],[-4.909163,-1.95214,5.7107453],[-4.3201332,-2.8185692,6.7909379],[-4.373363,-2.0307715,6.8548145],[-4.8139558,-2.2342606,5.7024608],[-4.7105155,-2.9331768,5.7863297],[-4.3894706,-2.8255031,6.8186731],[-4.4427004,-2.0377054,6.8825493],[-4.8832932,-2.2411945,5.7301955],[-4.7798533,-2.9401107,5.814065],[-4.4166136,-2.8093579,6.8089352],[-4.4670272,-2.0632396,6.869432],[-4.8918281,-2.2594352,5.7583814],[-4.7940402,-2.920162,5.8376679],[-3.9375505,-4.4779921,5.9737859],[-3.6602805,-4.2610569,6.8319945],[-4.2655559,-3.0223532,6.7863865],[-4.6440229,-3.1334624,5.8124409],[-4.0005136,-4.5077324,6.0016456],[-3.7232437,-4.2907968,6.8598542],[-4.3285189,-3.0520935,6.8142462],[-4.706986,-3.1632028,5.8403006],[-4.0205779,-4.4933701,6.0254736],[-3.7548048,-4.28543,6.8480964],[-4.34373,-3.0801876,6.8037205],[-4.7070746,-3.1868572,5.8686905]],"bolts":30}, + "Hull.BellySide.R": {"solid":[[2.0999999,2.2,3.9000001],[2.0999999,-2.4000001,3.95],[2.45,2.0,4.0999999],[2.45,-2.2,4.1500001],[2.45,2.0,4.8499999],[2.45,-2.2,4.9000001],[2.25,2.2,5.0999999],[2.25,-2.4000001,5.1500001],[1.8,2.2,3.9000001],[1.8,-2.4000001,5.1500001]],"facets":15,"panels":[[2.4300001,0.4573603,4.2283726],[2.4300001,1.89,4.2113171],[2.4300001,1.89,4.7413015],[2.4300001,0.4636687,4.7582817],[2.5050001,0.4573603,4.2283726],[2.5050001,1.89,4.2113171],[2.5050001,1.89,4.7413015],[2.5050001,0.4636687,4.7582817],[2.5250001,0.4775969,4.2481332],[2.5250001,1.87,4.2315569],[2.5250001,1.87,4.7215385],[2.5250001,0.4834292,4.7380452],[2.4300001,-2.0900002,4.7886829],[2.4300001,-2.0900002,4.2586985],[2.4300001,0.1873795,4.2315865],[2.4300001,0.193688,4.7614961],[2.4750001,-2.0900002,4.7886829],[2.4750001,-2.0900002,4.2586985],[2.4750001,0.1873795,4.2315865],[2.4750001,0.193688,4.7614961],[2.4950001,-2.0700002,4.7684431],[2.4950001,-2.0700002,4.2784615],[2.4950001,0.167619,4.2518234],[2.4950001,0.1734514,4.7417355],[2.2321301,1.8335732,5.0840106],[1.9212853,-2.2902241,5.1287899],[2.1400001,-2.2902241,5.1287899],[2.2321301,1.8343884,5.1590061],[1.9212853,-2.2894089,5.2037854],[2.1400001,-2.2894089,5.2037854],[2.2288792,1.7680224,5.179728],[1.9428494,-2.2691927,5.223567],[2.1204419,-2.2691927,5.223567]],"bolts":11} + }}} diff --git a/surfaces/blender/tests/test_plate.py b/surfaces/blender/tests/test_plate.py index 890da4b..4c05d49 100644 --- a/surfaces/blender/tests/test_plate.py +++ b/surfaces/blender/tests/test_plate.py @@ -4,12 +4,13 @@ tracks' own builders (fixtures/plates_*.json: each a table and the truth its bra Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) The truth is float32 (mathutils and Blender meshes) and plate.py is float64; KNOWN lists every fixture plate where -that, a corner the branch's builder lost, or a tie Blender's mesh order decided keeps the two apart, with what is -asserted of it instead. +that, a corner the branch's builder lost, or a tie Blender's mesh order decided keeps the two apart, with what it +is held to instead. """ from __future__ import annotations import copy +import hashlib import importlib import inspect import json @@ -65,6 +66,29 @@ def apart(a, b): return float(max(d.min(axis=1).max(), d.min(axis=0).max())) +def fixture(mech): + return json.loads((FIXTURES / f"plates_{mech}.json").read_text(encoding="utf-8")) + + +def across(mesh): + """A mesh mirrored across x = 0, each face wound the other way from where it started.""" + return mesh[0] * (-1, 1, 1), [face[:1] + face[:0:-1] for face in mesh[1]] + + +def rings(panels): + """Every panel's three rings (under the facet, under the rim, the rim), each flat in its own plane as (n, 2).""" + V, faces = panels + at = 0 + while at < len(faces): + n = len(faces[at]) + cap = V[faces[at + 1]] + normal = np.cross(cap - cap.mean(axis=0), np.roll(cap, -1, axis=0) - cap.mean(axis=0)).sum(axis=0) + x, y = plate._stand(normal / np.linalg.norm(normal)) + low = min(faces[at]) + yield [np.column_stack((V[low + k * n:low + (k + 1) * n] @ x, V[low + k * n:low + (k + 1) * n] @ y)) for k in range(3)] + at += 2 + 2 * n + + @unittest.skipIf(np is None, "numpy is not installed") class CheckTests(unittest.TestCase): def refused(self, document, path): @@ -318,6 +342,29 @@ class CladTests(unittest.TestCase): self.assertEqual(pair[1]["panels"][0].tobytes(), ten["panels"][0].tobytes()) self.assertNotEqual(pair[1]["panels"][0].tobytes(), plate.build(doc(row(clad=dict(CLAD, facets="all", seed=9))), -1)[0]["panels"][0].tobytes()) + def test_a_two_sided_row_with_one_seed_is_a_mirrored_pair(self): + cube = row(sides="both", clad=dict(CLAD, facets="all")) # every facet ties with another, every edge with three + skew = [[x + s, y, z] for x, y, s in ((1, 0, 0), (3, 0, 0), (4, 1, 0), (2, 1, 0)) for z in (0, 1)] # its top's two longest edges tie + for case in (cube, row(points=skew, sides="both", clad=dict(CLAD, facets="all"))): + right, left = plate.build(doc(case)) + self.assertGreater(right["report"]["panels"], 6) # facets were split: the cuts are mirrored too + self.assertEqual(left["report"], right["report"]) + for key in ("solid", "panels", "bolts"): + self.assertTrue(np.array_equal(across(right[key])[0], left[key][0])) + self.assertEqual(across(right[key])[1], left[key][1]) + self.assertAlmostEqual(volume(left["panels"]), volume(right["panels"]), places=12) + for a, b in zip(right["facets"], left["facets"]): + self.assertTrue(np.array_equal(a["normal"] * (-1, 1, 1), b["normal"]) and np.array_equal(a["centre"] * (-1, 1, 1), b["centre"]) and a["area"] == b["area"]) + back = plate.build(doc(case), -1) + self.assertEqual([e["name"] for e in back], ["p.L", "p.R"]) + self.assertEqual(back[0]["panels"][0].tobytes(), left["panels"][0].tobytes()) + self.assertEqual(back[1]["panels"][0].tobytes(), right["panels"][0].tobytes()) + + def test_a_pair_of_seeds_draws_each_side_on_its_own_solid(self): + pair = plate.build(doc(row(sides="both", clad=dict(CLAD, facets="all", seed=[5, 5])))) + self.assertGreater(apart(across(pair[0]["panels"])[0], pair[1]["panels"][0]), 0.1) + self.assertEqual(pair[1]["panels"][0].tobytes(), plate.build(doc(row(clad=dict(CLAD, facets="all"))), -1)[0]["panels"][0].tobytes()) + def test_a_split_facet_takes_two_panels_and_a_whole_one_a_panel(self): made = plate.build(doc(row(clad=dict(CLAD, facets=[{"n": [0, 0, 1], "cos": 0.9}], split=2.2))))[0] self.assertEqual(made["report"], {"corners": 8, "facets": 6, "panels": 2, "bolts": 8}) @@ -414,51 +461,84 @@ class DeterminismTests(unittest.TestCase): plate.build(table) self.assertEqual(table, kept) + def test_the_fixtures_build_to_one_hash_on_every_platform(self): + made = hashlib.sha256() + for mech in ("bastion", "paladin", "raptor"): + for case in fixture(mech)["cases"]: + for entry in plate.build(fixture(mech)["table"], case["side"]): + made.update(entry["name"].encode()) + for key in ("solid", "panels", "bolts"): + made.update(np.round(entry[key][0] / QUANTUM).astype(" 0.5; the cut's share (0.36, 0.64) -> (0.3, 0.7); the lift-order coin - removed; a slab's gap ignored (raptor). The outer test 0.97 -> 0.9 is CladTests' (no fixture facet stands - between the two).""" + removed; a slab's gap ignored (raptor); the clad of Hull.Quarter left out; Hull.BellySide.R's panels moved + 0.5 m. The outer test 0.97 -> 0.9 is CladTests' (no fixture facet stands between the two).""" + + def held(self, made, truth, solid, panels): + self.assertEqual(made["report"]["facets"], truth["facets"]) + self.assertEqual(made["report"]["bolts"], truth["bolts"]) + self.assertEqual(len(made["panels"][0]), len(truth["panels"])) + self.assertEqual(len(made["solid"][0]), len(truth["solid"])) + self.assertLessEqual(apart(made["solid"][0], truth["solid"]), solid) + self.assertLessEqual(apart(made["panels"][0], truth["panels"]), panels) def parity(self, mech, plates): - fixture = json.loads((FIXTURES / f"plates_{mech}.json").read_text(encoding="utf-8")) + table, cases, repaired = fixture(mech)["table"], fixture(mech)["cases"], fixture(mech).get("repaired", {"truth": {}})["truth"] seen = 0 - for case in fixture["cases"]: - built = {e["name"]: e for e in plate.build(fixture["table"], case["side"])} + self.assertEqual(set(repaired), {name for (m, name), kind in KNOWN.items() if m == mech and kind != "float32"}) + for case in cases: + built = {e["name"]: e for e in plate.build(table, case["side"])} for name, truth in case["truth"].items(): made, known = built[name], KNOWN.get((mech, name)) seen += 1 with self.subTest(plate=name, side=case["side"]): - solid, panels = apart(made["solid"][0], truth["solid"]), apart(made["panels"][0], truth["panels"]) if known == "corner": V, T = made["solid"][0], np.array(truth["solid"]) d = np.linalg.norm(V[:, None, :] - T[None, :, :], axis=2) self.assertLess(float(d.min(axis=0).max()), FLOAT32[0]) # every corner of the branch's is one of these self.assertEqual(int((d.min(axis=1) > 1e-3).sum()), 1) # and one more, which the faces do bound - continue - self.assertEqual(made["report"]["facets"], truth["facets"]) - self.assertEqual(made["report"]["bolts"], truth["bolts"]) - self.assertEqual(len(made["panels"][0]), len(truth["panels"])) - self.assertLessEqual(solid, FLOAT32[0] if known == "float32" else SOLID) - if known == "tie": - self.assertGreater(panels, 0.1) + self.held(made, repaired[name], *FLOAT32) + elif known == "tie": + self.assertGreater(apart(made["panels"][0], truth["panels"]), 0.1) # the branch cut from the other edge + self.held(made, dict(truth, panels=repaired[name]["panels"]), *FLOAT32) + self.assertEqual({key: repaired[name][key] for key in ("solid", "facets", "bolts")}, {key: truth[key] for key in ("solid", "facets", "bolts")}) else: - self.assertLessEqual(panels, FLOAT32[1] if known == "float32" else PANELS) + self.held(made, truth, *(FLOAT32 if known == "float32" else (SOLID, PANELS))) self.assertEqual(seen, plates) def test_bastion(self): @@ -471,7 +551,7 @@ class ParityTests(unittest.TestCase): self.parity("raptor", 50) def test_the_lost_corner_is_a_corner(self): - table = plate.check(json.loads((FIXTURES / "plates_bastion.json").read_text(encoding="utf-8"))["table"]) + table = plate.check(fixture("bastion")["table"]) quarter = next(r for r in table["plates"] if r["name"] == "Hull.Quarter") points, _ = plate._row_points(quarter, "plates") planes = [(np.array(f["normal"]) / np.linalg.norm(f["normal"]), np.array(f["at"])) for f in quarter["faces"]] @@ -479,6 +559,15 @@ class ParityTests(unittest.TestCase): self.assertTrue((slack < 1e-9).all()) # every corner is inside every face self.assertTrue(((np.abs(slack) < 1e-9).sum(axis=1) >= 3).all()) # and on three of them + def test_the_panels_whose_outline_crosses_itself(self): + crossed = set() + for mech in ("bastion", "paladin", "raptor"): + for case in fixture(mech)["cases"]: + for entry in plate.build(fixture(mech)["table"], case["side"]): + if entry["name"] in case["truth"]: + crossed |= {(mech, case["side"], entry["name"], k) for k, three in enumerate(rings(entry["panels"])) if any(plate._crosses(ring) for ring in three)} + self.assertEqual(crossed, CROSSED) + if __name__ == "__main__": unittest.main() From 0c0193a171832ef568887bee5da90151c5eae23b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 15:57:10 +0100 Subject: [PATCH 211/223] brokkr_kitbash: the one-driver rule judges the write, not the scene: only the loops a write touches are read A write touches a loop when a part it writes is the closing follower, the part closed on or the driver, or one of those hangs from it. A loop that already has a second driver refuses those writes and no others, so a camera, an empty or a part of another mechanism is posed, resized and given a parent in a scene that holds one (finding parent-hook-gates-on-scene-not-change). Every asker shares the rule: write_checks, detach, set_params and brokkr_parent_refusal. An untouched loop costs three stored pointers and a walk up its parents. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 34 ++++++++--- .../blender/tests/live/kitbash_follows.py | 58 +++++++++++++++++-- .../tests/live/kitbash_follows.result.json | 39 ++++++++++++- surfaces/blender/tests/test_kitbash.py | 2 +- 4 files changed, 115 insertions(+), 18 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 1d04944..6b16ba1 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -443,10 +443,13 @@ def followers(driver) -> list: def one_driver(stating: dict) -> None: - """The one-driver rule, over every loop in the scene as it would stand after a write: the driver of a loop is - the only input its two ends (the parent follower's parent, and the part closed on) depend on. `stating` is + """The one-driver rule, over each loop a write touches, as it would stand after the write: the driver of a loop + is the only input its two ends (the parent follower's parent, and the part closed on) depend on. `stating` is {part: (its parent, its connection's DOF kind, its joint record)} for each connection about to be written, and - (None, None, None) for one about to be cleared; every other part is read from the scene. Each revolute or + (None, None, None) for one about to be cleared; every other part is read from the scene. A write touches a loop + when a part in `stating` is the closing follower, the part closed on or the driver, or one of those hangs from + it: nothing else can change what the loop's ends depend on, so no other loop is read, and a loop that already + has a second driver refuses the writes that touch it and no others. Each revolute or prismatic joint between an end and the nearest part both ends hang from (or the root, when they share none) is the driver, follows it, or is held by limits of one value: a pin with no travel, which is what a real torque link's lug is, there to stop the rod rolling in its barrel. A joint there that follows another driver, or that @@ -456,9 +459,9 @@ def one_driver(stating: dict) -> None: read again by the attach that gives the driver a connection. write_checks (every write of a connection, and set_params before it rebuilds a mesh), detach and parent_refusal (Brokkr's setObjectParent) ask here before they write, so no action (attach, detach, clearing a follower, limits widened or cleared, any pose, a - new follow, set_params, a new parent) leaves a loop with two drivers, and a scene edited by hand into one is - refused its next write.""" - known, kits = {}, {} # each part's joint and each kit file are read once + new follow, set_params, a new parent) gives a loop a second driver, and a loop edited by hand into one is + refused the next write that touches it.""" + known, kits, hangs = {}, {}, {} # each part's joint and each kit file are read once; hangs: {part: whether it, or a part it hangs from, is in stating} def parent(o): return stating[o][0] if o in stating else o.parent @@ -472,7 +475,19 @@ def one_driver(stating: dict) -> None: known[o] = (kind, record["limits"], record["follows"]) if kind is not None else (None, None, None) return known[o] - for closing in sorted((o for o in bpy.data.objects if CLOSE in o and o.users_collection and (FOLLOWS in o or o in stating)), key=lambda o: o.name): + def touched(o) -> bool: + """Whether a part, or one it hangs from, is in `stating`: each part is walked once a call.""" + walked = [] + while isinstance(o, bpy.types.Object) and o not in hangs and o not in stating: + walked.append(o) + o = parent(o) + answer = isinstance(o, bpy.types.Object) and (o in stating or hangs[o]) + hangs.update(dict.fromkeys(walked, answer)) + return answer + + for closing in sorted((o for o in bpy.data.objects if CLOSE in o and (FOLLOWS in o or o in stating)), key=lambda o: o.name): + if not (touched(closing) or touched(closing.get(CLOSE_TO)) or touched(closing.get(FOLLOWS_DRIVER))) or not closing.users_collection: + continue # this write changes nothing the loop's ends depend on (the pointers are read as stored: users_collection searches the scene, so it is asked of a touched loop alone) follows, upper, to = joint(closing)[2], parent(closing), closure(closing)[1] driver = follows["driver"] if follows is not None and follows["kind"] == "loop" else None if driver is None or to is None or upper is None or parent(upper) is None or joint(driver)[0] is None or joint(upper)[2] != follows: @@ -500,7 +515,8 @@ def one_driver(stating: dict) -> None: def brokkr_parent_refusal(obj, parent) -> str | None: """Why an object may not be given `parent` (None clears it), or None when it may: the one-driver rule over the - scene as it would stand, the object's stated connection read on its new parent. Brokkr's setObjectParent asks + loops the object is part of or stands above (one_driver), as they would stand, the object's stated connection + read on its new parent. An object no loop hangs from is given any parent, whatever else the scene holds. Brokkr's setObjectParent asks every enabled add-on that defines this name before it writes a parent, so a new parent that would give a stated loop a second driver is refused there and then. Nothing else is asked: a parent that only leaves a connection not holding is drift, and reports show it.""" @@ -1015,7 +1031,7 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): """Change params of a placed kit part and rebuild its mesh in place: its modifiers and material slots stay, each shape keeps its faces' material, the Bevel width follows, and its connection and those of the parts attached to it are seated again on the moved sockets, through write_connections (a value outside its joint's - limits or a stray slide, written by hand, and a scene that holds a loop with a second driver, are refused + limits or a stray slide, written by hand, and a write that touches a loop with a second driver, are refused before anything changes); a closure is never seated and a follower never derived again, only reported""" bl_idname = "brokkr_kitbash.set_params" diff --git a/surfaces/blender/tests/live/kitbash_follows.py b/surfaces/blender/tests/live/kitbash_follows.py index 7d04ea1..a574528 100644 --- a/surfaces/blender/tests/live/kitbash_follows.py +++ b/surfaces/blender/tests/live/kitbash_follows.py @@ -18,7 +18,7 @@ barrel, so a lug with no travel is the mechanism and not a way around the kit; a two arms from the barrel's pin cannot face the rod's own); a second crank (Crank2 on the root Ground2) whose ram closes on the rocker, and a loop hung from its own driver (K3, B3, Rk3, Cp3 on the root G3), for the one-driver refusals at the statement, and after it an attach, a clear, widened limits, a pose over limits written by hand and a -detach that would each give a stated loop a second driver; Idle and Tip for the refusals; a tree of 264 struts with 62-character names for a joints +detach that would each give a stated loop a second driver; Idle and Tip for the refusals and for the writes a two-driver loop does not refuse; a tree of 264 struts with 62-character names for a joints report over several receipts. Bounds follow lodur:ruling:deterministic-bound-margin, both readings beside each; the result file carries the readings. """ @@ -472,12 +472,58 @@ try: refused("a pose of the driver after the lug's limits were widened by hand: the writer reads the rule before it writes", "brokkr_kitbash.slide", {"object_name": "T_Rod", "slide": 0.1}, "depend on more than one driver: 'T_Rod' and 'T_Lug' (it follows nothing and its joint has travel") refused("and a pose of the lug itself", "brokkr_kitbash.roll", {"object_name": "T_Lug", "roll": 95.0}, "depend on more than one driver: 'T_Rod' and 'T_Lug'") - shape = lambda: {name: np.array([v.co[:] for v in bpy.data.objects[name].data.vertices]).tobytes() for name in ("Idle", "Tip")} # noqa: E731 - was, tip_was = shape(), connection("Tip") - refused("set_params of an unrelated part in a scene that holds a second driver (finding set-params-writes-before-the-guard): the rule is read before the mesh is rebuilt", - "brokkr_kitbash.set_params", {"object_name": "Idle", "params": "length=0.6"}, + # the rule judges the write, not the scene: with the torque link holding a second driver, a write is refused when it touches that loop (a part of it, + # or one it hangs from) or would give another loop a second driver, and every other write is made (finding parent-hook-gates-on-scene-not-change) + shape = lambda *names: {name: np.array([v.co[:] for v in bpy.data.objects[name].data.vertices]).tobytes() for name in names} # noqa: E731 + was = shape("T_Lug", "T_Lower") + refused("set_params of the part a two-driver loop closes on (finding set-params-writes-before-the-guard): the rule is read before the mesh is rebuilt", + "brokkr_kitbash.set_params", {"object_name": "T_Lug", "params": "length=0.31"}, "the two ends of the loop 'T_Lower' closes, 'T_Barrel' (the base) and 'T_Lug' (closed on), depend on more than one driver: 'T_Rod' and 'T_Lug' (it follows nothing and its joint has travel", "nothing changed") - check("and nothing moved: the part's vertices and its child's connection read as before the refusal", shape() == was and connection("Tip") == tip_was and tip_was["holds"] is True, [tip_was, connection("Tip")]) + check("and nothing moved: the part's vertices read as before the refusal", shape("T_Lug", "T_Lower") == was) + refused("setObjectParent of the root a two-driver loop hangs from: the write touches the loop", "setObjectParent", {"targetObjectName": "T_Barrel", "parentObjectName": "Loose"}, + "the two ends of the loop 'T_Lower' closes, 'T_Barrel' (the base) and 'T_Lug' (closed on), depend on more than one driver: 'T_Rod' and 'T_Lug'", "nothing changed") + refused("setObjectParent that gives another loop a second driver, in a scene that already holds one: the four-bar's base under Idle", "setObjectParent", + {"targetObjectName": "Base", "parentObjectName": "Idle"}, + "the two ends of the loop 'A_Rod' closes, 'Pad' (the base) and 'Rocker' (closed on), depend on more than one driver: 'Crank' and 'Idle' (it follows nothing and its joint has travel", "nothing changed") + idle, tip_was = bpy.data.objects["Idle"], connection("Tip") + length, was = json.loads(idle["kit_params"])["length"], shape("Idle") + receipt, _ = send("brokkr_kitbash.set_params", object_name="Idle", params="length=0.6") + grown = receipt["status"] == "accepted" and shape("Idle") != was and connection("Tip")["holds"] is True + receipt2, _ = send("brokkr_kitbash.set_params", object_name="Idle", params=f"length={length!r}") + check("set_params of a part no loop hangs from is written in a scene that holds a second driver, and set back", + grown and receipt2["status"] == "accepted" and shape("Idle") == was and connection("Tip") == tip_was and tip_was["holds"] is True, [receipt["message"], receipt2["message"], tip_was, connection("Tip")]) + rolled = idle["kit_roll"] + receipt, _ = send("brokkr_kitbash.roll", object_name="Idle", roll=rolled + 5.0) + receipt2, _ = send("brokkr_kitbash.roll", object_name="Idle", roll=rolled) + check("a pose of a joint no loop hangs from is written in a scene that holds a second driver", receipt["status"] == "accepted" and receipt2["status"] == "accepted", [receipt["message"], receipt2["message"]]) + plain, cam = bpy.data.objects.new("PlainEmpty", None), bpy.data.objects.new("Cam", bpy.data.cameras.new("Cam")) # Soul's probe P2a, P2b: neither is a kit part + for made in (plain, cam): + bpy.context.scene.collection.objects.link(made) + asked = [] + for name, parent in (("Cam", "PlainEmpty"), ("PlainEmpty", "Ground"), ("PlainEmpty", "T_Lug"), ("Cam", "")): + receipt, _ = send("setObjectParent", targetObjectName=name, parentObjectName=parent) + asked.append((receipt["status"], bpy.data.objects[name].parent and bpy.data.objects[name].parent.name, str(receipt["message"])[:200])) + check("setObjectParent of a camera under an empty, of the empty under a kit part and under a part of the two-driver loop itself, and clearing the camera's, " + "are written in a scene that holds a second driver: nothing of a loop hangs from them", + [row[:2] for row in asked] == [("accepted", "PlainEmpty"), ("accepted", "Ground"), ("accepted", "T_Lug"), ("accepted", None)], asked) + receipt, _ = send("setObjectParent", targetObjectName="T_Barrel", parentObjectName="Cam") + check("and the loop's root under that camera is refused: the camera is no kit part, the root is what the loop hangs from", + receipt["status"] != "accepted" and "depend on more than one driver: 'T_Rod' and 'T_Lug'" in str(receipt["message"]) and t_barrel.parent is None, [receipt["status"], receipt["message"]]) + for made in (cam, plain): + bpy.data.objects.remove(made) + # a loop whose driver neither end hangs from, stated by hand on Loose and closing on Tip, whose two free pins are second drivers: a write of the + # driver that poses nothing (its followers are not written) still touches the loop + place("H_Upper", "strut", W), place("H_Lower", "strut", W) + attach("H_Upper", "end_a", "Loose", "end_a", 30.0), attach("H_Lower", "end_a", "H_Upper", "end_b", 40.0) + h_upper, h_lower = bpy.data.objects["H_Upper"], bpy.data.objects["H_Lower"] + h_lower["kit_close_socket"], h_lower["kit_close_to"], h_lower["kit_close_to_socket"] = "end_b", bpy.data.objects["Tip"], "end_b" + for made in (h_upper, h_lower): + made["kit_follows"], made["kit_follows_driver"] = '{"kind": "loop"}', crank + refused("set_params of the driver of a two-driver loop that neither end hangs from: the write touches the loop", "brokkr_kitbash.set_params", + {"object_name": "Crank", "params": f"length={json.loads(crank['kit_params'])['length']!r}"}, + "the two ends of the loop 'H_Lower' closes, 'Loose' (the base) and 'Tip' (closed on), depend on more than one driver: 'Crank' and 'Idle' (it follows nothing and its joint has travel", "nothing changed") + for made in (h_lower, h_upper): + bpy.data.objects.remove(made) t_lug["kit_min"], t_lug["kit_max"] = 90.0, 90.0 receipt, report = send("brokkr_kitbash.slide", object_name="T_Rod", slide=0.11) check("with the lug held again the driver is posed", receipt["status"] == "accepted" and report["closures"][0]["holds"] is True, receipt["message"]) diff --git a/surfaces/blender/tests/live/kitbash_follows.result.json b/surfaces/blender/tests/live/kitbash_follows.result.json index 7ffc432..6b6bdea 100644 --- a/surfaces/blender/tests/live/kitbash_follows.result.json +++ b/surfaces/blender/tests/live/kitbash_follows.result.json @@ -322,12 +322,47 @@ "detail": null }, { - "name": "refused, scene unchanged: set_params of an unrelated part in a scene that holds a second driver (finding set-params-writes-before-the-guard): the rule is read before the mesh is rebuilt", + "name": "refused, scene unchanged: set_params of the part a two-driver loop closes on (finding set-params-writes-before-the-guard): the rule is read before the mesh is rebuilt", "ok": true, "detail": null }, { - "name": "and nothing moved: the part's vertices and its child's connection read as before the refusal", + "name": "and nothing moved: the part's vertices read as before the refusal", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: setObjectParent of the root a two-driver loop hangs from: the write touches the loop", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: setObjectParent that gives another loop a second driver, in a scene that already holds one: the four-bar's base under Idle", + "ok": true, + "detail": null + }, + { + "name": "set_params of a part no loop hangs from is written in a scene that holds a second driver, and set back", + "ok": true, + "detail": null + }, + { + "name": "a pose of a joint no loop hangs from is written in a scene that holds a second driver", + "ok": true, + "detail": null + }, + { + "name": "setObjectParent of a camera under an empty, of the empty under a kit part and under a part of the two-driver loop itself, and clearing the camera's, are written in a scene that holds a second driver: nothing of a loop hangs from them", + "ok": true, + "detail": null + }, + { + "name": "and the loop's root under that camera is refused: the camera is no kit part, the root is what the loop hangs from", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params of the driver of a two-driver loop that neither end hangs from: the write touches the loop", "ok": true, "detail": null }, diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 02aa454..b73e2f2 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -2533,7 +2533,7 @@ class OwnershipTests(unittest.TestCase): self.assertIsNone(re.search(r"seat\(seated|driver_add\(|constraints\.new\(", source)) self.assertEqual(source.count("seat("), 5) # its def, write_connections, and a cutter's, a ribs' and a hose's own frames body = source.split("class BROKKR_KITBASH_OT_set_params(")[1].split("class BROKKR_KITBASH_OT_")[0] - self.assertLess(body.index("write_checks(entries)"), body.index("clear_geometry()")) # the writer's own checks, the one-driver rule with them (live: 'set_params of an unrelated part in a scene that holds a second driver') + self.assertLess(body.index("write_checks(entries)"), body.index("clear_geometry()")) # the writer's own checks, the one-driver rule with them (live: 'set_params of the part a two-driver loop closes on') self.assertLess(body.index("write_checks(entries)"), body.index("obj[PARAMS] =")) self.assertLess(body.index("clear_geometry()"), body.index("write_connections(entries)")) self.assertEqual(source.count("core.close_loop("), 1) From f91df3253e2a1d773797a445f3fddafa81e44ee6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 15:57:10 +0100 Subject: [PATCH 212/223] docs/kitbash.md, install.md, setObjectParent's row: which writes a two-driver loop refuses; the rig generator will read held rows Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_bridge/actions.json | 2 +- surfaces/blender/docs/install.md | 3 +- surfaces/blender/docs/kitbash.md | 35 ++++++++++++--------- 3 files changed, 24 insertions(+), 16 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/actions.json b/surfaces/blender/brokkr_bridge/actions.json index 3f6a8b9..441d6bd 100644 --- a/surfaces/blender/brokkr_bridge/actions.json +++ b/surfaces/blender/brokkr_bridge/actions.json @@ -29,7 +29,7 @@ {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, {"name": "visible", "type": "boolean", "default": true} ]}, - {"name": "setObjectParent", "doc": "Parent an object to another.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "setObjectParent", "doc": "Parent an object to another. Refused, with nothing changed, when an enabled add-on that defines brokkr_parent_refusal(object, parent) answers a reason, which is the message: brokkr_kitbash refuses a parent that would give a loop that follows a second driver, and any parent of a part such a loop hangs from while the loop already has one (both drivers are named; hold the joint, make it follow the driver, or clear the loop first). An object no loop hangs from is not refused.", "changesScene": true, "editModeSafe": false, "fields": [ {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, {"name": "parentObjectName", "type": "string", "doc": "empty or absent clears the parent"} ]}, diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index c6c67fa..b7d26e6 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -184,7 +184,8 @@ Behaviour the table does not say, per action: only to their own `objectType`. - `setObjectParent`: an empty or absent `parentObjectName` clears the parent. Before it writes, each enabled add-on that defines `brokkr_parent_refusal(object, parent)` is asked, and a reason it answers refuses the - intent with nothing changed (`brokkr_kitbash` answers its one-driver rule, `docs/kitbash.md`). + intent with nothing changed (`brokkr_kitbash` answers its one-driver rule over the loops the object is part + of or stands above, `docs/kitbash.md`; an object no loop hangs from is never refused by it). - `importGltf`: `filepath`, `.gltf` or `.glb`, relative to the add-on preference `Import Directory` (absolute paths, `..` and symlinks that resolve outside it are refused). Empty `Import Directory` disables the action. Needs Blender's glTF add-on. diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 33dfb1f..fe94903 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -222,14 +222,16 @@ and the part closed on) moves with the driver: it is the driver, follows it, or driver is the only input the two ends depend on: every revolute or prismatic joint between an end and the part the two ends share (or the root, when they share none) is the driver, follows it, or is held by limits of one value. A joint there that follows another driver, or that follows nothing and has travel, is a second driver: a pose of it -would open the loop, and nothing here solves a loop for two drivers. The rule is read over every loop in the scene -before each write, as the scene would stand after it (`one_driver`, asked by the one writer of connections, by -`set_params` before it rebuilds a mesh, by `detach` and by Brokkr's `setObjectParent`), so it holds after the loop -is stated as it does when `follow` states it. Each of these is refused with +would open the loop, and nothing here solves a loop for two drivers. The rule is read before each write, over +each loop the write touches, as the scene would stand after it (`one_driver`, asked by the one writer of +connections, by `set_params` before it rebuilds a mesh, by `detach` and by Brokkr's `setObjectParent`), so it holds +after the loop is stated as it does when `follow` states it. A write touches a loop when a part it writes is the +closing follower, the part closed on or the driver, or one of those hangs from it; no other write can change what +the loop's ends depend on, and no other loop is read. Each of these is refused with nothing changed, naming the loop's driver and each other one: `attach` of an end's root on a pin or a slide, `detach` of a part between an end and the part both ends hang from, `follow` with null on a follower between the ends, `joint` widening or clearing limits that held a pin there, `setObjectParent` giving or clearing a parent -between the ends, and any pose or `set_params` once such a joint was written by hand. To change a mechanism between a loop's ends, give the new joint its one driver or its one value first, or +between the ends, and any write that touches the loop once such a joint was written by hand. To change a mechanism between a loop's ends, give the new joint its one driver or its one value first, or clear the loop and state it again. A loop whose driver is detached is derived by nothing and is not read; the attach that gives the driver a connection again reads it. A torque link is the case for limits of one value: a real torque link exists to stop the rod rolling in its barrel, so its lug has no travel, and a strut pinned to @@ -259,10 +261,12 @@ limits first. One whose limits reach that far is refused by the bound above befo What followers give up: a loop of three or more unknowns, or one out of a plane, is not solved (follow-up `kit-follows-wider-loops`); a follower does not drive another; `set_params` never derives a follower again, so a -loop it opens reads `holds: false` until its driver is posed; and a scene that holds a loop -with a second driver (a limit widened by hand, a parent set in Blender's own interface, a saved file) is refused -every write of a connection, a `set_params` and a `setObjectParent`, related to the loop or not, until the joint -is held again, follows the driver, or the loop is cleared. A connection's row in a report carries `follows: {driver, kind, k, offset, holds, reason}`: +loop it opens reads `holds: false` until its driver is posed; and a loop +with a second driver (a limit widened by hand, a parent set in Blender's own interface, a saved file) refuses +every write that touches it (a write of a connection, a `set_params` or a `setObjectParent` of one of its parts +or of a part it hangs from, whether or not that write is the fault) until the joint is held again, follows the +driver, or the loop is cleared. A write that touches no such loop is made: a camera, an empty or a part of +another mechanism is posed and given a parent as before, and so is an object parented under a part of the loop. A connection's row in a report carries `follows: {driver, kind, k, offset, holds, reason}`: `holds` is false, with a reason, when the value stands off the ratio, the loop's closure does not hold, or the driver is gone or states no revolute or prismatic connection. Detaching a driver leaves its followers' statements; detaching a loop follower clears its partner's. No Blender driver or constraint is made: a follower's @@ -300,10 +304,12 @@ null, so a report of a sub-tree carries the joint the sub-tree hangs by. `parent the object the part hangs from: rigid connections fold into it and are counted in `rigid`. `axis` and `origin` are the parent socket's z and origin in the root object's frame. `min` and `max` are the limits less the value, the travel either way from the pose the report was taken at, which is the shape of Aetheria's `ShipJoint` (`Min` and `Max` about rest). `held` is true when the limits are of -one value: the joint has no travel (a torque link's lug held at `[90, 90]`), its `min` and `max` are 0, and a rig -makes a fixed bone for it and not a degree of freedom; a held row is in neither `unlimited` nor `rigid`. `driven` is null, or what the row follows -(`by` the driver's id, `kind`, `k`, `offset`): a driven row's value is derived, so a rig makes a driven bone for it -and not a degree of freedom. `unlimited` lists the ids of the rows this report carries that are not driven and +one value: the joint has no travel (a torque link's lug held at `[90, 90]`), its `min` and `max` are 0, and the +rig generator will make a fixed bone for it and not a degree of freedom (nothing reads joints rows yet: +`brokkr_rig` reads meshes); a held row is in neither `unlimited` nor `rigid`. `held` is computed from the limits +alone and is not the free `mechanism` label: a joint labelled `"held"` that has travel reads `held: false`. `driven` is null, or what the row follows +(`by` the driver's id, `kind`, `k`, `offset`): a driven row's value is derived, so the rig generator will make a +driven bone for it and not a degree of freedom. `unlimited` lists the ids of the rows this report carries that are not driven and state no limits, so an exporter that needs limits on every degree of freedom refuses by reading one field of each report. A tree whose rows a receipt cannot carry (about 60 rows, 33 with names of 62 characters) is read in pages: `jointsOmitted` counts the rows left off, `next` is then the id of the last row carried, and a call with `after` @@ -428,7 +434,8 @@ that breaks one (a `pipe_r` that no longer matches the flange it is bolted to) i connection. **Drift.** `setObjectTransform` and `setObjectParent` are Brokkr's own rows and can move or re-parent an attached -child; `setObjectParent` refuses only a parent that would give a stated loop a second driver ("Followers"). +child; `setObjectParent` refuses only a parent that would give a stated loop a second driver, or the parent of a +part a loop that already has one hangs from ("Followers"). Reports show it: a part's `connection` is `null`, or ```json From 40232be7874300dfe1f76bd3c22db926e3f7dcba Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 16:03:25 +0100 Subject: [PATCH 213/223] brokkr_kitbash.plate: clad carries bolt_mat and bevel (cut hard-plate-action) check writes the defaults in (gunmetal, 0.012) and bounds them; build draws nothing from either. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/plate.py | 4 +++- surfaces/blender/docs/kitbash.md | 2 ++ surfaces/blender/tests/test_plate.py | 16 ++++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/brokkr_kitbash/plate.py b/surfaces/blender/brokkr_kitbash/plate.py index 5417cad..8e8766f 100644 --- a/surfaces/blender/brokkr_kitbash/plate.py +++ b/surfaces/blender/brokkr_kitbash/plate.py @@ -170,7 +170,7 @@ def _check_slab(slab: Any, path: str) -> dict: def _check_clad(clad: Any, row: dict, path: str) -> dict: - _object(clad, path, ("mat", "min_area", "lifts", "inset", "gap", "split", "seed"), ("facets", "floor", "bolt_r")) + _object(clad, path, ("mat", "min_area", "lifts", "inset", "gap", "split", "seed"), ("facets", "floor", "bolt_r", "bolt_mat", "bevel")) out = {"mat": _name(clad["mat"], f"{path}.mat", 63, None)} facets = clad.get("facets", "outer" if "slab" in row else None) if facets is None: @@ -217,6 +217,8 @@ def _check_clad(clad: Any, row: dict, path: str) -> dict: raise PlateError(f"{path}.seed: wants an integer or [right, left]") out["seed"] = seed out["bolt_r"] = _number(clad.get("bolt_r", BOLT), f"{path}.bolt_r", 0.001, 1.0) + out["bolt_mat"] = _name(clad.get("bolt_mat", "gunmetal"), f"{path}.bolt_mat", 63, None) # carried, as row bevel is: build draws nothing from these two + out["bevel"] = _number(clad.get("bevel", 0.012), f"{path}.bevel", 0.0, 0.05) return out diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index ae8eb2e..63de66e 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -937,6 +937,8 @@ first. | `split` | a facet over this area is cut in two | | `seed` | an integer, or `[right, left]` on a row with `sides: "both"`. There is no default. One integer on a two-sided row makes a mirrored pair; a pair of seeds draws each side on its own solid, also where the two are equal. | | `bolt_r` | a bolt's corner radius (default 0.028) | +| `bolt_mat` | the bolts' material, 1 to 63 characters (default `gunmetal`). Carried: `build` draws nothing from it; `brokkr_kitbash.plates` reads it | +| `bevel` | the width of the panels' Bevel, 0 to 0.05 (default 0.012). Carried, as the row's `bevel` is | One `random.Random(seed)` draws, in facet order. A chosen facet over `split` is cut across its longest edge at a share drawn from 0.36 to 0.64 of that edge, the two parts `gap` apart; edges within 1e-9 m of the longest tie and diff --git a/surfaces/blender/tests/test_plate.py b/surfaces/blender/tests/test_plate.py index 4c05d49..ad6c9ca 100644 --- a/surfaces/blender/tests/test_plate.py +++ b/surfaces/blender/tests/test_plate.py @@ -101,8 +101,24 @@ class CheckTests(unittest.TestCase): slab = table["plates"][0]["slab"] self.assertEqual((slab["taper"], slab["back"], slab["gap"], slab["up"]), (0.04, 1.0, 0.0, [0.0, 0.0, 1.0])) self.assertEqual((table["plates"][0]["sides"], table["plates"][0]["mirror"], table["plates"][0]["clad"]["facets"], table["plates"][0]["clad"]["bolt_r"]), ("one", False, "outer", 0.028)) + self.assertEqual((table["plates"][0]["clad"]["bolt_mat"], table["plates"][0]["clad"]["bevel"]), ("gunmetal", 0.012)) self.assertEqual(plate.check(table), table) + def test_clad_carries_its_bolt_material_and_panel_bevel(self): + """Carried and never drawn from: a table that states them builds what one that leaves them out builds.""" + stated = plate.check(doc(row(slab=SLAB, clad=dict(CLAD, bolt_mat="steel", bevel=0.009)))) + self.assertEqual((stated["plates"][0]["clad"]["bolt_mat"], stated["plates"][0]["clad"]["bevel"]), ("steel", 0.009)) + ours, theirs = plate.build(stated)[0], plate.build(doc(row(slab=SLAB, clad=CLAD)))[0] + for key in ("solid", "panels", "bolts"): + self.assertTrue(np.array_equal(ours[key][0], theirs[key][0]) and ours[key][1] == theirs[key][1], key) + for value in (0.0, 0.05): + plate.check(doc(row(slab=SLAB, clad=dict(CLAD, bevel=value)))) + plate.check(doc(row(slab=SLAB, clad=dict(CLAD, bolt_mat="m" * 63)))) + for bad in (-0.001, 0.0501, "0.01", None, True): + self.refused(doc(row(slab=SLAB, clad=dict(CLAD, bevel=bad))), "plates[0].clad.bevel") + for bad in ("", "m" * 64, 3, None): + self.refused(doc(row(slab=SLAB, clad=dict(CLAD, bolt_mat=bad))), "plates[0].clad.bolt_mat") + def test_schema(self): self.refused({"schema": "brokkr.plates.v1", "plates": [row()]}, "document.schema") From cf268b67882a3b2fbf90d0c90f20a830dbe1ba8e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 16:23:38 +0100 Subject: [PATCH 214/223] brokkr_kitbash.plates: a plate table written into the scene, rebuilt in place (cut hard-plate-action) One writer of a hard plate's objects: the mesh on its host, a fit child per material for panels and bolts, an empty per anchor, their Kit Bevels (12 and 20 degrees through sync_bevel's angle argument), plate_kind and kit_plate. Refuses before it writes; the action row, its table tests and docs/kitbash.md, The action. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 181 +++++++++++++++++- .../brokkr_kitbash/brokkr_actions.json | 50 +++++ surfaces/blender/docs/kitbash.md | 50 ++++- surfaces/blender/tests/test_kitbash.py | 15 +- 4 files changed, 285 insertions(+), 11 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 83f47c5..562e3a1 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -60,6 +60,14 @@ a record: hose is its one writer, and the one thing read back from it is which t that crosses the same pin (it bends with the pin, so it is measured as an obstacle where it stands and not across the rolls: follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes that check). +plates writes hard armour plates. plate.py owns the table (brokkr.plates.v0) and every point of a plate, its panels, +bolts and anchor frames, in the table's frame; this file converts its arrays and nothing else. A plate is a mesh +object on its host under an identity parent inverse, with a child per material for its panels and bolts +(.fit.) and an empty per anchor (.mark., .port., kit_anchor on each). plates +is the one writer of those objects, their Kit Bevels, plate_kind and kit_plate. kit_plate is the checked row, kept as +a record: its presence admits a rebuild in place and nothing reads it to decide geometry. A plate is no kit part: +joints and report never list it, and a roll of its host carries it by Blender's parenting. + 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 @@ -85,7 +93,7 @@ try: except ImportError as error: # register() says so; the classes below only need something to subclass RESULT, PolishOperator, Refused, mesh_object, MISSING = "brokkr_mesh_polish_result", bpy.types.Operator, RuntimeError, None, error -from . import core, route +from . import core, plate, route KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" SOCKET, PARENT_SOCKET, ROLL = "kit_socket", "kit_parent_socket", "kit_roll" @@ -115,6 +123,11 @@ HOSE_OFFSETS = ((0.0, 0.0, 0.0), (0.5, 0.5, 0.5), (0.31, 0.67, 0.13)) # of a st HOSE_FINEST = 0.005 # metres: the least step, and the least a refused step is halved to for one more round of seeds HOSE_SEGMENTS = 12 # sides of a hose, a ferrule and a clamp's pad ROLL_STEP = 5.0 # degrees between the rolls of a joint's range that hose measures first: the step an assembly's clearance is read at +PLATE = "kit_plate" # on a hard plate: its checked row with side and prefix, as JSON; its presence admits a rebuild, and nothing reads it to decide geometry +PLATE_KIND = "plate_kind" # "hard" on a hard plate: report and paint data; plates is its one writer there +ANCHOR = "kit_anchor" # on a plate's anchor empty: {kind, id, height} of a mark or {kind, name} of a hose port, as JSON +PLATE_ANGLE, PANEL_ANGLE = math.radians(12.0), math.radians(20.0) # the Kit Bevel's angle limit on a plate, and on a child that holds its panels +ANCHORS = {"mark": "mark", "hose_port": "port"} # an anchor's kind to the part of its empty's name ROLL_FINEST = 0.3 # degrees: the half width under which a bin of rolls that falls short is refused instead of halved (5 degrees halved 4 times) @@ -147,11 +160,11 @@ def write_mesh(mesh, built) -> None: crease.data.foreach_set("value", np.isin(key(ends.reshape(-1, 2)), key(built.sharp))) -def sync_bevel(obj, width: float) -> None: +def sync_bevel(obj, width: float, angle: float = BEVEL_ANGLE) -> None: modifier = obj.modifiers.get(BEVEL) if modifier is None and width > 0: modifier = obj.modifiers.new(BEVEL, "BEVEL") - modifier.segments, modifier.limit_method, modifier.angle_limit = BEVEL_SEGMENTS, "ANGLE", BEVEL_ANGLE + modifier.segments, modifier.limit_method, modifier.angle_limit = BEVEL_SEGMENTS, "ANGLE", angle if modifier is not None: modifier.width = width @@ -2103,6 +2116,166 @@ class BROKKR_KITBASH_OT_hose(PolishOperator): return core.joined(shells) +class BROKKR_KITBASH_OT_plates(PolishOperator): + """Write a table of hard armour plates (brokkr.plates.v0) into the scene: each plate a mesh on its host, with its + panels and bolts as children per material and an empty per anchor; a plate this made is rebuilt in place""" + bl_idname = "brokkr_kitbash.plates" + bl_label = "Write Hard Plates" + host: bpy.props.StringProperty(name="Host", description="The object every plate is parented to; empty: none") + frame: bpy.props.StringProperty(name="Frame", description="The table's frame in the world, a JSON 4x4 of rows; empty: the host's world matrix, or the world with no host") + side: bpy.props.IntProperty(name="Side", default=1, min=-1, max=1, description="1, or -1: the table mirrored across its x = 0") + prefix: bpy.props.StringProperty(name="Prefix", description="Written before every plate's name") + table: bpy.props.StringProperty(name="Table", description="A brokkr.plates.v0 document, as JSON") + + @kit_work + def work(self, context): + host, world, table, built = self.read() + plans, taken = [], set() + for entry in built: + plans.append(self.plan(entry, table["plates"][entry["row"]], taken)) + inside = [plan["name"] for plan in plans if host is not None and (plan["name"] == host.name or plan["object"] in BROKKR_KITBASH_OT_hose.chain(host))] + if inside: + raise Refused(f"host {host.name!r} is, or stands under, the plate {inside[0]!r} this call writes: a plate is no host of itself; nothing changed.") + report = bounded({"plates": [{"name": plan["name"], "rebuilt": plan["object"] is not None, **plan["entry"]["report"], "anchors": [name for name, _, _ in plan["anchors"]]} for plan in plans], + "host": host.name if host else None, "side": self.side}, "write fewer plates in one call; nothing changed") + basis = (np.linalg.inv(np.array(host.matrix_world)) if host else np.eye(4)) @ world + for plan in plans: + entry, row, obj = plan["entry"], plan["row"], plan["object"] + if obj is None: + obj = bpy.data.objects.new(plan["name"], bpy.data.meshes.new(plan["name"])) + context.scene.collection.objects.link(obj) + self.write(obj.data, [entry["solid"]], row["mat"]) + self.stand(obj, host, world, basis) + sync_bevel(obj, row["bevel"], PLATE_ANGLE) + obj[PLATE_KIND], obj[PLATE] = "hard", json.dumps({**row, "side": entry["side"], "prefix": self.prefix}) + for child in plan["stale"]: + data = child.data + bpy.data.objects.remove(child) + if data is not None and not data.users: + bpy.data.meshes.remove(data) + for name, material, panels, parts in plan["fits"]: + child = bpy.data.objects.get(name) + if child is None: + child = bpy.data.objects.new(name, bpy.data.meshes.new(name)) + context.scene.collection.objects.link(child) + self.write(child.data, parts, material) + self.stand(child, obj, world, np.eye(4)) + if panels: + sync_bevel(child, row["clad"]["bevel"], PANEL_ANGLE) + if BEVEL in child.modifiers: + child.modifiers[BEVEL].segments = 1 + elif BEVEL in child.modifiers: + child.modifiers.remove(child.modifiers[BEVEL]) + for name, record, matrix in plan["anchors"]: + empty = bpy.data.objects.get(name) + if empty is None: + empty = bpy.data.objects.new(name, None) + empty.empty_display_size = 0.05 + context.scene.collection.objects.link(empty) + self.stand(empty, obj, world @ matrix, matrix) + empty[ANCHOR] = json.dumps(record) + return report + + def read(self): + """(host or None, the table's frame in the world, the checked table, plate.build's entries), each field refused by + shape, a PlateError with its path.""" + for name, text, least, most in (("host", self.host, 0, 63), ("frame", self.frame, 0, 1000), ("table", self.table, 1, 32000)): + if not least <= len(text) <= most: + raise Refused(f"{name} must be {least} to {most} characters, not {len(text)}; nothing changed.") + if not re.fullmatch(r"[A-Za-z0-9_.]{0,32}", self.prefix): + raise Refused(f"prefix {self.prefix!r} must be 0 to 32 characters from a-z A-Z 0-9 _ .; nothing changed.") + if self.side not in (1, -1): + raise Refused(f"side must be 1 or -1, not {self.side}; nothing changed.") + host = None + if self.host: + host = bpy.data.objects.get(self.host) + if host is None: + raise Refused(f"host: no object named {self.host!r}; nothing changed.") + rigid(host) + world = np.array(host.matrix_world) if host else np.eye(4) + if self.frame: + try: + rows = json.loads(self.frame) + except ValueError as error: + raise Refused(f"frame is not JSON ({error}); nothing changed.") from None + if not (isinstance(rows, list) and len(rows) == 4 and all(isinstance(r, list) and len(r) == 4 and all(core.finite(v) for v in r) for r in rows)): + raise Refused("frame must be a JSON array of 4 rows of 4 finite numbers; nothing changed.") + world = np.array(rows, dtype=np.float64) + turn = world[:3, :3] + if np.abs(turn.T @ turn - np.eye(3)).max() > RIGID or np.linalg.det(turn) < 0 or np.abs(world[3] - (0.0, 0.0, 0.0, 1.0)).max() > 0: + raise Refused("frame is not rigid: its 3x3 must be a rotation (no scale, mirror or shear) and its last row 0, 0, 0, 1; nothing changed.") + try: + document = json.loads(self.table) + except ValueError as error: + raise Refused(f"table is not JSON ({error}); nothing changed.") from None + try: + table = plate.check(document) + return host, world, table, plate.build(table, self.side) + except plate.PlateError as error: + raise Refused(f"table: {error}; nothing changed.") from None + + def plan(self, entry: dict, row: dict, taken: set) -> dict: + """What one built entry writes, refused before anything is written: {name, entry, row, object (the plate to + rebuild, or None), fits [(name, material, holds panels, meshes)], anchors [(name, record, matrix)], stale (the + plate's fit children and anchors this call no longer makes)}. `taken` is every name the call has planned.""" + name, path, clad = self.prefix + entry["name"], f"table.plates[{entry['row']}]", row["clad"] + for key, material in (("mat", row["mat"]),) + ((("clad.mat", clad["mat"]), ("clad.bolt_mat", clad["bolt_mat"])) if clad else ()): + if material not in bpy.data.materials: + raise Refused(f"{path}.{key}: no material named {material!r}; make it first (createMaterial); nothing changed.") + obj = bpy.data.objects.get(name) + if obj is not None: + if obj.type != "MESH" or PLATE not in obj: + raise Refused(f"{path}: an object named {name!r} exists and is no plate (it carries no {PLATE}): plates rebuilds only what plates made; nothing changed.") + live(obj, "rebuilding") + own_mesh(obj, "rebuilding") + fits = {} + if clad: + for material, panels, mesh in ((clad["mat"], True, entry["panels"]), (clad["bolt_mat"], False, entry["bolts"])): + if len(mesh[1]): + held = fits.setdefault(f"{name}.fit.{material}", [material, False, []]) + held[1], held[2] = held[1] or panels, held[2] + [mesh] + anchors = [] + for anchor in entry["anchors"]: + record = {"kind": anchor["kind"], "id": anchor["name"], "height": anchor["height"]} if anchor["kind"] == "mark" else {"kind": anchor["kind"], "name": anchor["name"]} + anchors.append((f"{name}.{ANCHORS[anchor['kind']]}.{anchor['name']}", record, np.array(anchor["matrix"]))) + for made, kind in [(name, None)] + [(child, "MESH") for child in fits] + [(empty, "EMPTY") for empty, _, _ in anchors]: + if len(made.encode("utf-8")) > 63: + raise Refused(f"{path}: the name {made!r} is {len(made.encode('utf-8'))} bytes, over the 63 an object's name holds: use a shorter prefix, row, material or anchor name; nothing changed.") + if made in taken: + raise Refused(f"{path}: the name {made!r} is made twice in this call; nothing changed.") + taken.add(made) + other = bpy.data.objects.get(made) + if kind is not None and other is not None: + if obj is None or other.parent != obj or other.type != kind: + raise Refused(f"{path}: an object named {made!r} exists and is not this plate's (a {'mesh' if kind == 'MESH' else 'empty'} child of {name!r}); nothing changed.") + if kind == "MESH": + live(other, "rebuilding") + own_mesh(other, "rebuilding") + stale = [] if obj is None else [child for child in obj.children if child.name not in taken + and ((child.type == "MESH" and child.name.startswith(name + ".fit.")) or (child.type == "EMPTY" and ANCHOR in child))] + return {"name": name, "entry": entry, "row": row, "object": obj, "fits": [(child, *held) for child, held in fits.items()], "anchors": anchors, "stale": stale} + + @staticmethod + def write(mesh, parts, material: str) -> None: + """Meshes (V, faces) joined into one datablock, cleared first: every face flat, its first material slot the + material; later slots stay.""" + mesh.clear_geometry() + offsets = np.cumsum([0] + [len(V) for V, _ in parts[:-1]]) + mesh.from_pydata(np.vstack([V for V, _ in parts]).tolist(), [], [[int(k + offset) for k in face] for (_, faces), offset in zip(parts, offsets) for face in faces]) + (mesh.attributes.get("sharp_face") or mesh.attributes.new("sharp_face", "BOOLEAN", "FACE")).data.foreach_set("value", np.ones(len(mesh.polygons), dtype=bool)) + mesh.update() + if len(mesh.materials): + mesh.materials[0] = bpy.data.materials[material] + else: + mesh.materials.append(bpy.data.materials[material]) + + @staticmethod + def stand(obj, parent, world, basis) -> None: + obj.parent = parent + obj.matrix_world = Matrix(np.asarray(world).tolist()) # read by a report; no depsgraph update here + seat(obj, basis) + + class BROKKR_KITBASH_OT_describe(PolishOperator): """List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame at default params""" @@ -2137,7 +2310,7 @@ classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KI BROKKR_KITBASH_OT_joint, BROKKR_KITBASH_OT_slide, BROKKR_KITBASH_OT_joints, BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_freeze, BROKKR_KITBASH_OT_thaw, BROKKR_KITBASH_OT_ribs, - BROKKR_KITBASH_OT_shell, BROKKR_KITBASH_OT_hose) + BROKKR_KITBASH_OT_shell, BROKKR_KITBASH_OT_hose, BROKKR_KITBASH_OT_plates) SETTLED_ON = (bpy.app.handlers.depsgraph_update_post, bpy.app.handlers.save_pre) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 93be89c..149e095 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -969,6 +969,56 @@ "default": "" } ] + }, + { + "name": "brokkr_kitbash.plates", + "doc": "Write a table of hard armour plates into the scene. table is a brokkr.plates.v0 document as JSON (docs/kitbash.md, Hard plates): {\"schema\": \"brokkr.plates.v0\", \"plates\": [row, ...]}, each row a convex faceted solid with optional clad (raised panels and their bolts) and fits (anchors on its face). The table's coordinates are metres in frame: a JSON 4x4 of rows in the world, rigid; empty, the host's world matrix, or the world with no host. side 1 builds the table as written and -1 mirrored across its x = 0. Each built plate is a mesh object named prefix + its name (.R and .L on a two-sided row), every face flat, parented to host under an identity parent inverse, with material mat, a Kit Bevel of the row's bevel (angle 12 degrees) and the properties plate_kind \"hard\" and kit_plate (its checked row, a record). Its panels are the child .fit. and its bolts .fit., one mesh per material, made only when not empty; a child that holds panels carries a Kit Bevel of clad.bevel (angle 20 degrees, one segment). Each anchor is an empty child at the anchor's frame: .mark. with kit_anchor {kind, id, height}, .port. with kit_anchor {kind, name}; brokkr_kitbash.hose takes a port empty's name as an end and leaves along its z. An object that carries kit_plate under a made name is rebuilt in place: it keeps its identity, its other children and its modifiers; its fit children are rewritten, made or removed, its anchors moved, and one the row no longer names removed. A plate is no kit part: joints and report do not list it, and a roll of its host carries it. Every material must exist (createMaterial). Refuses before it writes anything: a table the format refuses (the path is named), a missing material (named with its path), a host that is missing, scaled, mirrored or sheared, a frame that is not a rigid 4x4, a made name of over 63 bytes or taken by an object that is not this plate's, a frozen plate or one sharing its mesh, and a report over 16000 characters. Reports plates [{name, rebuilt, corners, facets, panels, bolts, anchors (the empties' names)}], host and side.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "host", + "type": "string", + "minLength": 0, + "maxLength": 63, + "default": "", + "doc": "the object every plate is parented to; empty: no parent" + }, + { + "name": "frame", + "type": "string", + "minLength": 0, + "maxLength": 1000, + "default": "", + "doc": "the table's frame in the world, a JSON array of 4 rows of 4 numbers, rigid; empty: the host's world matrix, or the world with no host" + }, + { + "name": "side", + "type": "integer", + "minimum": -1, + "maximum": 1, + "default": 1, + "doc": "1, or -1 for the table mirrored across its x = 0; 0 is refused" + }, + { + "name": "prefix", + "type": "string", + "minLength": 0, + "maxLength": 32, + "chars": "id", + "default": "", + "doc": "written before every plate's name: a-z A-Z 0-9 _ . (the action refuses a '-')" + }, + { + "name": "table", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 32000, + "doc": "a brokkr.plates.v0 document, as JSON" + } + ] } ] } diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 63de66e..37dee41 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -837,9 +837,9 @@ evaluation once for every `ribs` call; iterate planes on the cage before it is c `brokkr_kitbash/plate.py` owns a hard armour plate's geometry: a convex faceted solid, every facet flat, with raised detail panels, a bolt inside each panel corner, and the frames of what stands on it. It is numpy and the -standard library, as `core.py` and `route.py` are, and it is a library so far: `plate.check(document)` and -`plate.build(table, side=1)`. No action calls it yet and nothing here makes a Blender object. A plate the concept -draws curved is a shell (Making a shell); the two do not call each other. +standard library, as `core.py` and `route.py` are: `plate.check(document)` and `plate.build(table, side=1)`. +`brokkr_kitbash.plates` (The action, below) writes what `build` returns into the scene and decides none of it. A +plate the concept draws curved is a shell (Making a shell); the two do not call each other. A plate table is a data document: @@ -1007,6 +1007,49 @@ pinned from Starfire (Windows 11, numpy 2.5.4) and Yggdrasil (Debian 13, numpy 2 two hosts' coordinates differ by up to 2.7e-15 m, so the bytes of `build`'s arrays are equal between runs on one host and not between hosts. +### The action + +`brokkr_kitbash.plates` writes a table into the scene. It is the one writer of a hard plate's objects. + +| field | value | +| --- | --- | +| `table` | the `brokkr.plates.v0` document as JSON, 1 to 32000 characters | +| `host` | the object every plate is parented to, 0 to 63 characters; empty: no parent | +| `frame` | the table's frame in the world, a JSON array of 4 rows of 4 numbers, at most 1000 characters; empty: the host's world matrix, or the world with no host | +| `side` | 1, or -1 for the table mirrored across its x = 0 | +| `prefix` | written before every plate's name: 0 to 32 of a-z A-Z 0-9 _ . | + +Per built entry, N = `prefix` + its name: + +- A mesh object N: `build`'s solid in the table frame (`mesh.from_pydata`, every face flat), material `mat`. Its + parent is `host` under an identity parent inverse and its `matrix_basis` is host world^-1 x `frame`; with no + host its world matrix is `frame`. A Kit Bevel of the row's `bevel`, angle 12 degrees. ID properties + `plate_kind` = `"hard"` and `kit_plate`: the checked row with `side` and `prefix`, as JSON. `kit_plate` is a + record: its presence admits a rebuild and nothing reads it to decide geometry. +- `N.fit.` holds the panels and `N.fit.` the bolts: a child mesh per material (one + child when the two are the same material), identity basis, made only when its mesh is not empty. A child that + holds panels carries a Kit Bevel of `clad.bevel`, angle 20 degrees, one segment. +- One empty per anchor, a child of N at the anchor's matrix: `N.mark.` with `kit_anchor` + `{kind, id, height}`, `N.port.` with `kit_anchor` `{kind, name}` (JSON). A port empty is an end + `brokkr_kitbash.hose` takes by name: the hose leaves along its z, out of the face. + +An object named N that carries `kit_plate` is rebuilt in place: its mesh is cleared and rewritten, each +`N.fit.` child rewritten, made or removed as it is now empty or not, anchors kept by name and moved, and one +the row no longer names removed. N keeps its identity, its other children, its later material slots and its +modifiers. A frozen plate or one sharing its mesh is refused, as `shell` refuses. A plate is no kit part: +`joints` and `report` never list it, and a roll of its host carries it by Blender's parenting. The action +evaluates nothing. + +It refuses before anything is written, object count and names unchanged: a table `check` or `build` refuses (the +path in the message); a material `bpy.data.materials` lacks, named with its path (`mat`, `clad.mat`, +`clad.bolt_mat`); a host not found, or scaled, mirrored or sheared; a `frame` that is not a JSON 4x4 of finite +numbers or not rigid; N, a child's or an anchor's name taken by an object that is not this plate's (N without +`kit_plate`, or an object that is not N's child); a name made twice in one call; a made name over 63 bytes; a +host that is one of the call's plates or stands under one; a report over 16000 characters. + +The report: `{plates: [{name, rebuilt, corners, facets, panels, bolts, anchors}], host, side}`, `anchors` the +empties' names. + ## Hoses between sockets `brokkr_kitbash.hose` routes a bundle of hoses from one socket to another around everything in the scene: @@ -1451,6 +1494,7 @@ under such load (five runs), and reading a 336-face part takes 27 to 37 ms. | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | | `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | | `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `seed`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. | +| `brokkr_kitbash.plates` | `table` (a `brokkr.plates.v0` document, JSON), `host`, `frame` (empty, or a JSON 4x4 of rows), `side`, `prefix` | Writes hard plates: each a mesh on its host with `.fit.` children for panels and bolts and an empty per anchor; a plate it made is rebuilt in place. Reports `plates` (`name`, `rebuilt`, `corners`, `facets`, `panels`, `bolts`, `anchors`), `host`, `side`. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored value (`set_params`). A value outside its bounds is refused with the bounds in the message. diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 98feaca..9a3bb21 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -2000,7 +2000,7 @@ ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbas "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.joint", "brokkr_kitbash.slide", "brokkr_kitbash.joints", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.freeze", "brokkr_kitbash.thaw", "brokkr_kitbash.ribs", - "brokkr_kitbash.shell", "brokkr_kitbash.hose"] + "brokkr_kitbash.shell", "brokkr_kitbash.hose", "brokkr_kitbash.plates"] class CageTests(unittest.TestCase): @@ -2208,7 +2208,14 @@ class HostFileTests(unittest.TestCase): self.assertEqual([(row["name"], field["name"], field["default"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "boolean"], [("brokkr_kitbash.shell", "count_folds", False)]) # the one evaluation shell makes is asked for, never the default self.assertEqual([(row["name"], field["name"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "integer"], - [("brokkr_kitbash.shell", "levels"), ("brokkr_kitbash.hose", "count")]) + [("brokkr_kitbash.shell", "levels"), ("brokkr_kitbash.hose", "count"), ("brokkr_kitbash.plates", "side")]) + plates = {**envelope, "action": "brokkr_kitbash.plates", "table": '{"schema": "brokkr.plates.v0", "plates": []}'} + self.assertEqual([at.validate(plates, host)[k] for k in ("host", "frame", "side", "prefix")], ["", "", 1, ""]) + self.assertEqual(at.validate({**plates, "side": -1, "prefix": "Shin.", "table": "{" + " " * 31999, "frame": "[" + " " * 999}, host)["side"], -1) + for bad in ({**plates, "side": 2}, {**plates, "side": -2}, {**plates, "side": 0.5}, {**plates, "table": "{" + " " * 32000}, {**plates, "table": ""}, {**plates, "frame": "[" + " " * 1000}, + {**plates, "prefix": "a b"}, {**plates, "prefix": "p" * 33}, {**plates, "host": "h" * 64}, {k: v for k, v in plates.items() if k != "table"}, {**plates, "object_name": "P"}): + with self.assertRaises(at.IntentInvalid, msg=str(bad)[:200]): + at.validate(bad, host) sheet = json.dumps({"rings": [[[0, 0, 0], [1, 0, 0]], [[0, 0, 1], [1, 0, 1]]]}) shell = {**envelope, "action": "brokkr_kitbash.shell", "object_name": "Plate", "sheet": sheet} self.assertEqual([at.validate(shell, host)[k] for k in ("thickness", "offset", "levels", "bevel", "count_folds")], [0.05, -1, 3, 0, False]) @@ -2311,9 +2318,9 @@ class OwnershipTests(unittest.TestCase): self.assertNotIn(call, bodies["thaw"]) for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["freeze"], "bpy.data.meshes.new_from_object("), (bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()"), (bodies["set_params"], "write_mesh("), - (bodies["hose"], "write_mesh(")): + (bodies["hose"], "write_mesh("), (bodies["plates"], "clear_geometry()")): self.assertLess(body.index("live("), body.index(first_write)) - self.assertEqual(source.count("live("), 8) # its def and the seven callers above + self.assertEqual(source.count("live("), 10) # its def, the seven callers above and plates' two: a plate and a fit child # the frozen state has one writer: every write of kit_frozen, kit_kept and a fake user is in hold, which swaps the meshes too hold = source.split("\ndef hold(")[1].split("\n\n\n")[0] writes = r"\[(?:FROZEN|KEPT)\](?:, obj\.data)? =(?!=)|del \w+\[(?:FROZEN|KEPT)\]|use_fake_user = " From ea7759344d11f40cffb03121230e3fb1c593808c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 16:23:39 +0100 Subject: [PATCH 215/223] tests/live/kitbash_plates.py: plates against plate.build under the frame, a roll, a hose between ports, a rebuild, the refusals 54 checks in Blender 5.3 background on Starfire; bounds by the margin rule from fourteen mutants run against it. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/kitbash_plates.py | 440 ++++++++++++++++++ .../tests/live/kitbash_plates.result.json | 347 ++++++++++++++ 2 files changed, 787 insertions(+) create mode 100644 surfaces/blender/tests/live/kitbash_plates.py create mode 100644 surfaces/blender/tests/live/kitbash_plates.result.json diff --git a/surfaces/blender/tests/live/kitbash_plates.py b/surfaces/blender/tests/live/kitbash_plates.py new file mode 100644 index 0000000..fe3b326 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_plates.py @@ -0,0 +1,440 @@ +"""Live proof, in a background Blender, of brokkr_kitbash.plates through run_intent: a plate table written onto a +mechanical-kit link under a pin, each plate's mesh, fit children and anchor empties against plate.build's own answer +under the frame, the Kit Bevels, joints unchanged by the plates, a roll of the pin carrying every plate, a hose between +two port empties either side of the pin across its range, a rebuild in place, and each refusal leaving the scene as it +was. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_plates.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. + +The checks run inside one try: an uncaught error is a failed check that names the section it happened in, and the +result file is written and the checks printed whatever happened. +""" +import copy +import importlib +import json +import math +import os +import sys +import tempfile +import traceback +import types +from pathlib import Path + +import bpy +import numpy as np +from mathutils import Euler, Matrix + +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 + +reference = types.ModuleType("brokkr_kitbash_plates") # plate.py as the unit tests load it: what every reading here is taken against +reference.__path__ = [str(SURFACE / "brokkr_kitbash")] +sys.modules["brokkr_kitbash_plates"] = reference +plate = importlib.import_module("brokkr_kitbash_plates.plate") + +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-plates-")) +target.configure_action_dirs("", str(WORK)) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}, "reports": {}} +COUNT, SECTION = [0], ["setup"] +# The mutants of brokkr_kitbash.plates this suite was run against, each failing a check: X1 the frame applied twice (the +# basis host_world @ frame); X2 a rebuild that deletes the plate and makes it again; X3 an anchor left at its plate's +# origin; X4 a plate written with no parent; X5 the host's inverse as the parent inverse; X6 a kept anchor not moved; X7 +# the plate's Kit Bevel at shell's 30 degrees; X8 the panels' at 12; X9 a fit child parented to the host; X10 an +# anchor's basis under the frame again; X11 stale children kept; X12 no sharp_face written; X13 no material refusal; +# X14 no refusal of a taken child or anchor name. +# +# Metres between a written vertex in the world (the object's matrix_world on its mesh's own coordinates) and the same +# vertex of plate.build's answer under the frame this script holds, over every plate and fit child of the suite; inf +# when a face differs or is smooth. Shipped worst 8.5e-08 (float32 meshes and matrices); least claimed mutant 1.7 (X1); +# the geometric mean, separation 4400 each side. +WRITTEN = 3.8e-4 +# Largest entry of an anchor empty's matrix_world minus the frame @ plate.build's anchor matrix. Shipped worst 2.2e-07; +# least claimed mutant 0.041 (X6, on the rebuild that moves a port 0.05 along its face; X3 reads 1.5, X10 1.4); +# separation 430 each side. +ANCHORED = 9.5e-5 +# Largest entry of matrix_world after a roll of the pin minus (the shin's own motion @ matrix_world before), over +# every plate, fit child and anchor on the shin. Shipped worst 1.0e-07; least claimed mutant 0.23 (X4: the plate stays +# where it stood); separation 1500 each side. +CARRIED = 1.5e-4 +# Largest entry of a kept anchor's basis after a rebuild minus plate.build's matrix for the rebuilt row. Shipped worst +# 2.1e-07; least claimed mutant 0.049 (X6); separation 480 each side. +MOVED = 1.0e-4 +# Metres along a port's z between the port, as plate.build places it on the panel's top, and the nearest hose vertex +# within 1.5 hose radii of it; 1 when no vertex stands that near, or no hose was made. Shipped worst 3.9e-08; least +# claimed mutant 1 (X10: the hose is routed from where the empty stands, off the plate; under X1, X3 and X4 hose +# refuses); separation 5000 each side. +PORTED = 2.0e-4 +RADIUS, CLEARANCE = 0.006, 0.005 + + +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 section(name): + SECTION[0] = name + print("SECTION", name, flush=True) + + +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"])[:400], flush=True) + return receipt, result + + +def scene_state(): + return {o.name: (o.parent and o.parent.name, o.type, o.session_uid, 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())}, [(m.name, m.type, m.show_viewport) for m in o.modifiers], + o.data.name if o.type == "MESH" else None, len(o.data.polygons) if o.type == "MESH" else None, + [s.material and s.material.name for s in o.material_slots], + np.round(points(o)[:8], 6).tolist() if o.type == "MESH" else None) + for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes), sorted(c.name for c in bpy.data.collections) + + +def refused(label, fields, expected): + state = scene_state() + receipt, _ = send("brokkr_kitbash.plates", **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 place(name, part, params=""): + send("brokkr_kitbash.place_part", part=part, object_name=name, params=params) + return bpy.data.objects[name] + + +def points(obj): + out = np.zeros(3 * len(obj.data.vertices)) + obj.data.vertices.foreach_get("co", out) + return out.reshape(-1, 3) + + +def world(obj): + return np.array(obj.matrix_world, dtype=np.float64) + + +def under(matrix, V): + return np.asarray(V) @ matrix[:3, :3].T + matrix[:3, 3] + + +def joined(parts): + """Meshes (V, faces) as one: the vertices in order, and each face's vertex indices.""" + offsets = np.cumsum([0] + [len(V) for V, _ in parts[:-1]]) + return np.vstack([V for V, _ in parts]), [[int(k + offset) for k in face] for (_, faces), offset in zip(parts, offsets) for face in faces] + + +def written(obj, frame, parts): + """How far the object's mesh stands, in the world, from the meshes (V, faces) under frame; inf when the vertex + count, a face or a smooth face differs.""" + V, faces = joined(parts) + if len(obj.data.vertices) != len(V) or [list(p.vertices) for p in obj.data.polygons] != faces or any(p.use_smooth for p in obj.data.polygons): + return math.inf + return float(np.abs(under(world(obj), points(obj)) - under(frame, V)).max()) + + +def off(V, port): + """Metres along a port's z between the port and the nearest of the vertices within 1.5 hose radii of it; 1 when + none stands that near.""" + near = V[np.linalg.norm(V - port[:3, 3], axis=1) < 1.5 * RADIUS] + return abs(float(((near - port[:3, 3]) @ port[:3, 2]).min())) if len(near) else 1.0 + + +def bevel(obj): + modifier = obj.modifiers.get("Kit Bevel") + return None if modifier is None else (round(modifier.width, 6), round(math.degrees(modifier.angle_limit), 4), modifier.segments, modifier.limit_method) + + +def fits_of(entry, row): + """{material: [meshes]} of what a built entry's fit children hold, panels before bolts.""" + held = {} + if row["clad"]: + for material, mesh in ((row["clad"]["mat"], entry["panels"]), (row["clad"]["bolt_mat"], entry["bolts"])): + if len(mesh[1]): + held.setdefault(material, []).append(mesh) + return held + + +def proven(label, document, side, prefix, host, frame, report): + """Every object one accepted call wrote, against plate.build of the same document: the plates' meshes, parents, + bases, bevels and properties, each fit child, each anchor empty, and the report's rows.""" + table = plate.check(document) + built = plate.build(table, side) + host_world = world(host) if host else np.eye(4) + ok, detail, rows = True, [], [] + for entry in built: + row, name = table["plates"][entry["row"]], prefix + entry["name"] + obj = bpy.data.objects.get(name) + if obj is None or obj.type != "MESH": + ok, detail = False, detail + [f"{name}: not made"] + continue + apart = reading("written", written(obj, frame, [entry["solid"]])) + basis = np.abs(np.array(obj.matrix_basis) - np.linalg.inv(host_world) @ frame).max() + facts = {"apart": apart < WRITTEN, "parent": obj.parent == host, "inverse": np.array_equal(np.array(obj.matrix_parent_inverse), np.eye(4)), "basis": basis < WRITTEN, + "bevel": bevel(obj) == ((round(row["bevel"], 6), 12.0, 2, "ANGLE") if row["bevel"] > 0 else None), "kind": obj.get("plate_kind") == "hard", + "record": json.loads(obj.get("kit_plate", "null")) == {**row, "side": entry["side"], "prefix": prefix}, + "material": obj.material_slots[0].material.name == row["mat"], "noPart": "kit_part" not in obj} + held = fits_of(entry, row) + children = sorted(child.name for child in obj.children if child.type == "MESH") + facts["children"] = children == sorted(f"{name}.fit.{material}" for material in held) + for material, parts in held.items(): + child = bpy.data.objects.get(f"{name}.fit.{material}") + if child is None or child.parent != obj: + facts[f"fit {material}"] = False + continue + panels = material == row["clad"]["mat"] + facts[f"fit {material}"] = (reading("written", written(child, frame, parts)) < WRITTEN and np.array_equal(np.array(child.matrix_basis), np.eye(4)) + and np.array_equal(np.array(child.matrix_parent_inverse), np.eye(4)) and [s.material.name for s in child.material_slots] == [material] + and bevel(child) == ((round(row["clad"]["bevel"], 6), 20.0, 1, "ANGLE") if panels and row["clad"]["bevel"] > 0 else None)) + empties = sorted(child.name for child in obj.children if child.type == "EMPTY" and "kit_anchor" in child) + names = [] + for anchor in entry["anchors"]: + mark = anchor["kind"] == "mark" + names.append(f"{name}.{'mark' if mark else 'port'}.{anchor['name']}") + empty = bpy.data.objects.get(names[-1]) + if empty is None or empty.parent != obj or empty.type != "EMPTY": + facts[names[-1]] = False + continue + record = {"kind": "mark", "id": anchor["name"], "height": anchor["height"]} if mark else {"kind": "hose_port", "name": anchor["name"]} + facts[names[-1]] = (reading("anchored", np.abs(world(empty) - frame @ np.array(anchor["matrix"])).max()) < ANCHORED and json.loads(empty.get("kit_anchor", "null")) == record + and np.array_equal(np.array(empty.matrix_parent_inverse), np.eye(4))) + facts["anchors"] = empties == sorted(names) + rows.append({"name": name, **entry["report"], "anchors": names}) + if not all(facts.values()): + ok, detail = False, detail + [f"{name}: {[k for k, v in facts.items() if not v]}"] + reported = report and [{k: v for k, v in row.items() if k != "rebuilt"} for row in report["plates"]] + check(f"written-is-built: {label}", ok and reported == rows and report["host"] == (host.name if host else None) and report["side"] == side, detail or [reported, rows]) + return table, built + + +try: + section("knee") + for name in ("khaki", "olive_light", "gunmetal", "steel"): + bpy.data.materials.new(name) + STRUT = "length=0.8;width=0.08;thickness=0.05" + thigh = place("Thigh", "strut", STRUT) + send("setObjectTransform", targetObjectName="Thigh", location=[0.3, -0.2, 0.1], rotationEuler=[0.2, -0.3, 0.5]) # no frame here is the identity + shin = place("Shin", "strut", STRUT) + send("brokkr_kitbash.attach", object_name="Shin", socket="end_a", parent_name="Thigh", parent_socket="end_b_back", roll=0.0) + send("brokkr_kitbash.joint", object_name="Shin", record=json.dumps({"limits": [-20, 20]})) + bpy.context.view_layer.update() + _, joints_before = send("brokkr_kitbash.joints", object_name="Thigh") + count = len(bpy.data.objects) + + def slab(name, at, port, more=None): + """A plate facing the link's -y, 0.3 by 0.5, with one panel, a hose port on it and a numeral under it.""" + return {"name": name, "mat": "khaki", "bevel": 0.006, + "slab": {"at": at, "normal": [0, -1, 0], "up": [0, 0, 1], "outline": {"w": 0.3, "h": 0.5, "clip": 0.04}, "thick": 0.04}, + "clad": {"mat": "olive_light", "min_area": 0.01, "lifts": [0.01, 0.015], "inset": 0.03, "gap": 0.02, "split": 99.0, "seed": 7, "bolt_r": 0.008, **(more or {})}, + "fits": [{"kind": "hose_port", "name": port[0], "at": port[1]}, {"kind": "mark", "id": "num", "at": [0.0, -0.15], "height": 0.08}]} + + def doc(*rows): + return {"schema": "brokkr.plates.v0", "plates": [copy.deepcopy(r) for r in rows]} + + THIGH = doc(slab("Guard", [0.0, -0.12, 0.35], ("feed", [0.0, 0.1]))) + SHIN = doc(slab("Guard", [0.0, -0.115, 0.45], ("return", [0.0, -0.1]), {"bevel": 0.009})) + section("on the links") + receipt, report = send("brokkr_kitbash.plates", host="Thigh", prefix="Thigh.", table=json.dumps(THIGH)) + check("plates on the thigh are accepted and none is a rebuild", receipt["status"] == "accepted" and [row["rebuilt"] for row in report["plates"]] == [False], [receipt["status"], receipt["message"]]) + R["reports"]["thigh"] = report + bpy.context.view_layer.update() + proven("a plate on the thigh, the frame the host's", THIGH, 1, "Thigh.", thigh, world(thigh), report) + receipt, report = send("brokkr_kitbash.plates", host="Shin", prefix="Shin.", table=json.dumps(SHIN)) + bpy.context.view_layer.update() + shin_table, shin_built = proven("a plate on the shin, under the pin", SHIN, 1, "Shin.", shin, world(shin), report) + guard = bpy.data.objects["Thigh.Guard"] + check("a plate with a panel and its bolts has two fit children and two anchors, and the panel's child alone a bevel", + sorted(c.name for c in guard.children) == ["Thigh.Guard.fit.gunmetal", "Thigh.Guard.fit.olive_light", "Thigh.Guard.mark.num", "Thigh.Guard.port.feed"] + and len(bpy.data.objects["Thigh.Guard.fit.gunmetal"].data.polygons) == 8 * 8 and bevel(bpy.data.objects["Shin.Guard.fit.olive_light"]) == (0.009, 20.0, 1, "ANGLE") + and len(bpy.data.objects) == count + 10, [sorted(c.name for c in guard.children), len(bpy.data.objects["Thigh.Guard.fit.gunmetal"].data.polygons), len(bpy.data.objects) - count]) + _, joints_after = send("brokkr_kitbash.joints", object_name="Thigh") + check("roll-carries: joints lists the same rows with the plates as without", joints_before is not None and joints_after == joints_before, joints_after) + _, parts = send("brokkr_kitbash.report") + check("a plate is no kit part: report lists the two struts", parts is not None and [row["object"] for row in parts["parts"]] == ["Shin", "Thigh"], parts and [row.get("object") for row in parts["parts"]]) + + section("a frame of its own") + F = np.array(Matrix.Translation((1.5, 0.4, -0.3)) @ Euler((0.7, 0.2, -1.1)).to_matrix().to_4x4(), dtype=np.float64) + TWO = doc({"name": "Wing", "mat": "khaki", "bevel": 0.004, "sides": "both", + "slab": {"at": [0.4, 0.1, 0.0], "normal": [1, 0.2, 0.1], "outline": [[-0.2, 0.3], [0.2, 0.3], [0.3, 0.0], [0.2, -0.3], [-0.2, -0.3]], "thick": 0.05}, + "clad": {"mat": "steel", "bolt_mat": "steel", "min_area": 0.01, "lifts": [0.01, 0.02], "inset": 0.03, "gap": 0.02, "split": 0.1, "seed": [3, 4], "bolt_r": 0.006}, + "fits": [{"kind": "hose_port", "name": "p", "at": [0.0, 0.0], "lift": 0.01}]}, + {"name": "Lump", "mat": "gunmetal", "points": [[0, 0, 0], [0.2, 0, 0], [0, 0.2, 0], [0, 0, 0.2], [0.15, 0.15, 0.15]]}) + for side, prefix in ((1, "F."), (-1, "G.")): + receipt, report = send("brokkr_kitbash.plates", host="Thigh", prefix=prefix, frame=json.dumps(F.tolist()), side=side, table=json.dumps(TWO)) + bpy.context.view_layer.update() + check(f"plates under a stated frame are accepted at side {side}", receipt["status"] == "accepted", [receipt["status"], receipt["message"]]) + proven(f"a two-sided row and a bare one under a stated frame, side {side}: panels and bolts of one material are one child", TWO, side, prefix, thigh, F, report) + check("a bare plate has no child and no bevel; a two-sided row is two plates", + not bpy.data.objects["F.Lump"].children and bevel(bpy.data.objects["F.Lump"]) is None and all(name in bpy.data.objects for name in ("F.Wing.R", "F.Wing.L", "G.Wing.R", "G.Wing.L")), None) + receipt, report = send("brokkr_kitbash.plates", prefix="Free.", table=json.dumps(TWO)) + bpy.context.view_layer.update() + proven("no host and no frame: the table's frame is the world", TWO, 1, "Free.", None, np.eye(4), report) + + section("roll") + carried = [o for o in bpy.data.objects if o.name.startswith("Shin.")] + stays = [o for o in bpy.data.objects if o.name.startswith(("Thigh.", "F.", "Free."))] + before = {o.name: world(o) for o in carried + stays + [shin]} + receipt, _ = send("brokkr_kitbash.roll", object_name="Shin", roll=15.0) + bpy.context.view_layer.update() + motion = world(shin) @ np.linalg.inv(before["Shin"]) + check("the roll moved the shin", receipt["status"] == "accepted" and np.abs(motion - np.eye(4)).max() > 0.05, receipt["message"]) + check("roll-carries: every plate, fit child and anchor on the shin stands at the roll @ where it stood", len(carried) == 5 + and reading("carried", max(np.abs(world(o) - motion @ before[o.name]).max() for o in carried)) < CARRIED, R["readings"]) + check("what stands on the thigh or on nothing stayed", all(np.array_equal(world(o), before[o.name]) for o in stays), None) + send("brokkr_kitbash.roll", object_name="Shin", roll=0.0) + bpy.context.view_layer.update() + + section("hose") + ports = [bpy.data.objects["Thigh.Guard.port.feed"], bpy.data.objects["Shin.Guard.port.return"]] + HOSE = {"object_name": "Feed", "start": ports[0].name, "end": ports[1].name, "radius": RADIUS, "clearance": CLEARANCE, "joint": json.dumps({"socket": "Shin:end_a_back", "standoff": 0.25})} + receipt, report = send("brokkr_kitbash.hose", **HOSE) + R["reports"]["hose"] = report + check("hose-between-ports: a hose routes between the two plates' port empties through the pin point, clear across the pin's range", + receipt["status"] == "accepted" and report["hoses"] == 1 and report["nonManifoldEdges"] == 0 and report["rolls"] >= 9 and report["clearance"] >= CLEARANCE + and report["worstClearance"] >= CLEARANCE, [receipt["status"], receipt["message"], report]) + if receipt["status"] == "accepted": + feed = bpy.data.objects["Feed"] + bpy.context.view_layer.update() + V = under(world(feed), points(feed)) + expected = [world(shin if index else thigh) @ np.array(next(a for a in plate.build(plate.check(SHIN if index else THIGH))[0]["anchors"] if a["kind"] == "hose_port")["matrix"]) for index in (0, 1)] + check("hose-between-ports: each end stands on its port, as plate.build places it on the panel's top, and leaves along its z", + all(reading("ported", off(V, port)) < PORTED for port in expected) and feed.parent == ports[0], R["readings"]) + else: + reading("ported", 1.0) + + section("rebuild") + wing = bpy.data.objects["F.Wing.R"] + uid, mesh_uid = wing.session_uid, wing.data.session_uid + foreign = bpy.data.objects.new("Foreign", None) + bpy.context.scene.collection.objects.link(foreign) + foreign.parent = wing + later = wing.modifiers.new("Hers", "TRIANGULATE") + wing.data.materials.append(bpy.data.materials["gunmetal"]) + AGAIN = copy.deepcopy(TWO) + AGAIN["plates"][0]["slab"]["thick"] = 0.08 + AGAIN["plates"][0]["fits"] = [{"kind": "hose_port", "name": "p", "at": [0.05, 0.0], "lift": 0.01}, {"kind": "mark", "id": "n", "at": [0.0, 0.1], "height": 0.05}] + port_uid = bpy.data.objects["F.Wing.R.port.p"].session_uid + count = len(bpy.data.objects) + receipt, report = send("brokkr_kitbash.plates", host="Thigh", prefix="F.", frame=json.dumps(F.tolist()), table=json.dumps(AGAIN)) + bpy.context.view_layer.update() + check("rebuild-in-place: a second call on the same names reports every plate rebuilt", receipt["status"] == "accepted" and [row["rebuilt"] for row in report["plates"]] == [True, True, True], + [receipt["status"], receipt["message"]]) + _, again_built = proven("the rebuilt plates are the changed table's", AGAIN, 1, "F.", thigh, F, report) + check("rebuild-in-place: the plate is the object it was, on the mesh it had, with her child, her modifier after the Kit Bevel and her second material slot", + bpy.data.objects["F.Wing.R"].session_uid == uid and wing.data.session_uid == mesh_uid and foreign.parent == wing and [m.name for m in wing.modifiers] == ["Kit Bevel", "Hers"] + and [s.material.name for s in wing.material_slots] == ["khaki", "gunmetal"] and len(bpy.data.objects) == count + 2, [m.name for m in wing.modifiers]) + port = bpy.data.objects["F.Wing.R.port.p"] + check("rebuild-in-place: a kept anchor is the empty it was, moved to the row's new place", port.session_uid == port_uid + and reading("moved", np.abs(np.array(port.matrix_basis) - np.array(next(a for a in again_built[0]["anchors"] if a["name"] == "p")["matrix"])).max()) < MOVED, R["readings"]) + BARE = copy.deepcopy(AGAIN) + del BARE["plates"][0]["clad"] + BARE["plates"][0]["fits"] = [{"kind": "mark", "id": "n", "at": [0.0, 0.1], "height": 0.05}] + receipt, report = send("brokkr_kitbash.plates", host="Thigh", prefix="F.", frame=json.dumps(F.tolist()), table=json.dumps(BARE)) + bpy.context.view_layer.update() + proven("a rebuild without clad removes the fit child, and the anchor the row no longer names", BARE, 1, "F.", thigh, F, report) + check("rebuild-in-place: the dropped child and anchor are gone, her child stays, and no mesh is left behind", + "F.Wing.R.fit.steel" not in bpy.data.objects and "F.Wing.R.port.p" not in bpy.data.objects and foreign.parent == wing and "F.Wing.R.fit.steel" not in bpy.data.meshes + and len(bpy.data.objects) == count + 2 - 4, sorted(o.name for o in bpy.data.objects)) + receipt, report = send("brokkr_kitbash.plates", host="Shin", prefix="F.", table=json.dumps(AGAIN)) + bpy.context.view_layer.update() + proven("a rebuild onto another host and frame makes the child and anchor again", AGAIN, 1, "F.", shin, world(shin), report) + check("rebuild-in-place: still the same object", bpy.data.objects["F.Wing.R"].session_uid == uid and wing.parent == shin, None) + + section("refusals") + ONE = doc({"name": "Lump", "mat": "gunmetal", "points": [[0, 0, 0], [0.2, 0, 0], [0, 0.2, 0], [0, 0, 0.2]]}) + CLAD = slab("Guard", [0.0, -0.12, 0.35], ("feed", [0.0, 0.1])) + call = lambda document, **more: {"host": "Thigh", "prefix": "N.", "table": json.dumps(document), **more} # noqa: E731 + refused("a table the format refuses, by its path", call(doc({**ONE["plates"][0], "colour": "red"})), "table: plates[0].colour: unknown key") + refused("a row that bounds no solid", call(doc({"name": "Flat", "mat": "gunmetal", "points": [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]]})), "table: plates[0]") + refused("a table that is not JSON", call(ONE, table="{"), "table is not JSON") + refused("a row material the file lacks", call(doc({**ONE["plates"][0], "mat": "brass"})), "table.plates[0].mat: no material named 'brass'") + refused("a clad material the file lacks", call(doc({**CLAD, "clad": {**CLAD["clad"], "mat": "brass"}})), "table.plates[0].clad.mat: no material named 'brass'") + refused("a bolt material the file lacks", call(doc({**CLAD, "clad": {**CLAD["clad"], "bolt_mat": "brass"}})), "table.plates[0].clad.bolt_mat: no material named 'brass'") + refused("a second row's missing material, after a first row that would be written", call(doc(ONE["plates"][0], {**ONE["plates"][0], "name": "Other", "mat": "brass"})), "table.plates[1].mat") + refused("a host that is not there", call(ONE, host="Hip"), "host: no object named 'Hip'") + scaled = bpy.data.objects.new("Scaled", None) + bpy.context.scene.collection.objects.link(scaled) + scaled.scale = (1.0, 2.0, 1.0) + bpy.context.view_layer.update() + refused("a host that is scaled", call(ONE, host="Scaled"), "'Scaled' is scaled, mirrored or sheared") + eye = np.eye(4) + refused("a frame that is not JSON", call(ONE, frame="[[1, 0"), "frame is not JSON") + refused("a frame of three rows", call(ONE, frame=json.dumps(eye[:3].tolist())), "frame must be a JSON array of 4 rows of 4 finite numbers") + refused("a frame with a number that is not finite", call(ONE, frame=json.dumps(eye.tolist()).replace("1.0", "NaN", 1)), "frame must be a JSON array of 4 rows of 4 finite numbers") + refused("a frame that scales", call(ONE, frame=json.dumps((eye * [2, 1, 1, 1]).tolist())), "frame is not rigid") + refused("a frame that mirrors", call(ONE, frame=json.dumps((eye * [-1, 1, 1, 1]).tolist())), "frame is not rigid") + refused("a frame whose last row is no frame's", call(ONE, frame=json.dumps((eye + np.outer([0, 0, 0, 1], [0.5, 0, 0, 0])).tolist())), "frame is not rigid") + refused("side 0", call(ONE, side=0), "side must be 1 or -1") + refused("a prefix with a character the names do not take", call(ONE, prefix="a-b"), "prefix 'a-b' must be 0 to 32 characters") + refused("a plate's name taken by an object plates did not make", call(ONE, prefix="", table=json.dumps(doc({**ONE["plates"][0], "name": "Shin"}))), "an object named 'Shin' exists and is no plate") + stray = bpy.data.objects.new("N.Guard.fit.olive_light", bpy.data.meshes.new("stray")) + bpy.context.scene.collection.objects.link(stray) + refused("a fit child's name taken, the plate new", call(doc(CLAD)), "an object named 'N.Guard.fit.olive_light' exists and is not this plate's") + stray.name = "Thigh.Guard.port.spare" + spare = copy.deepcopy(THIGH) + spare["plates"][0]["fits"].append({"kind": "hose_port", "name": "spare", "at": [0.05, 0.0]}) + refused("an anchor's name taken by an object that is no child of the plate, on a rebuild", call(spare, prefix="Thigh."), "an object named 'Thigh.Guard.port.spare' exists and is not this plate's") + refused("a row whose name is another row's fit child", call(doc(CLAD, {**ONE["plates"][0], "name": "Guard.fit.gunmetal"})), "the name 'N.Guard.fit.gunmetal' is made twice") + refused("a made name over 63 bytes", call(doc({**CLAD, "name": "G" * 40}), prefix="P" * 20), "bytes, over the 63 an object's name holds") + refused("a host that is the plate", call(THIGH, host="Thigh.Guard", prefix="Thigh."), "a plate is no host of itself") + refused("a host under the plate", call(THIGH, host="Thigh.Guard.port.feed", prefix="Thigh."), "a plate is no host of itself") + many = doc(*[{"name": f"a{index:03d}", "mat": "gunmetal", "points": [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]]} for index in range(256)]) + refused("a report a receipt does not carry", call(many, table=json.dumps(many, separators=(",", ":"))), "over the 16000 a receipt carries") + twin = bpy.data.objects.new("Twin", guard.data) + bpy.context.scene.collection.objects.link(twin) + refused("a plate that shares its mesh", call(THIGH, prefix="Thigh."), "'Thigh.Guard' shares its mesh") + bpy.data.objects.remove(twin) + receipt, _ = send("brokkr_kitbash.freeze", object_name="Thigh.Guard") + refused("a frozen plate", call(THIGH, prefix="Thigh."), "'Thigh.Guard' is frozen") + send("brokkr_kitbash.thaw", object_name="Thigh.Guard") + receipt, report = send("brokkr_kitbash.plates", host="Thigh", prefix="Thigh.", table=json.dumps(THIGH)) + bpy.context.view_layer.update() + check("thawed, the plate is rebuilt", receipt["status"] == "accepted" and report["plates"][0]["rebuilt"], [receipt["status"], receipt["message"]]) + proven("the thawed plate", THIGH, 1, "Thigh.", thigh, world(thigh), report) +except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file + check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:]) +finally: + R["ok"] = all(c["ok"] for c in R["checks"]) + R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} + Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") + for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) + print("READINGS", R["readings"], flush=True) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/kitbash_plates.result.json b/surfaces/blender/tests/live/kitbash_plates.result.json new file mode 100644 index 0000000..73d80c8 --- /dev/null +++ b/surfaces/blender/tests/live/kitbash_plates.result.json @@ -0,0 +1,347 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "plates on the thigh are accepted and none is a rebuild", + "ok": true, + "detail": null + }, + { + "name": "written-is-built: a plate on the thigh, the frame the host's", + "ok": true, + "detail": null + }, + { + "name": "written-is-built: a plate on the shin, under the pin", + "ok": true, + "detail": null + }, + { + "name": "a plate with a panel and its bolts has two fit children and two anchors, and the panel's child alone a bevel", + "ok": true, + "detail": null + }, + { + "name": "roll-carries: joints lists the same rows with the plates as without", + "ok": true, + "detail": null + }, + { + "name": "a plate is no kit part: report lists the two struts", + "ok": true, + "detail": null + }, + { + "name": "plates under a stated frame are accepted at side 1", + "ok": true, + "detail": null + }, + { + "name": "written-is-built: a two-sided row and a bare one under a stated frame, side 1: panels and bolts of one material are one child", + "ok": true, + "detail": null + }, + { + "name": "plates under a stated frame are accepted at side -1", + "ok": true, + "detail": null + }, + { + "name": "written-is-built: a two-sided row and a bare one under a stated frame, side -1: panels and bolts of one material are one child", + "ok": true, + "detail": null + }, + { + "name": "a bare plate has no child and no bevel; a two-sided row is two plates", + "ok": true, + "detail": null + }, + { + "name": "written-is-built: no host and no frame: the table's frame is the world", + "ok": true, + "detail": null + }, + { + "name": "the roll moved the shin", + "ok": true, + "detail": null + }, + { + "name": "roll-carries: every plate, fit child and anchor on the shin stands at the roll @ where it stood", + "ok": true, + "detail": null + }, + { + "name": "what stands on the thigh or on nothing stayed", + "ok": true, + "detail": null + }, + { + "name": "hose-between-ports: a hose routes between the two plates' port empties through the pin point, clear across the pin's range", + "ok": true, + "detail": null + }, + { + "name": "hose-between-ports: each end stands on its port, as plate.build places it on the panel's top, and leaves along its z", + "ok": true, + "detail": null + }, + { + "name": "rebuild-in-place: a second call on the same names reports every plate rebuilt", + "ok": true, + "detail": null + }, + { + "name": "written-is-built: the rebuilt plates are the changed table's", + "ok": true, + "detail": null + }, + { + "name": "rebuild-in-place: the plate is the object it was, on the mesh it had, with her child, her modifier after the Kit Bevel and her second material slot", + "ok": true, + "detail": null + }, + { + "name": "rebuild-in-place: a kept anchor is the empty it was, moved to the row's new place", + "ok": true, + "detail": null + }, + { + "name": "written-is-built: a rebuild without clad removes the fit child, and the anchor the row no longer names", + "ok": true, + "detail": null + }, + { + "name": "rebuild-in-place: the dropped child and anchor are gone, her child stays, and no mesh is left behind", + "ok": true, + "detail": null + }, + { + "name": "written-is-built: a rebuild onto another host and frame makes the child and anchor again", + "ok": true, + "detail": null + }, + { + "name": "rebuild-in-place: still the same object", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a table the format refuses, by its path", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a row that bounds no solid", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a table that is not JSON", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a row material the file lacks", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a clad material the file lacks", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a bolt material the file lacks", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a second row's missing material, after a first row that would be written", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a host that is not there", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a host that is scaled", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a frame that is not JSON", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a frame of three rows", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a frame with a number that is not finite", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a frame that scales", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a frame that mirrors", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a frame whose last row is no frame's", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: side 0", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a prefix with a character the names do not take", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a plate's name taken by an object plates did not make", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a fit child's name taken, the plate new", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: an anchor's name taken by an object that is no child of the plate, on a rebuild", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a row whose name is another row's fit child", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a made name over 63 bytes", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a host that is the plate", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a host under the plate", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a report a receipt does not carry", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a plate that shares its mesh", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a frozen plate", + "ok": true, + "detail": null + }, + { + "name": "thawed, the plate is rebuilt", + "ok": true, + "detail": null + }, + { + "name": "written-is-built: the thawed plate", + "ok": true, + "detail": null + } + ], + "hostErrors": [], + "readings": { + "anchored": 2.2e-07, + "carried": 1e-07, + "moved": 2.1e-07, + "ported": 3.9e-08, + "written": 8.5e-08 + }, + "reports": { + "thigh": { + "plates": [ + { + "name": "Thigh.Guard", + "rebuilt": false, + "corners": 16, + "facets": 10, + "panels": 1, + "bolts": 8, + "anchors": [ + "Thigh.Guard.port.feed", + "Thigh.Guard.mark.num" + ] + } + ], + "host": "Thigh", + "side": 1 + }, + "hose": { + "object": "Feed", + "rebuilt": false, + "hoses": 1, + "length": 0.834382, + "lengthChange": 0.002158, + "floor": 0.048, + "clearance": 0.042341, + "capped": 0.121, + "voxels": [ + 42560, + 36456 + ], + "seed": { + "step": 0.02, + "offset": [ + 0.0, + 0.0, + 0.0 + ], + "refined": false + }, + "sag": [ + 0.007788, + 0.003557 + ], + "rolls": 9, + "worstRoll": -20.0, + "worstClearance": 0.043363, + "faces": 1078, + "volume": 0.000105174, + "nonManifoldEdges": 0, + "radii": { + "least": 0.056641, + "corners": [ + 0.071927, + 1.931459, + 0.258593, + 3.432944, + 0.056641 + ] + } + } + }, + "ok": true +} \ No newline at end of file From 679062ca9a8c352e6e2d5a3899468be8a33a38d7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 16:29:16 +0100 Subject: [PATCH 216/223] brokkr_kitbash: a loop with a second driver is told by every read of it: follows.holds false, and the joints report's manyDrivers Which joints are a loop's drivers is read in one place, loop_drivers. one_driver refuses a write by it; follows_report and the joints report read the scene as it stands by it, so a second driver no action wrote (limits widened by hand, a saved file) reads holds false on both followers, naming both drivers, and is listed as {loop, drivers} in manyDrivers beside unlimited and rigid. Finding two-driver-loop-reported-nowhere. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 82 +++++++++++++------ .../brokkr_kitbash/brokkr_actions.json | 2 +- surfaces/blender/docs/kitbash.md | 19 +++-- .../blender/tests/live/kitbash_follows.py | 21 ++++- .../tests/live/kitbash_follows.result.json | 15 ++++ surfaces/blender/tests/test_kitbash.py | 10 +++ 6 files changed, 118 insertions(+), 31 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 6b16ba1..94ae606 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -442,6 +442,45 @@ def followers(driver) -> list: key=lambda o: o.name) +def loop_drivers(closing, parent=None, joint=None): + """What the two ends of the loop `closing` closes depend on beside its driver: (driver, (the base, the part + closed on), {another driver: why}), or None for a loop that is derived by nothing (its driver is gone or states + no DOF connection, it closes on nothing, or its parent does not follow with it). Each revolute or prismatic + joint between an end and the nearest part both ends hang from (or the root, when they share none) is the + driver, follows it, or is held by limits of one value; one that follows another driver, or follows nothing and + has travel, is another driver. A joint both ends hang from moves them together and is not counted. The one + reading of the rule: one_driver refuses a write by it, reading the scene as the write would leave it (`parent` + and `joint` are then its own), and a report reads the scene as it stands (follows_report, the joints + report's manyDrivers), so a loop with a second driver that no write made is told by every read of it.""" + if parent is None: + def parent(o): + return o.parent + if joint is None: + def joint(o): + kind = connection_kind(o)[0] + record = joint_record(o) if kind is not None else None + return (kind, record["limits"], record["follows"]) if kind is not None else (None, None, None) + follows, upper, to = joint(closing)[2], parent(closing), closure(closing)[1] + driver = follows["driver"] if follows is not None and follows["kind"] == "loop" else None + if driver is None or to is None or upper is None or parent(upper) is None or joint(driver)[0] is None or joint(upper)[2] != follows: + return None + ends, chains = (parent(upper), to), [[], []] # each end and what it hangs from, up to the root + for found, o in zip(chains, ends): + while o is not None: + found.append(o) + o = parent(o) + others = {} # {a part whose pose moves one end against the other, and is not the driver: why} + for o in (o for found in chains for o in found if not (o in chains[0] and o in chains[1])): + kind, limits, its = joint(o) + if kind is None or o == driver or its is not None and its["driver"] in (None, driver): + continue + if its is not None: + others.setdefault(its["driver"], f"{o.name!r} follows it") + elif limits is None or limits[0] < limits[1]: # limits of one value hold a joint still + others.setdefault(o, "it follows nothing and its joint has travel, so it is posed by hand") + return driver, ends, dict(sorted(others.items(), key=lambda item: item[0].name)) + + def one_driver(stating: dict) -> None: """The one-driver rule, over each loop a write touches, as it would stand after the write: the driver of a loop is the only input its two ends (the parent follower's parent, and the part closed on) depend on. `stating` is @@ -460,7 +499,8 @@ def one_driver(stating: dict) -> None: and set_params before it rebuilds a mesh), detach and parent_refusal (Brokkr's setObjectParent) ask here before they write, so no action (attach, detach, clearing a follower, limits widened or cleared, any pose, a new follow, set_params, a new parent) gives a loop a second driver, and a loop edited by hand into one is - refused the next write that touches it.""" + refused the next write that touches it. Which joints are drivers is loop_drivers' reading, the one the reports + take of the scene as it stands.""" known, kits, hangs = {}, {}, {} # each part's joint and each kit file are read once; hangs: {part: whether it, or a part it hangs from, is in stating} def parent(o): @@ -488,27 +528,10 @@ def one_driver(stating: dict) -> None: for closing in sorted((o for o in bpy.data.objects if CLOSE in o and (FOLLOWS in o or o in stating)), key=lambda o: o.name): if not (touched(closing) or touched(closing.get(CLOSE_TO)) or touched(closing.get(FOLLOWS_DRIVER))) or not closing.users_collection: continue # this write changes nothing the loop's ends depend on (the pointers are read as stored: users_collection searches the scene, so it is asked of a touched loop alone) - follows, upper, to = joint(closing)[2], parent(closing), closure(closing)[1] - driver = follows["driver"] if follows is not None and follows["kind"] == "loop" else None - if driver is None or to is None or upper is None or parent(upper) is None or joint(driver)[0] is None or joint(upper)[2] != follows: - continue - ends, chains = (parent(upper), to), [[], []] # each end and what it hangs from, up to the root - for found, o in zip(chains, ends): - while o is not None: - found.append(o) - o = parent(o) - others = {} # {a part whose pose moves one end against the other, and is not the driver: why} - for o in (o for found in chains for o in found if not (o in chains[0] and o in chains[1])): - kind, limits, its = joint(o) - if kind is None or o == driver or its is not None and its["driver"] in (None, driver): - continue - if its is not None: - others.setdefault(its["driver"], f"{o.name!r} follows it") - elif limits is None or limits[0] < limits[1]: # limits of one value hold a joint still - others.setdefault(o, "it follows nothing and its joint has travel, so it is posed by hand") + driver, ends, others = loop_drivers(closing, parent, joint) or (None, None, None) if others: raise Refused(f"the two ends of the loop {closing.name!r} closes, {ends[0].name!r} (the base) and {ends[1].name!r} (closed on), depend on more than one driver: {driver.name!r} and " - f"{', '.join(f'{o.name!r} ({why})' for o, why in sorted(others.items(), key=lambda item: item[0].name))}. A follower takes its value from " + f"{', '.join(f'{o.name!r} ({why})' for o, why in others.items())}. A follower takes its value from " "one driver, and a pose of another would open the loop: every joint between the two ends is the driver, follows it, or is held by " f"limits of one value. Give it that first, or clear the loop (brokkr_kitbash.follow on {closing.name!r} with record null); nothing changed.") @@ -652,8 +675,10 @@ def driven(driver, sockets, stated, roll: float, slide: float, record, stating=N def follows_report(obj, record: dict, kind, stated) -> dict | None: """None for a connection that follows nothing, else {driver, kind, k, offset, holds, reason}. A ratio holds when - the value stands within HELD of k x the driver's + offset (a roll: of a turn of it); a loop when the closure its - closing part states holds. holds is false with a reason when the driver is gone or states no DOF connection. + the value stands within HELD of k x the driver's + offset (a roll: of a turn of it); a loop when its two ends + depend on its one driver (loop_drivers) and the closure its closing part states holds: a loop with a second + driver (limits widened by hand, a saved file) reads false and names each, whether or not the closure stands + closed, since a pose of the other would open it. holds is false with a reason when the driver is gone or states no DOF connection. Derived at each report; stored nowhere.""" follows = record["follows"] if follows is None: @@ -673,8 +698,12 @@ def follows_report(obj, record: dict, kind, stated) -> dict | None: else: pair = loop_pair(obj) found = closure_report(pair[1], *built_part(pair[1])) if pair is not None else None + others = (loop_drivers(pair[1]) or (None, None, {}))[2] if pair is not None else {} if found is None: row["reason"] = "its loop has no partner: a closing part and its parent, both following the driver" + elif others: + row["reason"] = (f"the loop {pair[1].name!r} closes has more than one driver: {driver.name!r} and {', '.join(f'{o.name!r} ({why})' for o, why in others.items())}. " + "Hold that joint by limits of one value, have it follow the driver, or clear the loop (brokkr_kitbash.follow with record null)") elif not found["holds"]: row["reason"] = f"the closure {pair[1].name!r} states does not hold ({found['reason']}): pose the driver" row["holds"] = row["reason"] is None @@ -1317,11 +1346,12 @@ class BROKKR_KITBASH_OT_joints(PolishOperator): @kit_work def work(self, context): - root, kits, entries = mesh_object(self.object_name), {}, [] + root, kits, entries, tree = mesh_object(self.object_name), {}, [], set() built_part(root, kits) todo = [root] while todo: # depth first, children by name: the order core.joint_rows reads a joint's parent joint in child = todo.pop() + tree.add(child) if child != root or link(child) is not None and child.parent is not None and PART in child.parent: # the root's own joint comes first, parent null part, built = built_part(child, kits) stated = link(child) @@ -1337,7 +1367,11 @@ class BROKKR_KITBASH_OT_joints(PolishOperator): rows, rigid_count = core.joint_rows(np.array(root.matrix_world, dtype=np.float64), entries) ids = [row["id"] for row in rows] report = {"schema": "brokkr.joints", "version": 2, "root": root.name, "frame": "the root object's: Blender axes (+Z up), metres", "rigid": rigid_count, - "unlimited": [], "next": max(ids, key=lambda name: len(json.dumps(name)), default=None)} + "unlimited": [], "manyDrivers": [], "next": max(ids, key=lambda name: len(json.dumps(name)), default=None)} + for closing in sorted((o for o in bpy.data.objects if CLOSE in o and FOLLOWS in o and o.users_collection), key=lambda o: o.name): + driver, ends, others = loop_drivers(closing) or (None, None, None) # of the whole tree, as rigid is: every page carries it + if others and tree & {closing, closing.parent, driver, *ends, *others}: + report["manyDrivers"].append({"loop": closing.name, "drivers": [driver.name, *(o.name for o in others)]}) if self.after: if self.after not in ids: raise Refused(f"after {self.after!r} is not the id of a joint under {root.name!r}: it is the `next` of the report before, or empty.") diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 8a2f11c..fd8bf94 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -360,7 +360,7 @@ }, { "name": "brokkr_kitbash.joints", - "doc": "The joints of the tree of kit parts attached under a root part, as {schema: brokkr.joints, version: 2, root, frame, rigid, unlimited, next, joints}. A row per revolute or prismatic connection, depth first with children by name, so a joint's parent row comes before it; a root that itself states a revolute or prismatic connection has its own row first, parent null: id (the child object), parent (the id of the nearest joint above, or null: rigid connections fold into it and are counted in rigid), part, socket ('Object:socket', the parent socket), kind, axis and origin (that socket's z and origin in the root object's frame: Blender axes, +Z up, metres), value (the roll in degrees or the slide in metres now), limits ([lo, hi] or null), min and max (the limits less the value: the travel either way from this pose), held (true when the limits are of one value: the joint has no travel, as a torque link's lug held at [90, 90], so a rig makes a fixed bone and not a DOF; such a row is in neither unlimited nor rigid), mechanism, compliance and driven (null, or {by: the driver's id, kind: ratio | loop, k, offset}: the value is derived from the driver's, so a rig makes a driven bone and not a DOF). kind is revolute or prismatic: Aetheria's ShipJoint calls them rotate and slide, one to one. unlimited lists the ids of the rows this report carries that are not driven and state no limits: an exporter that needs limits refuses by this one field of each report. Axis, origin and order are derived at each report from the kits and the parent tree; nothing stores them. Rows a receipt cannot carry are counted in jointsOmitted, and next is then the id of the last row carried (else null): call again with after set to it for the rows that follow and their unlimited ids; a report is never over a receipt and always carries a row. after refuses an id that is no row's. Refuses a connection that cannot be read. Evaluates no modifier.", + "doc": "The joints of the tree of kit parts attached under a root part, as {schema: brokkr.joints, version: 2, root, frame, rigid, unlimited, manyDrivers, next, joints}. A row per revolute or prismatic connection, depth first with children by name, so a joint's parent row comes before it; a root that itself states a revolute or prismatic connection has its own row first, parent null: id (the child object), parent (the id of the nearest joint above, or null: rigid connections fold into it and are counted in rigid), part, socket ('Object:socket', the parent socket), kind, axis and origin (that socket's z and origin in the root object's frame: Blender axes, +Z up, metres), value (the roll in degrees or the slide in metres now), limits ([lo, hi] or null), min and max (the limits less the value: the travel either way from this pose), held (true when the limits are of one value: the joint has no travel, as a torque link's lug held at [90, 90], so a rig makes a fixed bone and not a DOF; such a row is in neither unlimited nor rigid), mechanism, compliance and driven (null, or {by: the driver's id, kind: ratio | loop, k, offset}: the value is derived from the driver's, so a rig makes a driven bone and not a DOF). kind is revolute or prismatic: Aetheria's ShipJoint calls them rotate and slide, one to one. unlimited lists the ids of the rows this report carries that are not driven and state no limits: an exporter that needs limits refuses by this one field of each report. manyDrivers lists each loop with more than one driver that has a part in the tree (a limit widened by hand, a saved file: no action writes one), as {loop: the closing part, drivers: [the loop's driver, each other one]}: its driven rows are not a function of one driver, so a rig refuses the tree while the list is not empty; it is of the whole tree and every page carries it. Axis, origin and order are derived at each report from the kits and the parent tree; nothing stores them. Rows a receipt cannot carry are counted in jointsOmitted, and next is then the id of the last row carried (else null): call again with after set to it for the rows that follow and their unlimited ids; a report is never over a receipt and always carries a row. after refuses an id that is no row's. Refuses a connection that cannot be read. Evaluates no modifier.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index fe94903..0e587bf 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -267,8 +267,13 @@ every write that touches it (a write of a connection, a `set_params` or a `setOb or of a part it hangs from, whether or not that write is the fault) until the joint is held again, follows the driver, or the loop is cleared. A write that touches no such loop is made: a camera, an empty or a part of another mechanism is posed and given a parent as before, and so is an object parented under a part of the loop. A connection's row in a report carries `follows: {driver, kind, k, offset, holds, reason}`: -`holds` is false, with a reason, when the value stands off the ratio, the loop's closure does not hold, or the -driver is gone or states no revolute or prismatic connection. Detaching a driver leaves its followers' +`holds` is false, with a reason, when the value stands off the ratio, the loop has more than one driver, the loop's +closure does not hold, or the driver is gone or states no revolute or prismatic connection. A loop with a second +driver reads `holds: false` on both its followers whether or not its closure stands closed, and the reason names +the loop, its driver and each other one: the remedy is to hold that joint, have it follow the driver or clear the +loop, not to pose the driver. The joints report lists the same loops in `manyDrivers`. Both read the scene as it +stands by the reading the refusals use, so a second driver that no action wrote is told by the next report and +not first by a refused write. Detaching a driver leaves its followers' statements; detaching a loop follower clears its partner's. No Blender driver or constraint is made: a follower's pose is its stored value, as every connection's is. @@ -284,7 +289,7 @@ nothing: ```json {"schema": "brokkr.joints", "version": 2, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres", - "rigid": 2, "unlimited": ["Barrel"], "next": null, "joints": [ + "rigid": 2, "unlimited": ["Barrel"], "manyDrivers": [], "next": null, "joints": [ {"id": "Strut", "parent": null, "part": "strut", "socket": "Mount:pivot", "kind": "revolute", "axis": [0.0, 1.0, 0.0], "origin": [0.436, 0.0, 0.85368], "value": -113.019997, "limits": [-116.02, -40.02], "min": -3.000003, "max": 72.999997, "mechanism": "knee", "compliance": null, "held": false, "driven": null}, @@ -311,7 +316,11 @@ alone and is not the free `mechanism` label: a joint labelled `"held"` that has (`by` the driver's id, `kind`, `k`, `offset`): a driven row's value is derived, so the rig generator will make a driven bone for it and not a degree of freedom. `unlimited` lists the ids of the rows this report carries that are not driven and state no limits, so an exporter that needs limits on every degree of freedom refuses by reading one field of each -report. A tree whose rows a receipt cannot carry (about 60 rows, 33 with names of 62 characters) is read in pages: +report. `manyDrivers` lists each loop with more than one driver that has a part in the tree under the root (its +closing part, that part's parent, the part closed on, the base, or one of its drivers), as +`{"loop": the closing part, "drivers": [the loop's driver, each other one]}` by the closing part's name: its +driven rows are not a function of one driver, so a rig generator refuses the tree while the list is not empty. It +is of the whole tree, as `rigid` is, and every page carries it. A tree whose rows a receipt cannot carry (about 60 rows, 33 with names of 62 characters) is read in pages: `jointsOmitted` counts the rows left off, `next` is then the id of the last row carried, and a call with `after` set to it carries the rows that follow, with their own `unlimited`. A row and its id in `unlimited` are kept or left off together, so a report is never over a receipt and always carries a row. @@ -1362,7 +1371,7 @@ under such load (five runs), and reading a 336-face part takes 27 to 37 ms. | `brokkr_kitbash.reach` | `object_name`, `socket` (one of the part's), `height` (metres, -1000 to 1000), `direction_x`, `direction_y`, `direction_z` (world; default 0, 0, 1) | Solves the roll that brings the socket's origin to `height` along the direction, the nearer of the two, and turns the part to it. Refuses a height out of reach, naming the range. Reports the part, `reached: {roll, residual}` and `closures`. | | `brokkr_kitbash.joint` | `object_name`, `record` (a JSON object of any of `limits`: `[lo, hi]` or null; `mechanism`: a label or null; `compliance`: `{hertz, damping_ratio}` or null) | States the joint record of an attached part's connection; a key left out keeps what is stated and null clears it. A follower keeps its derived value, and a driver's followers are derived again. Refuses a rigid connection naming its socket type, limits that do not hold the value the joint has, revolute limits over a turn or past 360, prismatic limits past 10 m, and compliance on a revolute joint or without limits. Reports the part and `closures` as `roll` does | | `brokkr_kitbash.slide` | `object_name`, `slide` (metres, -10 to 10) | Slides an attached part along its parent socket's normal on a prismatic connection, where it hangs, and every follower of it with it. Refuses a revolute or rigid connection naming its socket type, a slide outside the joint's limits, and a follower. Reports the part and `closures` as `roll` does | -| `brokkr_kitbash.joints` | `object_name` (the root, a kit part), `after` (default empty: an id, the `next` of the report before) | Reports the joints of the tree attached under the root as `brokkr.joints` version 2: a row per revolute or prismatic connection, parents first and the root's own first when it states one, with `id`, `parent`, `part`, `socket`, `kind`, `axis`, `origin`, `value`, `limits`, `min`, `max`, `held`, `mechanism`, `compliance` and `driven`, in the root's frame, and `unlimited` and `next` beside them ("Joint records"). With `after`, the rows after that id. Changes nothing and evaluates no modifier. | +| `brokkr_kitbash.joints` | `object_name` (the root, a kit part), `after` (default empty: an id, the `next` of the report before) | Reports the joints of the tree attached under the root as `brokkr.joints` version 2: a row per revolute or prismatic connection, parents first and the root's own first when it states one, with `id`, `parent`, `part`, `socket`, `kind`, `axis`, `origin`, `value`, `limits`, `min`, `max`, `held`, `mechanism`, `compliance` and `driven`, in the root's frame, and `unlimited`, `manyDrivers` (the loops with more than one driver) and `next` beside them ("Joint records"). With `after`, the rows after that id. Changes nothing and evaluates no modifier. | | `brokkr_kitbash.follow` | `object_name` (the follower; for a loop, the part that states the closure), `record` (JSON: `{driver, kind: "ratio", k, offset}`, `{driver, kind: "loop"}` or null) | States that the part's joint follows the driver's, by a ratio or by keeping its closure closed with its parent's joint, and moves it there at once; null clears the statement, and a loop partner's with it ("Followers"). Refuses a rigid connection, a driver that is the follower, below it or itself a follower, a follower that already follows or drives another, a ratio whose driver states no limits, and a loop without a closure that holds, with both ends or neither moving with the driver, whose ends depend on another driver or on a joint posed by hand, that is not planar or that stands at a dead centre. Reports the part, `followers` and `closures`. | | `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. | | `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added; `booleansOmitted` counts rows a receipt had no room for) and `evaluated`. | diff --git a/surfaces/blender/tests/live/kitbash_follows.py b/surfaces/blender/tests/live/kitbash_follows.py index a574528..bd86bb8 100644 --- a/surfaces/blender/tests/live/kitbash_follows.py +++ b/surfaces/blender/tests/live/kitbash_follows.py @@ -18,7 +18,7 @@ barrel, so a lug with no travel is the mechanism and not a way around the kit; a two arms from the barrel's pin cannot face the rod's own); a second crank (Crank2 on the root Ground2) whose ram closes on the rocker, and a loop hung from its own driver (K3, B3, Rk3, Cp3 on the root G3), for the one-driver refusals at the statement, and after it an attach, a clear, widened limits, a pose over limits written by hand and a -detach that would each give a stated loop a second driver; Idle and Tip for the refusals and for the writes a two-driver loop does not refuse; a tree of 264 struts with 62-character names for a joints +detach that would each give a stated loop a second driver, and the reads that tell of one made by hand (follows.holds, the joints report's manyDrivers); Idle and Tip for the refusals and for the writes a two-driver loop does not refuse; a tree of 264 struts with 62-character names for a joints report over several receipts. Bounds follow lodur:ruling:deterministic-bound-margin, both readings beside each; the result file carries the readings. """ @@ -472,6 +472,20 @@ try: refused("a pose of the driver after the lug's limits were widened by hand: the writer reads the rule before it writes", "brokkr_kitbash.slide", {"object_name": "T_Rod", "slide": 0.1}, "depend on more than one driver: 'T_Rod' and 'T_Lug' (it follows nothing and its joint has travel") refused("and a pose of the lug itself", "brokkr_kitbash.roll", {"object_name": "T_Lug", "roll": 95.0}, "depend on more than one driver: 'T_Rod' and 'T_Lug'") + # a second driver no write made is told by every read of the loop, while its closure still stands closed (finding two-driver-loop-reported-nowhere): + # each follower's follows row reads holds false and names both drivers, and the joints report of a tree the loop is in lists the loop by its closing part + told = "the loop 'T_Lower' closes has more than one driver: 'T_Rod' and 'T_Lug' (it follows nothing and its joint has travel, so it is posed by hand)" + rows = {name: send("brokkr_kitbash.report", object_name=name)[1]["parts"][0] for name in ("T_Upper", "T_Lower")} + check("a loop given a second driver by hand reads follows.holds false on both followers, naming both drivers, while its closure holds", + all(row["connection"]["follows"]["holds"] is False and row["connection"]["follows"]["reason"].startswith(told) for row in rows.values()) + and rows["T_Lower"]["closure"]["holds"] is True, [{name: row["connection"] for name, row in rows.items()}, rows["T_Lower"]["closure"]]) + receipt, joints = send("brokkr_kitbash.joints", object_name="T_Barrel") + receipt2, joints2 = send("brokkr_kitbash.joints", object_name="T_Lug") + receipt3, joints3 = send("brokkr_kitbash.joints", object_name="Ground") + check("the joints report lists a loop with a second driver in manyDrivers, by its closing part and with both drivers: in a report of the whole mechanism, " + "in one of the second driver's own sub-tree, and not in one of a tree the loop is no part of", + all(r["status"] == "accepted" for r in (receipt, receipt2, receipt3)) and joints["manyDrivers"] == [{"loop": "T_Lower", "drivers": ["T_Rod", "T_Lug"]}] == joints2["manyDrivers"] + and joints3["manyDrivers"] == [], [receipt["message"], joints and joints.get("manyDrivers"), joints2 and joints2.get("manyDrivers"), joints3 and joints3.get("manyDrivers")]) # the rule judges the write, not the scene: with the torque link holding a second driver, a write is refused when it touches that loop (a part of it, # or one it hangs from) or would give another loop a second driver, and every other write is made (finding parent-hook-gates-on-scene-not-change) shape = lambda *names: {name: np.array([v.co[:] for v in bpy.data.objects[name].data.vertices]).tobytes() for name in names} # noqa: E731 @@ -527,6 +541,11 @@ try: t_lug["kit_min"], t_lug["kit_max"] = 90.0, 90.0 receipt, report = send("brokkr_kitbash.slide", object_name="T_Rod", slide=0.11) check("with the lug held again the driver is posed", receipt["status"] == "accepted" and report["closures"][0]["holds"] is True, receipt["message"]) + receipt, report = send("brokkr_kitbash.report", object_name="T_Lower") + receipt2, joints = send("brokkr_kitbash.joints", object_name="T_Barrel") + check("and with one driver again the follower's follows row holds and the joints report lists no loop", + receipt["status"] == "accepted" and receipt2["status"] == "accepted" and report["parts"][0]["connection"]["follows"] == {"driver": "T_Rod", "kind": "loop", "k": None, "offset": None, "holds": True, "reason": None} + and joints["manyDrivers"] == [], [receipt["message"], report and report["parts"][0]["connection"], joints and joints.get("manyDrivers")]) receipt, joints = send("brokkr_kitbash.joints", object_name="T_Barrel") check("the torque link has one degree of freedom: the rod's slide is its one row with travel that nothing drives, the lug is its one held row, the arms are driven, and no row is unlimited", receipt["status"] == "accepted" and [(row["id"], row["kind"], row["driven"] and row["driven"]["by"], row["min"], row["max"], row["held"]) for row in joints["joints"]] == [ diff --git a/surfaces/blender/tests/live/kitbash_follows.result.json b/surfaces/blender/tests/live/kitbash_follows.result.json index 6b6bdea..c285ef5 100644 --- a/surfaces/blender/tests/live/kitbash_follows.result.json +++ b/surfaces/blender/tests/live/kitbash_follows.result.json @@ -321,6 +321,16 @@ "ok": true, "detail": null }, + { + "name": "a loop given a second driver by hand reads follows.holds false on both followers, naming both drivers, while its closure holds", + "ok": true, + "detail": null + }, + { + "name": "the joints report lists a loop with a second driver in manyDrivers, by its closing part and with both drivers: in a report of the whole mechanism, in one of the second driver's own sub-tree, and not in one of a tree the loop is no part of", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: set_params of the part a two-driver loop closes on (finding set-params-writes-before-the-guard): the rule is read before the mesh is rebuilt", "ok": true, @@ -371,6 +381,11 @@ "ok": true, "detail": null }, + { + "name": "and with one driver again the follower's follows row holds and the joints report lists no loop", + "ok": true, + "detail": null + }, { "name": "the torque link has one degree of freedom: the rod's slide is its one row with travel that nothing drives, the lug is its one held row, the arms are driven, and no row is unlimited", "ok": true, diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index b73e2f2..7507714 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -2550,6 +2550,16 @@ class OwnershipTests(unittest.TestCase): # clear, widened limits, a pose, a set_params, a detach and a new parent after the loop is stated are each refused) rule = source.split("\ndef one_driver(")[1].split("\n\n\n")[0] self.assertEqual((source.count("one_driver("), source.count("depend on more than one driver")), (4, 1)) + # which joints are a loop's drivers is read in one place, loop_drivers: the rule refuses by it and the reads tell by it (finding + # two-driver-loop-reported-nowhere), so a second driver no write made is in a follower's follows row and the joints report's manyDrivers + # (live: 'a loop given a second driver by hand reads follows.holds false' and 'the joints report lists a loop with a second driver') + self.assertEqual((source.count("loop_drivers("), source.count("it follows nothing and its joint has travel"), rule.count("loop_drivers(closing, parent, joint)")), (4, 1, 1)) + teller = source.split("\ndef follows_report(")[1].split("\n\n\n")[0] + self.assertLess(teller.index("loop_drivers(pair[1])"), teller.index("elif others:")) + self.assertLess(teller.index("elif others:"), teller.index('elif not found["holds"]:')) # a second driver is told before an open closure: 'pose the driver' is not its remedy + joints = source.split("class BROKKR_KITBASH_OT_joints(")[1].split("class BROKKR_KITBASH_OT_")[0] + self.assertIn('report["manyDrivers"].append({"loop": closing.name, "drivers": [driver.name, *(o.name for o in others)]})', joints) + self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|\w+\[[A-Z_]+\]\s*=(?!=)|\bdel ", source.split("\ndef loop_drivers(")[1].split("\n\n\n")[0])) asker = source.split("\ndef brokkr_parent_refusal(")[1].split("\n\n\n")[0] self.assertIn("one_driver({obj: (parent, kind,", asker) self.assertIsNone(re.search(r"\.parent\s*=(?!=)|\bseat\(|\w+\[\w+\]\s*=(?!=)|\bdel ", asker + asked)) From 351918a8a2ce7b323f0caf04dcaf72fe278fa409 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 16:48:04 +0100 Subject: [PATCH 217/223] live: kitbash_pose pins the joints report's key set with manyDrivers; its result file from this run Finding kitbash-pose-pins-joints-keys. The pin stays an exact set. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/kitbash_pose.py | 2 +- surfaces/blender/tests/live/kitbash_pose.result.json | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/surfaces/blender/tests/live/kitbash_pose.py b/surfaces/blender/tests/live/kitbash_pose.py index 82130d8..1db1680 100644 --- a/surfaces/blender/tests/live/kitbash_pose.py +++ b/surfaces/blender/tests/live/kitbash_pose.py @@ -446,7 +446,7 @@ try: table = {row["id"]: row for row in (joints or {}).get("joints", [])} check("joints reports the tree under the tank: schema, the root's frame, a row per DOF connection depth first with children by name, parents first, rigid ones counted", receipt["status"] == "accepted" and {k: v for k, v in joints.items() if k != "joints"} == {"schema": "brokkr.joints", "version": 2, "root": "Tank", "frame": "the root object's: Blender axes (+Z up), metres", "rigid": 2, - "unlimited": ["Barrel", "Toe", "Ram"], "next": None} + "unlimited": ["Barrel", "Toe", "Ram"], "manyDrivers": [], "next": None} and [row["id"] for row in joints["joints"]] == ["Strut", "Barrel", "Rod", "Hinge", "Toe", "Ram"], [receipt["message"], joints]) check("a joint's parent is the nearest DOF connection above it, not the object it hangs from: the toe's is the hinge, through the rigid foot; the rod's is the barrel", {name: row["parent"] for name, row in table.items()} == {"Strut": None, "Barrel": "Strut", "Rod": "Barrel", "Hinge": "Strut", "Toe": "Hinge", "Ram": "Strut"} and toe.parent == foot, diff --git a/surfaces/blender/tests/live/kitbash_pose.result.json b/surfaces/blender/tests/live/kitbash_pose.result.json index 50ea94b..4315c85 100644 --- a/surfaces/blender/tests/live/kitbash_pose.result.json +++ b/surfaces/blender/tests/live/kitbash_pose.result.json @@ -503,6 +503,7 @@ "Toe", "Ram" ], + "manyDrivers": [], "next": null, "joints": [ { From 677c98297a9359a667adc4a0eb253471036bbaa6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 16:18:34 +0100 Subject: [PATCH 218/223] plates_bastion.json: repaired.how quotes the generator's script and its two edits as code The repaired truths of Hull.Quarter and Hull.BellySide.R were made by a scratch script; the block now says how to make them again from the branch at source.sha (Soul s2 Low repaired-truth-script-and-tie-pick). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/fixtures/plates_bastion.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/surfaces/blender/tests/fixtures/plates_bastion.json b/surfaces/blender/tests/fixtures/plates_bastion.json index f57150a..77308d7 100644 --- a/surfaces/blender/tests/fixtures/plates_bastion.json +++ b/surfaces/blender/tests/fixtures/plates_bastion.json @@ -43,7 +43,7 @@ "Hull.BellySide.L": {"solid":[[-2.0999999,2.2,3.9000001],[-2.0999999,-2.4000001,3.95],[-2.45,2.0,4.0999999],[-2.45,-2.2,4.1500001],[-2.45,2.0,4.8499999],[-2.45,-2.2,4.9000001],[-2.25,2.2,5.0999999],[-2.25,-2.4000001,5.1500001],[-1.8,2.2,3.9000001],[-1.8,-2.4000001,5.1500001]],"facets":15,"panels":[[-2.4300001,-2.0900002,4.2586985],[-2.4300001,-2.0900002,4.7886829],[-2.4300001,0.1687398,4.7617931],[-2.4300001,0.1624316,4.2318835],[-2.5050001,-2.0900002,4.2586985],[-2.5050001,-2.0900002,4.7886829],[-2.5050001,0.1687398,4.7617931],[-2.5050001,0.1624316,4.2318835],[-2.5250001,-2.0700002,4.2784615],[-2.5250001,-2.0700002,4.7684431],[-2.5250001,0.1485032,4.7420325],[-2.5250001,0.1426711,4.2521205],[-2.4300001,0.4387209,4.7585793],[-2.4300001,1.89,4.7413015],[-2.4300001,1.89,4.2113171],[-2.4300001,0.4324124,4.2286692],[-2.4750001,0.4387209,4.7585793],[-2.4750001,1.89,4.7413015],[-2.4750001,1.89,4.2113171],[-2.4750001,0.4324124,4.2286692],[-2.4950001,0.4584814,4.7383423],[-2.4950001,1.87,4.7215385],[-2.4950001,1.87,4.2315569],[-2.4950001,0.4526491,4.2484298],[-2.2321301,1.8335732,5.0840106],[-2.1400001,-2.2902241,5.1287899],[-1.9212852,-2.2902241,5.1287899],[-2.2321301,1.8340623,5.1290078],[-2.1400001,-2.2897351,5.1737871],[-1.9212852,-2.2897351,5.1737871],[-2.2288792,1.7676963,5.1497297],[-2.1204419,-2.2695189,5.1935692],[-1.9428494,-2.2695189,5.1935692]],"bolts":11} }} ], - "repaired": {"how": {"corner": "the branch's builder with massing.corners' inside test at 1e-5 m in place of 1e-6: the corner float32 lost is kept", "tie": "the branch's massing.clad cutting from the other of the split facet's two equally long edges"}, "truth": { + "repaired": {"how": {"script": "Blender 5.3 in the background at source.sha, with surfaces/blender/experiments/mechs on sys.path: import mechlib, massing, bastion_body, bastion_form. For a plate of bastion_form.PLATES built as key at side sx (1 for .R, -1 for .L): obj = massing.hard(key, pts, None, plate[\"mat\"], mirror=plate.get(\"mirror\", False), bevel=plate[\"bevel\"], sx=sx); g, bolts = mechlib.Geo(), mechlib.Geo(); clad(obj, g, keep=bastion_body.outward, seed=seed, bolts=bolts), seed the table's clad.seed for that side. solid is obj.data.vertices, facets len(obj.data.polygons), panels g.bm.verts, bolts len(bolts.bm.verts) // 12, coordinates rounded to 7 places.", "corner": "Hull.Quarter.R and .L: pts = massing.corners([bastion_body._face(f) for f in plate[\"faces\"]], tol=1e-5) where the branch calls it at its default, tol=1e-6 (the slack of its inside test, all(n.dot(p) <= d + tol ...)): the corner float32 lost is kept. clad is massing.clad.", "tie": "Hull.BellySide.R: pts = bastion_body._points(plate), and clad is massing.clad with two lines added after its line `k = max(range(len(pts)), key=lambda i: (pts[(i + 1) % len(pts)] - pts[i]).length)`: `tied = [i for i in range(len(pts)) if abs((pts[(i + 1) % len(pts)] - pts[i]).length - (pts[(k + 1) % len(pts)] - pts[k]).length) < 1e-5]` and `k = next((i for i in tied if i != k), k) if len(tied) == 2 else k`: the cut starts from the other of the split facet's two equally long edges."}, "truth": { "Hull.Quarter.R": {"solid":[[4.2910318,-2.9193861,6.8925695],[4.7526722,-3.0549133,5.7045879],[4.3936944,-1.4,7.0157642],[4.9976001,-1.4,5.506],[3.5958304,-4.3421259,6.9449539],[3.9363332,-4.6085348,5.8910241],[1.75,-4.8604336,7.409956],[1.75,-5.3931999,5.9851837],[2.5643883,-1.4,7.5279703],[1.75,-2.3254409,7.6634545],[2.5643883,-1.4,5.5060005],[1.75,-2.3254409,5.6170526]],"facets":8,"panels":[[2.6039631,-1.5075765,7.4852662],[1.8505968,-2.3636744,7.6105995],[1.8505968,-3.7839808,7.4685688],[3.7708514,-3.7307458,6.9362202],[4.181469,-2.8904121,6.9052806],[4.2749047,-1.5075765,7.0174022],[2.6160405,-1.5118898,7.5284004],[1.8626742,-2.3679876,7.6537333],[1.8626742,-3.7882941,7.5117025],[3.7829289,-3.7350593,6.9793544],[4.1935463,-2.8947253,6.9484148],[4.2869821,-1.5118899,7.0605364],[2.6295795,-1.5337148,7.543292],[1.8873084,-2.3772049,7.6667795],[1.8873082,-3.7697763,7.5275221],[3.7765129,-3.7174025,7.0037818],[4.1799693,-2.8917232,6.9733815],[4.2717276,-1.5337149,7.0834904],[1.8505965,-4.0526409,7.4417028],[1.8505965,-4.7160707,7.37536],[3.5181954,-4.2478104,6.9552579],[3.6377716,-4.0030956,6.9462481],[1.8707256,-4.0598297,7.5135922],[1.8707258,-4.7232594,7.4472499],[3.5383244,-4.2549992,7.0271478],[3.6579008,-4.0102844,7.0181379],[1.8953596,-4.0811133,7.5254316],[1.8953596,-4.6992774,7.4636159],[3.5305526,-4.2401166,7.0516772],[3.6317692,-4.0329757,7.0440507],[2.7647738,-4.5948009,7.0421376],[1.8471562,-4.8524671,7.273304],[1.8471562,-5.2996264,6.0774708],[2.8457143,-4.9412479,6.0344653],[2.7796867,-4.6345687,7.0570083],[1.862069,-4.8922348,7.2881742],[1.8620691,-5.3393941,6.0923409],[2.8606274,-4.9810157,6.049336],[2.7687323,-4.6642437,7.0491562],[1.8875668,-4.9116745,7.2711391],[1.8875669,-5.3432689,6.1169314],[2.8469315,-4.9989567,6.075614],[3.5113626,-4.385159,6.8540578],[3.0230417,-4.5222793,6.9770751],[3.0996346,-4.8501167,6.0235305],[3.7892847,-4.6026044,5.9938288],[3.5362175,-4.4514389,6.8788414],[3.0478966,-4.5885587,7.0018592],[3.1244895,-4.9163966,6.0483146],[3.8141394,-4.6688843,6.0186129],[3.5286927,-4.4801512,6.8701258],[3.0752041,-4.6074901,6.9843683],[3.1484115,-4.9208369,6.0729723],[3.7952363,-4.688694,6.0451155],[4.3817148,-1.9071758,6.8648353],[4.3201332,-2.8185694,6.7909379],[4.710516,-2.9331768,5.7863297],[4.8316121,-2.1149623,5.6881447],[4.4233174,-1.9113361,6.8814764],[4.3617358,-2.8227296,6.8075786],[4.7521186,-2.9373369,5.8029709],[4.8732147,-2.1191227,5.7047858],[4.4476438,-1.9368703,6.8683591],[4.3888788,-2.8065846,6.7978411],[4.7663054,-2.9173882,5.8265738],[4.8817496,-2.1373634,5.7329712],[4.9214897,-1.5076798,5.6152711],[4.4087076,-1.5076798,6.8972268],[4.400281,-1.6323925,6.887115],[4.8708658,-1.8497338,5.6563177],[4.9908276,-1.5146136,5.6430063],[4.478045,-1.5146136,6.924962],[4.4696183,-1.6393265,6.9148502],[4.9402032,-1.8566676,5.6840525],[4.9988408,-1.536377,5.6716146],[4.5026264,-1.5363771,6.9121504],[4.4966955,-1.6241521,6.9050336],[4.9545536,-1.8356153,5.7075229],[4.2655559,-3.0223532,6.786387],[3.6602807,-4.2610564,6.8319945],[3.9375505,-4.4779921,5.9737864],[4.6440229,-3.1334624,5.8124413],[4.3285189,-3.0520933,6.8142467],[3.723244,-4.2907968,6.8598547],[4.0005136,-4.5077324,6.001646],[4.706986,-3.1632028,5.840301],[4.34373,-3.0801873,6.8037205],[3.7548051,-4.28543,6.8480964],[4.0205779,-4.4933701,6.0254736],[4.7070746,-3.186857,5.868691]],"bolts":30}, "Hull.Quarter.L": {"solid":[[-4.2910318,-2.9193861,6.8925695],[-4.7526722,-3.0549133,5.7045879],[-4.3936944,-1.4,7.0157642],[-4.9976001,-1.4,5.506],[-3.5958304,-4.3421259,6.9449539],[-3.9363332,-4.6085348,5.8910241],[-1.75,-4.8604336,7.409956],[-1.75,-5.3931999,5.9851837],[-2.5643883,-1.4,7.5279703],[-1.75,-2.3254409,7.6634545],[-2.5643883,-1.4,5.5060005],[-1.75,-2.3254409,5.6170526]],"facets":8,"panels":[[-1.8505965,-4.7160707,7.3753595],[-1.8505963,-4.0014849,7.4468179],[-3.6631114,-3.9512372,6.9443383],[-3.5181952,-4.2478104,6.9552579],[-1.8707256,-4.7232594,7.4472494],[-1.8707255,-4.0086741,7.5187078],[-3.6832407,-3.9584262,7.0162282],[-3.5383244,-4.2549992,7.0271473],[-1.8953596,-4.6992774,7.4636154],[-1.8953595,-4.0299578,7.5305471],[-3.6571088,-3.9811172,7.042141],[-3.5305526,-4.2401166,7.0516772],[-1.8505961,-3.7328248,7.4736838],[-1.8505962,-2.3636742,7.6105995],[-2.6039624,-1.5075763,7.4852662],[-4.2749043,-1.5075763,7.0174017],[-4.1814685,-2.8904119,6.9052796],[-3.7961907,-3.6788878,6.93431],[-1.8626735,-3.7371383,7.5168176],[-1.8626738,-2.3679876,7.6537333],[-2.61604,-1.5118898,7.5283999],[-4.2869816,-1.5118897,7.0605354],[-4.1935458,-2.8947253,6.9484134],[-3.8082683,-3.6832011,6.9774437],[-1.8873075,-3.7186203,7.5326371],[-1.8873078,-2.3772047,7.666779],[-2.6295791,-1.5337147,7.543292],[-4.2717271,-1.5337147,7.0834894],[-4.1799688,-2.8917229,6.9733806],[-3.8018522,-3.6655443,7.0018711],[-3.5113626,-4.385159,6.8540568],[-3.7892847,-4.6026049,5.9938283],[-2.8620911,-4.9353704,6.0337601],[-2.7814307,-4.5901232,7.0379415],[-3.5362175,-4.4514389,6.8788409],[-3.8141396,-4.6688843,6.0186124],[-2.8869457,-5.0016503,6.0585442],[-2.8062856,-4.6564031,7.0627251],[-3.5286927,-4.4801512,6.8701248],[-3.7952363,-4.6886945,6.0451145],[-2.9108679,-5.0060902,6.0832024],[-2.8335931,-4.6753345,7.0452342],[-2.6081707,-5.0265012,6.0446959],[-1.8471559,-5.2996264,6.0774708],[-1.8471559,-4.8524671,7.273304],[-2.5231626,-4.6626449,7.103004],[-2.6230836,-5.0662689,6.059566],[-1.8620688,-5.3393941,6.0923409],[-1.8620689,-4.8922348,7.2881746],[-2.5380757,-4.7024126,7.1178746],[-2.6093876,-5.0842099,6.0858445],[-1.8875666,-5.3432684,6.1169314],[-1.8875667,-4.9116745,7.2711396],[-2.5271213,-4.7320881,7.1100225],[-4.3919301,-1.7559885,6.8770943],[-4.4087081,-1.5076798,6.8972273],[-4.9214902,-1.5076798,5.615272],[-4.85321,-1.969032,5.6706338],[-4.4335327,-1.7601488,6.8937349],[-4.4503107,-1.5118401,6.9138684],[-4.9630928,-1.5118401,5.6319127],[-4.8948126,-1.9731923,5.6872749],[-4.4606104,-1.7449744,6.8839188],[-4.4748921,-1.5336035,6.9010572],[-4.9711065,-1.5336035,5.660521],[-4.909163,-1.95214,5.7107453],[-4.3201332,-2.8185692,6.7909379],[-4.373363,-2.0307715,6.8548145],[-4.8139558,-2.2342606,5.7024608],[-4.7105155,-2.9331768,5.7863297],[-4.3894706,-2.8255031,6.8186731],[-4.4427004,-2.0377054,6.8825493],[-4.8832932,-2.2411945,5.7301955],[-4.7798533,-2.9401107,5.814065],[-4.4166136,-2.8093579,6.8089352],[-4.4670272,-2.0632396,6.869432],[-4.8918281,-2.2594352,5.7583814],[-4.7940402,-2.920162,5.8376679],[-3.9375505,-4.4779921,5.9737859],[-3.6602805,-4.2610569,6.8319945],[-4.2655559,-3.0223532,6.7863865],[-4.6440229,-3.1334624,5.8124409],[-4.0005136,-4.5077324,6.0016456],[-3.7232437,-4.2907968,6.8598542],[-4.3285189,-3.0520935,6.8142462],[-4.706986,-3.1632028,5.8403006],[-4.0205779,-4.4933701,6.0254736],[-3.7548048,-4.28543,6.8480964],[-4.34373,-3.0801876,6.8037205],[-4.7070746,-3.1868572,5.8686905]],"bolts":30}, "Hull.BellySide.R": {"solid":[[2.0999999,2.2,3.9000001],[2.0999999,-2.4000001,3.95],[2.45,2.0,4.0999999],[2.45,-2.2,4.1500001],[2.45,2.0,4.8499999],[2.45,-2.2,4.9000001],[2.25,2.2,5.0999999],[2.25,-2.4000001,5.1500001],[1.8,2.2,3.9000001],[1.8,-2.4000001,5.1500001]],"facets":15,"panels":[[2.4300001,0.4573603,4.2283726],[2.4300001,1.89,4.2113171],[2.4300001,1.89,4.7413015],[2.4300001,0.4636687,4.7582817],[2.5050001,0.4573603,4.2283726],[2.5050001,1.89,4.2113171],[2.5050001,1.89,4.7413015],[2.5050001,0.4636687,4.7582817],[2.5250001,0.4775969,4.2481332],[2.5250001,1.87,4.2315569],[2.5250001,1.87,4.7215385],[2.5250001,0.4834292,4.7380452],[2.4300001,-2.0900002,4.7886829],[2.4300001,-2.0900002,4.2586985],[2.4300001,0.1873795,4.2315865],[2.4300001,0.193688,4.7614961],[2.4750001,-2.0900002,4.7886829],[2.4750001,-2.0900002,4.2586985],[2.4750001,0.1873795,4.2315865],[2.4750001,0.193688,4.7614961],[2.4950001,-2.0700002,4.7684431],[2.4950001,-2.0700002,4.2784615],[2.4950001,0.167619,4.2518234],[2.4950001,0.1734514,4.7417355],[2.2321301,1.8335732,5.0840106],[1.9212853,-2.2902241,5.1287899],[2.1400001,-2.2902241,5.1287899],[2.2321301,1.8343884,5.1590061],[1.9212853,-2.2894089,5.2037854],[2.1400001,-2.2894089,5.2037854],[2.2288792,1.7680224,5.179728],[1.9428494,-2.2691927,5.223567],[2.1204419,-2.2691927,5.223567]],"bolts":11} From 7cb7d0993b319b8a3c48a5c1a1720a944d22742e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 16:18:34 +0100 Subject: [PATCH 219/223] plate.inset2d drops an edge that runs backwards; bolts follow; CROSSED goes inset2d is the one inset of every ring (slab gap and taper, panel outline, rim, bolt ring). After the corner move it drops every edge left running backwards, the shortest first, and meets its neighbours on their own moved lines; nothing left is an empty ring. A panel with no room for its bolt ring has no bolts, heads under two radii apart are one at their middle, and a rim the chamfer would cost a corner is not chamfered. An equal seed pair is refused. Tests: every inset2d call of the three fixtures against a half-plane clip (812 calls, 782 with no clamped corner within 1e-12 m); no panel or bolt ring of any plate at either side turns right or crosses and no heads overlap; EVENT holds the 31 fixture plates whose bolts or corners changed; every two-sided fixture row on one seed is a mirrored pair. HASH re-pinned, equal on Starfire and Yggdrasil. Cut aetheria-release:cut_spec:cut-plate-inset-edge-event.r1. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/plate.py | 57 ++++- surfaces/blender/docs/kitbash.md | 38 ++- surfaces/blender/tests/test_plate.py | 284 ++++++++++++++++++++--- 3 files changed, 325 insertions(+), 54 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/plate.py b/surfaces/blender/brokkr_kitbash/plate.py index 8e8766f..93573f7 100644 --- a/surfaces/blender/brokkr_kitbash/plate.py +++ b/surfaces/blender/brokkr_kitbash/plate.py @@ -212,6 +212,8 @@ def _check_clad(clad: Any, row: dict, path: str) -> dict: raise PlateError(f"{path}.seed: a pair of seeds is for a row with sides \"both\"") if len(seed) != 2 or not all(whole(v) for v in seed): raise PlateError(f"{path}.seed: wants an integer or [right, left]") + if seed[0] == seed[1]: + raise PlateError(f"{path}.seed: an equal pair draws two different layouts; write one seed for a mirrored pair") seed = list(seed) elif not whole(seed): raise PlateError(f"{path}.seed: wants an integer or [right, left]") @@ -337,18 +339,35 @@ def plane_basis(normal, up=(0.0, 0.0, 1.0), right=None, path: str = "plane"): def inset2d(ring, c: float) -> np.ndarray: - """A convex counter-clockwise outline moved in by c on every edge; a sharp corner moves at most c / MITER.""" + """A convex counter-clockwise outline moved in by c on every edge; a sharp corner moves at most c / MITER. An + edge the move leaves running backwards (or no longer than TIE) is dropped, the shortest first, and its two + neighbours meet where their own lines moved in by c cross. Empty, shape (0, 2), when nothing is left: under + three edges, or two neighbours that never meet.""" ring = np.asarray(ring, dtype=np.float64) + count = len(ring) + ways = [(ring[(k + 1) % count] - ring[k]) / np.linalg.norm(ring[(k + 1) % count] - ring[k]) for k in range(count)] + lefts = [np.array([-e[1], e[0]]) for e in ways] out = np.empty_like(ring) - for i in range(len(ring)): - p0, p1, p2 = ring[i - 1], ring[i], ring[(i + 1) % len(ring)] - e0, e1 = (p1 - p0) / np.linalg.norm(p1 - p0), (p2 - p1) / np.linalg.norm(p2 - p1) - n0, n1 = np.array([-e0[1], e0[0]]), np.array([-e1[1], e1[0]]) - miter = n0 + n1 + for i in range(count): + n0 = lefts[i - 1] + miter = n0 + lefts[i] length = np.linalg.norm(miter) miter = miter / length if length > 0 else n0 - out[i] = p1 + miter * (c / max(float(miter @ n0), MITER)) - return out + out[i] = ring[i] + miter * (c / max(float(miter @ n0), MITER)) + live, pts = list(range(count)), list(out) # pts[i] starts edge live[i] + while True: + m = len(live) + runs = [float((pts[(i + 1) % m] - pts[i]) @ ways[live[i]]) for i in range(m)] + i = min(range(m), key=runs.__getitem__) + if runs[i] > TIE: + return out if m == count else np.array(pts) + a, b = live[i - 1], live[(i + 1) % m] + cross = ways[a][0] * ways[b][1] - ways[a][1] * ways[b][0] + if m <= 3 or abs(cross) < 1e-12: + return np.zeros((0, 2)) + start = ring[b] + lefts[b] * c - ring[a] - lefts[a] * c + pts[(i + 1) % m] = ring[a] + lefts[a] * c + ways[a] * ((start[0] * ways[b][1] - start[1] * ways[b][0]) / cross) + del pts[i], live[i] def slab_points(origin, a, b, n, outline, thick: float, taper: float, back: float, gap: float) -> np.ndarray: @@ -666,10 +685,12 @@ def clip(poly: list[np.ndarray], point: np.ndarray, normal: np.ndarray) -> list[ def prism(mesh: _Mesh, origin, x, y, z, outline: np.ndarray, depth: float, chamfer: float) -> None: - """A block on a counter-clockwise outline, drawn depth along z, its far rim chamfered.""" + """A block on a counter-clockwise outline, drawn depth along z, its far rim chamfered; the rim is the outline + itself where the chamfer leaves it fewer corners.""" c = min(chamfer, 0.45 * depth) - rings = [(outline, 0.0), (outline, depth - c), (inset2d(outline, c) if c > 1e-6 else outline, depth)] n = len(outline) + rim = inset2d(outline, c) if c > 1e-6 else outline + rings = [(outline, 0.0), (outline, depth - c), (rim if len(rim) == n else outline, depth)] verts = [origin + x * q[0] + y * q[1] + z * h for ring, h in rings for q in ring] faces = [list(reversed(range(n))), [2 * n + k for k in range(n)]] for low in (0, n): @@ -688,7 +709,9 @@ def hex_bolt(mesh: _Mesh, origin, x, y, z, r: float, depth: float) -> None: def panel(panels: _Mesh, bolts: _Mesh, polygon: list[np.ndarray], out: np.ndarray, lift: float, inset: float, bolt_r: float) -> bool: """A raised panel on a flat convex polygon: the polygon moved in inset on every edge, standing lift over it from - SINK below, its far rim chamfered; a bolt inside each of its corners. False for a polygon too small for one.""" + SINK below, its far rim chamfered; a bolt inside each of its corners, 3.2 bolt_r in, none where that leaves no + ring, and bolts whose centres stand under 2 bolt_r apart made one at their middle. False for a polygon too small + for a panel, or one the inset leaves nothing of.""" pts = np.array(polygon) centre = pts.mean(axis=0) normal = np.cross(pts - centre, np.roll(pts, -1, axis=0) - centre).sum(axis=0) @@ -703,7 +726,17 @@ def panel(panels: _Mesh, bolts: _Mesh, polygon: list[np.ndarray], out: np.ndarra if _area2(inner) < PANEL_MIN[0] * _area2(flat) or _area2(inner) < PANEL_MIN[1]: return False prism(panels, centre - normal * SINK, x, y, normal, inner, lift + SINK, CHAMFER) - for q in inset2d(inner, 3.2 * bolt_r): + heads = list(inset2d(inner, 3.2 * bolt_r)) + k = 0 + while k < len(heads) > 1: # neighbours in ring order, the first pair first + after = (k + 1) % len(heads) + if np.linalg.norm(heads[after] - heads[k]) < 2 * bolt_r: + heads[k] = (heads[k] + heads[after]) / 2 + del heads[after] + k = 0 + else: + k += 1 + for q in heads: hex_bolt(bolts, centre + x * q[0] + y * q[1] + normal * (lift + 0.3 * bolt_r), x, y, normal, bolt_r, 0.6 * bolt_r) return True diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 1ff9134..c82223f 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1039,7 +1039,7 @@ first. | `inset` | how far a panel stands in from its facet's edges | | `gap` | the seam between the two panels of a split facet | | `split` | a facet over this area is cut in two | -| `seed` | an integer, or `[right, left]` on a row with `sides: "both"`. There is no default. One integer on a two-sided row makes a mirrored pair; a pair of seeds draws each side on its own solid, also where the two are equal. | +| `seed` | an integer, or `[right, left]` on a row with `sides: "both"`. There is no default. One integer on a two-sided row makes a mirrored pair; a pair of seeds draws each side on its own solid, and an equal pair is refused: it would draw two different layouts, and one seed is how a row asks for the same on both sides. | | `bolt_r` | a bolt's corner radius (default 0.028) | | `bolt_mat` | the bolts' material, 1 to 63 characters (default `gunmetal`). Carried: `build` draws nothing from it; `brokkr_kitbash.plates` reads it | | `bevel` | the width of the panels' Bevel, 0 to 0.05 (default 0.012). Carried, as the row's `bevel` is | @@ -1047,16 +1047,19 @@ first. One `random.Random(seed)` draws, in facet order. A chosen facet over `split` is cut across its longest edge at a share drawn from 0.36 to 0.64 of that edge, the two parts `gap` apart; edges within 1e-9 m of the longest tie and go to the edge whose middle is greater by x, y, z. Then every chosen facet draws once: under 0.5 the parts take -`l0, l1`, otherwise `l1, l0`. A panel is its part moved in by `inset` (a sharp corner moves at most inset / 0.3), -refused under a quarter of the part's area or under 0.02 m2; it is a prism from 0.02 below the facet to its lift -above, its far rim chamfered 0.02. A hexagonal bolt of radius `bolt_r` stands inside each panel corner, 3.2 -`bolt_r` in. +`l0, l1`, otherwise `l1, l0`. A panel is its part moved in by `inset`, not made where that leaves nothing, under a +quarter of the part's area or under 0.02 m2; it is a prism from 0.02 below the facet to its lift above, its far +rim chamfered 0.02 (not chamfered where the chamfer would cost the rim a corner). A hexagonal bolt of radius +`bolt_r` stands inside each panel corner, on the panel's outline moved in 3.2 `bolt_r`: a panel with no room for +that ring has no bolts, and bolts whose centres would stand under 2 `bolt_r` apart are one bolt at their middle +(neighbours in ring order, the first such pair first, until none is left). -The inset moves each corner along its own miter and does not look at its neighbours, so where it passes the two -ends of a short edge over each other the panel's outline crosses itself. `build` makes that panel as it stands; -Blender fills a face that crosses itself by where its loop starts, so the same vertices can render differently -from another builder's mesh. Two of the 104 fixture panels do it (bastion's `Hull.Cheek.R` and paladin's -`Thigh.Outer`), and the test names them. +One inset, `inset2d`, makes every such ring: a slab's `gap` and `taper`, a panel's outline, its rim and its bolt +ring. It moves each corner along its miter (a sharp corner at most the distance / 0.3). An edge that move leaves +running backwards, its two ends passed over each other, is dropped, the shortest first, and its two neighbours +meet where their own lines moved in cross; under three edges, or two neighbours that never meet, nothing is left +and the ring is empty. For a convex outline with no corner at the 0.3 limit that is exactly what stands the +distance inside every edge. A ring no edge of which runs backwards is the corner move alone, to the byte. ### Anchors @@ -1089,7 +1092,8 @@ Every refusal is a `PlateError` (a `ValueError`) that names the path, as `plates or two; a name built twice; a number that is not finite; an outline under 3 points or over 64, one that crosses itself, repeats a point or has zero area; `thick`, `taper`, `back` or `gap` outside 0.001 to 2, 0 to 0.5, 0.1 to 1.5 and 0 to 0.5; a `taper` of half the outline's least width or more; corners that are not a plate; faces that -bound nothing; points in one plane; a pair of seeds on a one-sided row, or no seed; an `up` along the normal; a +bound nothing; points in one plane; a pair of seeds on a one-sided row, an equal pair, or no seed; an `up` along +the normal; a fit on a row with no face; an unknown fit kind; two anchors of one name in a row. ### Against the mech tracks' builders @@ -1104,7 +1108,17 @@ eight stand 1 to 2 micrometres (solid) or 29 micrometres (panels) from the float so the branch's solid is smaller than the table's and its panels are another solid's; and one of bastion's two belly-side plates splits its panel from the other of two equally long edges. Those three are held, solid, facets, panels and bolts, to `repaired` in `plates_bastion.json`: the branch's own builder run in Blender 5.3 with the -inside test at 1e-5 m, and with its clad cutting from the other tied edge. +inside test at 1e-5 m, and with its clad cutting from the other tied edge; `repaired.how` quotes both edits as +code. + +The branches' inset has no edge event, so 31 of the 126 are held to another bolt count, each named in the test's +`EVENT`: eleven stand bare (raptor's thin trims and paladin's tail have no room for a bolt ring), and the +others lose one to four to a ring with no room, a dropped edge or heads that would overlap. Two of them, bastion's `Hull.Cheek.R` +and paladin's `Thigh.Outer`, have a panel whose outline dropped a corner, and that panel's vertices are held to +no truth. What holds every ring instead: every `inset2d` call the three fixtures make at both sides (812) stands +inside its outline, and the 782 with no corner at the miter limit equal, within 1e-12 m, the outline's half-planes +moved in and clipped (37 of them an edge or more short, 22 empty); and no panel ring or bolt ring of any plate at +either side turns right or crosses, and no two bolt heads of a panel overlap. The same test builds the three fixtures to one sha256 of every coordinate rounded to 1e-9 m and every face, pinned from Starfire (Windows 11, numpy 2.5.4) and Yggdrasil (Debian 13, numpy 2.2.4 on the system LAPACK). The diff --git a/surfaces/blender/tests/test_plate.py b/surfaces/blender/tests/test_plate.py index ad6c9ca..c3e3388 100644 --- a/surfaces/blender/tests/test_plate.py +++ b/surfaces/blender/tests/test_plate.py @@ -5,7 +5,7 @@ Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; The truth is float32 (mathutils and Blender meshes) and plate.py is float64; KNOWN lists every fixture plate where that, a corner the branch's builder lost, or a tie Blender's mesh order decided keeps the two apart, with what it -is held to instead. +is held to instead, and EVENT every one whose bolts or panel corners the inset's edge event changes. """ from __future__ import annotations @@ -18,7 +18,9 @@ import math import sys import types import unittest +import warnings from pathlib import Path +from unittest import mock SURFACE = Path(__file__).resolve().parents[1] FIXTURES = Path(__file__).resolve().parent / "fixtures" @@ -89,6 +91,137 @@ def rings(panels): at += 2 + 2 * n +def corner_move(ring, c): + """(ring, clamped): every corner moved along its miter by c, at most c / MITER, and whether any met that limit: + the inset before any edge is dropped.""" + ring = np.asarray(ring, dtype=np.float64) + out, clamped = np.empty_like(ring), False + for i in range(len(ring)): + p0, p1, p2 = ring[i - 1], ring[i], ring[(i + 1) % len(ring)] + e0, e1 = (p1 - p0) / np.linalg.norm(p1 - p0), (p2 - p1) / np.linalg.norm(p2 - p1) + n0, n1 = np.array([-e0[1], e0[0]]), np.array([-e1[1], e1[0]]) + miter = (n0 + n1) / np.linalg.norm(n0 + n1) + clamped = clamped or float(miter @ n0) < plate.MITER + out[i] = p1 + miter * (c / max(float(miter @ n0), plate.MITER)) + return out, clamped + + +def depths(points, ring): + """How far each point stands inside each edge's line of a counter-clockwise ring: (points, edges).""" + ring = np.asarray(ring, dtype=np.float64) + edges = np.roll(ring, -1, axis=0) - ring + lefts = np.column_stack((-edges[:, 1], edges[:, 0])) / np.linalg.norm(edges, axis=1)[:, None] + return np.einsum("pek,ek->pe", np.asarray(points, dtype=np.float64)[:, None, :] - ring[None, :, :], lefts) + + +def half_planes(ring, c): + """What is left of a convex counter-clockwise ring c inside every edge's line: a square around the ring clipped + by each edge's half-plane moved in by c. Empty, shape (0, 2), where nothing is.""" + ring = np.asarray(ring, dtype=np.float64) + (x0, y0), (x1, y1) = ring.min(axis=0) - 1, ring.max(axis=0) + 1 + poly = [np.array(p) for p in ((x0, y0), (x1, y0), (x1, y1), (x0, y1))] + for k in range(len(ring)): + edge = ring[(k + 1) % len(ring)] - ring[k] + left = np.array([-edge[1], edge[0]]) / np.linalg.norm(edge) + deep = [float((p - ring[k]) @ left) - c for p in poly] + kept = [] + for i, p in enumerate(poly): + j = (i + 1) % len(poly) + if deep[i] >= 0: + kept.append(p) + if (deep[i] > 0) != (deep[j] > 0) and deep[i] != deep[j]: + kept.append(p + (poly[j] - p) * (deep[i] / (deep[i] - deep[j]))) + poly = kept + if len(poly) < 3: + return np.zeros((0, 2)) + return np.array(poly) + + +def turns(ring): + """Each corner's turn (the cross product of the unit edges into and out of it): over 0 is a left turn.""" + ring = np.asarray(ring, dtype=np.float64) + edges = np.roll(ring, -1, axis=0) - ring + edges = edges / np.linalg.norm(edges, axis=1)[:, None] + before = np.roll(edges, 1, axis=0) + return before[:, 0] * edges[:, 1] - before[:, 1] * edges[:, 0] + + +def apart2(a, b): + """apart, for rings in a plane; an empty ring stands nowhere near one that is not.""" + return apart(np.column_stack((a, np.zeros(len(a)))), np.column_stack((b, np.zeros(len(b))))) + + +def sides(mech): + """Every row of a fixture as a one-sided row alone, at each side, with the seed build draws that side from: + (side, row name, table of that one row).""" + for one in fixture(mech)["table"]["plates"]: + for side in (1, -1): + alone = dict(one, sides="one") + if one.get("clad") and isinstance(one["clad"]["seed"], list): + alone["clad"] = dict(one["clad"], seed=one["clad"]["seed"][0 if side > 0 else 1]) + yield side, one["name"], {"schema": "brokkr.plates.v0", "plates": [alone]} + + +@unittest.skipIf(np is None, "numpy is not installed") +class InsetTests(unittest.TestCase): + """plate.inset2d, the one inset of every ring. Kills: the edge event removed; the vanish test at three edges + made two; the shortest-first pick made the first edge found (the clamped sliver alone: without a clamped corner + every order drops the same edges).""" + + def test_a_short_edge_is_dropped_and_its_neighbours_meet(self): + ring = [[0, 0], [4, 0], [4, 3], [2.1, 4], [1.9, 4]] # the top edge is 0.2 long + made = plate.inset2d(ring, 0.5) + self.assertEqual(len(made), 4) + self.assertLess(apart2(made, half_planes(ring, 0.5)), 1e-12) + self.assertGreater(float(depths(made, ring).min()), 0.5 - 1e-12) + self.assertEqual(len(plate.inset2d(ring, 0.05)), 5) + + def test_nothing_left_is_an_empty_ring(self): + cases = (([[0, 0], [3, 0], [3, 1], [0, 1]], 0.5), ([[0, 0], [3, 0], [3, 1], [0, 1]], 0.6), ([[0, 0], [4, 0], [0, 3]], 1.01), ([[0, 0], [1, 0], [1, 1], [0, 1]], 0.7), + ([[2, 0], [0, 1], [0, 0]], 0.5)) # its sharp corner is clamped: two edges are left that run forwards + with warnings.catch_warnings(): + warnings.simplefilter("error") # the long sides of the rectangle never meet + for ring, c in cases: + self.assertEqual(plate.inset2d(ring, c).shape, (0, 2)) + self.assertEqual(half_planes(ring, c + 1e-9).shape, (0, 2)) + self.assertEqual(len(plate.inset2d([[0, 0], [4, 0], [0, 3]], 0.99)), 3) # the triangle's inradius is 1 + + def test_a_ring_with_room_is_the_corner_move_to_the_byte(self): + hexagon = [[math.cos(k * math.pi / 3), math.sin(k * math.pi / 3)] for k in range(6)] + for ring, c in ((hexagon, 0.2), ([[0, 0], [4, 0], [4, 3], [2.1, 4], [1.9, 4]], 0.05), ([[0, 0], [5, 0], [0, 1]], 0.1)): + self.assertEqual(plate.inset2d(ring, c).tobytes(), corner_move(ring, c)[0].tobytes()) + self.assertTrue(corner_move([[0, 0], [5, 0], [0, 1]], 0.1)[1]) # its sharp corner is clamped + + def test_the_shortest_edge_goes_first(self): + sliver = [[11, 1], [12, 1], [6, 3], [4, 3], [6, 2]] # two corners clamped, three edges run backwards + made = plate.inset2d(sliver, 0.5) + self.assertLess(apart2(made, np.array([[6.516380, 2.300827], [5.918861, 2.5], [5.622082, 2.617078]])), 1e-6) + self.assertGreater(float(depths(made, sliver).min()), 0) + + def test_every_inset_of_the_fixtures_is_what_the_half_planes_leave(self): + inset, calls = plate.inset2d, [] + + def spy(ring, c): + calls.append((np.array(ring, dtype=np.float64), c, inset(ring, c))) + return calls[-1][2] + with mock.patch.object(plate, "inset2d", spy): + for mech in ("bastion", "paladin", "raptor"): + for side in (1, -1): + plate.build(fixture(mech)["table"], side) + held = dropped = empty = 0 + for ring, c, made in calls: + if float(turns(ring).min()) <= 0: # a slab's outline need not be convex: no edge of those runs backwards + self.assertEqual(made.tobytes(), corner_move(ring, c)[0].tobytes()) + continue + if len(made): + self.assertGreater(float(depths(made, ring).min()), 0) # clamped or not, it stands inside its outline + self.assertGreater(float(turns(made).min()), 0) + if not corner_move(ring, c)[1]: + self.assertLess(apart2(made, half_planes(ring, c)), 1e-12) + held, dropped, empty = held + 1, dropped + (0 < len(made) < len(ring)), empty + (not len(made)) + self.assertEqual((len(calls), held, dropped, empty), (812, 782, 37, 22)) + + @unittest.skipIf(np is None, "numpy is not installed") class CheckTests(unittest.TestCase): def refused(self, document, path): @@ -187,6 +320,9 @@ class CheckTests(unittest.TestCase): self.refused(doc(row(slab=SLAB, clad=dict(CLAD, seed=[1, 2]))), "plates[0].clad.seed") plate.check(doc(row(slab=SLAB, sides="both", clad=dict(CLAD, seed=[1, 2])))) + def test_an_equal_seed_pair(self): + self.refused(doc(row(slab=SLAB, sides="both", clad=dict(CLAD, seed=[5, 5]))), "plates[0].clad.seed: an equal pair") + def test_no_default_seed(self): self.refused(doc(row(slab=SLAB, clad={k: v for k, v in CLAD.items() if k != "seed"})), "plates[0].clad.seed") self.refused(doc(row(slab=SLAB, clad=dict(CLAD, seed=1.5))), "plates[0].clad.seed") @@ -376,10 +512,55 @@ class CladTests(unittest.TestCase): self.assertEqual(back[0]["panels"][0].tobytes(), left["panels"][0].tobytes()) self.assertEqual(back[1]["panels"][0].tobytes(), right["panels"][0].tobytes()) - def test_a_pair_of_seeds_draws_each_side_on_its_own_solid(self): - pair = plate.build(doc(row(sides="both", clad=dict(CLAD, facets="all", seed=[5, 5])))) - self.assertGreater(apart(across(pair[0]["panels"])[0], pair[1]["panels"][0]), 0.1) - self.assertEqual(pair[1]["panels"][0].tobytes(), plate.build(doc(row(clad=dict(CLAD, facets="all"))), -1)[0]["panels"][0].tobytes()) + def test_every_fixture_pair_row_on_one_seed_is_a_mirrored_pair(self): + pairs = mirrored = 0 + for mech in ("bastion", "paladin", "raptor"): + table = fixture(mech)["table"] + for one in table["plates"]: + if one.get("clad") and isinstance(one["clad"]["seed"], list): + one["clad"]["seed"] = one["clad"]["seed"][0] + pairs += 1 + built = plate.build(table) + for right, left in zip(built, built[1:]): + if right["name"].endswith(".R") and right["row"] == left["row"]: + mirrored += 1 + with self.subTest(plate=right["name"]): + self.assertEqual(left["report"], right["report"]) + for key in ("solid", "panels", "bolts"): + self.assertTrue(np.array_equal(across(right[key])[0], left[key][0])) + self.assertEqual(across(right[key])[1], left[key][1]) + self.assertEqual((pairs, mirrored), (23, 38)) # every two-sided row of the three, 23 of them rewritten + + def test_bolt_heads_too_close_are_one_at_their_middle(self): + strip = [np.array(p, dtype=float) for p in ([-0.5, -0.1, 0], [0.5, -0.1, 0], [0.5, 0.1, 0], [-0.5, 0.1, 0])] + panels, bolts = plate._Mesh(), plate._Mesh() + self.assertTrue(plate.panel(panels, bolts, strip, np.array([0.0, 0.0, 1.0]), 0.04, 0.0, 0.028)) + heads = bolts.done()[0].reshape(-1, 12, 3).mean(axis=1) # the bolt ring is 0.8208 by 0.0208: its ends are 0.0208 apart + self.assertLess(apart(heads, [[-0.4104, 0, 0.0484], [0.4104, 0, 0.0484]]), 1e-12) + self.assertEqual(len(heads), 2) + wide = [p * (1, 1.5, 1) for p in strip] # 0.1208 apart: four bolts + bolts = plate._Mesh() + plate.panel(plate._Mesh(), bolts, wide, np.array([0.0, 0.0, 1.0]), 0.04, 0.0, 0.028) + self.assertEqual(len(bolts.done()[0]) // 12, 4) + thin = [p * (1, 0.85, 1) for p in strip] # 0.17 wide: no bolt ring, a bare panel + panels, bolts = plate._Mesh(), plate._Mesh() + self.assertTrue(plate.panel(panels, bolts, thin, np.array([0.0, 0.0, 1.0]), 0.04, 0.0, 0.028)) + self.assertEqual((len(panels.done()[0]), len(bolts.done()[0])), (12, 0)) + + def test_a_rim_the_chamfer_leaves_fewer_corners_is_the_outline(self): + mesh, axes = plate._Mesh(), np.eye(3) + plate.prism(mesh, np.zeros(3), *axes, np.array([[0, 0], [1, 0], [1, 1], [0.502, 1.2], [0.498, 1.2], [0, 1]], dtype=float), 0.1, 0.02) + V = mesh.done()[0] + self.assertEqual(len(V), 18) + self.assertTrue(np.array_equal(V[12:, :2], V[:6, :2])) # the edge 0.004 long has no room for a chamfer of 0.02 + plate.prism(mesh, np.zeros(3), *axes, np.array([[0, 0], [1, 0], [1, 1], [0, 1]], dtype=float), 0.1, 0.02) + self.assertTrue(np.allclose(mesh.done()[0][26:, :2], [[0.02, 0.02], [0.98, 0.02], [0.98, 0.98], [0.02, 0.98]], atol=1e-12)) + + def test_no_panel_where_the_inset_leaves_nothing(self): + strip = [np.array(p, dtype=float) for p in ([-0.5, -0.1, 0], [0.5, -0.1, 0], [0.5, 0.1, 0], [-0.5, 0.1, 0])] + panels, bolts = plate._Mesh(), plate._Mesh() + self.assertFalse(plate.panel(panels, bolts, strip, np.array([0.0, 0.0, 1.0]), 0.04, 0.1, 0.028)) + self.assertEqual((len(panels.verts), len(bolts.verts)), (0, 0)) def test_a_split_facet_takes_two_panels_and_a_whole_one_a_panel(self): made = plate.build(doc(row(clad=dict(CLAD, facets=[{"n": [0, 0, 1], "cos": 0.9}], split=2.2))))[0] @@ -507,55 +688,72 @@ KNOWN = {("bastion", "Hull.Cheek.R"): "float32", ("bastion", "Hull.Cheek.L"): "f ("raptor", "Torso.Belt3.R"): "float32", ("raptor", "Torso.Belt3.L"): "float32"} SOLID, PANELS = 1e-6, 1e-5 # the cut's tolerances, metres FLOAT32 = (4e-6, 4e-5) # for a KNOWN plate: a few float32 steps at 8 m, and the same through an inset -# Panels whose outline crosses itself: the inset passes the two ends of a short edge over each other, as the branches' own inset does. -# Blender fills such a cap by where its loop starts, and a facet's loop starts at plate.py's least vertex but at Blender's own in a -# branch's mesh: that is the whole of Hull.Cheek.R's difference in a render (109 pixels at 1024 from above, vertices 2e-6 m apart). -CROSSED = {("bastion", 1, "Hull.Cheek.R", 4), ("paladin", 1, "Thigh.Outer", 0)} # (mech, side, plate, panel) +# Fixture plates the inset's edge event changes from the branch's truth, which has no such event: (mech, side, plate) to (bolts, +# panel corners dropped). A bolt ring with no room is no bolts, an edge of it that ran backwards is one bolt less, and heads under two +# radii apart are one. Each is held to this bolt count in place of the truth's; one whose panel outline dropped a corner (three +# vertices, one in each ring of the prism) is held to that vertex count and to no panel vertex of the truth. A plate may be KNOWN too. +EVENT = {("bastion", 1, "Hull.Cheek.R"): (32, 1), ("bastion", 1, "Hull.Cheek.L"): (32, 0), ("bastion", 1, "Hull.Quarter.R"): (29, 0), + ("bastion", 1, "Hull.BellySide.R"): (10, 0), ("bastion", 1, "Hull.BellySide.L"): (10, 0), + ("paladin", 1, "Thigh.Outer"): (11, 1), ("paladin", 1, "Thigh.Inner"): (9, 0), ("paladin", 1, "Shin.Greave"): (11, 0), + ("paladin", 1, "Shin.Ankle"): (4, 0), ("paladin", 1, "Pelvis.Wing.R"): (3, 0), ("paladin", 1, "Pelvis.Wing.L"): (3, 0), + ("paladin", 1, "Pelvis.Tail"): (0, 0), ("paladin", -1, "Thigh.Outer"): (11, 0), ("paladin", -1, "Thigh.Inner"): (8, 0), + ("raptor", 1, "Torso.Jaw2.R"): (2, 0), ("raptor", 1, "Torso.Jaw2.L"): (2, 0), ("raptor", 1, "Torso.Jaw3.R"): (2, 0), + ("raptor", 1, "Torso.Jaw3.L"): (2, 0), ("raptor", 1, "Torso.JawLip2.R"): (0, 0), ("raptor", 1, "Torso.JawLip2.L"): (0, 0), + ("raptor", 1, "Torso.ShoulderDeck.R"): (3, 0), ("raptor", 1, "Torso.ShoulderDeck.L"): (3, 0), ("raptor", 1, "Torso.Belt1.R"): (0, 0), + ("raptor", 1, "Torso.Belt1.L"): (0, 0), ("raptor", 1, "Torso.Belt2.R"): (0, 0), ("raptor", 1, "Torso.Belt2.L"): (0, 0), + ("raptor", 1, "Torso.Lip2.R"): (0, 0), ("raptor", 1, "Torso.Lip2.L"): (0, 0), ("raptor", 1, "Torso.Hood1D.R"): (0, 0), + ("raptor", 1, "Torso.Hood1D.L"): (0, 0), ("raptor", 1, "Torso.Hood1F.R"): (7, 0)} # The three fixtures' builds as one sha256, of coordinates rounded to QUANTUM metres and of every face. Starfire (Windows 11, numpy -# 2.5.4) and Yggdrasil (Debian 13, numpy 2.2.4 on the system LAPACK) give this hash; their coordinates differ in 3,221 of 34,359 by up -# to 2.7e-15 m and in no face. QUANTUM is TIE: 3.7e5 times that, and 1e3 under the least difference KNOWN holds (1.06e-6 m). +# 2.5.4) and Yggdrasil (Debian 13, numpy 2.2.4 on the system LAPACK) give this hash; their numbers (every coordinate and anchor matrix +# entry) differ in 2,821 of 30,909 by up to 2.7e-15 m and in no face. QUANTUM is TIE: 3.7e5 times that, and 1e3 under the least difference KNOWN holds (1.06e-6 m). QUANTUM = 1e-9 -HASH = "ff870b40db0baac928dd6462260e92e8c4e1ebb77f80adc15e1aff551fe41f0e" +HASH = "ee58f30a9492f1a7b0809b92bf46aa5fd01d1e06a6fa40edde15b2842f4afa1e" @unittest.skipIf(np is None, "numpy is not installed") class ParityTests(unittest.TestCase): """plate.build against each branch's own builder: solid vertices as a set, facet count, panel vertices as a set, - bolt count. Kills: the miter clamp 0.3 -> 0.5; the cut's share (0.36, 0.64) -> (0.3, 0.7); the lift-order coin + bolt count; a plate of EVENT to its bolt count there. Kills: an EVENT bolt count one off; the miter clamp 0.3 -> 0.5; the cut's share (0.36, 0.64) -> (0.3, 0.7); the lift-order coin removed; a slab's gap ignored (raptor); the clad of Hull.Quarter left out; Hull.BellySide.R's panels moved 0.5 m. The outer test 0.97 -> 0.9 is CladTests' (no fixture facet stands between the two).""" - def held(self, made, truth, solid, panels): + def held(self, made, truth, solid, panels, event=None): + bolts, dropped = event or (truth["bolts"], 0) self.assertEqual(made["report"]["facets"], truth["facets"]) - self.assertEqual(made["report"]["bolts"], truth["bolts"]) - self.assertEqual(len(made["panels"][0]), len(truth["panels"])) + self.assertEqual(made["report"]["bolts"], bolts) + self.assertEqual(len(made["panels"][0]), len(truth["panels"]) - 3 * dropped) self.assertEqual(len(made["solid"][0]), len(truth["solid"])) self.assertLessEqual(apart(made["solid"][0], truth["solid"]), solid) - self.assertLessEqual(apart(made["panels"][0], truth["panels"]), panels) + if not dropped: + self.assertLessEqual(apart(made["panels"][0], truth["panels"]), panels) def parity(self, mech, plates): table, cases, repaired = fixture(mech)["table"], fixture(mech)["cases"], fixture(mech).get("repaired", {"truth": {}})["truth"] - seen = 0 + seen, events = 0, set() self.assertEqual(set(repaired), {name for (m, name), kind in KNOWN.items() if m == mech and kind != "float32"}) for case in cases: built = {e["name"]: e for e in plate.build(table, case["side"])} for name, truth in case["truth"].items(): - made, known = built[name], KNOWN.get((mech, name)) + made, known, event = built[name], KNOWN.get((mech, name)), EVENT.get((mech, case["side"], name)) seen += 1 + branch = repaired[name] if known == "corner" else truth + if made["report"]["bolts"] != branch["bolts"] or len(made["panels"][0]) != len(branch["panels"]): + events.add((mech, case["side"], name)) with self.subTest(plate=name, side=case["side"]): if known == "corner": V, T = made["solid"][0], np.array(truth["solid"]) d = np.linalg.norm(V[:, None, :] - T[None, :, :], axis=2) self.assertLess(float(d.min(axis=0).max()), FLOAT32[0]) # every corner of the branch's is one of these self.assertEqual(int((d.min(axis=1) > 1e-3).sum()), 1) # and one more, which the faces do bound - self.held(made, repaired[name], *FLOAT32) + self.held(made, repaired[name], *FLOAT32, event) elif known == "tie": self.assertGreater(apart(made["panels"][0], truth["panels"]), 0.1) # the branch cut from the other edge - self.held(made, dict(truth, panels=repaired[name]["panels"]), *FLOAT32) + self.held(made, dict(truth, panels=repaired[name]["panels"]), *FLOAT32, event) self.assertEqual({key: repaired[name][key] for key in ("solid", "facets", "bolts")}, {key: truth[key] for key in ("solid", "facets", "bolts")}) else: - self.held(made, truth, *(FLOAT32 if known == "float32" else (SOLID, PANELS))) + self.held(made, truth, *(FLOAT32 if known == "float32" else (SOLID, PANELS)), event) self.assertEqual(seen, plates) + self.assertEqual(events, {key for key in EVENT if key[0] == mech}) def test_bastion(self): self.parity("bastion", 23) @@ -575,14 +773,40 @@ class ParityTests(unittest.TestCase): self.assertTrue((slack < 1e-9).all()) # every corner is inside every face self.assertTrue(((np.abs(slack) < 1e-9).sum(axis=1) >= 3).all()) # and on three of them - def test_the_panels_whose_outline_crosses_itself(self): - crossed = set() - for mech in ("bastion", "paladin", "raptor"): - for case in fixture(mech)["cases"]: - for entry in plate.build(fixture(mech)["table"], case["side"]): - if entry["name"] in case["truth"]: - crossed |= {(mech, case["side"], entry["name"], k) for k, three in enumerate(rings(entry["panels"])) if any(plate._crosses(ring) for ring in three)} - self.assertEqual(crossed, CROSSED) + def test_no_ring_runs_backwards(self): + """Every panel of every fixture plate, at both sides: its three rings and its bolts' ring turn left at every + corner and do not cross, the rim's edges run the way the outline's do, and no two of its bolts' heads overlap. + Kills: the edge event removed (bastion's Hull.Cheek first); the merge of near heads removed.""" + prism, bolt, heads, panels = plate.prism, plate.hex_bolt, [], 0 + + def spy_prism(*args): + heads.append([]) + return prism(*args) + + def spy_bolt(mesh, origin, x, y, z, r, depth): + heads[-1].append((float(origin @ x), float(origin @ y), r)) + return bolt(mesh, origin, x, y, z, r, depth) + with mock.patch.object(plate, "prism", spy_prism), mock.patch.object(plate, "hex_bolt", spy_bolt): + for mech in ("bastion", "paladin", "raptor"): + for side, name, table in sides(mech): + del heads[:] + drawn = list(rings(plate.build(table, side)[0]["panels"])) + self.assertEqual(len(drawn), len(heads)) + for k, (three, ring) in enumerate(zip(drawn, heads)): + panels += 1 + with self.subTest(mech=mech, side=side, plate=name, panel=k): + for one in three: + self.assertGreater(float(turns(one).min()), 0) + self.assertFalse(plate._crosses(one)) + self.assertGreater(float(((np.roll(three[2], -1, axis=0) - three[2]) * (np.roll(three[0], -1, axis=0) - three[0])).sum(axis=1).min()), 0) + at = np.array([h[:2] for h in ring]).reshape(-1, 2) + if len(at) > 2: + self.assertGreater(float(turns(at).min()), 0) + self.assertFalse(plate._crosses(at)) + for i in range(len(at)): + for j in range(i): + self.assertGreaterEqual(float(np.linalg.norm(at[i] - at[j])), 2 * ring[0][2]) + self.assertEqual(panels, 128) if __name__ == "__main__": From 555b6124fafc104b9a37df00e2b81c4bd944dc53 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 16:51:34 +0100 Subject: [PATCH 220/223] plate.inset2d: half-planes where an edge runs backwards; a sharp corner held only where that is sound; a reflex outline refused; the merge restart held Soul s1 on cut plate-inset-edge-event: - clamped-event-bolts-off-plate: the forwards test reads where the lines cross, not the corners held at MITER; an edge running backwards gives the outline clipped by every edge's half-plane, so no corner leaves the outline. Blade plates (14 to 32 degrees) and 3,000 drawn rings hold it. - nonconvex-thin-tab-erases-ring: an outline that is not convex with an edge running backwards is refused at slab.outline (NotConvex); the oracle test holds the 6 raptor calls c clear of every edge. - merge-restart-unpinned: three near heads across the ring start are one. - cut-hard-plate-action.s1.live-test-bolts-literal-pr46: tests/live/kitbash_plates.py reads the bolt polygon count off plate.build. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/plate.py | 63 ++++---- surfaces/blender/docs/kitbash.md | 24 ++- surfaces/blender/tests/live/kitbash_plates.py | 4 +- surfaces/blender/tests/test_plate.py | 140 ++++++++++++++++-- 4 files changed, 179 insertions(+), 52 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/plate.py b/surfaces/blender/brokkr_kitbash/plate.py index 93573f7..8789fad 100644 --- a/surfaces/blender/brokkr_kitbash/plate.py +++ b/surfaces/blender/brokkr_kitbash/plate.py @@ -48,6 +48,7 @@ TIE = 1e-9 # areas (m2) and lengths (m) closer than this are equal: th OUTER = 0.97 # clad facets "outer": the facet's normal on the face's normal is over this SHARE = (0.36, 0.64) # where a split panel's cut falls along the facet's longest edge MITER = 0.3 # an inset corner moves at most c / MITER +REFLEX = 1e-6 # an outline corner turning right by more than this (the sine) makes the outline not convex PANEL_MIN = (0.25, 0.02) # a panel under this share of its facet, or under this many m2, is not made SINK, CHAMFER = 0.02, 0.02 # a panel starts this far under its facet; its far rim is chamfered this much BOLT = 0.028 @@ -59,6 +60,10 @@ class PlateError(ValueError): """The plate table breaks a rule of the format, or a row bounds no solid; the message names the path.""" +class NotConvex(PlateError): + """inset2d met an edge running backwards on an outline that is not convex: half-planes do not bound that one.""" + + # --- reading the table ---------------------------------------------------------------------------------------------- def _number(value: Any, path: str, low: float | None = None, high: float | None = None) -> float: if not core.finite(value): @@ -339,35 +344,37 @@ def plane_basis(normal, up=(0.0, 0.0, 1.0), right=None, path: str = "plane"): def inset2d(ring, c: float) -> np.ndarray: - """A convex counter-clockwise outline moved in by c on every edge; a sharp corner moves at most c / MITER. An - edge the move leaves running backwards (or no longer than TIE) is dropped, the shortest first, and its two - neighbours meet where their own lines moved in by c cross. Empty, shape (0, 2), when nothing is left: under - three edges, or two neighbours that never meet.""" + """A counter-clockwise outline moved in by c on every edge, and it stands inside the outline. Each corner moves + along its miter to where its two edges' lines, moved in by c, cross. Where every edge still runs forwards + (longer than TIE) those corners are the answer, a sharp one held to c / MITER from where it was unless that + turns the ring the other way at some corner. Otherwise a convex outline gives what its edges' half-planes, each + moved in by c, leave of it, sharp corners and all: empty, shape (0, 2), when that is nothing. An outline that is + not convex is refused there: NotConvex, naming the first point whose edge ran backwards; a slab's row adds its + path.""" ring = np.asarray(ring, dtype=np.float64) count = len(ring) ways = [(ring[(k + 1) % count] - ring[k]) / np.linalg.norm(ring[(k + 1) % count] - ring[k]) for k in range(count)] lefts = [np.array([-e[1], e[0]]) for e in ways] - out = np.empty_like(ring) + turn = lambda into, away: float(into[0] * away[1] - into[1] * away[0]) # noqa: E731 + met, out = np.empty_like(ring), np.empty_like(ring) for i in range(count): n0 = lefts[i - 1] miter = n0 + lefts[i] length = np.linalg.norm(miter) miter = miter / length if length > 0 else n0 + met[i] = ring[i] + miter * (c / max(float(miter @ n0), 1e-12)) out[i] = ring[i] + miter * (c / max(float(miter @ n0), MITER)) - live, pts = list(range(count)), list(out) # pts[i] starts edge live[i] - while True: - m = len(live) - runs = [float((pts[(i + 1) % m] - pts[i]) @ ways[live[i]]) for i in range(m)] - i = min(range(m), key=runs.__getitem__) - if runs[i] > TIE: - return out if m == count else np.array(pts) - a, b = live[i - 1], live[(i + 1) % m] - cross = ways[a][0] * ways[b][1] - ways[a][1] * ways[b][0] - if m <= 3 or abs(cross) < 1e-12: - return np.zeros((0, 2)) - start = ring[b] + lefts[b] * c - ring[a] - lefts[a] * c - pts[(i + 1) % m] = ring[a] + lefts[a] * c + ways[a] * ((start[0] * ways[b][1] - start[1] * ways[b][0]) / cross) - del pts[i], live[i] + back = [k for k in range(count) if float((met[(k + 1) % count] - met[k]) @ ways[k]) <= TIE] + if not back and (np.array_equal(met, out) or all( + turn(out[k] - out[k - 1], out[(k + 1) % count] - out[k]) * turn(ways[k - 1], ways[k]) >= 0 for k in range(count))): + return out + if any(turn(ways[k - 1], ways[k]) < -REFLEX for k in range(count)): + raise NotConvex(f"the outline is not convex and, moved in {c}, " + (f"its edge from point {back[0]} runs backwards" if back else "a sharp corner turns it the other way")) + left = list(ring) + for k in range(count): + left = clip(left, ring[k] + lefts[k] * c, -lefts[k]) + left = [p for k, p in enumerate(left) if np.linalg.norm(p - left[k - 1]) > TIE] + return np.array(left) if len(left) > 2 else np.zeros((0, 2)) def slab_points(origin, a, b, n, outline, thick: float, taper: float, back: float, gap: float) -> np.ndarray: @@ -461,13 +468,17 @@ def _row_points(row: dict, path: str): origin = np.array(slab["at"]) a, b, n = plane_basis(slab["normal"], slab["up"], slab.get("right"), f"{at}.normal") ring = np.array(outline_points(slab["outline"]), dtype=np.float64) - _check_ring(ring, f"{at}.{'corners' if 'corners' in slab else 'outline'}") - drawn = inset2d(ring if _area2(ring) > 0 else ring[::-1], slab["gap"]) if slab["gap"] else ring - if slab["gap"] and _area2(drawn) <= 0: - raise PlateError(f"{at}.gap: {slab['gap']} leaves nothing of the outline") - if slab["taper"] and 2 * slab["taper"] >= _width(drawn): - raise PlateError(f"{at}.taper: {slab['taper']} is half the outline's least width ({_width(drawn):.4f}) or more") - points = slab_points(origin, a, b, n, ring, slab["thick"], slab["taper"], slab["back"], slab["gap"]) + key = f"{at}.{'corners' if 'corners' in slab else 'outline'}" + _check_ring(ring, key) + try: + drawn = inset2d(ring if _area2(ring) > 0 else ring[::-1], slab["gap"]) if slab["gap"] else ring + if slab["gap"] and _area2(drawn) <= 0: + raise PlateError(f"{at}.gap: {slab['gap']} leaves nothing of the outline") + if slab["taper"] and 2 * slab["taper"] >= _width(drawn): + raise PlateError(f"{at}.taper: {slab['taper']} is half the outline's least width ({_width(drawn):.4f}) or more") + points = slab_points(origin, a, b, n, ring, slab["thick"], slab["taper"], slab["back"], slab["gap"]) + except NotConvex as error: + raise PlateError(f"{key}: {error}") from None face = (origin, a, b, n) elif "sections" in row: points = section_points(row["sections"]) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index c82223f..eda6812 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1055,11 +1055,16 @@ that ring has no bolts, and bolts whose centres would stand under 2 `bolt_r` apa (neighbours in ring order, the first such pair first, until none is left). One inset, `inset2d`, makes every such ring: a slab's `gap` and `taper`, a panel's outline, its rim and its bolt -ring. It moves each corner along its miter (a sharp corner at most the distance / 0.3). An edge that move leaves -running backwards, its two ends passed over each other, is dropped, the shortest first, and its two neighbours -meet where their own lines moved in cross; under three edges, or two neighbours that never meet, nothing is left -and the ring is empty. For a convex outline with no corner at the 0.3 limit that is exactly what stands the -distance inside every edge. A ring no edge of which runs backwards is the corner move alone, to the byte. +ring. What it returns stands inside the outline. It moves each corner along its miter to where its two edges' +lines, moved in, cross. Where every edge then still runs forwards, those corners are the ring, a sharp one held to +the distance / 0.3 from where it was (unless that would turn the ring the other way at some corner): the corner +move alone, to the byte. Where an edge runs backwards, its two ends passed over each other, a convex outline +gives what its edges' half-planes, each moved in, leave of it: the edges with no room are gone, the sharp corners +stand where the lines cross, and where nothing is left the ring is empty. So a sharp corner jumps inward, from +the 0.3 limit to the crossing, at the distance where the ring first loses an edge. A slab's outline need not be +convex: with every edge running forwards it is moved corner by corner; with one running backwards `check` refuses +the row at `slab.outline` (or `slab.corners`), naming the first point whose edge did, because half-planes do not +bound such an outline. ### Anchors @@ -1116,9 +1121,12 @@ The branches' inset has no edge event, so 31 of the 126 are held to another bolt others lose one to four to a ring with no room, a dropped edge or heads that would overlap. Two of them, bastion's `Hull.Cheek.R` and paladin's `Thigh.Outer`, have a panel whose outline dropped a corner, and that panel's vertices are held to no truth. What holds every ring instead: every `inset2d` call the three fixtures make at both sides (812) stands -inside its outline, and the 782 with no corner at the miter limit equal, within 1e-12 m, the outline's half-planes -moved in and clipped (37 of them an edge or more short, 22 empty); and no panel ring or bolt ring of any plate at -either side turns right or crosses, and no two bolt heads of a panel overlap. +inside its outline. The 6 on a slab outline that is not convex are the corner move, every corner the distance +clear of every edge; 24 hold a sharp corner at the 0.3 limit with every edge running forwards; the other 782 +equal, within 1e-12 m, the outline's half-planes moved in and clipped (37 of them an edge or more short, 22 +empty). 3,000 drawn convex rings are held the same way, and every bolt of 104 blade plates (tips of 14 to 32 +degrees) stands whole on its plate. No panel ring or bolt ring of any plate at either side turns right or +crosses, and no two bolt heads of a panel overlap. The same test builds the three fixtures to one sha256 of every coordinate rounded to 1e-9 m and every face, pinned from Starfire (Windows 11, numpy 2.5.4) and Yggdrasil (Debian 13, numpy 2.2.4 on the system LAPACK). The diff --git a/surfaces/blender/tests/live/kitbash_plates.py b/surfaces/blender/tests/live/kitbash_plates.py index fe3b326..8463e73 100644 --- a/surfaces/blender/tests/live/kitbash_plates.py +++ b/surfaces/blender/tests/live/kitbash_plates.py @@ -275,14 +275,14 @@ try: check("plates on the thigh are accepted and none is a rebuild", receipt["status"] == "accepted" and [row["rebuilt"] for row in report["plates"]] == [False], [receipt["status"], receipt["message"]]) R["reports"]["thigh"] = report bpy.context.view_layer.update() - proven("a plate on the thigh, the frame the host's", THIGH, 1, "Thigh.", thigh, world(thigh), report) + _, thigh_built = proven("a plate on the thigh, the frame the host's", THIGH, 1, "Thigh.", thigh, world(thigh), report) receipt, report = send("brokkr_kitbash.plates", host="Shin", prefix="Shin.", table=json.dumps(SHIN)) bpy.context.view_layer.update() shin_table, shin_built = proven("a plate on the shin, under the pin", SHIN, 1, "Shin.", shin, world(shin), report) guard = bpy.data.objects["Thigh.Guard"] check("a plate with a panel and its bolts has two fit children and two anchors, and the panel's child alone a bevel", sorted(c.name for c in guard.children) == ["Thigh.Guard.fit.gunmetal", "Thigh.Guard.fit.olive_light", "Thigh.Guard.mark.num", "Thigh.Guard.port.feed"] - and len(bpy.data.objects["Thigh.Guard.fit.gunmetal"].data.polygons) == 8 * 8 and bevel(bpy.data.objects["Shin.Guard.fit.olive_light"]) == (0.009, 20.0, 1, "ANGLE") + and len(bpy.data.objects["Thigh.Guard.fit.gunmetal"].data.polygons) == len(thigh_built[0]["bolts"][1]) > 0 and bevel(bpy.data.objects["Shin.Guard.fit.olive_light"]) == (0.009, 20.0, 1, "ANGLE") and len(bpy.data.objects) == count + 10, [sorted(c.name for c in guard.children), len(bpy.data.objects["Thigh.Guard.fit.gunmetal"].data.polygons), len(bpy.data.objects) - count]) _, joints_after = send("brokkr_kitbash.joints", object_name="Thigh") check("roll-carries: joints lists the same rows with the plates as without", joints_before is not None and joints_after == joints_before, joints_after) diff --git a/surfaces/blender/tests/test_plate.py b/surfaces/blender/tests/test_plate.py index c3e3388..99b1a94 100644 --- a/surfaces/blender/tests/test_plate.py +++ b/surfaces/blender/tests/test_plate.py @@ -15,6 +15,7 @@ import importlib import inspect import json import math +import random import sys import types import unittest @@ -137,6 +138,29 @@ def half_planes(ring, c): return np.array(poly) +def clear(points, ring): + """How far the nearest edge of a ring (the segment, not its line) stands from each point.""" + ring, points = np.asarray(ring, dtype=np.float64), np.asarray(points, dtype=np.float64) + a, edge = ring[None, :, :], (np.roll(ring, -1, axis=0) - ring)[None, :, :] + along = np.clip(((points[:, None, :] - a) * edge).sum(axis=2) / (edge * edge).sum(axis=2), 0, 1) + return np.linalg.norm(points[:, None, :] - a - edge * along[:, :, None], axis=2).min(axis=1) + + +def within(point, ring): + """Whether a point stands inside a ring, convex or not: a ray to +x crosses its edges an odd number of times.""" + a, b = np.asarray(ring, dtype=np.float64), np.roll(np.asarray(ring, dtype=np.float64), -1, axis=0) + over = (a[:, 1] > point[1]) != (b[:, 1] > point[1]) + return bool(np.sum(a[over, 0] + (point[1] - a[over, 1]) * (b[over, 0] - a[over, 0]) / (b[over, 1] - a[over, 1]) > point[0]) % 2) + + +def blade(tip, length, rear, bolt_r=0.03): + """A blade plate 0.4 thick, its tip at the origin `tip` degrees wide, `rear` across its far end, clad on top.""" + half = math.tan(math.radians(tip / 2)) * 0.7 * length + top = [(0, 0), (0.7 * length, -half), (length, -rear / 2), (length, rear / 2), (0.7 * length, half)] + clad = {"mat": "c", "facets": [{"n": [0, 0, 1], "cos": 0.6}], "min_area": 0.01, "lifts": [0.045, 0.075], "inset": 0.11, "gap": 0.05, "split": 99, "seed": 1, "bolt_r": bolt_r} + return doc(row("Fin", clad=clad, points=[[x, y, z] for z in (0, 0.4) for x, y in top])) + + def turns(ring): """Each corner's turn (the cross product of the unit edges into and out of it): over 0 is a left turn.""" ring = np.asarray(ring, dtype=np.float64) @@ -164,9 +188,10 @@ def sides(mech): @unittest.skipIf(np is None, "numpy is not installed") class InsetTests(unittest.TestCase): - """plate.inset2d, the one inset of every ring. Kills: the edge event removed; the vanish test at three edges - made two; the shortest-first pick made the first edge found (the clamped sliver alone: without a clamped corner - every order drops the same edges).""" + """plate.inset2d, the one inset of every ring. Kills: the half-planes left out (the corner move returned whatever + its edges do); the forwards test read off the corners held at MITER and not off where the lines cross; the turn + test of the held corners removed; a ring that is not convex given to the half-planes; a right turn of a rounding + read as not convex; a half-plane left out; the ring of under three corners or of corners TIE apart returned.""" def test_a_short_edge_is_dropped_and_its_neighbours_meet(self): ring = [[0, 0], [4, 0], [4, 3], [2.1, 4], [1.9, 4]] # the top edge is 0.2 long @@ -192,11 +217,51 @@ class InsetTests(unittest.TestCase): self.assertEqual(plate.inset2d(ring, c).tobytes(), corner_move(ring, c)[0].tobytes()) self.assertTrue(corner_move([[0, 0], [5, 0], [0, 1]], 0.1)[1]) # its sharp corner is clamped - def test_the_shortest_edge_goes_first(self): - sliver = [[11, 1], [12, 1], [6, 3], [4, 3], [6, 2]] # two corners clamped, three edges run backwards - made = plate.inset2d(sliver, 0.5) - self.assertLess(apart2(made, np.array([[6.516380, 2.300827], [5.918861, 2.5], [5.622082, 2.617078]])), 1e-6) - self.assertGreater(float(depths(made, sliver).min()), 0) + def test_a_sharp_corner_held_back_is_no_way_out_of_the_outline(self): + sliver = [[11, 1], [12, 1], [6, 3], [4, 3], [6, 2]] # two corners sharp: an edge goes at 0.3, all of it at 0.5 + kite = [[4, 1], [7, 0], [3, 2], [0, 3]] # held at MITER every edge runs forwards, and two corners stand outside + wedge = [[0, 1], [6, 1], [7, 3], [3, 2]] # every edge runs forwards where the lines cross; held, the ring turns right + for ring, c, corners in ((sliver, 0.3, 4), (sliver, 0.5, 0), (kite, 0.5, 0), (wedge, 0.5, 4)): + made = plate.inset2d(ring, c) + self.assertEqual(len(made), corners) + self.assertLess(apart2(made, half_planes(ring, c)), 1e-12) + self.assertLess(float(depths(corner_move(kite, 0.5)[0], kite).min()), -0.05) + self.assertLess(float(turns(corner_move(wedge, 0.5)[0]).min()), 0) + + def test_every_inset_of_a_convex_ring_stands_inside_it(self): + draw, rings_, held, dropped, empty = random.Random(7), 0, 0, 0, 0 + while rings_ < 3000: + at = sorted(draw.uniform(0, 2 * math.pi) for _ in range(draw.choice((3, 4, 5, 6, 7)))) + wide, tall = draw.uniform(0.15, 2.0), draw.uniform(0.02, 0.5) + ring = np.array([[wide * math.cos(u), tall * math.sin(u)] for u in at]) + if float(np.linalg.norm(np.roll(ring, -1, axis=0) - ring, axis=1).min()) < 0.005 or float(turns(ring).min()) < 1e-4: + continue + c, rings_ = draw.choice((0.01, 0.03, 0.1, 0.25)), rings_ + 1 + made, (moved, clamped) = plate.inset2d(ring, c), corner_move(ring, c) + if made.tobytes() == moved.tobytes(): + held += clamped + self.assertGreater(float(depths(made, ring).min()), 0) + self.assertGreater(float(turns(made).min()), 0) + self.assertLess(apart2(made, half_planes(ring, c)), 1e-12 if not clamped else math.inf) + else: + dropped, empty = dropped + (len(made) > 0), empty + (not len(made)) + self.assertLess(apart2(made, half_planes(ring, c)), 1e-12) + self.assertEqual((held, dropped, empty), HELD) + + def test_an_outline_that_is_not_convex_is_moved_or_refused(self): + tab = [[0, 0], [4, 0], [4, 2], [2.2, 2], [2.2, 2.8], [1.8, 2.8], [1.8, 2], [0, 2]] # a tab 0.4 wide on a 4 by 2 body + for c in (0.05, 0.15): + made = plate.inset2d(tab, c) + self.assertEqual(made.tobytes(), corner_move(tab, c)[0].tobytes()) + self.assertGreater(float(clear(made, tab).min()), c - 1e-12) + self.assertTrue(all(within(p, tab) for p in made) and not plate._crosses(made)) + with self.assertRaises(plate.NotConvex) as caught: + plate.inset2d(tab, 0.25) + self.assertIn("its edge from point 4 runs backwards", str(caught.exception)) + straight = [[0, 0], [3 * 0.3, 3 * 0.3 * 0.3], [3, 3 * 0.3], [3, 3 * 0.3 + 0.2], [0, 1]] # its second point is on a straight run + self.assertTrue(-1e-12 < float(turns(straight)[1]) < 0) # and turns right by a rounding: that is no outline to refuse + self.assertEqual(len(plate.inset2d(straight, 0.15)), 3) + self.assertLess(apart2(plate.inset2d(straight, 0.15), half_planes(straight, 0.15)), 1e-12) def test_every_inset_of_the_fixtures_is_what_the_half_planes_leave(self): inset, calls = plate.inset2d, [] @@ -208,18 +273,26 @@ class InsetTests(unittest.TestCase): for mech in ("bastion", "paladin", "raptor"): for side in (1, -1): plate.build(fixture(mech)["table"], side) - held = dropped = empty = 0 + reflex = held = dropped = empty = 0 for ring, c, made in calls: - if float(turns(ring).min()) <= 0: # a slab's outline need not be convex: no edge of those runs backwards - self.assertEqual(made.tobytes(), corner_move(ring, c)[0].tobytes()) + moved, clamped = corner_move(ring, c) + if float(turns(ring).min()) <= 0: # a slab's outline need not be convex: every corner moved, c clear of every edge + reflex += 1 + self.assertEqual(made.tobytes(), moved.tobytes()) + self.assertFalse(clamped) + self.assertGreater(float(clear(made, ring).min()), c - 1e-12) + self.assertTrue(all(within(p, ring) for p in made) and not plate._crosses(made)) + self.assertGreater(float((turns(made) * turns(ring)).min()), 0) continue if len(made): - self.assertGreater(float(depths(made, ring).min()), 0) # clamped or not, it stands inside its outline + self.assertGreater(float(depths(made, ring).min()), 0) # it stands inside its outline self.assertGreater(float(turns(made).min()), 0) - if not corner_move(ring, c)[1]: - self.assertLess(apart2(made, half_planes(ring, c)), 1e-12) - held, dropped, empty = held + 1, dropped + (0 < len(made) < len(ring)), empty + (not len(made)) - self.assertEqual((len(calls), held, dropped, empty), (812, 782, 37, 22)) + if clamped and made.tobytes() == moved.tobytes(): + held += 1 # a sharp corner held at MITER: inside, turning left, not the half-planes + continue + self.assertLess(apart2(made, half_planes(ring, c)), 1e-12) + dropped, empty = dropped + (0 < len(made) < len(ring)), empty + (not len(made)) + self.assertEqual((len(calls), reflex, held, dropped, empty), (812, 6, 24, 37, 22)) @unittest.skipIf(np is None, "numpy is not installed") @@ -293,6 +366,12 @@ class CheckTests(unittest.TestCase): def test_outline_of_zero_area(self): self.refused(doc(row(slab=dict(SLAB, outline=[[0, 0], [1, 0], [2, 0]]))), "plates[0].slab.outline: the outline has zero area") + def test_an_outline_not_convex_that_the_gap_or_the_taper_collapses(self): + tab = [[0, 0], [4, 0], [4, 2], [2.2, 2], [2.2, 2.8], [1.8, 2.8], [1.8, 2], [0, 2]] + self.refused(doc(row(slab=dict(SLAB, outline=tab, gap=0.25))), "plates[0].slab.outline: the outline is not convex and, moved in 0.25, its edge from point 4 runs backwards") + self.refused(doc(row(slab=dict(SLAB, outline=tab, gap=0.15, taper=0.06))), "plates[0].slab.outline: the outline is not convex and, moved in 0.06,") + plate.check(doc(row(slab=dict(SLAB, outline=tab, gap=0.15)))) + def test_slab_ranges(self): for key, low, high in (("thick", 0.0005, 2.5), ("taper", -0.01, 0.6), ("back", 0.05, 1.6), ("gap", -0.01, 0.6)): for value in (low, high): @@ -547,6 +626,34 @@ class CladTests(unittest.TestCase): self.assertTrue(plate.panel(panels, bolts, thin, np.array([0.0, 0.0, 1.0]), 0.04, 0.0, 0.028)) self.assertEqual((len(panels.done()[0]), len(bolts.done()[0])), (12, 0)) + def test_three_near_heads_across_the_ring_start_are_one(self): + """Kills: the merge going on from the pair before in place of the first pair (it leaves two heads 1.9 r apart).""" + r = 0.03 + heads = np.array([[1.9, 0.9], [1.5, 40], [-18, 40], [-18, 9], [0, 0], [1.9, -0.9]]) * r # the last and the first 1.8 r apart, their middle 1.9 r from the one before + outline = corner_move(heads, -(0.05 + 3.2 * r))[0] + self.assertLess(apart2(plate.inset2d(plate.inset2d(outline, 0.05), 3.2 * r), heads), 1e-12) + bolts = plate._Mesh() + self.assertTrue(plate.panel(plate._Mesh(), bolts, [np.array([x, y, 0.0]) for x, y in outline], np.array([0.0, 0.0, 1.0]), 0.04, 0.05, r)) + made = bolts.done()[0].reshape(-1, 12, 3).mean(axis=1)[:, :2] + self.assertLess(apart2(made, np.array([[1.5, 40], [-18, 40], [-18, 9], [0.95, 0]]) * r), 1e-12) + + def test_every_bolt_of_a_blade_plate_stands_on_it(self): + """Kills: the half-planes left out (10 of these blades then put a bolt off the plate, the worst 3.3 m).""" + entry = plate.build(blade(20, 1.5, 0.3), 1)[0] # its bolt ring is narrower than the bolts stand in: no ring, no bolts + self.assertEqual((entry["report"]["panels"], entry["report"]["bolts"]), (1, 0)) + bolted, least = 0, math.inf + for tip in (14, 16, 18, 20, 22, 25, 28, 32): + for length in (0.8, 1.2, 1.5, 2.0, 3.0): + for rear in (0.1, 0.2, 0.3, 0.4, 0.6): + entry = plate.build(blade(tip, length, rear), 1)[0] + V, faces = entry["solid"] + (top,) = [face for face in faces if all(V[k][2] > 0.3 for k in face)] + if entry["report"]["bolts"]: + bolted += 1 + least = min(least, float(depths(entry["bolts"][0].reshape(-1, 12, 3).mean(axis=1)[:, :2], V[top][:, :2]).min())) + self.assertEqual(bolted, 104) + self.assertGreater(least, 0.03) # a head's corners reach bolt_r: every head whole on its facet + def test_a_rim_the_chamfer_leaves_fewer_corners_is_the_outline(self): mesh, axes = plate._Mesh(), np.eye(3) plate.prism(mesh, np.zeros(3), *axes, np.array([[0, 0], [1, 0], [1, 1], [0.502, 1.2], [0.498, 1.2], [0, 1]], dtype=float), 0.1, 0.02) @@ -707,6 +814,7 @@ EVENT = {("bastion", 1, "Hull.Cheek.R"): (32, 1), ("bastion", 1, "Hull.Cheek.L") # 2.5.4) and Yggdrasil (Debian 13, numpy 2.2.4 on the system LAPACK) give this hash; their numbers (every coordinate and anchor matrix # entry) differ in 2,821 of 30,909 by up to 2.7e-15 m and in no face. QUANTUM is TIE: 3.7e5 times that, and 1e3 under the least difference KNOWN holds (1.06e-6 m). QUANTUM = 1e-9 +HELD = (816, 585, 1022) # of 3,000 drawn convex rings: sharp corners held at MITER, rings that lost an edge, rings left empty HASH = "ee58f30a9492f1a7b0809b92bf46aa5fd01d1e06a6fa40edde15b2842f4afa1e" From efab6f655d37ad207c8ea819c0fcfbb7cb8afd17 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 16:52:23 +0100 Subject: [PATCH 221/223] tests/live/kitbash_plates.result.json: the run at the half-plane inset (54 checks, 4 bolts a guard) Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/kitbash_plates.result.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/surfaces/blender/tests/live/kitbash_plates.result.json b/surfaces/blender/tests/live/kitbash_plates.result.json index 73d80c8..be8856e 100644 --- a/surfaces/blender/tests/live/kitbash_plates.result.json +++ b/surfaces/blender/tests/live/kitbash_plates.result.json @@ -278,7 +278,7 @@ "carried": 1e-07, "moved": 2.1e-07, "ported": 3.9e-08, - "written": 8.5e-08 + "written": 8.4e-08 }, "reports": { "thigh": { @@ -289,7 +289,7 @@ "corners": 16, "facets": 10, "panels": 1, - "bolts": 8, + "bolts": 4, "anchors": [ "Thigh.Guard.port.feed", "Thigh.Guard.mark.num" From 86b123685eecb9ca5110c0ef7116423cdccfeb51 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 18:02:28 +0100 Subject: [PATCH 222/223] plate.inset2d follows the ring in, edge by edge; NotSimple where it would meet itself; build builds what check passes; any two near bolt heads are one; the tip step stated (cut plate-inset-edge-event, Soul s2) - build-nonconvex-facet: a facet ring that would meet itself takes no panel, bolts or rim, never a refusal - heads-overlap-across-ring: the merge reads pairs further apart round the ring after neighbours; 0 overlaps on 3,591 blades - nonconvex-refusal-both-ways: the tab builds once its end runs out; a neck is refused at half its width, by check and build alike - tip-jump-at-edge-drop: kitbash.md states the step and a test pins it Co-Authored-By: Claude Opus 5.5 --- surfaces/blender/brokkr_kitbash/plate.py | 138 +++++++++++++---- surfaces/blender/docs/kitbash.md | 61 ++++++-- surfaces/blender/tests/test_plate.py | 189 ++++++++++++++++++++--- 3 files changed, 318 insertions(+), 70 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/plate.py b/surfaces/blender/brokkr_kitbash/plate.py index 8789fad..be0150c 100644 --- a/surfaces/blender/brokkr_kitbash/plate.py +++ b/surfaces/blender/brokkr_kitbash/plate.py @@ -48,7 +48,8 @@ TIE = 1e-9 # areas (m2) and lengths (m) closer than this are equal: th OUTER = 0.97 # clad facets "outer": the facet's normal on the face's normal is over this SHARE = (0.36, 0.64) # where a split panel's cut falls along the facet's longest edge MITER = 0.3 # an inset corner moves at most c / MITER -REFLEX = 1e-6 # an outline corner turning right by more than this (the sine) makes the outline not convex +REFLEX = 1e-6 # a corner turning right by more than this (radians) can reach an edge that is not its own +PARALLEL = 1e-9 # two edges whose normals cross by less than this (the sine) are parallel PANEL_MIN = (0.25, 0.02) # a panel under this share of its facet, or under this many m2, is not made SINK, CHAMFER = 0.02, 0.02 # a panel starts this far under its facet; its far rim is chamfered this much BOLT = 0.028 @@ -60,8 +61,8 @@ class PlateError(ValueError): """The plate table breaks a rule of the format, or a row bounds no solid; the message names the path.""" -class NotConvex(PlateError): - """inset2d met an edge running backwards on an outline that is not convex: half-planes do not bound that one.""" +class NotSimple(PlateError): + """inset2d cannot keep the ring simple: moved in, a corner that turns right reaches an edge that is not its own.""" # --- reading the table ---------------------------------------------------------------------------------------------- @@ -345,18 +346,22 @@ def plane_basis(normal, up=(0.0, 0.0, 1.0), right=None, path: str = "plane"): def inset2d(ring, c: float) -> np.ndarray: """A counter-clockwise outline moved in by c on every edge, and it stands inside the outline. Each corner moves - along its miter to where its two edges' lines, moved in by c, cross. Where every edge still runs forwards - (longer than TIE) those corners are the answer, a sharp one held to c / MITER from where it was unless that - turns the ring the other way at some corner. Otherwise a convex outline gives what its edges' half-planes, each - moved in by c, leave of it, sharp corners and all: empty, shape (0, 2), when that is nothing. An outline that is - not convex is refused there: NotConvex, naming the first point whose edge ran backwards; a slab's row adds its - path.""" + along its miter, where its two edges' lines, moved in, cross. Where no edge runs out of length on the way (TIE) + those corners are the answer, a sharp one held to c / MITER from where it was unless that turns the ring the + other way at some corner. Otherwise the ring is followed in: the edge that runs out first is dropped where it + does and its neighbours meet there, then the next, the sharp corners standing where the lines cross; two edges + left facing each other on one line take the shorter away, two left on one line are one. Empty, shape (0, 2), + when nothing is left. A corner that turns right can reach an edge that is not its own before c: the ring would + meet itself there, and NotSimple names them; a slab's row adds its path. An outline with no right turn over + REFLEX never does.""" ring = np.asarray(ring, dtype=np.float64) count = len(ring) ways = [(ring[(k + 1) % count] - ring[k]) / np.linalg.norm(ring[(k + 1) % count] - ring[k]) for k in range(count)] lefts = [np.array([-e[1], e[0]]) for e in ways] turn = lambda into, away: float(into[0] * away[1] - into[1] * away[0]) # noqa: E731 + move = lambda n0, n1: (n0 + n1) * (2.0 / max(float((n0 + n1) @ (n0 + n1)), 1e-24)) # noqa: E731 the miter over its cosine, with no 1 + cos lost to rounding at a sharp corner met, out = np.empty_like(ring), np.empty_like(ring) + corners = [] # where a corner stood, at what inset, its move per metre, its turn for i in range(count): n0 = lefts[i - 1] miter = n0 + lefts[i] @@ -364,15 +369,68 @@ def inset2d(ring, c: float) -> np.ndarray: miter = miter / length if length > 0 else n0 met[i] = ring[i] + miter * (c / max(float(miter @ n0), 1e-12)) out[i] = ring[i] + miter * (c / max(float(miter @ n0), MITER)) - back = [k for k in range(count) if float((met[(k + 1) % count] - met[k]) @ ways[k]) <= TIE] - if not back and (np.array_equal(met, out) or all( - turn(out[k] - out[k - 1], out[(k + 1) % count] - out[k]) * turn(ways[k - 1], ways[k]) >= 0 for k in range(count))): - return out - if any(turn(ways[k - 1], ways[k]) < -REFLEX for k in range(count)): - raise NotConvex(f"the outline is not convex and, moved in {c}, " + (f"its edge from point {back[0]} runs backwards" if back else "a sharp corner turns it the other way")) - left = list(ring) - for k in range(count): - left = clip(left, ring[k] + lefts[k] * c, -lefts[k]) + corners.append((ring[i], 0.0, move(n0, lefts[i]), math.atan2(turn(ways[i - 1], ways[i]), float(ways[i - 1] @ ways[i])))) + live = list(range(count)) # the edges left, in ring order: corner j stands where live[j - 1] meets live[j] + + def at(j: int, t: float) -> np.ndarray: + q, since, move, _ = corners[j % len(corners)] + return q + move * (t - since) + now = 0.0 + while len(live) > 2: + n = len(live) + first, when = None, math.inf + for j in range(n): # the edge that runs out first, of those with no length left at c + if float((at(j + 1, c) - at(j, c)) @ ways[live[j]]) > TIE: + continue + length, rate = float((at(j + 1, now) - at(j, now)) @ ways[live[j]]), float((corners[(j + 1) % n][2] - corners[j][2]) @ ways[live[j]]) + t = min(now + max(length, 0.0) / -rate, c) if rate < 0 else now + if t < when: + first, when = j, t + for j in range(n): # a corner turning right that reaches another edge before that + if corners[j][3] >= -REFLEX: + continue + for m in range(n): + if m in (j, (j - 1) % n): + continue + edge = live[m] + closing = 1.0 - float(lefts[edge] @ corners[j][2]) + ahead = float(lefts[edge] @ (at(j, now) - ring[edge])) - now + if closing <= 1e-12 or ahead < -TIE: + continue + t = now + max(ahead, 0.0) / closing + if t <= min(when - TIE, c + TIE) and float((at(j, t) - at(m, t)) @ ways[edge]) >= -TIE and float((at(m + 1, t) - at(j, t)) @ ways[edge]) >= -TIE: + raise NotSimple(f"moved in {c}, the outline meets itself: the corner of the edges from points {live[j - 1]} and {live[j]} reaches the edge from point {edge}") + if first is None: + break + now = when + q, angle = at(first, now), corners[first][3] + corners[(first + 1) % n][3] + del live[first], corners[first] + i = first % len(live) # the corner the dropped edge's two ends are now + while len(live) > 2: + n = len(live) + a, b = live[i - 1], live[i] + level = abs(turn(lefts[a], lefts[b])) <= PARALLEL + if not level and angle < math.pi: # a corner: it turns left by less than half a turn + corners[i] = (q, now, move(lefts[a], lefts[b]), angle) + break + if level and float(lefts[a] @ lefts[b]) > 0: # one line: the two edges are one edge, and no corner is between them + del live[i], corners[i] + break + span = float((q - at(i - 1, now)) @ ways[a]), float((at(i + 1, now) - q) @ ways[b]) # facing each other: the shorter is gone + if span[1] < span[0] - TIE: + q, angle = at(i + 1, now), angle + corners[(i + 1) % n][3] + else: + q, angle = at(i - 1, now), angle + corners[i - 1][3] + (corners[(i + 1) % n][3] if span[1] <= span[0] + TIE else 0.0) + i = (i - 1) % n + del live[i], corners[i] + i %= len(live) + if span[1] <= span[0] + TIE: + del live[i], corners[i] + i %= max(len(live), 1) + if len(live) == count: + held = np.array_equal(met, out) or all(turn(out[k] - out[k - 1], out[(k + 1) % count] - out[k]) * turn(ways[k - 1], ways[k]) >= 0 for k in range(count)) + return out if held else met + left = [at(j, c) for j in range(len(live))] if len(live) > 2 else [] left = [p for k, p in enumerate(left) if np.linalg.norm(p - left[k - 1]) > TIE] return np.array(left) if len(left) > 2 else np.zeros((0, 2)) @@ -477,7 +535,7 @@ def _row_points(row: dict, path: str): if slab["taper"] and 2 * slab["taper"] >= _width(drawn): raise PlateError(f"{at}.taper: {slab['taper']} is half the outline's least width ({_width(drawn):.4f}) or more") points = slab_points(origin, a, b, n, ring, slab["thick"], slab["taper"], slab["back"], slab["gap"]) - except NotConvex as error: + except NotSimple as error: raise PlateError(f"{key}: {error}") from None face = (origin, a, b, n) elif "sections" in row: @@ -695,12 +753,22 @@ def clip(poly: list[np.ndarray], point: np.ndarray, normal: np.ndarray) -> list[ return out +def _moved(outline: np.ndarray, c: float) -> np.ndarray: + """inset2d for a ring build makes of a facet: empty where the outline, moved in, would meet itself. No table row + draws such a ring, so there is none to refuse; a slab's outline is refused in _row_points, which check and build + both run.""" + try: + return inset2d(outline, c) + except NotSimple: + return np.zeros((0, 2)) + + def prism(mesh: _Mesh, origin, x, y, z, outline: np.ndarray, depth: float, chamfer: float) -> None: """A block on a counter-clockwise outline, drawn depth along z, its far rim chamfered; the rim is the outline itself where the chamfer leaves it fewer corners.""" c = min(chamfer, 0.45 * depth) n = len(outline) - rim = inset2d(outline, c) if c > 1e-6 else outline + rim = _moved(outline, c) if c > 1e-6 else outline rings = [(outline, 0.0), (outline, depth - c), (rim if len(rim) == n else outline, depth)] verts = [origin + x * q[0] + y * q[1] + z * h for ring, h in rings for q in ring] faces = [list(reversed(range(n))), [2 * n + k for k in range(n)]] @@ -719,10 +787,10 @@ def hex_bolt(mesh: _Mesh, origin, x, y, z, r: float, depth: float) -> None: def panel(panels: _Mesh, bolts: _Mesh, polygon: list[np.ndarray], out: np.ndarray, lift: float, inset: float, bolt_r: float) -> bool: - """A raised panel on a flat convex polygon: the polygon moved in inset on every edge, standing lift over it from - SINK below, its far rim chamfered; a bolt inside each of its corners, 3.2 bolt_r in, none where that leaves no - ring, and bolts whose centres stand under 2 bolt_r apart made one at their middle. False for a polygon too small - for a panel, or one the inset leaves nothing of.""" + """A raised panel on a flat polygon, a facet or a part of one: the polygon moved in inset on every edge, + standing lift over it from SINK below, its far rim chamfered; a bolt inside each of its corners, 3.2 bolt_r in, + none where that leaves no ring, and any two bolts whose centres stand under 2 bolt_r apart made one at their + middle. False for a polygon too small for a panel, or one the inset leaves nothing of or cannot keep simple.""" pts = np.array(polygon) centre = pts.mean(axis=0) normal = np.cross(pts - centre, np.roll(pts, -1, axis=0) - centre).sum(axis=0) @@ -733,20 +801,22 @@ def panel(panels: _Mesh, bolts: _Mesh, polygon: list[np.ndarray], out: np.ndarra pts, normal = pts[::-1], -normal x, y = _stand(normal) flat = np.column_stack(((pts - centre) @ x, (pts - centre) @ y)) - inner = inset2d(flat, inset) + inner = _moved(flat, inset) if _area2(inner) < PANEL_MIN[0] * _area2(flat) or _area2(inner) < PANEL_MIN[1]: return False prism(panels, centre - normal * SINK, x, y, normal, inner, lift + SINK, CHAMFER) - heads = list(inset2d(inner, 3.2 * bolt_r)) - k = 0 - while k < len(heads) > 1: # neighbours in ring order, the first pair first - after = (k + 1) % len(heads) - if np.linalg.norm(heads[after] - heads[k]) < 2 * bolt_r: - heads[k] = (heads[k] + heads[after]) / 2 - del heads[after] - k = 0 - else: + heads = list(_moved(inner, 3.2 * bolt_r)) + reach, k = 1, 0 + while reach <= len(heads) // 2: # the pair fewest corners apart round the ring first, of those the first + other = (k + reach) % len(heads) + if np.linalg.norm(heads[other] - heads[k]) < 2 * bolt_r: + heads[k] = (heads[k] + heads[other]) / 2 + del heads[other] + reach, k = 1, 0 + elif k + 1 < len(heads): k += 1 + else: + reach, k = reach + 1, 0 for q in heads: hex_bolt(bolts, centre + x * q[0] + y * q[1] + normal * (lift + 0.3 * bolt_r), x, y, normal, bolt_r, 0.6 * bolt_r) return True diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index eda6812..e83da17 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1051,20 +1051,38 @@ go to the edge whose middle is greater by x, y, z. Then every chosen facet draws quarter of the part's area or under 0.02 m2; it is a prism from 0.02 below the facet to its lift above, its far rim chamfered 0.02 (not chamfered where the chamfer would cost the rim a corner). A hexagonal bolt of radius `bolt_r` stands inside each panel corner, on the panel's outline moved in 3.2 `bolt_r`: a panel with no room for -that ring has no bolts, and bolts whose centres would stand under 2 `bolt_r` apart are one bolt at their middle -(neighbours in ring order, the first such pair first, until none is left). +that ring has no bolts, and any two bolts whose centres would stand under 2 `bolt_r` apart are one bolt at their +middle, in the first one's place in the ring. Neighbours in ring order are read first, from the first corner, then +pairs one corner further apart round the ring, and after each joining the reading starts again; so no two bolt +heads of a panel overlap, neighbours or not. One inset, `inset2d`, makes every such ring: a slab's `gap` and `taper`, a panel's outline, its rim and its bolt -ring. What it returns stands inside the outline. It moves each corner along its miter to where its two edges' -lines, moved in, cross. Where every edge then still runs forwards, those corners are the ring, a sharp one held to -the distance / 0.3 from where it was (unless that would turn the ring the other way at some corner): the corner -move alone, to the byte. Where an edge runs backwards, its two ends passed over each other, a convex outline -gives what its edges' half-planes, each moved in, leave of it: the edges with no room are gone, the sharp corners -stand where the lines cross, and where nothing is left the ring is empty. So a sharp corner jumps inward, from -the 0.3 limit to the crossing, at the distance where the ring first loses an edge. A slab's outline need not be -convex: with every edge running forwards it is moved corner by corner; with one running backwards `check` refuses -the row at `slab.outline` (or `slab.corners`), naming the first point whose edge did, because half-planes do not -bound such an outline. +ring. What it returns stands inside the outline. It moves each corner along its miter, where its two edges' +lines, moved in, cross. Where no edge runs out of length on the way, those corners are the ring, a sharp one held +to the distance / 0.3 from where it was (unless that would turn the ring the other way at some corner): the +corner move alone, to the byte. Otherwise the ring is followed in, as a straight skeleton's front is: the edge +that runs out first is dropped where it does and its two neighbours meet there, then the next, and the sharp +corners stand where the lines cross. Two edges left facing each other on one line (a tab's sides when its end has +run out) take the shorter away, both when they are equal, and two left on one line are one edge. Where nothing is +left the ring is empty. For a convex outline that is what its edges' half-planes, each moved in, leave of it. + +A held corner steps. While no edge has run out, a corner sharper than 35 degrees (the sine of its half angle +under 0.3) stands distance / 0.3 along its miter; from the distance where the ring first loses an edge it stands +where its lines cross, distance / that sine along the same miter. The step is their difference and no more: on a +10.5 degree tip that loses its first edge at 0.109, from 0.36 to 1.19 m from the outline's corner. It is the +skeleton's own corner the step lands on, and it is inside the outline before and after; a facet near that +distance changes its panel by the step for a small change of `inset`. + +An outline need not be convex: a slab's may be drawn so, and facets within 0.5 degrees of each other are one +facet whose outline can turn right. Its corners that turn right move in too, faster the sharper they are (the +distance / the sine of half the corner), and such a corner can reach an edge that is not its own: a neck between +two parallel edges closes at half its width. From there the ring would meet itself and be two rings or none, and +`inset2d` refuses it (`NotSimple`, a `PlateError`), naming the corner's two edges and the edge it reaches. For a +slab's `gap` or `taper` that is the row's refusal at `slab.outline` (or `slab.corners`), from `check` and from +`build` in the same words, since both make the slab's points the same way. A facet is no row's drawing: where +the inset of a facet or of a facet's part would meet itself, that part takes no panel; where the bolt ring of a +panel would, the panel takes no bolts; where the rim would, the rim is the outline. So `build` refuses nothing +that `check` passed. ### Anchors @@ -1096,7 +1114,8 @@ Every refusal is a `PlateError` (a `ValueError`) that names the path, as `plates `plates[0].clad.seed`: a schema that is not `brokkr.plates.v0`; an unknown key anywhere; a row with no solid form or two; a name built twice; a number that is not finite; an outline under 3 points or over 64, one that crosses itself, repeats a point or has zero area; `thick`, `taper`, `back` or `gap` outside 0.001 to 2, 0 to 0.5, 0.1 to -1.5 and 0 to 0.5; a `taper` of half the outline's least width or more; corners that are not a plate; faces that +1.5 and 0 to 0.5; a `taper` of half the outline's least width or more; a `gap` or `taper` at which an outline +that is not convex would meet itself; corners that are not a plate; faces that bound nothing; points in one plane; a pair of seeds on a one-sided row, an equal pair, or no seed; an `up` along the normal; a fit on a row with no face; an unknown fit kind; two anchors of one name in a row. @@ -1123,10 +1142,18 @@ and paladin's `Thigh.Outer`, have a panel whose outline dropped a corner, and th no truth. What holds every ring instead: every `inset2d` call the three fixtures make at both sides (812) stands inside its outline. The 6 on a slab outline that is not convex are the corner move, every corner the distance clear of every edge; 24 hold a sharp corner at the 0.3 limit with every edge running forwards; the other 782 -equal, within 1e-12 m, the outline's half-planes moved in and clipped (37 of them an edge or more short, 22 -empty). 3,000 drawn convex rings are held the same way, and every bolt of 104 blade plates (tips of 14 to 32 -degrees) stands whole on its plate. No panel ring or bolt ring of any plate at either side turns right or -crosses, and no two bolt heads of a panel overlap. +equal, within 1e-12 m, the outline's half-planes moved in and clipped by the test's own clipper (37 of them an +edge or more short, 22 empty). 3,000 drawn convex rings are held the same way, and every bolt of 104 blade plates +(tips of 14 to 32 degrees) stands whole on its plate. No panel ring or bolt ring of any plate at either side turns +right or crosses, and no two bolt heads of a panel overlap; nor do any two on 3,591 blade plates (tips of 8 to 44 +degrees), 50 of which kept such a pair while only neighbours were joined. + +No fixture facet turns right, so 1,500 drawn sheets hold that case: 5 to 9 points up to 12 mm off one plane, whose +top facets the hull makes one. Each passes `check` and builds. Of their 519 rings that turn right, 84 lose an +edge, and each of those stands inside its outline without crossing, the distance clear of every edge, each of its +edges along one of the outline's in the outline's order; 2, both bolt rings, would meet themselves, and their +panels stand bare. A two-lobed facet with a neck holds the rest: no panel at an inset over half the neck, a bare +panel under it, and a prism whose rim would meet itself keeps its outline for a rim. The same test builds the three fixtures to one sha256 of every coordinate rounded to 1e-9 m and every face, pinned from Starfire (Windows 11, numpy 2.5.4) and Yggdrasil (Debian 13, numpy 2.2.4 on the system LAPACK). The diff --git a/surfaces/blender/tests/test_plate.py b/surfaces/blender/tests/test_plate.py index 99b1a94..e331030 100644 --- a/surfaces/blender/tests/test_plate.py +++ b/surfaces/blender/tests/test_plate.py @@ -153,12 +153,41 @@ def within(point, ring): return bool(np.sum(a[over, 0] + (point[1] - a[over, 1]) * (b[over, 0] - a[over, 0]) / (b[over, 1] - a[over, 1]) > point[0]) % 2) -def blade(tip, length, rear, bolt_r=0.03): - """A blade plate 0.4 thick, its tip at the origin `tip` degrees wide, `rear` across its far end, clad on top.""" +def blade_top(tip, length, rear): + """A blade's outline: its tip at the origin `tip` degrees wide, widest at 0.7 of its length, `rear` across its far end.""" half = math.tan(math.radians(tip / 2)) * 0.7 * length - top = [(0, 0), (0.7 * length, -half), (length, -rear / 2), (length, rear / 2), (0.7 * length, half)] - clad = {"mat": "c", "facets": [{"n": [0, 0, 1], "cos": 0.6}], "min_area": 0.01, "lifts": [0.045, 0.075], "inset": 0.11, "gap": 0.05, "split": 99, "seed": 1, "bolt_r": bolt_r} - return doc(row("Fin", clad=clad, points=[[x, y, z] for z in (0, 0.4) for x, y in top])) + return [(0, 0), (0.7 * length, -half), (length, -rear / 2), (length, rear / 2), (0.7 * length, half)] + + +def blade(tip, length, rear, inset=0.11, bolt_r=0.03): + """A blade plate 0.4 thick on blade_top, clad on top.""" + clad = {"mat": "c", "facets": [{"n": [0, 0, 1], "cos": 0.6}], "min_area": 0.01, "lifts": [0.045, 0.075], "inset": inset, "gap": 0.05, "split": 99, "seed": 1, "bolt_r": bolt_r} + return doc(row("Fin", clad=clad, points=[[x, y, z] for z in (0, 0.4) for x, y in blade_top(tip, length, rear)])) + + +def followed(made, ring, c): + """Whether a ring is its outline moved in by c, edges dropped or not: it stands inside the outline and does not + cross, c clear of every edge of it, and each of its edges runs along one of the outline's, c inside that edge's + line, in the outline's order.""" + made, ring = np.asarray(made, dtype=np.float64), np.asarray(ring, dtype=np.float64) + if not all(within(p, ring) for p in made) or plate._crosses(made) or float(clear(made, ring).min()) < c - 1e-9: + return False + ways = [(np.roll(r, -1, axis=0) - r) / np.linalg.norm(np.roll(r, -1, axis=0) - r, axis=1)[:, None] for r in (made, ring)] + along = [[j for j in range(len(ring)) if ways[0][i] @ ways[1][j] > 1 - 1e-9 and abs(float((made[i] - ring[j]) @ (-ways[1][j][1], ways[1][j][0])) - c) < 1e-9] + for i in range(len(made))] + took = [] + for found in along: # of two outline edges on one line, the next one round + if not found: + return False + took.append(next((j for j in found if took and j > took[-1]), found[0])) + return sum(took[i] < took[i - 1] for i in range(len(took))) == 1 + + +def sheet(top, inset=0.11, bolt_r=0.03): + """A sheet 0.3 thick under `top`, its top facets clad: points that stand a little off one plane make top facets + within MERGE of each other, which the hull makes one facet that need not be convex.""" + clad = {"mat": "c", "facets": [{"n": [0, 0, 1], "cos": 0.6}], "min_area": 0.01, "lifts": [0.045, 0.075], "inset": inset, "gap": 0.05, "split": 99, "seed": 1, "bolt_r": bolt_r} + return doc(row("Fin", clad=clad, points=[list(p) for p in top] + [[x, y, z - 0.3] for x, y, z in top])) def turns(ring): @@ -248,20 +277,55 @@ class InsetTests(unittest.TestCase): self.assertLess(apart2(made, half_planes(ring, c)), 1e-12) self.assertEqual((held, dropped, empty), HELD) - def test_an_outline_that_is_not_convex_is_moved_or_refused(self): + def test_an_outline_that_is_not_convex_is_followed_in(self): tab = [[0, 0], [4, 0], [4, 2], [2.2, 2], [2.2, 2.8], [1.8, 2.8], [1.8, 2], [0, 2]] # a tab 0.4 wide on a 4 by 2 body - for c in (0.05, 0.15): + for c in (0.05, 0.15, 0.1999): made = plate.inset2d(tab, c) self.assertEqual(made.tobytes(), corner_move(tab, c)[0].tobytes()) - self.assertGreater(float(clear(made, tab).min()), c - 1e-12) - self.assertTrue(all(within(p, tab) for p in made) and not plate._crosses(made)) - with self.assertRaises(plate.NotConvex) as caught: - plate.inset2d(tab, 0.25) - self.assertIn("its edge from point 4 runs backwards", str(caught.exception)) + self.assertTrue(followed(made, tab, c)) + arm = [[0, 0], [4, 0], [4, 2], [0.4, 2], [0.4, 5], [0, 5]] # an arm 0.4 wide up the body's left side + self.assertEqual(len(plate.inset2d(arm, 0.1999)), 6) + for outline in (tab, arm): # the tab's end runs out at 0.2: its sides face each other and go, the body's top is one edge again + for c in (0.2001, 0.25, 0.9): + made = plate.inset2d(outline, c) + self.assertLess(apart2(made, [[c, c], [4 - c, c], [4 - c, 2 - c], [c, 2 - c]]), 1e-12) + self.assertTrue(len(made) == 4 and followed(made, outline, c)) + self.assertEqual(plate.inset2d(outline, 1.0001).shape, (0, 2)) + barb = [[0, 0], [6, 0], [2, 0.5], [0, 2]] # a sharp tip whose upper edge ends at a corner turning right + self.assertEqual(plate.inset2d(barb, 0.2).tobytes(), corner_move(barb, 0.2)[0].tobytes()) + made = plate.inset2d(barb, 0.3) # that edge has run out: its two neighbours bound a triangle + self.assertLess(apart2(made, half_planes([[0, 0], [8 / 3, 0], [0, 2]], 0.3)), 1e-12) + self.assertTrue(len(made) == 3 and followed(made, barb, 0.3)) straight = [[0, 0], [3 * 0.3, 3 * 0.3 * 0.3], [3, 3 * 0.3], [3, 3 * 0.3 + 0.2], [0, 1]] # its second point is on a straight run - self.assertTrue(-1e-12 < float(turns(straight)[1]) < 0) # and turns right by a rounding: that is no outline to refuse - self.assertEqual(len(plate.inset2d(straight, 0.15)), 3) - self.assertLess(apart2(plate.inset2d(straight, 0.15), half_planes(straight, 0.15)), 1e-12) + self.assertTrue(-1e-12 < float(turns(straight)[1]) < 0) # and turns right by a rounding: no corner that can reach an edge + made = plate.inset2d(straight, 0.15) # its short edge runs out; the point on the run stays a point on the run + self.assertTrue(len(made) == 4 and followed(made, straight, 0.15)) + self.assertLess(apart2(made[[0, 2, 3]], half_planes(straight, 0.15)), 1e-12) + + def test_an_outline_that_would_meet_itself_is_refused_at_half_its_neck(self): + neck = [[0, 0], [2, 0], [2, 0.9], [4, 0.9], [4, 0], [6, 0], [6, 2], [4, 2], [4, 1.1], [2, 1.1], [2, 2], [0, 2]] # two lobes, a neck 0.2 wide + for c in (0.05, 0.0999): + made = plate.inset2d(neck, c) + self.assertEqual(made.tobytes(), corner_move(neck, c)[0].tobytes()) + self.assertTrue(followed(made, neck, c)) + for c in (0.1001, 0.15, 0.3): + with self.assertRaises(plate.NotSimple) as caught: + plate.inset2d(neck, c) + self.assertEqual(str(caught.exception), f"moved in {c}, the outline meets itself: the corner of the edges from points 1 and 2 reaches the edge from point 8") + hook = [[0, -2], [3, -2], [3, 5], [0, 5], [0, 2.2], [2, 1.5], [0, 0.8]] # a corner turning right, 1 from the far side + reach = 1 / (1 + math.hypot(2, 0.7) / 0.7) # it moves in 3.03 for the far side's 1: they meet at 0.2483 + self.assertTrue(followed(plate.inset2d(hook, reach - 1e-4), hook, reach - 1e-4)) + self.assertRaises(plate.NotSimple, plate.inset2d, hook, reach + 1e-4) + + def test_a_held_corner_steps_to_the_crossing_where_the_ring_first_loses_an_edge(self): + """The step kitbash.md states: c / MITER from the outline's corner while every edge has length, c over the sine + of half the corner from there on, and never out of the outline.""" + top, sine = blade_top(10.5, 2.43, 0.2), math.sin(math.radians(10.5 / 2)) + for c, corners, tip in ((0.05, 5, 0.05 / plate.MITER), (0.108, 5, 0.108 / plate.MITER), (0.109, 4, 0.109 / sine), (0.15, 4, 0.15 / sine)): + made = plate.inset2d(top, c) + self.assertEqual(len(made), corners) + self.assertLess(abs(float(np.linalg.norm(made, axis=1).min()) - tip), 1e-12) + self.assertGreater(float(depths(made, top).min()), 0) def test_every_inset_of_the_fixtures_is_what_the_half_planes_leave(self): inset, calls = plate.inset2d, [] @@ -366,11 +430,20 @@ class CheckTests(unittest.TestCase): def test_outline_of_zero_area(self): self.refused(doc(row(slab=dict(SLAB, outline=[[0, 0], [1, 0], [2, 0]]))), "plates[0].slab.outline: the outline has zero area") - def test_an_outline_not_convex_that_the_gap_or_the_taper_collapses(self): + def test_an_outline_not_convex_is_refused_where_the_gap_or_the_taper_makes_it_meet_itself(self): tab = [[0, 0], [4, 0], [4, 2], [2.2, 2], [2.2, 2.8], [1.8, 2.8], [1.8, 2], [0, 2]] - self.refused(doc(row(slab=dict(SLAB, outline=tab, gap=0.25))), "plates[0].slab.outline: the outline is not convex and, moved in 0.25, its edge from point 4 runs backwards") - self.refused(doc(row(slab=dict(SLAB, outline=tab, gap=0.15, taper=0.06))), "plates[0].slab.outline: the outline is not convex and, moved in 0.06,") - plate.check(doc(row(slab=dict(SLAB, outline=tab, gap=0.15)))) + neck = [[0, 0], [2, 0], [2, 0.9], [4, 0.9], [4, 0], [6, 0], [6, 2], [4, 2], [4, 1.1], [2, 1.1], [2, 2], [0, 2]] + meets = "the outline meets itself: the corner of the edges from points 1 and 2 reaches the edge from point 8" + for document, message in ((doc(row(slab=dict(SLAB, outline=neck, gap=0.15))), f"plates[0].slab.outline: moved in 0.15, {meets}"), + (doc(row(slab=dict(SLAB, outline=neck, gap=0.05, taper=0.06))), f"plates[0].slab.outline: moved in 0.06, {meets}")): + self.refused(document, message) + with self.assertRaises(plate.PlateError) as caught: # build refuses what check does, in the same words + plate.build(document) + self.assertEqual(str(caught.exception), message) + plate.check(doc(row(slab=dict(SLAB, outline=neck, gap=0.0999, taper=0.0)))) + for gap in (0.15, 0.25): # the tab is gone at 0.2: the slab is the body's + (entry,) = plate.build(plate.check(doc(row(slab=dict(SLAB, outline=tab, gap=gap, taper=0.0))))) + self.assertEqual(entry["report"]["corners"], 12 if gap < 0.2 else 8) def test_slab_ranges(self): for key, low, high in (("thick", 0.0005, 2.5), ("taper", -0.01, 0.6), ("back", 0.05, 1.6), ("gap", -0.01, 0.6)): @@ -637,6 +710,18 @@ class CladTests(unittest.TestCase): made = bolts.done()[0].reshape(-1, 12, 3).mean(axis=1)[:, :2] self.assertLess(apart2(made, np.array([[1.5, 40], [-18, 40], [-18, 9], [0.95, 0]]) * r), 1e-12) + def test_two_near_heads_that_are_not_neighbours_are_one(self): + """Kills: the merge reading neighbours in ring order only (it leaves the second and the fourth 1.8 r apart).""" + r = 0.06 + heads = np.array([[2.2, 0], [0, 0.9], [-2.2, 0], [0, -0.9]]) * r # neighbours 2.38 r apart, the second and the fourth 1.8 r + outline = corner_move(heads, -(0.05 + 3.2 * r))[0] + self.assertLess(apart2(plate.inset2d(plate.inset2d(outline, 0.05), 3.2 * r), heads), 1e-12) + bolts = plate._Mesh() + self.assertTrue(plate.panel(plate._Mesh(), bolts, [np.array([x, y, 0.0]) for x, y in outline], np.array([0.0, 0.0, 1.0]), 0.04, 0.05, r)) + made = bolts.done()[0].reshape(-1, 12, 3).mean(axis=1)[:, :2] + self.assertLess(apart2(made, np.array([[2.2, 0], [0, 0], [-2.2, 0]]) * r), 1e-12) + self.assertLess(float(np.abs(made[1]).max()), 1e-12) # the one made of two stands where the first of them stood in the ring + def test_every_bolt_of_a_blade_plate_stands_on_it(self): """Kills: the half-planes left out (10 of these blades then put a bolt off the plate, the worst 3.3 m).""" entry = plate.build(blade(20, 1.5, 0.3), 1)[0] # its bolt ring is narrower than the bolts stand in: no ring, no bolts @@ -654,6 +739,72 @@ class CladTests(unittest.TestCase): self.assertEqual(bolted, 104) self.assertGreater(least, 0.03) # a head's corners reach bolt_r: every head whole on its facet + def test_no_two_bolt_heads_of_a_blade_plate_overlap(self): + """3,591 blades, tips of 8 to 44 degrees. Kills: the merge reading neighbours in ring order only (50 of them + then keep two heads under 2 bolt_r apart, the nearest 0.27).""" + bolted, heads, nearest = 0, 0, math.inf + for tip in range(8, 46, 2): + for length in (0.5, 0.8, 1.0, 1.5, 2.0, 3.0, 4.0): + for rear in (0.03, 0.06, 0.1, 0.15, 0.2, 0.3, 0.4, 0.6, 0.8): + for inset in (0.05, 0.11, 0.2): + at = plate.build(blade(tip, length, rear, inset), 1)[0]["bolts"][0].reshape(-1, 12, 3).mean(axis=1) + bolted, heads = bolted + (len(at) > 0), heads + len(at) + if len(at) > 1: + nearest = min(nearest, float((np.linalg.norm(at[:, None] - at[None], axis=2) + 9 * np.eye(len(at))).min())) + self.assertEqual((bolted, heads), (1857, 7446)) + self.assertGreaterEqual(nearest, 2 * 0.03) + + def test_a_facet_that_is_not_convex_is_built_as_check_says(self): + """Top facets within MERGE of each other are one facet, and that one need not be convex. Soul's table, then + 1,500 drawn like it. Kills: an inset that refuses such a facet (build then raises on 77 sheets check passed); + panel taking that refusal for the table's (the 3 rings that would meet themselves raise).""" + soul = [[0.46231115288947655, -0.7464122608740515, 0.005076090953713479], [0.48625943944459826, -0.5771679834143375, 0.006610213759068515], + [0.7933326463565815, 0.3201403232773634, 0.009341146944706617], [-0.06168868858561849, 0.6415607593647952, 0.006680572413020032], + [-0.5231073349097417, 0.9203597671588255, 0.00622360127002797], [0.8223018952005992, -0.9577282429612575, 0.0028711637754610976], + [0.7686109712617415, -0.6216304824437804, 0.007801596935861264]] + (entry,) = plate.build(plate.check(sheet(soul)), 1) + self.assertEqual(entry["report"], {"corners": 9, "facets": 8, "panels": 1, "bolts": 3}) + inset, calls = plate.inset2d, [] + + def spy(ring, c): + calls.append([np.array(ring, dtype=np.float64), c, None]) + calls[-1][2] = inset(ring, c) + return calls[-1][2] + draw, tally = random.Random(5), {"reflex": 0, "short": 0, "met": 0, "panels": 0, "bolts": 0} + with mock.patch.object(plate, "inset2d", spy): + for _ in range(1500): + top = [[draw.uniform(-1, 1), draw.uniform(-1, 1), draw.uniform(0, 0.012)] for _ in range(draw.randint(5, 9))] + del calls[:] + (entry,) = plate.build(plate.check(sheet(top, draw.choice((0.05, 0.11, 0.2)))), 1) + tally["panels"], tally["bolts"] = tally["panels"] + entry["report"]["panels"], tally["bolts"] + entry["report"]["bolts"] + at = entry["bolts"][0].reshape(-1, 12, 3).mean(axis=1) + self.assertTrue(len(at) < 2 or float((np.linalg.norm(at[:, None] - at[None], axis=2) + 9 * np.eye(len(at))).min()) >= 2 * 0.03) + for ring, c, made in calls: + if float(turns(ring).min()) < -plate.REFLEX: + tally["reflex"], tally["met"] = tally["reflex"] + 1, tally["met"] + (made is None) + if made is not None and len(made) != len(ring): + tally["short"] += 1 + self.assertTrue(not len(made) or followed(made, ring, c)) + self.assertEqual(tally, {"reflex": 519, "short": 84, "met": 2, "panels": 1991, "bolts": 5946}) + + def test_a_ring_that_would_meet_itself_is_left_out_and_not_refused(self): + """Kills: panel or prism letting NotSimple through (build would refuse what check passed).""" + neck = [[0, 0], [2, 0], [2, 0.9], [4, 0.9], [4, 0], [6, 0], [6, 2], [4, 2], [4, 1.1], [2, 1.1], [2, 2], [0, 2]] # two lobes, a neck 0.2 wide + facet, up = [np.array([x, y, 0.0]) for x, y in neck], np.array([0.0, 0.0, 1.0]) + self.assertRaises(plate.NotSimple, plate.inset2d, neck, 0.15) + panels, bolts = plate._Mesh(), plate._Mesh() + self.assertFalse(plate.panel(panels, bolts, facet, up, 0.04, 0.15, 0.03)) # the panel's outline would: no panel + self.assertEqual((len(panels.verts), len(bolts.verts)), (0, 0)) + self.assertTrue(plate.panel(panels, bolts, facet, up, 0.04, 0.05, 0.03)) # its neck is 0.1 wide and the bolts stand 0.096 in: a bare panel + self.assertEqual((len(panels.verts), len(bolts.verts)), (36, 0)) + self.assertTrue(plate.panel(plate._Mesh(), bolts, facet, up, 0.04, 0.001, 0.03)) # a neck 0.198 wide: the bolts' ring keeps 0.006 of it, + self.assertEqual(len(bolts.verts), 12 * 10) # and its heads across each end of the neck are one: 10 of 12 + thin = np.array([[x, y if y in (0, 2) else 1 + (y - 1) * 0.15] for x, y in neck]) # a neck 0.03 wide: the rim, 0.02 in, would + mesh = plate._Mesh() + plate.prism(mesh, np.zeros(3), *np.eye(3), thin, 0.1, 0.02) + V = mesh.done()[0] + self.assertTrue(np.array_equal(V[24:, :2], thin) and np.array_equal(V[12:24, :2], thin)) + def test_a_rim_the_chamfer_leaves_fewer_corners_is_the_outline(self): mesh, axes = plate._Mesh(), np.eye(3) plate.prism(mesh, np.zeros(3), *axes, np.array([[0, 0], [1, 0], [1, 1], [0.502, 1.2], [0.498, 1.2], [0, 1]], dtype=float), 0.1, 0.02) From f8b2893eaa000af08dd13ee6498ffc19fe636287 Mon Sep 17 00:00:00 2001 From: Eureka Date: Thu, 3 Dec 2026 17:54:30 +0000 Subject: [PATCH 223/223] brokkr_kitbash.plate: fit rows part, bolts and step from kits/fittings.v0.json (cut plate-fittings-kit) (#48) --- surfaces/blender/brokkr_kitbash/__init__.py | 10 +- .../brokkr_kitbash/brokkr_actions.json | 2 +- .../brokkr_kitbash/kits/fittings.v0.json | 144 +++++++++++ surfaces/blender/brokkr_kitbash/plate.py | 170 ++++++++++-- surfaces/blender/docs/kitbash.md | 89 ++++++- surfaces/blender/tests/live/kitbash_plates.py | 56 +++- .../tests/live/kitbash_plates.result.json | 88 +++++++ surfaces/blender/tests/test_kitbash.py | 155 ++++++++++- surfaces/blender/tests/test_plate.py | 244 ++++++++++++++++-- surfaces/blender/tests/test_ram.py | 2 +- 10 files changed, 896 insertions(+), 64 deletions(-) create mode 100644 surfaces/blender/brokkr_kitbash/kits/fittings.v0.json diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 0770c52..5e76075 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -61,8 +61,8 @@ that crosses the same pin (it bends with the pin, so it is measured as an obstac follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes that check). plates writes hard armour plates. plate.py owns the table (brokkr.plates.v0) and every point of a plate, its panels, -bolts and anchor frames, in the table's frame; this file converts its arrays and nothing else. A plate is a mesh -object on its host under an identity parent inverse, with a child per material for its panels and bolts +bolts, fittings and anchor frames, in the table's frame; this file converts its arrays and nothing else. A plate is a mesh +object on its host under an identity parent inverse, with a child per material for its panels, bolts and fittings (.fit.) and an empty per anchor (.mark., .port., kit_anchor on each). plates is the one writer of those objects, their Kit Bevels, plate_kind and kit_plate. kit_plate is the checked row, kept as a record: its presence admits a rebuild in place and nothing reads it to decide geometry. A plate is no kit part: @@ -2698,7 +2698,9 @@ class BROKKR_KITBASH_OT_plates(PolishOperator): rebuild, or None), fits [(name, material, holds panels, meshes)], anchors [(name, record, matrix)], stale (the plate's fit children and anchors this call no longer makes)}. `taken` is every name the call has planned.""" name, path, clad = self.prefix + entry["name"], f"table.plates[{entry['row']}]", row["clad"] - for key, material in (("mat", row["mat"]),) + ((("clad.mat", clad["mat"]), ("clad.bolt_mat", clad["bolt_mat"])) if clad else ()): + named = [("mat", row["mat"])] + ([("clad.mat", clad["mat"]), ("clad.bolt_mat", clad["bolt_mat"])] if clad else []) + named += [(f"fits[{j}].{key}", fit[key]) for j, fit in enumerate(row["fits"]) for key in ("mat", "bolt_mat") if key in fit] + for key, material in named: if material not in bpy.data.materials: raise Refused(f"{path}.{key}: no material named {material!r}; make it first (createMaterial); nothing changed.") obj = bpy.data.objects.get(name) @@ -2713,6 +2715,8 @@ class BROKKR_KITBASH_OT_plates(PolishOperator): if len(mesh[1]): held = fits.setdefault(f"{name}.fit.{material}", [material, False, []]) held[1], held[2] = held[1] or panels, held[2] + [mesh] + for material, mesh in entry["fits"].items(): + fits.setdefault(f"{name}.fit.{material}", [material, False, []])[2].append(mesh) anchors = [] for anchor in entry["anchors"]: record = {"kind": anchor["kind"], "id": anchor["name"], "height": anchor["height"]} if anchor["kind"] == "mark" else {"kind": anchor["kind"], "name": anchor["name"]} diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 9c35c74..78d2146 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -1004,7 +1004,7 @@ }, { "name": "brokkr_kitbash.plates", - "doc": "Write a table of hard armour plates into the scene. table is a brokkr.plates.v0 document as JSON (docs/kitbash.md, Hard plates): {\"schema\": \"brokkr.plates.v0\", \"plates\": [row, ...]}, each row a convex faceted solid with optional clad (raised panels and their bolts) and fits (anchors on its face). The table's coordinates are metres in frame: a JSON 4x4 of rows in the world, rigid; empty, the host's world matrix, or the world with no host. side 1 builds the table as written and -1 mirrored across its x = 0. Each built plate is a mesh object named prefix + its name (.R and .L on a two-sided row), every face flat, parented to host under an identity parent inverse, with material mat, a Kit Bevel of the row's bevel (angle 12 degrees) and the properties plate_kind \"hard\" and kit_plate (its checked row, a record). Its panels are the child .fit. and its bolts .fit., one mesh per material, made only when not empty; a child that holds panels carries a Kit Bevel of clad.bevel (angle 20 degrees, one segment). Each anchor is an empty child at the anchor's frame: .mark. with kit_anchor {kind, id, height}, .port. with kit_anchor {kind, name}; brokkr_kitbash.hose takes a port empty's name as an end and leaves along its z. An object that carries kit_plate under a made name is rebuilt in place: it keeps its identity, its other children and its modifiers; its fit children are rewritten, made or removed, its anchors moved, and one the row no longer names removed. A plate is no kit part: joints and report do not list it, and a roll of its host carries it. Every material must exist (createMaterial). Refuses before it writes anything: a table the format refuses (the path is named), a missing material (named with its path), a host that is missing, scaled, mirrored or sheared, a frame that is not a rigid 4x4, a made name of over 63 bytes or taken by an object that is not this plate's, a frozen plate or one sharing its mesh, and a report over 16000 characters. Reports plates [{name, rebuilt, corners, facets, panels, bolts, anchors (the empties' names)}], host and side.", + "doc": "Write a table of hard armour plates into the scene. table is a brokkr.plates.v0 document as JSON (docs/kitbash.md, Hard plates): {\"schema\": \"brokkr.plates.v0\", \"plates\": [row, ...]}, each row a convex faceted solid with optional clad (raised panels and their bolts) and fits (anchors on its face, and fittings: parts of the fittings kit, rim bolts and steps). The table's coordinates are metres in frame: a JSON 4x4 of rows in the world, rigid; empty, the host's world matrix, or the world with no host. side 1 builds the table as written and -1 mirrored across its x = 0. Each built plate is a mesh object named prefix + its name (.R and .L on a two-sided row), every face flat, parented to host under an identity parent inverse, with material mat, a Kit Bevel of the row's bevel (angle 12 degrees) and the properties plate_kind \"hard\" and kit_plate (its checked row, a record). Its panels are the child .fit., its bolts .fit. and each fitting .fit., one mesh per material, made only when not empty; a child that holds panels carries a Kit Bevel of clad.bevel (angle 20 degrees, one segment). Each anchor is an empty child at the anchor's frame: .mark. with kit_anchor {kind, id, height}, .port. with kit_anchor {kind, name}; brokkr_kitbash.hose takes a port empty's name as an end and leaves along its z. An object that carries kit_plate under a made name is rebuilt in place: it keeps its identity, its other children and its modifiers; its fit children are rewritten, made or removed, its anchors moved, and one the row no longer names removed. A plate is no kit part: joints and report do not list it, and a roll of its host carries it. Every material must exist (createMaterial). Refuses before it writes anything: a table the format refuses (the path is named), a missing material (named with its path), a host that is missing, scaled, mirrored or sheared, a frame that is not a rigid 4x4, a made name of over 63 bytes or taken by an object that is not this plate's, a frozen plate or one sharing its mesh, and a report over 16000 characters. Reports plates [{name, rebuilt, corners, facets, panels, bolts, anchors (the empties' names)}], host and side.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/brokkr_kitbash/kits/fittings.v0.json b/surfaces/blender/brokkr_kitbash/kits/fittings.v0.json new file mode 100644 index 0000000..0557683 --- /dev/null +++ b/surfaces/blender/brokkr_kitbash/kits/fittings.v0.json @@ -0,0 +1,144 @@ +{ + "schema": "brokkr.kit.v0", + "kit": "fittings", + "doc": "What stands on a hard plate's face (brokkr_kitbash.plate's fit rows): each part stands on +z from z = 0 in its own frame, whose origin is the fit's place on the face, z the face's normal and y the face's up; metres. One material a part; no sockets.", + "socketTypes": {}, + "parts": [ + { + "name": "bolt", + "doc": "A hex head on a washer: a rim bolt, and what a bolts row stands along a slab's outline.", + "params": [ + {"name": "r", "type": "number", "min": 0.004, "max": 0.1, "default": 0.017, "doc": "the head's radius to its corners; the washer is 1.55 r"} + ], + "shapes": [ + {"shape": "tube", "r0": "1.55*r", "r1": "1.55*r", "length": 0.004, "segments": 14, "at": [0, 0, -0.0005], "rot": [0, 0, 90]}, + {"shape": "tube", "r0": "r", "r1": "r", "length": "0.7*r", "segments": 6, "at": [0, 0, 0.0035], "rot": [0, 0, 90]} + ], + "sockets": [] + }, + { + "name": "slot", + "doc": "The raised rim of a w by h slot: four bars around the opening. The opening's dark floor is a pit row under it.", + "params": [ + {"name": "w", "type": "number", "min": 0.01, "max": 2, "default": 0.2, "doc": "the opening across (x)"}, + {"name": "h", "type": "number", "min": 0.005, "max": 2, "default": 0.04, "doc": "the opening along up (y)"} + ], + "shapes": [ + {"shape": "box", "size": ["w+0.06", 0.032, 0.028], "at": [0, "h/2+0.016", 0.014]}, + {"shape": "box", "size": ["w+0.06", 0.032, 0.028], "at": [0, "-h/2-0.016", 0.014]}, + {"shape": "box", "size": [0.032, "h", 0.028], "at": ["w/2+0.016", 0, 0.014]}, + {"shape": "box", "size": [0.032, "h", 0.028], "at": ["-w/2-0.016", 0, 0.014]} + ], + "sockets": [] + }, + { + "name": "pit", + "doc": "The dark box that reads as the hole under a slot or behind a vent: w by h, depth tall, count of them pitch apart along y, centred. A slot's is 0.012 deep; a vents row's is 0.01 deep with the vents' count and a pitch of 2.7 h.", + "params": [ + {"name": "w", "type": "number", "min": 0.005, "max": 2, "default": 0.2, "doc": "across (x)"}, + {"name": "h", "type": "number", "min": 0.005, "max": 2, "default": 0.04, "doc": "along up (y)"}, + {"name": "depth", "type": "number", "min": 0.001, "max": 0.2, "default": 0.012, "doc": "how far it stands off the face"}, + {"name": "count", "type": "integer", "min": 1, "max": 64, "default": 1, "doc": "copies along y, centred"}, + {"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": ["w", "h", "depth"], "at": [0, "-(count-1)*pitch/2", "depth/2"]}} + ], + "sockets": [] + }, + { + "name": "vents", + "doc": "A stack of louvre lips tilted 28 degrees over w by h openings, 2.7 h apart along y, centred. The openings' dark floors are a pit row under it.", + "params": [ + {"name": "w", "type": "number", "min": 0.01, "max": 2, "default": 0.3, "doc": "an opening across (x)"}, + {"name": "h", "type": "number", "min": 0.005, "max": 0.5, "default": 0.03, "doc": "an opening along up (y)"}, + {"name": "count", "type": "integer", "min": 1, "max": 64, "default": 4, "doc": "lips"} + ], + "shapes": [ + {"shape": "repeat", "count": "count", "step": [0, "2.7*h", 0], "of": {"shape": "box", "size": ["w+0.04", "0.9*h", 0.012], "at": [0, "0.75*h-(count-1)*2.7*h/2", 0.014], "rot": [-28, 0, 0]}} + ], + "sockets": [] + }, + { + "name": "access_port", + "doc": "A round access port's body: a turned ring of radius r around a sunk cover with a raised boss. Its eight bolts are a port_bolts row at the same place.", + "params": [ + {"name": "r", "type": "number", "min": 0.02, "max": 1, "default": 0.12, "doc": "the port's radius"} + ], + "shapes": [ + {"shape": "lathe", "segments": 28, "profile": [[0, 0], ["r", 0], ["r", 0.035], ["0.82*r", 0.05], ["0.82*r", 0.022], ["0.34*r", 0.022], ["0.34*r", 0.045], [0, 0.045]]} + ], + "sockets": [] + }, + { + "name": "port_bolts", + "doc": "The eight hex heads on an access port's rim, on a circle 0.91 r, standing from the rim's shoulder (z 0.035): a row of its own, so the heads take their own material.", + "params": [ + {"name": "r", "type": "number", "min": 0.02, "max": 1, "default": 0.12, "doc": "the port's radius"} + ], + "shapes": [ + {"shape": "tube", "r0": "0.07*r", "r1": "0.07*r", "length": 0.012, "segments": 6, "at": ["0.91*r", 0, 0.035], "rot": [0, 0, 90]}, + {"shape": "tube", "r0": "0.07*r", "r1": "0.07*r", "length": 0.012, "segments": 6, "at": ["0.6434671708797584*r", "0.6434671708797584*r", 0.035], "rot": [0, 0, 90]}, + {"shape": "tube", "r0": "0.07*r", "r1": "0.07*r", "length": 0.012, "segments": 6, "at": [0, "0.91*r", 0.035], "rot": [0, 0, 90]}, + {"shape": "tube", "r0": "0.07*r", "r1": "0.07*r", "length": 0.012, "segments": 6, "at": ["-0.6434671708797584*r", "0.6434671708797584*r", 0.035], "rot": [0, 0, 90]}, + {"shape": "tube", "r0": "0.07*r", "r1": "0.07*r", "length": 0.012, "segments": 6, "at": ["-0.91*r", 0, 0.035], "rot": [0, 0, 90]}, + {"shape": "tube", "r0": "0.07*r", "r1": "0.07*r", "length": 0.012, "segments": 6, "at": ["-0.6434671708797584*r", "-0.6434671708797584*r", 0.035], "rot": [0, 0, 90]}, + {"shape": "tube", "r0": "0.07*r", "r1": "0.07*r", "length": 0.012, "segments": 6, "at": [0, "-0.91*r", 0.035], "rot": [0, 0, 90]}, + {"shape": "tube", "r0": "0.07*r", "r1": "0.07*r", "length": 0.012, "segments": 6, "at": ["0.6434671708797584*r", "-0.6434671708797584*r", 0.035], "rot": [0, 0, 90]} + ], + "sockets": [] + }, + { + "name": "handle", + "doc": "A grab handle along y: a square bar of side 2 r on two posts, bent over at lift, each post on a washer and a hex foot. Roll 90 lays it along the face's a.", + "params": [ + {"name": "length", "type": "number", "min": 0.05, "max": 2, "default": 0.3, "doc": "between the posts"}, + {"name": "lift", "type": "number", "min": 0.02, "max": 0.5, "default": 0.065, "doc": "the bar's centre over the face"}, + {"name": "r", "type": "number", "min": 0.004, "max": 0.05, "default": 0.016, "doc": "half the bar's side"} + ], + "shapes": [ + {"shape": "extrude", "section": "box", "w": "2*r", "h": "2*r", "t": "r", "path": [[0, "-length/2", -0.004], [0, "-length/2", "lift-min(0.4*lift,0.2*length)"], [0, "-length/2+0.1339745962155613*min(0.4*lift,0.2*length)", "lift-0.5*min(0.4*lift,0.2*length)"], [0, "-length/2+0.5*min(0.4*lift,0.2*length)", "lift-0.1339745962155613*min(0.4*lift,0.2*length)"], [0, "-length/2+min(0.4*lift,0.2*length)", "lift"], [0, "length/2-min(0.4*lift,0.2*length)", "lift"], [0, "length/2-0.5*min(0.4*lift,0.2*length)", "lift-0.1339745962155613*min(0.4*lift,0.2*length)"], [0, "length/2-0.1339745962155613*min(0.4*lift,0.2*length)", "lift-0.5*min(0.4*lift,0.2*length)"], [0, "length/2", "lift-min(0.4*lift,0.2*length)"], [0, "length/2", -0.004]], "up": [1, 0, 0]}, + {"shape": "tube", "r0": "2.3*r", "r1": "2.3*r", "length": 0.008, "segments": 12, "at": [0, "-length/2", 0], "rot": [0, 0, 90]}, + {"shape": "tube", "r0": "2.3*r", "r1": "2.3*r", "length": 0.008, "segments": 12, "at": [0, "length/2", 0], "rot": [0, 0, 90]}, + {"shape": "tube", "r0": "1.5*r", "r1": "1.5*r", "length": 0.008, "segments": 6, "at": [0, "-length/2", 0.008], "rot": [0, 0, 90]}, + {"shape": "tube", "r0": "1.5*r", "r1": "1.5*r", "length": 0.008, "segments": 6, "at": [0, "length/2", 0.008], "rot": [0, 0, 90]} + ], + "sockets": [] + }, + { + "name": "eye", + "doc": "A lifting eye: a bolted pad, a neck, and a ring standing in the plane of y and z.", + "params": [ + {"name": "size", "type": "number", "min": 0.03, "max": 0.5, "default": 0.1, "doc": "the ring's outer diameter is 1.1 size"} + ], + "shapes": [ + {"shape": "box", "size": ["1.1*size", "2*size", 0.012], "at": [0, 0, 0.004]}, + {"shape": "tube", "r0": "0.11*size", "r1": "0.11*size", "length": 0.008, "segments": 6, "at": [0, "-0.72*size", 0.01], "rot": [0, 0, 90]}, + {"shape": "tube", "r0": "0.11*size", "r1": "0.11*size", "length": 0.008, "segments": 6, "at": [0, "0.72*size", 0.01], "rot": [0, 0, 90]}, + {"shape": "box", "size": ["0.34*size", "0.5*size", "0.24*size"], "at": [0, 0, "0.012+0.1*size"]}, + {"shape": "lathe", "segments": 20, "loop": true, "profile": [["0.55*size", 0], ["0.5119238815542512*size", "0.09192388155425119*size"], ["0.42*size", "0.13*size"], ["0.3280761184457488*size", "0.09192388155425119*size"], ["0.29*size", 0], ["0.3280761184457488*size", "-0.09192388155425119*size"], ["0.42*size", "-0.13*size"], ["0.5119238815542512*size", "-0.09192388155425119*size"]], "at": [0, 0, "0.012+0.62*size"], "rot": [0, 90, 0]} + ], + "sockets": [] + }, + { + "name": "louvres", + "doc": "A framed bank of n slanted slats, w by h between the frame's middles: x along the slats, y up.", + "params": [ + {"name": "w", "type": "number", "min": 0.1, "max": 4, "default": 0.6, "doc": "across (x), between the side bars' middles"}, + {"name": "h", "type": "number", "min": 0.1, "max": 4, "default": 0.72, "doc": "along up (y), between the top and bottom bars' middles"}, + {"name": "n", "type": "integer", "min": 1, "max": 64, "default": 6, "doc": "slats"}, + {"name": "depth", "type": "number", "min": 0.01, "max": 0.5, "default": 0.05, "doc": "how far the frame stands"}, + {"name": "frame", "type": "number", "min": 0.01, "max": 0.5, "default": 0.07, "doc": "the frame bars' width, under w and h"}, + {"name": "slant", "type": "number", "min": 0, "max": 80, "default": 25, "doc": "degrees a slat is tilted about x"} + ], + "shapes": [ + {"shape": "box", "size": ["w+frame", "frame", "depth"], "at": [0, "-0.5*h", "0.5*depth"]}, + {"shape": "box", "size": ["w+frame", "frame", "depth"], "at": [0, "0.5*h", "0.5*depth"]}, + {"shape": "box", "size": ["frame", "h+frame", "depth"], "at": ["-0.5*w", 0, "0.5*depth"]}, + {"shape": "box", "size": ["frame", "h+frame", "depth"], "at": ["0.5*w", 0, "0.5*depth"]}, + {"shape": "repeat", "count": "n", "step": [0, "(h-frame)/n", 0], "of": {"shape": "box", "size": ["w-frame", "0.75*(h-frame)/n", "0.25*depth"], "at": [0, "-0.5*(h-frame)+0.5*(h-frame)/n", "0.3*depth"], "rot": ["slant", 0, 0]}} + ], + "sockets": [] + } + ] +} diff --git a/surfaces/blender/brokkr_kitbash/plate.py b/surfaces/blender/brokkr_kitbash/plate.py index be0150c..d3e721f 100644 --- a/surfaces/blender/brokkr_kitbash/plate.py +++ b/surfaces/blender/brokkr_kitbash/plate.py @@ -2,13 +2,17 @@ numpy and the standard library only, tested without Blender (tests/test_plate.py); docs/kitbash.md, Hard plates, states the format in full. A hard plate is a convex faceted solid: every facet flat, every edge a chamfer the -caller's Bevel makes. This module turns one table into each plate's solid, its detail panels, their corner bolts -and the frames of its anchors. The table alone decides the result: coordinates are metres in the table's own frame +caller's Bevel makes. This module turns one table into each plate's solid, its detail panels, their corner bolts, +the frames of its anchors and the fittings that stand on its face. The table and kits/fittings.v0.json decide the result: coordinates are metres in the table's own frame (no host and no world reach this module), every clad carries its seed as data, and facets are ordered by a rule on the solid as built in the table frame. A row: name, mat, bevel, sides ("one" or "both"), mirror, exactly one solid form, clad, face, fits. +Fits, each standing on the row's face: the anchors mark and hose_port (a frame), and the fittings part (a part of +the fittings kit at a place, built by core.build), bolts (bolt parts along a slab's outline) and step (a raised +panel on an outline). + Solid forms, each a set of points whose convex hull is the plate: faces [{at, normal} | {through: [a, b, c], out}, ...]: the corners of what the half-spaces bound slab {at, normal, up, right, outline, thick, taper, back, gap}: an outline drawn on the outer face, the @@ -20,7 +24,7 @@ Solid forms, each a set of points whose convex hull is the plate: check(document) returns the table with every default written in, or raises PlateError naming the path. build(table, side=1) returns one entry per plate built: name, solid (V, faces), facets, panels (V, faces), -bolts (V, faces), anchors, report. Both are pure: nothing is cached and nothing is written. +bolts (V, faces), fits {mat: (V, faces)}, anchors, report. Both are pure: nothing is cached and nothing is written. """ from __future__ import annotations @@ -54,7 +58,10 @@ PANEL_MIN = (0.25, 0.02) # a panel under this share of its facet, or under this SINK, CHAMFER = 0.02, 0.02 # a panel starts this far under its facet; its far rim is chamfered this much BOLT = 0.028 RANGES = {"thick": (0.001, 2.0), "taper": (0.0, 0.5), "back": (0.1, 1.5), "gap": (0.0, 0.5), "lift": (0.0, 1.0)} -KINDS = ("mark", "hose_port") +KINDS = ("mark", "hose_port", "part", "bolts", "step") +ANCHORS = KINDS[:2] # a fit that is a frame; the others are geometry +KIT = "fittings" # the kit a part row's part is of, and the bolt of a bolts row +PARAMS = 256 # the most characters a fit's params may run class PlateError(ValueError): @@ -236,7 +243,28 @@ def _name(value: Any, path: str, most: int, pattern: str | None) -> str: return value -def _check_row(row: Any, path: str) -> dict: +def _fittings(kit: dict) -> dict: + """The fittings kit's parts, read into `kit` the first time a call wants them.""" + if not kit: + kit.update(core.load_kit(KIT)) + return kit["parts"] + + +def _part_params(kit: dict, part: Any, text: Any, path: str) -> str: + """A fit's params text, checked against the part's bounds by core.""" + parts = _fittings(kit) + if not isinstance(part, str) or part not in parts: + raise PlateError(f"{path}.part: {part!r} is no part of the {KIT} kit (its parts: {', '.join(parts)})") + if not isinstance(text, str) or len(text) > PARAMS: + raise PlateError(f"{path}.params: wants 'name=value; ...' of at most {PARAMS} characters") + try: + core.resolve_params(parts[part], core.parse_params(text)) + except core.KitError as error: + raise PlateError(f"{path}.params: {error}") from None + return text + + +def _check_row(row: Any, path: str, kit: dict) -> dict: forms = ("faces", "slab", "sections", "points") _object(row, path, ("name", "mat"), ("bevel", "sides", "mirror", "clad", "face", "fits") + forms) out = {"name": _name(row["name"], f"{path}.name", 48, r"[A-Za-z0-9_.]+"), "mat": _name(row["mat"], f"{path}.mat", 63, None), @@ -287,13 +315,32 @@ def _check_row(row: Any, path: str) -> dict: if kind == "mark": _object(fit, at, ("kind", "id", "at", "height")) entry = {"kind": kind, "id": _name(fit["id"], f"{at}.id", 63, None), "at": _vector(fit["at"], f"{at}.at", 2), "height": _number(fit["height"], f"{at}.height", 1e-4, 100.0)} - else: + elif kind == "hose_port": _object(fit, at, ("kind", "name", "at"), ("lift",)) entry = {"kind": kind, "name": _name(fit["name"], f"{at}.name", 63, None), "at": _vector(fit["at"], f"{at}.at", 2), "lift": _number(fit.get("lift", 0.0), f"{at}.lift", -1.0, 1.0)} - name = entry.get("id", entry.get("name")) - if name in names: - raise PlateError(f"{at}: a second anchor named {name!r} in this row") - names.add(name) + elif kind == "part": + _object(fit, at, ("kind", "part", "at", "mat"), ("roll", "lift", "params")) + entry = {"kind": kind, "part": fit["part"], "at": _vector(fit["at"], f"{at}.at", 2), "roll": _number(fit.get("roll", 0.0), f"{at}.roll", -360.0, 360.0), + "lift": _number(fit.get("lift", 0.0), f"{at}.lift", -1.0, 1.0), "params": _part_params(kit, fit["part"], fit.get("params", ""), at)} + elif kind == "bolts": + if form != "slab": + raise PlateError(f"{at}: a bolts row stands along a slab's outline; this row is no slab") + _object(fit, at, ("kind", "inset", "spacing", "mat"), ("lift", "params")) + entry = {"kind": kind, "inset": _number(fit["inset"], f"{at}.inset", 0.0, 10.0), "spacing": _number(fit["spacing"], f"{at}.spacing", 1e-3, 100.0), + "lift": _number(fit.get("lift", 0.0), f"{at}.lift", -1.0, 1.0), "params": _part_params(kit, "bolt", fit.get("params", ""), at)} + else: + _object(fit, at, ("kind", "outline", "at", "lift", "mat"), ("bolt_mat",)) + entry = {"kind": kind, "outline": [_vector(p, f"{at}.outline[{k}]", 2) for k, p in enumerate(_list(fit["outline"], f"{at}.outline", OUTLINE))], + "at": _vector(fit["at"], f"{at}.at", 2), "lift": _number(fit["lift"], f"{at}.lift", 0.0, 1.0)} + _check_ring(np.array(entry["outline"]), f"{at}.outline") + entry["bolt_mat"] = _name(fit.get("bolt_mat", "gunmetal"), f"{at}.bolt_mat", 63, None) + if kind in ANCHORS: + name = entry.get("id", entry.get("name")) + if name in names: + raise PlateError(f"{at}: a second anchor named {name!r} in this row") + names.add(name) + else: + entry["mat"] = _name(fit["mat"], f"{at}.mat", 63, None) fits.append(entry) out["fits"] = fits return out @@ -303,20 +350,23 @@ def check(document: Any) -> dict: """The table with every default written in. Raises PlateError naming the path of what breaks the format, and of a row that bounds no solid: every row's solid and anchors are made here once, at side +1, and build makes them the same way, so build meets no refusal check has not.""" - table = _read(document) + kit: dict = {} + table = _read(document, kit) for i, row in enumerate(table["plates"]): points, face = _row_points(row, f"plates[{i}]") hull(_mirrored(points, row["mirror"]), f"plates[{i}]") for j, fit in enumerate(row["fits"]): - _frame(face[0], face[3], (0.0, 0.0, 1.0) if fit["kind"] == "mark" else face[2], f"plates[{i}].fits[{j}]") + if fit["kind"] in ANCHORS: + _frame(face[0], face[3], (0.0, 0.0, 1.0) if fit["kind"] == "mark" else face[2], f"plates[{i}].fits[{j}]") + fit_meshes(row, face, 0.0, 1, kit, f"plates[{i}]") return table -def _read(document: Any) -> dict: +def _read(document: Any, kit: dict) -> dict: _object(document, "document", ("schema", "plates")) if document["schema"] != SCHEMA: raise PlateError(f"document.schema: {document['schema']!r} is not {SCHEMA}") - rows = [_check_row(row, f"plates[{i}]") for i, row in enumerate(_list(document["plates"], "plates", ROWS))] + rows = [_check_row(row, f"plates[{i}]", kit) for i, row in enumerate(_list(document["plates"], "plates", ROWS))] built: dict[str, int] = {} for i, row in enumerate(rows): for name in ((row["name"] + ".R", row["name"] + ".L") if row["sides"] == "both" else (row["name"],)): @@ -327,9 +377,9 @@ def _read(document: Any) -> dict: # --- points of a solid form ----------------------------------------------------------------------------------------- -def _frame(point, normal, up, path: str) -> np.ndarray: +def _frame(point, normal, up, path: str, roll: float = 0.0) -> np.ndarray: try: - return core.surface_frame(point, normal, up) + return core.surface_frame(point, normal, up, roll) except core.KitError as error: raise PlateError(f"{path}: {error}") from None @@ -879,6 +929,76 @@ def clad_layout(V: np.ndarray, faces, facets, clad: dict, seed: int, face_n, sid return panels.done(), bolts.done(), made, on_face +# --- fittings --------------------------------------------------------------------------------------------------------- +def _slab_ring(slab: dict, face) -> np.ndarray: + """A slab's outline as drawn on its face, counter-clockwise in the face's (a, b): the outline, in by its gap.""" + origin, a, b, _ = face + if "corners" in slab: + corners = np.array(slab["corners"]) + ring = np.column_stack(((corners - origin) @ a, (corners - origin) @ b)) + else: + ring = np.array(outline_points(slab["outline"]), dtype=np.float64) + if _area2(ring) < 0: + ring = ring[::-1] + return inset2d(ring, slab["gap"]) if slab["gap"] else ring + + +def fit_meshes(row: dict, face, top: float, side: int, kit: dict, path: str): + """({mat: (V, faces)}, count): the fittings of one checked row at `side`, merged by material in row order, and + how many stand. A part's frame is the face's at the fit's place: z the normal, y the face's b, turned by roll; at + side -1 the place, normal and b are mirrored, the frame made right-handed and the roll negated. A part row and + a step stand on the face's top (the face plus `top`, the clad's lift there); a bolts row fastens the plate + itself and stands on the bare face; where the outline moved in by its inset and the taper leaves no ring, or a ring + that would meet itself, it stands no bolts. Raises PlateError for what the kit refuses at these params and for a step too small for a + panel.""" + held: dict[str, _Mesh] = {} + count = 0 + if face is None: + return {}, 0 + origin, a, b, n = face + flip = np.array([float(side), 1.0, 1.0]) + + def part(name: str, params: str, at: str): + try: + built = core.build(_fittings(kit)[name], core.parse_params(params)) + except core.KitError as error: + raise PlateError(f"{at}: {error}") from None + ends = np.cumsum(built.counts) + return built.V, [built.faces[end - size:end].tolist() for end, size in zip(ends, built.counts)] + + def stand(mesh, x: float, y: float, z: float, roll: float, mat: str, at: str) -> None: + frame = _frame((origin + a * x + b * y + n * z) * flip, n * flip, b * flip, at, -roll if side < 0 else roll) + held.setdefault(mat, _Mesh()).add(mesh[0] @ frame[:3, :3].T + frame[:3, 3], mesh[1]) + + for j, fit in enumerate(row["fits"]): + at = f"{path}.fits[{j}]" + if fit["kind"] == "part": + stand(part(fit["part"], fit["params"], at), *fit["at"], top + fit["lift"], fit["roll"], fit["mat"], at) + count += 1 + elif fit["kind"] == "bolts": + slab = row["slab"] + drawn = _slab_ring(slab, face) + try: + ring = inset2d(drawn, fit["inset"] + slab["taper"]) + except NotSimple: # a ring that would meet itself stands no bolts + continue + if len(ring) < 3: # a vanished ring stands no bolts (plate-bolts-follow-edge-event) + continue + bolt = part("bolt", fit["params"], at) + for k in range(len(ring)): + p, q = ring[k], ring[(k + 1) % len(ring)] + along = max(1, int(float(np.linalg.norm(q - p)) / fit["spacing"])) + for m in range(along): + stand(bolt, *(p + (q - p) * ((m + 0.5) / along)), fit["lift"], 0.0, fit["mat"], at) + count += along + elif fit["kind"] == "step": + polygon = [(origin + a * (fit["at"][0] + x) + b * (fit["at"][1] + y) + n * top) * flip for x, y in fit["outline"]] + if not panel(held.setdefault(fit["mat"], _Mesh()), held.setdefault(fit["bolt_mat"], _Mesh()), polygon, n * flip, fit["lift"], 0.0, BOLT): + raise PlateError(f"{at}.outline: under {PANEL_MIN[1]} m2: too small for a panel") + count += 1 + return {mat: mesh.done() for mat, mesh in held.items() if mesh.faces}, count + + # --- build ------------------------------------------------------------------------------------------------------------ def _across(mesh): """A mesh (V, faces) mirrored across x = 0, its faces wound outward still and starting where they did.""" @@ -894,10 +1014,12 @@ def build(table: Any, side: int = 1) -> list[dict]: every point before the hull, and facets, ties and draws are those of the mirrored solid as built, which is not the mirror of side +1's panels; a clad selector's direction is mirrored with it. Each entry: {name, row (its index in the table), mat, bevel, side, solid: (V, faces), facets, panels: (V, faces), bolts: (V, faces), - anchors: [{kind, name, matrix, mirrored, height?}], report: {corners, facets, panels, bolts}}.""" + fits: {mat: (V, faces)}, anchors: [{kind, name, matrix, mirrored, height?}], report: {corners, facets, panels, + bolts, fits}}. fits are drawn where the panels are, so a mirrored .L's are the mirror of its .R's.""" if side not in (1, -1): raise PlateError(f"side: {side!r} is not 1 or -1") - table = _read(table) + kit: dict = {} + table = _read(table, kit) built = [] for i, row in enumerate(table["plates"]): path = f"plates[{i}]" @@ -917,13 +1039,15 @@ def build(table: Any, side: int = 1) -> list[dict]: if clad is not None: seed = clad["seed"][0 if where > 0 else 1] if pair else clad["seed"] panels, bolts, made, top = clad_layout(V, faces, facets, clad, seed, None if face is None else face[3] * turn, where) - drawn[where] = ((V, faces), facets, panels, bolts, made, top) - solid, facets, panels, bolts, made, top = drawn[where] + drawn[where] = ((V, faces), facets, panels, bolts, made, top, *fit_meshes(row, face, top, where, kit, path)) + solid, facets, panels, bolts, made, top, fits, stood = drawn[where] if where != s: - solid, panels, bolts = _across(solid), _across(panels), _across(bolts) + solid, panels, bolts, fits = _across(solid), _across(panels), _across(bolts), {mat: _across(mesh) for mat, mesh in fits.items()} facets = [{"normal": f["normal"] * flip, "area": f["area"], "centre": f["centre"] * flip} for f in facets] anchors = [] for j, fit in enumerate(row["fits"]): + if fit["kind"] not in ANCHORS: + continue origin, a, b, n = face at = (origin + a * fit["at"][0] + b * fit["at"][1] + n * (top + fit.get("lift", 0.0))) * flip up = (0.0, 0.0, 1.0) if fit["kind"] == "mark" else b * flip @@ -932,6 +1056,6 @@ def build(table: Any, side: int = 1) -> list[dict]: anchor["height"] = fit["height"] anchors.append(anchor) built.append({"name": row["name"] + ((".R" if s > 0 else ".L") if row["sides"] == "both" else ""), "row": i, "mat": row["mat"], "bevel": row["bevel"], "side": s, - "solid": solid, "facets": facets, "panels": panels, "bolts": bolts, "anchors": anchors, - "report": {"corners": len(solid[0]), "facets": len(solid[1]), "panels": made, "bolts": len(bolts[0]) // 12}}) + "solid": solid, "facets": facets, "panels": panels, "bolts": bolts, "fits": fits, "anchors": anchors, + "report": {"corners": len(solid[0]), "facets": len(solid[1]), "panels": made, "bolts": len(bolts[0]) // 12, "fits": stood}}) return built diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index e83da17..7501d96 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -973,7 +973,7 @@ plates somewhere owns that matrix. The table alone decides the result. A table h | one solid form | `faces`, `slab`, `sections` or `points` (below) | | `clad` | `null` or the detail plating (below) | | `face` | `{at, normal, up, right}`: the face anchors stand on, for a row that is not a slab | -| `fits` | anchors (below) | +| `fits` | anchors and fittings (below) | `mirror` and `sides` are independent. A two-sided row with one seed, or with no clad, is drawn once, at side +1, and its `.L` is the mirror of its `.R`: the same facets in the same order, the same cuts and lifts, every face @@ -1084,25 +1084,57 @@ the inset of a facet or of a facet's part would meet itself, that part takes no panel would, the panel takes no bolts; where the rim would, the rim is the outline. So `build` refuses nothing that `check` passed. -### Anchors +### Anchors and fits -A fit is a frame on the face, at `[a, b]` in the face's (a, b), standing on the face's top: the face, plus -`lifts[0]` where a panel stands on it. Two kinds: +A fit stands on the row's face (a slab's outer face, or the `face` another row names), at `[a, b]` in the face's +(a, b). The face's top is the face, plus `lifts[0]` where a panel stands on it. Up to 64 a row; any other kind is +refused. + +Two kinds are anchors, a frame and no geometry: - `{kind: "mark", id, at, height}`: z is the face's normal and y the table's +z projected off it, so a numeral - stands upright whatever the plate's lean. -- `{kind: "hose_port", name, at, lift}`: z out of the face, y the face's up, `lift` (default 0) further out. + stands upright whatever the plate's lean. On the face's top. +- `{kind: "hose_port", name, at, lift}`: z out of the face, y the face's up, `lift` (default 0) over the top. `build` returns each as `{kind, name, matrix, mirrored}` (and `height` for a mark). At side -1 the position, normal and up are mirrored and the frame is made right-handed again (x = y cross z); `mirrored` says so. What stands on -an anchor is its owner's business; the fittings the mech tracks draw on a face (bolt rows, slots, vents, ports, -handles, eyes, louvres, steps) are not fits of this table yet, and any other kind is refused. +an anchor is its owner's business. + +Three kinds are fittings, geometry `build` makes: + +- `{kind: "part", part, at, roll, lift, params, mat}`: a part of the fittings kit (below) built by `core.build` at + `params` (`"k=v; ..."`, default the part's defaults) and placed by the fit's frame: z the face's normal, y the + face's up, turned `roll` degrees about the normal (default 0, -360 to 360), its origin `lift` (default 0, -1 to + 1) over the face's top. +- `{kind: "bolts", inset, spacing, lift, params, mat}`: the kit's `bolt` along a slab's outline. The outline as + drawn (in by the slab's `gap`) is moved in by `inset` + the slab's `taper` (0 to 10), by `inset2d` as a + panel's bolt ring is, so the ring can have fewer edges than the outline; each edge of that ring takes `max(1, int(length / spacing))` bolts, bolt j at + `(j + 0.5) / count` along it. `params` are the bolt's. A rim bolt fastens the plate, not its cladding: the row + stands on the bare face, `lift` (default 0) over it, whatever panel the face carries. Where the inset leaves no + ring, or a ring that would meet itself (an outline that is not convex), the row stands no bolts: the ruling + plate-bolts-follow-edge-event. Refused on a row that is no slab. +- `{kind: "step", outline, at, lift, mat, bolt_mat}`: a raised panel on `outline` (3 to 64 `[a, b]` points, either + winding, about `at`) on the face's top: the clad's panel with inset 0, from 0.02 under the top to `lift` (0 to + 1) over it, its far rim chamfered 0.02, a hexagonal bolt of radius 0.028 inside each corner in `bolt_mat` + (default `gunmetal`). Refused under 0.02 m2. + +`mat` is the fitting's material, 1 to 63 characters. A part is one material: a fitting of two is two rows at one +place (a slot or a vents row and the `pit` under it; an `access_port` and its `port_bolts`). + +At side -1 a fitting's place, normal and up are mirrored, its frame made right-handed and its roll negated, so a +part that is the same across its own x stands as the mirror of side +1's. On a two-sided row drawn once (one seed, +or no clad) the `.L` fittings are the `.R`'s mirrored across x = 0, as its panels are. + +Refused, naming the path: a part the kit does not have (its parts are listed); params the part does not have or +outside its bounds, and what the part's shapes refuse at those params (`core`'s message); a `mat` over 63 +characters. ### What build returns One entry per plate built, in the table's order: `name`, `row` (its index), `mat`, `bevel`, `side`, `solid: (V, faces)`, `facets` (each face's `normal`, `area`, `centre`), `panels: (V, faces)`, `bolts: (V, faces)`, -`anchors`, and `report: {corners, facets, panels, bolts}`. `V` is an (N, 3) float64 array; faces are lists of +`fits: {mat: (V, faces)}` (the row's fittings, merged by material in row order), `anchors`, and +`report: {corners, facets, panels, bolts, fits}`, `fits` the count that stand (a bolts row counts each bolt). `V` is an (N, 3) float64 array; faces are lists of vertex indices wound outward. `check` returns the table with every default written in. Both are pure functions. Building the three mech fixtures takes 0.5 to 0.9 s each (23 to 50 plates, medians of 5 on Starfire, Python @@ -1118,7 +1150,8 @@ itself, repeats a point or has zero area; `thick`, `taper`, `back` or `gap` outs that is not convex would meet itself; corners that are not a plate; faces that bound nothing; points in one plane; a pair of seeds on a one-sided row, an equal pair, or no seed; an `up` along the normal; a -fit on a row with no face; an unknown fit kind; two anchors of one name in a row. +fit on a row with no face; an unknown fit kind; two anchors of one name in a row; and what Anchors and fits lists +for a fitting. ### Against the mech tracks' builders @@ -1179,9 +1212,12 @@ Per built entry, N = `prefix` + its name: host its world matrix is `frame`. A Kit Bevel of the row's `bevel`, angle 12 degrees. ID properties `plate_kind` = `"hard"` and `kit_plate`: the checked row with `side` and `prefix`, as JSON. `kit_plate` is a record: its presence admits a rebuild and nothing reads it to decide geometry. -- `N.fit.` holds the panels and `N.fit.` the bolts: a child mesh per material (one - child when the two are the same material), identity basis, made only when its mesh is not empty. A child that - holds panels carries a Kit Bevel of `clad.bevel`, angle 20 degrees, one segment. +- `N.fit.` holds the panels, `N.fit.` the bolts and `N.fit.` each fitting of that + `mat` (a step's corner bolts under its `bolt_mat`): a child mesh per material, the panels, then the bolts, + then the fittings in row order where they share one; identity basis, made only when its mesh is not empty. A + child that holds panels carries a Kit Bevel of `clad.bevel`, angle 20 degrees, one segment, and a fitting of + the panels' material is bevelled with them; any other child carries none. Every material a fit names must be + in the file. - One empty per anchor, a child of N at the anchor's matrix: `N.mark.` with `kit_anchor` `{kind, id, height}`, `N.port.` with `kit_anchor` `{kind, name}` (JSON). A port empty is an end `brokkr_kitbash.hose` takes by name: the hose leaves along its z, out of the face. @@ -1648,7 +1684,7 @@ under such load (five runs), and reading a 336-face part takes 27 to 37 ms. | `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. | | `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. | | `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `seed`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. | -| `brokkr_kitbash.plates` | `table` (a `brokkr.plates.v0` document, JSON), `host`, `frame` (empty, or a JSON 4x4 of rows), `side`, `prefix` | Writes hard plates: each a mesh on its host with `.fit.` children for panels and bolts and an empty per anchor; a plate it made is rebuilt in place. Reports `plates` (`name`, `rebuilt`, `corners`, `facets`, `panels`, `bolts`, `anchors`), `host`, `side`. | +| `brokkr_kitbash.plates` | `table` (a `brokkr.plates.v0` document, JSON), `host`, `frame` (empty, or a JSON 4x4 of rows), `side`, `prefix` | Writes hard plates: each a mesh on its host with `.fit.` children for panels, bolts and fittings and an empty per anchor; a plate it made is rebuilt in place. Reports `plates` (`name`, `rebuilt`, `corners`, `facets`, `panels`, `bolts`, `anchors`), `host`, `side`. | `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. @@ -1692,6 +1728,31 @@ The tank's port is 0.4 of its radius across (0.12 m here), so the tee and the no `pipe_r` and `throat_r`. `set_params` on the tank carries the tee and the nozzle out with its port. The receipts file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the saved `.blend`. +## The fittings kit + +`kits/fittings.v0.json`: nine parts that stand on a hard plate's face, placed by `brokkr_kitbash.plate`'s fit rows +(Hard plates, Anchors and fits). Each stands on +z from z = 0 in its own frame: the origin is the fit's place, z the +face's normal, y the face's up. One material a part and no sockets. The defaults are the mech tracks' sizes. + +| part | params | what it is | +| --- | --- | --- | +| `bolt` | `r` | a hex head (r to its corners, 0.7 r tall) on a washer 1.55 r; the bolt of a `bolts` row | +| `slot` | `w`, `h` | the rim of a w by h slot: four bars 0.032 wide, 0.028 tall | +| `pit` | `w`, `h`, `depth`, `count`, `pitch` | the dark box under an opening, `count` of them `pitch` apart along y, centred. Under a slot: depth 0.012. Under vents: depth 0.01, the vents' count, pitch 2.7 h | +| `vents` | `w`, `h`, `count` | `count` louvre lips tilted 28 degrees, 2.7 h apart along y, centred | +| `access_port` | `r` | a turned ring of radius r around a sunk cover with a raised boss, 28 segments | +| `port_bolts` | `r` | the port's eight hex heads on a circle 0.91 r, standing from the ring's shoulder at z 0.035 | +| `handle` | `length`, `lift`, `r` | a bar along y on two posts, bent over at `lift`, a washer and a hex foot under each post. `roll` 90 lays it along the face's a | +| `eye` | `size` | a lifting eye: a pad with two bolts, a neck, and a ring standing in the plane of y and z | +| `louvres` | `w`, `h`, `n`, `depth`, `frame`, `slant` | a framed bank of n slats tilted `slant` degrees about x; `frame` is under w and h | + +Each part's points are the tracks' own (`surface.py`'s bolt row, grab handle and lifting eye, `hardplate.py`'s +slot, vents and port, `hardpoint.py`'s louvres) within 2e-8 m, float32 against float64, with two differences the +kit format sets: the handle's bar is a square section of side 2 r, mitred at its bends, where the tracks swept an +octagon; and the eye's pad is a plain box where the tracks' was a rounded outline with a chamfered rim. A handle +whose bar is thick against its bend (`r` over about a quarter of `min(0.4 lift, 0.2 length)`) may fold on the +inside of a turn, and is refused. + ## The mechanical kit `kits/mechanical.v0.json`: thirteen parts, each along +z, with socket types `flange` (equal), `mount` (fits), diff --git a/surfaces/blender/tests/live/kitbash_plates.py b/surfaces/blender/tests/live/kitbash_plates.py index 8463e73..47a5bd3 100644 --- a/surfaces/blender/tests/live/kitbash_plates.py +++ b/surfaces/blender/tests/live/kitbash_plates.py @@ -1,8 +1,8 @@ """Live proof, in a background Blender, of brokkr_kitbash.plates through run_intent: a plate table written onto a mechanical-kit link under a pin, each plate's mesh, fit children and anchor empties against plate.build's own answer under the frame, the Kit Bevels, joints unchanged by the plates, a roll of the pin carrying every plate, a hose between -two port empties either side of the pin across its range, a rebuild in place, and each refusal leaving the scene as it -was. Not part of the unittest run: it needs Blender. +two port empties either side of the pin across its range, a rebuild in place, each refusal leaving the scene as it +was, and a slab with a fit row of every kind written into a child per material. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_plates.py -- @@ -67,7 +67,8 @@ COUNT, SECTION = [0], ["setup"] # origin; X4 a plate written with no parent; X5 the host's inverse as the parent inverse; X6 a kept anchor not moved; X7 # the plate's Kit Bevel at shell's 30 degrees; X8 the panels' at 12; X9 a fit child parented to the host; X10 an # anchor's basis under the frame again; X11 stale children kept; X12 no sharp_face written; X13 no material refusal; -# X14 no refusal of a taken child or anchor name. +# X14 no refusal of a taken child or anchor name; X15 a row's fittings not written (plan leaves entry["fits"] out); X16 no +# refusal of a fit's missing material. # # Metres between a written vertex in the world (the object's matrix_world on its mesh's own coordinates) and the same # vertex of plate.build's answer under the frame this script holds, over every plate and fit child of the suite; inf @@ -183,12 +184,14 @@ def bevel(obj): def fits_of(entry, row): - """{material: [meshes]} of what a built entry's fit children hold, panels before bolts.""" + """{material: [meshes]} of what a built entry's fit children hold: panels, bolts, then the row's fittings.""" held = {} if row["clad"]: for material, mesh in ((row["clad"]["mat"], entry["panels"]), (row["clad"]["bolt_mat"], entry["bolts"])): if len(mesh[1]): held.setdefault(material, []).append(mesh) + for material, mesh in entry["fits"].items(): + held.setdefault(material, []).append(mesh) return held @@ -219,7 +222,7 @@ def proven(label, document, side, prefix, host, frame, report): if child is None or child.parent != obj: facts[f"fit {material}"] = False continue - panels = material == row["clad"]["mat"] + panels = bool(row["clad"]) and material == row["clad"]["mat"] facts[f"fit {material}"] = (reading("written", written(child, frame, parts)) < WRITTEN and np.array_equal(np.array(child.matrix_basis), np.eye(4)) and np.array_equal(np.array(child.matrix_parent_inverse), np.eye(4)) and [s.material.name for s in child.material_slots] == [material] and bevel(child) == ((round(row["clad"]["bevel"], 6), 20.0, 1, "ANGLE") if panels and row["clad"]["bevel"] > 0 else None)) @@ -428,6 +431,49 @@ try: bpy.context.view_layer.update() check("thawed, the plate is rebuilt", receipt["status"] == "accepted" and report["plates"][0]["rebuilt"], [receipt["status"], receipt["message"]]) proven("the thawed plate", THIGH, 1, "Thigh.", thigh, world(thigh), report) + + section("fittings") + for name in ("pit", "machine"): + bpy.data.materials.new(name) + KIT = slab("Kit", [0.0, -0.3, 0.3], ("feed", [0.0, 0.1])) + KIT["sides"] = "both" + KIT["fits"] += [{"kind": "bolts", "inset": 0.012, "spacing": 0.08, "params": "r=0.006", "mat": "gunmetal"}, + {"kind": "part", "part": "slot", "at": [0.0, 0.18], "params": "w=0.08; h=0.02", "mat": "khaki"}, + {"kind": "part", "part": "pit", "at": [0.0, 0.18], "params": "w=0.08; h=0.02", "mat": "pit"}, + {"kind": "part", "part": "vents", "at": [-0.06, 0.03], "params": "w=0.06; h=0.012; count=3", "mat": "khaki"}, + {"kind": "part", "part": "pit", "at": [-0.06, 0.03], "params": "w=0.06; h=0.012; depth=0.01; count=3; pitch=0.0324", "mat": "pit"}, + {"kind": "part", "part": "access_port", "at": [0.07, -0.1], "params": "r=0.03", "mat": "machine"}, + {"kind": "part", "part": "port_bolts", "at": [0.07, -0.1], "params": "r=0.03", "mat": "gunmetal"}, + {"kind": "part", "part": "handle", "at": [-0.07, -0.1], "roll": 90.0, "params": "length=0.1; lift=0.04; r=0.004", "mat": "gunmetal"}, + {"kind": "part", "part": "eye", "at": [0.08, 0.12], "lift": 0.002, "params": "size=0.03", "mat": "gunmetal"}, + {"kind": "part", "part": "louvres", "at": [0.0, -0.18], "params": "w=0.1; h=0.1; n=3; depth=0.02; frame=0.02", "mat": "steel"}, + {"kind": "step", "outline": [[-0.1, -0.06], [0.1, -0.06], [0.1, 0.06], [-0.1, 0.06]], "at": [0.0, 0.0], "lift": 0.012, "mat": "olive_light", "bolt_mat": "steel"}] + FITS = doc(KIT) + before = scene_state() + refused("a fit whose material is not in the file", call(doc({**KIT, "fits": KIT["fits"] + [{"kind": "part", "part": "bolt", "at": [0, 0], "mat": "brass"}]}), prefix="Fit."), "table.plates[0].fits[13].mat: no material named 'brass'") + refused("a step whose bolts' material is not in the file", call(doc({**KIT, "fits": [{**KIT["fits"][-1], "bolt_mat": "brass"}]}), prefix="Fit."), "table.plates[0].fits[0].bolt_mat: no material named 'brass'") + refused("a part the fittings kit does not have", call(doc({**KIT, "fits": [{"kind": "part", "part": "rivet", "at": [0, 0], "mat": "steel"}]}), prefix="Fit."), "table: plates[0].fits[0].part: 'rivet' is no part of the fittings kit") + check("refused, the fittings call left the scene as it was", scene_state() == before) + receipt, report = send("brokkr_kitbash.plates", host="Thigh", prefix="Fit.", table=json.dumps(FITS)) + bpy.context.view_layer.update() + check("a slab with a fit row of every kind is accepted", receipt["status"] == "accepted", [receipt["status"], receipt["message"]]) + R["reports"]["fittings"] = report + _, fit_built = proven("a row of every fit kind, on both sides", FITS, 1, "Fit.", thigh, world(thigh), report) + mats = ["gunmetal", "khaki", "machine", "olive_light", "pit", "steel"] + for side in "RL": + kit_plate = bpy.data.objects.get(f"Fit.Kit.{side}") + check(f"fits-written: Kit.{side} has a fit child per material, the fittings beside the panels and their bolts", + kit_plate is not None and sorted(c.name for c in kit_plate.children if c.type == "MESH") == [f"Fit.Kit.{side}.fit.{m}" for m in mats] + and bevel(bpy.data.objects[f"Fit.Kit.{side}.fit.olive_light"]) == (0.012, 20.0, 1, "ANGLE") and bevel(bpy.data.objects[f"Fit.Kit.{side}.fit.pit"]) is None, + kit_plate and sorted(c.name for c in kit_plate.children)) + check("the report counts what stands: the rim's bolts, nine parts and a step", report is not None and [row["fits"] for row in report["plates"]] == [fit_built[0]["report"]["fits"]] * 2 + and fit_built[0]["report"]["fits"] > 11, report and [row.get("fits") for row in report["plates"]]) + BARE = doc({**KIT, "fits": KIT["fits"][:3]}) + receipt, report = send("brokkr_kitbash.plates", host="Thigh", prefix="Fit.", table=json.dumps(BARE)) + bpy.context.view_layer.update() + proven("rebuilt with the rim's bolts alone", BARE, 1, "Fit.", thigh, world(thigh), report) + check("a rebuild removes the fit children it no longer makes", sorted(c.name for c in bpy.data.objects["Fit.Kit.R"].children if c.type == "MESH") == ["Fit.Kit.R.fit.gunmetal", "Fit.Kit.R.fit.olive_light"] + and "Fit.Kit.R.fit.pit" not in bpy.data.objects, sorted(c.name for c in bpy.data.objects["Fit.Kit.R"].children)) except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:]) finally: diff --git a/surfaces/blender/tests/live/kitbash_plates.result.json b/surfaces/blender/tests/live/kitbash_plates.result.json index be8856e..e2bb566 100644 --- a/surfaces/blender/tests/live/kitbash_plates.result.json +++ b/surfaces/blender/tests/live/kitbash_plates.result.json @@ -270,6 +270,61 @@ "name": "written-is-built: the thawed plate", "ok": true, "detail": null + }, + { + "name": "refused, scene unchanged: a fit whose material is not in the file", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a step whose bolts' material is not in the file", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a part the fittings kit does not have", + "ok": true, + "detail": null + }, + { + "name": "refused, the fittings call left the scene as it was", + "ok": true, + "detail": null + }, + { + "name": "a slab with a fit row of every kind is accepted", + "ok": true, + "detail": null + }, + { + "name": "written-is-built: a row of every fit kind, on both sides", + "ok": true, + "detail": null + }, + { + "name": "fits-written: Kit.R has a fit child per material, the fittings beside the panels and their bolts", + "ok": true, + "detail": null + }, + { + "name": "fits-written: Kit.L has a fit child per material, the fittings beside the panels and their bolts", + "ok": true, + "detail": null + }, + { + "name": "the report counts what stands: the rim's bolts, nine parts and a step", + "ok": true, + "detail": null + }, + { + "name": "written-is-built: rebuilt with the rim's bolts alone", + "ok": true, + "detail": null + }, + { + "name": "a rebuild removes the fit children it no longer makes", + "ok": true, + "detail": null } ], "hostErrors": [], @@ -290,6 +345,7 @@ "facets": 10, "panels": 1, "bolts": 4, + "fits": 0, "anchors": [ "Thigh.Guard.port.feed", "Thigh.Guard.mark.num" @@ -341,6 +397,38 @@ 0.056641 ] } + }, + "fittings": { + "plates": [ + { + "name": "Fit.Kit.R", + "rebuilt": false, + "corners": 16, + "facets": 10, + "panels": 1, + "bolts": 4, + "fits": 26, + "anchors": [ + "Fit.Kit.R.port.feed", + "Fit.Kit.R.mark.num" + ] + }, + { + "name": "Fit.Kit.L", + "rebuilt": false, + "corners": 16, + "facets": 10, + "panels": 1, + "bolts": 4, + "fits": 26, + "anchors": [ + "Fit.Kit.L.port.feed", + "Fit.Kit.L.mark.num" + ] + } + ], + "host": "Thigh", + "side": 1 } }, "ok": true diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 7f6b933..d75a57c 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -245,7 +245,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: cutters, frame, mechanical"): + with self.assertRaisesRegex(core.KitError, "no kit named 'absent'; kits: cutters, fittings, frame, 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") @@ -923,6 +923,157 @@ class FrameKitTests(unittest.TestCase): @unittest.skipIf(np is None, "numpy is not installed") +class FittingsKitTests(unittest.TestCase): + """kits/fittings.v0.json: what brokkr_kitbash.plate stands on a face.""" + PARTS = ["bolt", "slot", "pit", "vents", "access_port", "port_bolts", "handle", "eye", "louvres"] + + @classmethod + def setUpClass(cls): + cls.kit = core.load_kit("fittings") + + def shells(self, built): + """Each shape's faces as a Built of their own: a part's shells stand through each other, and each is held closed.""" + counts = built.counts.tolist() + starts = np.concatenate([[0], np.cumsum(counts)[:-1]]) + for index in sorted(set(built.shape.tolist())): + own = [k for k in range(len(counts)) if built.shape[k] == index] + yield built._replace(faces=np.concatenate([built.faces[starts[k]:starts[k] + counts[k]] for k in own]), counts=np.array([counts[k] for k in own])) + + def test_the_kit_is_its_nine_parts_and_no_sockets(self): + self.assertEqual(list(self.kit["parts"]), self.PARTS) + self.assertEqual(self.kit["socketTypes"], {}) + self.assertEqual([part["sockets"] for part in self.kit["parts"].values()], [[]] * 9) + + def test_the_defaults_are_the_kits_doc(self): + """What a row that names no params gets, part by part.""" + self.assertEqual({name: {p["name"]: p["default"] for p in part["params"]} for name, part in self.kit["parts"].items()}, { + "bolt": {"r": 0.017}, "slot": {"w": 0.2, "h": 0.04}, "pit": {"w": 0.2, "h": 0.04, "depth": 0.012, "count": 1, "pitch": 0}, + "vents": {"w": 0.3, "h": 0.03, "count": 4}, "access_port": {"r": 0.12}, "port_bolts": {"r": 0.12}, "handle": {"length": 0.3, "lift": 0.065, "r": 0.016}, + "eye": {"size": 0.1}, "louvres": {"w": 0.6, "h": 0.72, "n": 6, "depth": 0.05, "frame": 0.07, "slant": 25}}) + + def test_every_part_builds_closed_and_wound_out_from_the_face(self): + for name, part in self.kit["parts"].items(): + rng = random.Random(f"fittings.{name}") + draws = [{}] + [{p["name"]: rng.randint(p["min"], p["max"]) if p["type"] == "integer" else rng.uniform(p["min"], p["max"]) for p in part["params"]} for _ in range(16)] + for draw in draws: + if name == "louvres" and draw and draw["frame"] >= min(draw["w"], draw["h"]): + with self.assertRaises(core.KitError): + core.build(part, draw) + continue + if name == "handle" and draw and draw["r"] > 0.25 * min(0.4 * draw["lift"], 0.2 * draw["length"]): + try: # a bar thick against its bend may fold on the inside of a turn: core refuses it by name + core.build(part, draw) + except core.KitError as error: + self.assertIn("the section folds there", str(error)) + continue + built = core.build(part, draw) + self.assertTrue(closed_and_oriented(built), (name, draw)) + for shell in self.shells(built): + self.assertGreater(signed_volume(shell), 0, (name, draw)) + self.assertGreater(float(built.V[:, 2].max()), 0.0, (name, draw)) + floor = float(core.build(part).V[:, 2].min()) + self.assertGreaterEqual(floor, {"bolt": -0.0005, "handle": -0.004, "eye": -0.002, "louvres": -0.008}.get(name, 0.0), name) # what a part sinks into the face at its defaults + + def test_the_bolt_is_the_tracks_washer_and_head(self): + built = core.build(self.kit["parts"]["bolt"], {"r": 0.017}) + washer, head = built.V[:28], built.V[28:] + self.assertLess(float(np.abs(np.linalg.norm(washer[:, :2], axis=1) - 1.55 * 0.017).max()), 1e-15) + self.assertLess(float(np.abs(np.linalg.norm(head[:, :2], axis=1) - 0.017).max()), 1e-15) + self.assertEqual(sorted(set(np.round(built.V[:, 2], 12).tolist())), [-0.0005, 0.0035, 0.0035 + 0.7 * 0.017]) + self.assertLess(abs(float(head[0, 0])), 1e-15) # a corner on +y, as the tracks' heads stand + + + # Shapes: each part at params off its defaults, every shell's place and size from the kit's doc. A reading is how + # far a built point or extent stands from the stated one (metres). Shipped: float rounding, held as 2.2e-16 a metre. + # Least claimed mutants: port_bolts' heads on 0.9 r (0.91 shipped) at r 0.1, a slot bar 0.001 off, the port's heads + # 0.001 up: each reads 1e-3. The bound is the geometric mean, 4.7e-10 (lodur:ruling:deterministic-bound-margin). + SHAPED = 4.7e-10 + TOPOLOGY = {"slot": (32, 24, 4), "pit": (24, 18, 3), "vents": (24, 18, 3), "access_port": (170, 196, 1), "port_bolts": (96, 64, 8), + "handle": (112, 82, 5), "eye": (200, 188, 5), "louvres": (64, 48, 8)} + + def pieces(self, built, each=None): + """Each shape's points; a repeat's copies apart, `each` points a copy.""" + counts = built.counts.tolist() + starts = np.concatenate([[0], np.cumsum(counts)[:-1]]).astype(int) + out = [] + for index in sorted(set(built.shape.tolist())): + points = built.V[sorted({int(v) for k in range(len(counts)) if built.shape[k] == index for v in built.faces[starts[k]:starts[k] + counts[k]]})] + out += [points[i:i + each] for i in range(0, len(points), each)] if each else [points] + return out + + def box(self, points, centre, size, slant=0.0): + """How far a box's extents stand from a box of size about centre, turned slant degrees about x.""" + c, s = math.cos(math.radians(slant)), abs(math.sin(math.radians(slant))) + half = np.array([size[0] / 2, size[1] / 2 * c + size[2] / 2 * s, size[1] / 2 * s + size[2] / 2 * c]) + return float(np.abs(np.array([points.min(axis=0), points.max(axis=0)]) - [np.array(centre) - half, np.array(centre) + half]).max()) + + def tube(self, points, axis, radius, low, high): + """How far a tube's points stand from radius about the vertical through axis (x, y), from low to high.""" + return max(float(np.abs(np.linalg.norm(points[:, :2] - axis, axis=1) - radius).max()), abs(float(points[:, 2].min()) - low), abs(float(points[:, 2].max()) - high)) + + def built(self, name, params): + b = core.build(self.kit["parts"][name], core.parse_params(params)) + self.assertEqual((len(b.V), len(b.counts), b.shell_count), self.TOPOLOGY[name], name) + self.assertTrue(closed_and_oriented(b), name) + return b + + def test_slot_and_pit_are_their_boxes(self): + """The slot's four bars around a w by h opening, 0.032 wide and 0.028 tall; the pit's count boxes pitch apart.""" + w, h = 0.3, 0.1 + bars = self.pieces(self.built("slot", "w=0.3; h=0.1")) + for points, centre, size in zip(bars, ([0, h / 2 + 0.016, 0.014], [0, -h / 2 - 0.016, 0.014], [w / 2 + 0.016, 0, 0.014], [-w / 2 - 0.016, 0, 0.014]), + ([w + 0.06, 0.032, 0.028],) * 2 + ([0.032, h, 0.028],) * 2): + self.assertLess(self.box(points, centre, size), self.SHAPED, centre) + for k, points in enumerate(self.pieces(self.built("pit", "w=0.1; h=0.03; depth=0.02; count=3; pitch=0.08"), 8)): + self.assertLess(self.box(points, [0, -0.08 + 0.08 * k, 0.01], [0.1, 0.03, 0.02]), self.SHAPED, k) + + def test_vents_and_louvres_lean_their_own_ways(self): + """A vents lip is tilted 28 degrees with its upper edge down to the face; a louvre slat is turned slant + degrees with its upper edge up off it.""" + h = 0.04 + for k, points in enumerate(self.pieces(self.built("vents", "w=0.2; h=0.04; count=3"), 8)): + self.assertLess(self.box(points, [0, 0.75 * h - 2.7 * h + 2.7 * h * k, 0.014], [0.24, 0.9 * h, 0.012], 28), self.SHAPED, k) + self.assertLess(float(points[np.argmax(points[:, 1]), 2]), 0.014, k) + w, h, n, depth, frame = 0.5, 0.4, 4, 0.06, 0.05 + louvres = self.built("louvres", "w=0.5; h=0.4; n=4; depth=0.06; frame=0.05; slant=30") + for points, centre, size in zip(self.pieces(louvres)[:4], ([0, -h / 2, depth / 2], [0, h / 2, depth / 2], [-w / 2, 0, depth / 2], [w / 2, 0, depth / 2]), + ([w + frame, frame, depth],) * 2 + ([frame, h + frame, depth],) * 2): + self.assertLess(self.box(points, centre, size), self.SHAPED, centre) + pitch = (h - frame) / n + for k, points in enumerate(self.pieces(louvres, 8)[4:]): + self.assertLess(self.box(points, [0, -0.5 * (h - frame) + 0.5 * pitch + pitch * k, 0.3 * depth], [w - frame, 0.75 * pitch, 0.25 * depth], 30), self.SHAPED, k) + self.assertGreater(float(points[np.argmax(points[:, 1]), 2]), 0.3 * depth, k) + + def test_access_port_is_its_profile_turned_and_its_heads_on_the_rim(self): + """The port's 28 turns of its eight profile points; eight hex heads of 0.07 r on 0.91 r at 45 degree steps, + from the shoulder (0.035) up 0.012.""" + r = 0.1 + port = self.built("access_port", "r=0.1") + turned = {(round(float(np.hypot(x, y)) / r, 9), round(float(z), 9)) for x, y, z in port.V} + self.assertEqual(turned, {(0.0, 0.0), (1.0, 0.0), (1.0, 0.035), (0.82, 0.05), (0.82, 0.022), (0.34, 0.022), (0.34, 0.045), (0.0, 0.045)}) + for k, points in enumerate(self.pieces(self.built("port_bolts", "r=0.1"))): + turn = math.radians(45 * k) + self.assertLess(self.tube(points, 0.91 * r * np.array([math.cos(turn), math.sin(turn)]), 0.07 * r, 0.035, 0.047), self.SHAPED, k) + + def test_handle_and_eye_stand_their_shells(self): + """The handle's bar 2 r square from 0.004 under the face to lift + r, its posts length apart on a washer of + 2.3 r and a hex foot of 1.5 r; the eye's pad, two heads 0.72 size off its middle, a neck, and a ring of 0.29 + to 0.55 size about 0.012 + 0.62 size, 0.26 size thick across x.""" + length, lift, r = 0.4, 0.08, 0.012 + bar, *feet = self.pieces(self.built("handle", "length=0.4; lift=0.08; r=0.012")) + self.assertLess(float(np.abs(np.array([bar.min(axis=0), bar.max(axis=0)]) - [[-r, -length / 2 - r, -0.004], [r, length / 2 + r, lift + r]]).max()), self.SHAPED) + for points, y, radius, low in zip(feet, (-1, 1, -1, 1), (2.3 * r, 2.3 * r, 1.5 * r, 1.5 * r), (0.0, 0.0, 0.008, 0.008)): + self.assertLess(self.tube(points, [0, y * length / 2], radius, low, low + 0.008), self.SHAPED, (y, radius)) + size = 0.12 + pad, *heads, neck, ring = self.pieces(self.built("eye", "size=0.12")) + self.assertLess(self.box(pad, [0, 0, 0.004], [1.1 * size, 2 * size, 0.012]), self.SHAPED) + for points, y in zip(heads, (-1, 1)): + self.assertLess(self.tube(points, [0, y * 0.72 * size], 0.11 * size, 0.01, 0.018), self.SHAPED, y) + self.assertLess(self.box(neck, [0, 0, 0.012 + 0.1 * size], [0.34 * size, 0.5 * size, 0.24 * size]), self.SHAPED) + across = np.hypot(ring[:, 1], ring[:, 2] - (0.012 + 0.62 * size)) + self.assertLess(max(abs(float(across.min()) - 0.29 * size), abs(float(across.max()) - 0.55 * size), abs(float(np.abs(ring[:, 0]).max()) - 0.13 * size)), self.SHAPED) + + 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 @@ -2509,7 +2660,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", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json", "plate.py", "ram.py", "route.py"]) + self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "fittings.v0.json", "frame.v0.json", "mechanical.v0.json", "plate.py", "ram.py", "route.py"]) for pattern in self.PACKAGE: for name, text in self.sources().items(): if pattern is self.PACKAGE[2] and name == "__init__.py": diff --git a/surfaces/blender/tests/test_plate.py b/surfaces/blender/tests/test_plate.py index e331030..15d4f8c 100644 --- a/surfaces/blender/tests/test_plate.py +++ b/surfaces/blender/tests/test_plate.py @@ -36,6 +36,7 @@ if np is not None: package.__path__ = [str(SURFACE / "brokkr_kitbash")] sys.modules["brokkr_kitbash_plates"] = package plate = importlib.import_module("brokkr_kitbash_plates.plate") + core = importlib.import_module("brokkr_kitbash_plates.core") BOX = [{"at": [1, 0, 0], "normal": [1, 0, 0]}, {"at": [-1, 0, 0], "normal": [-1, 0, 0]}, {"at": [0, 1, 0], "normal": [0, 1, 0]}, {"at": [0, -1, 0], "normal": [0, -1, 0]}, {"at": [0, 0, 1], "normal": [0, 0, 1]}, {"through": [[0, 0, -1], [1, 0, -1], [0, 1, -1]], "out": [0, 0, -1]}] @@ -485,9 +486,9 @@ class CheckTests(unittest.TestCase): def test_unknown_fit_kind(self): with self.assertRaises(plate.PlateError) as caught: - plate.check(doc(row(slab=SLAB, fits=[{"kind": "bolts", "at": [0, 0]}]))) + plate.check(doc(row(slab=SLAB, fits=[{"kind": "rivets", "at": [0, 0]}]))) self.assertIn("plates[0].fits[0].kind", str(caught.exception)) - self.assertIn("mark, hose_port", str(caught.exception)) + self.assertIn("mark, hose_port, part, bolts, step", str(caught.exception)) def test_duplicate_anchor_name(self): fits = [{"kind": "mark", "id": "a", "at": [0, 0], "height": 0.3}, {"kind": "hose_port", "name": "a", "at": [0.1, 0]}] @@ -514,7 +515,7 @@ class CheckTests(unittest.TestCase): class SolidTests(unittest.TestCase): def test_a_cube_from_six_faces(self): made = plate.build(doc(row()))[0] - self.assertEqual(made["report"], {"corners": 8, "facets": 6, "panels": 0, "bolts": 0}) + self.assertEqual(made["report"], {"corners": 8, "facets": 6, "panels": 0, "bolts": 0, "fits": 0}) self.assertEqual(sorted(map(tuple, np.round(made["solid"][0]).astype(int).tolist())), sorted((x, y, z) for x in (-1, 1) for y in (-1, 1) for z in (-1, 1))) self.assertAlmostEqual(volume(made["solid"]), 8.0, places=12) @@ -763,7 +764,7 @@ class CladTests(unittest.TestCase): [-0.5231073349097417, 0.9203597671588255, 0.00622360127002797], [0.8223018952005992, -0.9577282429612575, 0.0028711637754610976], [0.7686109712617415, -0.6216304824437804, 0.007801596935861264]] (entry,) = plate.build(plate.check(sheet(soul)), 1) - self.assertEqual(entry["report"], {"corners": 9, "facets": 8, "panels": 1, "bolts": 3}) + self.assertEqual(entry["report"], {"corners": 9, "facets": 8, "panels": 1, "bolts": 3, "fits": 0}) inset, calls = plate.inset2d, [] def spy(ring, c): @@ -822,7 +823,7 @@ class CladTests(unittest.TestCase): def test_a_split_facet_takes_two_panels_and_a_whole_one_a_panel(self): made = plate.build(doc(row(clad=dict(CLAD, facets=[{"n": [0, 0, 1], "cos": 0.9}], split=2.2))))[0] - self.assertEqual(made["report"], {"corners": 8, "facets": 6, "panels": 2, "bolts": 8}) + self.assertEqual(made["report"], {"corners": 8, "facets": 6, "panels": 2, "bolts": 8, "fits": 0}) self.assertEqual((len(made["panels"][0]), len(made["bolts"][0])), (24, 96)) self.assertGreater(volume(made["panels"]), 0) self.assertAlmostEqual(volume(made["bolts"]), 8 * 1.5 * math.sqrt(3) * 0.028 ** 2 * 0.6 * 0.028, places=12) @@ -904,6 +905,209 @@ class AnchorTests(unittest.TestCase): self.assertLess(float(np.abs(np.array(made["anchors"][0]["matrix"])[:3, 3] - np.array([0.2, 1.01, 0.3])).max()), 1e-12) +def placed(part, params, frame): + """A fittings part's vertices at params, placed by a 4x4 frame.""" + V = core.build(core.load_kit("fittings")["parts"][part], core.parse_params(params)).V + return V @ frame[:3, :3].T + frame[:3, 3] + + +RIM = {"at": [0.5, 1.0, 0.2], "normal": [0.06, 1, 0.05], "right": [1, 0, 0], "outline": {"w": 1.0, "h": 0.6, "clip": 0.0}, "thick": 0.2, "taper": 0.04} +PIT = {"kind": "part", "part": "pit", "at": [0.1, -0.05], "roll": 30, "lift": 0.01, "params": "w=0.2; h=0.05", "mat": "pit"} +STEP = {"kind": "step", "outline": [[-0.15, -0.1], [0.15, -0.1], [0.2, 0.1], [-0.15, 0.1]], "at": [0.05, 0.02], "lift": 0.03, "mat": "olive_light"} +# One row of each fit kind, on a clad slab built on both sides: what the hash holds of fits. +FITTED = {"name": "Fitted", "mat": "olive", "sides": "both", "slab": RIM, "clad": dict(CLAD, split=99), "fits": [ + {"kind": "bolts", "inset": 0.04, "spacing": 0.2, "mat": "gunmetal"}, PIT, STEP, + {"kind": "part", "part": "slot", "at": [0.1, -0.05], "roll": 30, "lift": 0.01, "params": "w=0.2; h=0.05", "mat": "olive"}, + {"kind": "part", "part": "vents", "at": [-0.25, 0.0], "mat": "olive"}, {"kind": "part", "part": "access_port", "at": [0.3, 0.12], "params": "r=0.08", "mat": "machine"}, + {"kind": "part", "part": "port_bolts", "at": [0.3, 0.12], "params": "r=0.08", "mat": "gunmetal"}, {"kind": "part", "part": "handle", "at": [0.0, 0.2], "roll": 90, "mat": "gunmetal"}, + {"kind": "part", "part": "eye", "at": [-0.3, -0.18], "mat": "gunmetal"}, {"kind": "part", "part": "louvres", "at": [0.0, 0.0], "params": "w=0.2; h=0.2; n=3", "mat": "olive"}]} + + +@unittest.skipIf(np is None, "numpy is not installed") +class FitTests(unittest.TestCase): + """Fit rows that are geometry. A reading is how far the built points stand from the stated ones (apart, metres); + each bound is the geometric mean of the shipped reading and the mutant's (lodur:ruling:deterministic-bound-margin).""" + # fit-frames: shipped 0.0 here, held as 2.2e-16 (a float's spacing at 1 m); the roll not negated at side -1 reads 0.10, the clad top + # left out 0.05: the bound is 3e-9, 1e7 each side of both + HELD = 3e-9 + + def frame(self, at, lift, roll, side=1, slab=RIM): + a, b, n = plate.plane_basis(slab["normal"], (0, 0, 1), slab.get("right")) + flip = np.array([side, 1.0, 1.0]) + return core.surface_frame((np.array(slab["at"]) + a * at[0] + b * at[1] + n * lift) * flip, n * flip, b * flip, -roll if side < 0 else roll) + + def test_a_part_stands_in_the_fits_frame(self): + made = plate.build(doc(row(slab=RIM, fits=[PIT])))[0] + self.assertEqual((list(made["fits"]), made["report"]["fits"]), (["pit"], 1)) + V, faces = made["fits"]["pit"] + self.assertLess(apart(V, placed("pit", PIT["params"], self.frame(PIT["at"], 0.01, 30))), self.HELD) + self.assertEqual([len(f) for f in faces], [4] * 6) + self.assertGreater(volume((V, faces)), 0) + + def test_right_handed_at_side_minus_one_with_the_roll_negated(self): + """fit-frames. Mutant: roll not negated at side -1.""" + made = plate.build(doc(row(slab=RIM, fits=[PIT])), -1)[0] + frame = self.frame(PIT["at"], 0.01, 30, -1) + a, b, n = plate.plane_basis(RIM["normal"], (0, 0, 1), RIM["right"]) + self.assertAlmostEqual(float(np.linalg.det(frame[:3, :3])), 1.0, places=12) + self.assertLess(float(np.abs(frame[:3, 2] - n * (-1, 1, 1)).max()), 1e-12) + self.assertLess(apart(made["fits"]["pit"][0], placed("pit", PIT["params"], frame)), self.HELD) + self.assertGreater(volume(made["fits"]["pit"]), 0) # wound outward still + mirror = plate.build(doc(row(slab=RIM, fits=[PIT])), 1)[0]["fits"]["pit"][0] * (-1, 1, 1) + self.assertLess(apart(made["fits"]["pit"][0], mirror), self.HELD) # a part the same across its x: side -1 is the mirror + + def test_a_part_and_a_step_stand_on_the_clad_top_and_bolts_on_the_bare_face(self): + fits = [{"kind": "bolts", "inset": 0.04, "spacing": 0.2, "lift": 0.002, "mat": "gunmetal"}, PIT, STEP] + bare = plate.build(doc(row(slab=RIM, fits=fits)))[0]["fits"] + clad = plate.build(doc(row(slab=RIM, fits=fits, clad=dict(CLAD, mat="clad", lifts=[0.05, 0.05], split=99))))[0]["fits"] + n = plate.plane_basis(RIM["normal"])[2] + for mat in ("pit", "olive_light"): + self.assertLess(apart(clad[mat][0], bare[mat][0] + n * 0.05), self.HELD, mat) + self.assertLess(apart(clad["pit"][0], placed("pit", PIT["params"], self.frame(PIT["at"], 0.06, 30))), self.HELD) + bolts, step = len(placed("bolt", "", np.eye(4))) * 12, 12 * 2 + self.assertEqual(len(bare["gunmetal"][0]), bolts + step) + self.assertEqual(float(np.abs(clad["gunmetal"][0][:bolts] - bare["gunmetal"][0][:bolts]).max()), 0.0) # the rim's bolts fasten the plate, under its cladding + self.assertLess(apart(bare["gunmetal"][0][:40], placed("bolt", "", self.frame([-0.42 + 0.105, -0.22], 0.002, 0))), self.HELD) + + def bolts_by_edge(self, spacing, counts): + made = plate.build(doc(row(slab=RIM, fits=[{"kind": "bolts", "inset": 0.04, "spacing": spacing, "mat": "gunmetal"}])))[0] + a, b, n = plate.plane_basis(RIM["normal"], (0, 0, 1), RIM["right"]) + each = len(placed("bolt", "", np.eye(4))) + V = made["fits"]["gunmetal"][0].reshape(-1, each, 3) + self.assertEqual((len(V), made["report"]["fits"]), (sum(counts), sum(counts))) + ring = np.array([[-0.42, -0.22], [0.42, -0.22], [0.42, 0.22], [-0.42, 0.22]]) # the outline in 0.04 + the taper 0.04, counter-clockwise from where the row's runs + want = [ring[k] + (ring[(k + 1) % 4] - ring[k]) * (j + 0.5) / count for k, count in enumerate(counts) for j in range(count)] + # a bolt's own points: its washer's 28 and its head's 12 are each centred on its axis + got = [[float((bolt[:28].mean(axis=0) - RIM["at"]) @ a), float((bolt[:28].mean(axis=0) - RIM["at"]) @ b)] for bolt in V] + return float(np.abs(np.array(got) - np.array(want)).max()) + + def test_bolts_stand_along_the_outline_moved_in(self): + """bolt-rim: 0.84 and 0.44 edges. At spacing 0.2, 4, 2, 4, 2; at 0.15 (5.6 and 2.9 to an edge), 5, 2, 5, 2. + Mutant int -> round: 6, 3, 6, 3 at 0.15 (the count differs; at 0.2 it gives the same 4, 2, 4, 2).""" + self.assertLess(self.bolts_by_edge(0.2, [4, 2, 4, 2]), 1e-12) + self.assertLess(self.bolts_by_edge(0.15, [5, 2, 5, 2]), 1e-12) + self.assertLess(self.bolts_by_edge(5.0, [1, 1, 1, 1]), 1e-12) + + def test_bolts_follow_a_gapped_outline_of_either_winding(self): + slab = dict(RIM, outline=[[-0.5, -0.3], [-0.5, 0.3], [0.5, 0.3], [0.5, -0.3]], gap=0.05) + made = plate.build(doc(row(slab=slab, fits=[{"kind": "bolts", "inset": 0.04, "spacing": 5.0, "mat": "gunmetal"}])))[0] + a, b, n = plate.plane_basis(RIM["normal"], (0, 0, 1), RIM["right"]) + V = made["fits"]["gunmetal"][0].reshape(4, -1, 3) + got = sorted([round(float((bolt[:28].mean(axis=0) - RIM["at"]) @ a), 9), round(float((bolt[:28].mean(axis=0) - RIM["at"]) @ b), 9)] for bolt in V) + self.assertEqual(got, [[-0.37, 0.0], [0.0, -0.17], [0.0, 0.17], [0.37, 0.0]]) + self.assertGreater(volume(made["fits"]["gunmetal"]), 0) + + def test_a_vanished_ring_stands_no_bolts(self): + """Ruling plate-bolts-follow-edge-event: a bolts row whose outline, moved in by its inset and the taper, leaves + no ring stands no bolts, and the table checks and builds. Thin: 0.1 wide, in 0.06 + 0.04 across it. Both ways: + a 0.2 square in 0.07 + 0.04 and 0.12 + 0.04 turns half round with its area positive. Mutant: the guard a sign + of the area, the shipped state at 9dd543f (the square stands 4 crossed bolts).""" + bolts = {"kind": "bolts", "inset": 0.06, "spacing": 5.0, "mat": "gunmetal"} + for outline, inset, count in (([0.1, 0.6], 0.06, 0), ([0.2, 0.2], 0.07, 0), ([0.2, 0.2], 0.12, 0), ([0.2, 0.2], 0.05, 4), ([0.1, 0.6], 0.005, 4)): + table = doc(row(slab=dict(RIM, outline={"w": outline[0], "h": outline[1], "clip": 0.0}), fits=[dict(bolts, inset=inset), PIT])) + plate.check(table) + made = plate.build(table)[0] + self.assertEqual((made["report"]["fits"], "gunmetal" in made["fits"]), (count + 1, count > 0), (outline, inset)) + self.assertLess(apart(made["fits"]["pit"][0], placed("pit", PIT["params"], self.frame(PIT["at"], 0.01, 30))), self.HELD) + + def test_a_ring_that_stands_or_would_meet_itself(self): + """A bolt ring inset2d returns with a corner less still stands its bolts: a 0.4 square clipped 0.05, in 0.11 + + 0.04, loses its clipped edges and stands 4 (mutant: an edge-direction guard against the drawn outline, 34da146, + stands none). A ring that would meet itself stands no bolts, and the table checks and builds: a unit square + notched 0.1 wide and 0.8 deep, in 0.1, 0.15 and 0.25 + 0.02 (mutant: NotSimple not caught, check refuses).""" + bolts = {"kind": "bolts", "inset": 0.11, "spacing": 5.0, "mat": "gunmetal"} + made = plate.build(doc(row(slab=dict(RIM, outline={"w": 0.4, "h": 0.4, "clip": 0.05}), fits=[bolts])))[0] + self.assertEqual(made["report"]["fits"], 4) + notched = [[-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [0.05, 0.5], [0.05, -0.3], [-0.05, -0.3], [-0.05, 0.5], [-0.5, 0.5]] + for inset, count in ((0.1, 0), (0.15, 0), (0.25, 0), (0.03, 23)): + table = doc(row(slab=dict(RIM, taper=0.02, outline=notched), fits=[dict(bolts, inset=inset, spacing=0.2), PIT])) + plate.check(table) + made = plate.build(table)[0] + self.assertEqual((made["report"]["fits"], "gunmetal" in made["fits"]), (count + 1, count > 0), inset) + + def test_a_step_is_a_panel_on_its_outline(self): + made = plate.build(doc(row(slab=RIM, fits=[STEP])))[0] + a, b, n = plate.plane_basis(RIM["normal"], (0, 0, 1), RIM["right"]) + panels, bolts = plate._Mesh(), plate._Mesh() + polygon = [np.array(RIM["at"]) + a * (0.05 + x) + b * (0.02 + y) for x, y in STEP["outline"]] + self.assertTrue(plate.panel(panels, bolts, polygon, n, 0.03, 0.0, plate.BOLT)) + self.assertEqual(list(made["fits"]), ["olive_light", "gunmetal"]) + for mat, mesh in (("olive_light", panels), ("gunmetal", bolts)): + self.assertEqual(float(np.abs(made["fits"][mat][0] - mesh.done()[0]).max()), 0.0) + self.assertEqual(made["fits"][mat][1], mesh.done()[1]) + named = plate.build(doc(row(slab=RIM, fits=[dict(STEP, bolt_mat="steel")])))[0] + self.assertEqual(list(named["fits"]), ["olive_light", "steel"]) + + def test_the_left_of_a_one_seed_row_is_the_right_mirrored(self): + """mirror. Mutant: the .L's fits drawn at side -1 (right-handed frames) and not mirrored.""" + for clad in (None, dict(CLAD, split=99)): + right, left = plate.build(doc(dict(FITTED, clad=clad))) + self.assertEqual((right["name"], left["name"], left["report"]["fits"]), ("Fitted.R", "Fitted.L", right["report"]["fits"])) + self.assertEqual(list(left["fits"]), list(right["fits"])) + for mat in right["fits"]: + V, faces = across(right["fits"][mat]) + self.assertEqual(float(np.abs(left["fits"][mat][0] - V).max()), 0.0, mat) + self.assertEqual(left["fits"][mat][1], faces) + self.assertGreater(volume(left["fits"][mat]), 0, mat) + pair = plate.build(doc(dict(FITTED, clad=dict(CLAD, split=99, seed=[5, 9]))))[1] # a pair of seeds: the left is drawn at side -1 + slot = [f for f in FITTED["fits"] if f.get("part") == "slot"][0] + self.assertLess(apart(pair["fits"]["olive"][0][:32], placed("slot", slot["params"], self.frame(slot["at"], CLAD["lifts"][0] + 0.01, 30, -1))), self.HELD) + + def test_fits_of_one_material_merge_in_row_order(self): + made = plate.build(doc(row(slab=RIM, fits=[PIT, {"kind": "mark", "id": "m", "at": [0, 0], "height": 0.1}, dict(PIT, at=[-0.2, 0.1], roll=0, lift=0)])))[0] + self.assertEqual((made["report"]["fits"], len(made["anchors"]), len(made["fits"]["pit"][0]), made["fits"]["pit"][1][6]), (2, 1, 16, [8, 11, 10, 9])) + self.assertLess(apart(made["fits"]["pit"][0][8:], placed("pit", PIT["params"], self.frame([-0.2, 0.1], 0.0, 0))), self.HELD) + + def test_every_part_stands_on_a_face_at_its_defaults(self): + for name in core.load_kit("fittings")["parts"]: + made = plate.build(doc(row(face={"at": [0, 1, 0], "normal": [0, 1, 0]}, fits=[{"kind": "part", "part": name, "at": [0.1, 0.2], "mat": "m"}])))[0] + V = made["fits"]["m"][0] + self.assertLess(apart(V, placed(name, "", core.surface_frame([-0.1, 1.0, 0.2], [0, 1, 0], [0, 0, 1]))), self.HELD, name) # a is b cross n: -x here + self.assertGreater(float(V[:, 1].max()), 1.01, name) + self.assertGreater(float(V[:, 1].min()), 0.99, name) + + def refused(self, fit, *wants, slab=RIM, **more): + with self.assertRaises(plate.PlateError) as caught: + plate.check(doc(row(fits=[fit], **({"slab": slab} if slab else {}), **more))) + for want in wants: + self.assertIn(want, str(caught.exception)) + + def test_refusals_name_the_path(self): + part = {"kind": "part", "part": "pit", "at": [0, 0], "mat": "pit"} + self.refused(dict(part, part="rivet"), "plates[0].fits[0].part: 'rivet' is no part of the fittings kit", "bolt, slot, pit, vents, access_port, port_bolts, handle, eye, louvres") + self.refused(dict(part, part=["pit"]), "plates[0].fits[0].part") + self.refused(dict(part, params="w=9"), "plates[0].fits[0].params: kit 'fittings' part 'pit' param 'w' = 9.0 is outside [0.005, 2]") + self.refused(dict(part, params="wide=1"), "plates[0].fits[0].params", "has no param 'wide'") + self.refused(dict(part, params="w"), "plates[0].fits[0].params", "is not name=value") + self.refused(dict(part, params="w=0.1;" + " " * 256), "plates[0].fits[0].params: wants") + self.refused(dict(part, params=3), "plates[0].fits[0].params: wants") + self.refused(dict(part, mat="m" * 64), "plates[0].fits[0].mat") + self.refused({k: v for k, v in part.items() if k != "mat"}, "plates[0].fits[0].mat: missing") + self.refused(dict(part, roll=361), "plates[0].fits[0].roll") + self.refused(dict(part, height=1), "plates[0].fits[0].height: unknown key") + self.refused(part, "plates[0].fits[0]: a fit stands on a face", slab=None) + self.refused(dict(part, part="louvres", params="w=0.1; frame=0.3"), "plates[0].fits[0]: kit 'fittings' part 'louvres'", "every size must be above 0") + bolts = {"kind": "bolts", "inset": 0.04, "spacing": 0.2, "mat": "gunmetal"} + self.refused(bolts, "plates[0].fits[0]: a bolts row stands along a slab's outline; this row is no slab", slab=None, face={"at": [0, 1, 0], "normal": [0, 1, 0]}) + self.refused(dict(bolts, mat="m" * 64), "plates[0].fits[0].mat") + self.refused(dict(bolts, spacing=0), "plates[0].fits[0].spacing") + self.refused(dict(bolts, params="r=1"), "plates[0].fits[0].params: kit 'fittings' part 'bolt' param 'r'") + self.refused(dict(STEP, mat="m" * 64), "plates[0].fits[0].mat") + self.refused(dict(STEP, bolt_mat=""), "plates[0].fits[0].bolt_mat") + self.refused(dict(STEP, outline=STEP["outline"][:2]), "plates[0].fits[0].outline: wants 3 to 64 entries") + self.refused(dict(STEP, outline=[[0, 0], [0.3, 0.3], [0.3, 0], [0, 0.2]]), "plates[0].fits[0].outline: the outline crosses itself") + self.refused(dict(STEP, outline=[[0, 0], [0.1, 0], [0.1, 0.1]]), "plates[0].fits[0].outline: under 0.02 m2") + self.refused({k: v for k, v in STEP.items() if k != "lift"}, "plates[0].fits[0].lift: missing") + plate.check(doc(row(slab=RIM, fits=[part, dict(part), bolts, STEP]))) # geometry fits carry no name: two alike are two fits + + def test_check_writes_a_fit_s_defaults_in(self): + fits = plate.check(doc(row(slab=RIM, fits=[{"kind": "part", "part": "eye", "at": [0, 0], "mat": "g"}, {"kind": "bolts", "inset": 0.04, "spacing": 0.2, "mat": "g"}, STEP])))["plates"][0]["fits"] + self.assertEqual(fits[0], {"kind": "part", "part": "eye", "at": [0.0, 0.0], "roll": 0.0, "lift": 0.0, "params": "", "mat": "g"}) + self.assertEqual(fits[1], {"kind": "bolts", "inset": 0.04, "spacing": 0.2, "lift": 0.0, "params": "", "mat": "g"}) + self.assertEqual(fits[2], dict(STEP, outline=[[float(v) for v in p] for p in STEP["outline"]], bolt_mat="gunmetal")) + self.assertEqual(plate.check({"schema": plate.SCHEMA, "plates": [dict(row(slab=RIM), fits=fits)]})["plates"][0]["fits"], fits) + + @unittest.skipIf(np is None, "numpy is not installed") class DeterminismTests(unittest.TestCase): def test_the_table_and_the_side_are_the_only_inputs(self): @@ -921,15 +1125,23 @@ class DeterminismTests(unittest.TestCase): for mech in ("bastion", "paladin", "raptor"): for case in fixture(mech)["cases"]: for entry in plate.build(fixture(mech)["table"], case["side"]): - made.update(entry["name"].encode()) - for key in ("solid", "panels", "bolts"): - made.update(np.round(entry[key][0] / QUANTUM).astype("